From 875b0739aa8bed310e59ef22764f6b37d7e82862 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Sat, 11 May 2024 16:54:11 -0500 Subject: [PATCH 01/10] Enforce aliases for 'k8s.io/apimachinery/pkg/util/errors' and 'k8s.io/apimachinery/pkg/api/errors' --- .golangci.yaml | 9 ++++ cmd/pinniped/cmd/whoami.go | 6 +-- cmd/pinniped/cmd/whoami_test.go | 4 +- internal/clientcertissuer/issuer.go | 6 +-- internal/concierge/apiserver/apiserver.go | 4 +- .../concierge/impersonator/impersonator.go | 4 +- .../impersonator/impersonator_test.go | 10 ++-- .../controller/apicerts/apiservice_updater.go | 6 +-- internal/controller/apicerts/certs_expirer.go | 6 +-- internal/controller/apicerts/certs_manager.go | 6 +-- .../controller/apicerts/certs_observer.go | 6 +-- .../jwtcachefiller/jwtcachefiller.go | 4 +- .../webhookcachefiller/webhookcachefiller.go | 8 +-- .../impersonatorconfig/impersonator_config.go | 29 +++++------ .../impersonator_config_test.go | 6 +-- .../controller/kubecertagent/kubecertagent.go | 4 +- .../kubecertagent/kubecertagent_test.go | 4 +- .../kubecertagent/legacypodcleaner.go | 8 +-- .../kubecertagent/legacypodcleaner_test.go | 6 +-- .../pod_command_executor_test.go | 4 +- .../federation_domain_watcher.go | 8 +-- .../generator/federation_domain_secrets.go | 10 ++-- .../federation_domain_secrets_test.go | 6 +-- .../generator/supervisor_secrets.go | 8 +-- .../generator/supervisor_secrets_test.go | 8 +-- .../supervisorconfig/jwks_writer.go | 10 ++-- .../oidcclientwatcher/oidc_client_watcher.go | 6 +-- .../supervisorconfig/tls_cert_observer.go | 6 +-- .../clientregistry/clientregistry.go | 4 +- .../fositestorage/accesstoken/accesstoken.go | 4 +- .../authorizationcode/authorizationcode.go | 6 +-- .../openidconnect/openidconnect.go | 4 +- internal/fositestorage/pkce/pkce.go | 4 +- .../refreshtoken/refreshtoken.go | 4 +- internal/groupsuffix/groupsuffix.go | 4 +- internal/kubeclient/middleware.go | 6 +-- .../localuserauthenticator.go | 6 +-- .../oidcclientsecretstorage.go | 6 +-- internal/supervisor/apiserver/apiserver.go | 4 +- internal/testutil/fakekubeapi/fakekubeapi.go | 4 +- .../concierge_credentialrequest_test.go | 4 +- .../concierge_impersonation_proxy_test.go | 52 +++++++++---------- .../concierge_jwtauthenticator_status_test.go | 4 +- .../concierge_kubecertagent_test.go | 8 +-- ...cierge_webhookauthenticator_status_test.go | 4 +- test/integration/concierge_whoami_test.go | 6 +-- test/integration/kubeclient_test.go | 8 +-- test/integration/supervisor_discovery_test.go | 4 +- ...supervisor_federationdomain_status_test.go | 4 +- .../supervisor_oidc_client_test.go | 4 +- .../supervisor_oidcclientsecret_test.go | 6 +-- ...ervisor_storage_garbage_collection_test.go | 12 ++--- test/integration/supervisor_storage_test.go | 4 +- test/testlib/client.go | 12 ++--- 54 files changed, 199 insertions(+), 191 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 4aa0ac499..1504f4263 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -48,6 +48,7 @@ linters: - fatcontext # - canonicalheader Can't do this one since it alerts on valid headers such as X-XSS-Protection - spancheck + - importas issues: exclude-dirs: @@ -91,3 +92,11 @@ linters-settings: - end - record-error - set-status + importas: + no-unaliased: true # All packages explicitly listed below must be aliased + no-extra-aliases: false # Allow other aliases than the ones explicitly listed below + alias: + - pkg: k8s.io/apimachinery/pkg/util/errors + alias: utilerrors + - pkg: k8s.io/apimachinery/pkg/api/errors + alias: apierrors diff --git a/cmd/pinniped/cmd/whoami.go b/cmd/pinniped/cmd/whoami.go index 4a5415c5a..e4aea18ae 100644 --- a/cmd/pinniped/cmd/whoami.go +++ b/cmd/pinniped/cmd/whoami.go @@ -1,4 +1,4 @@ -// Copyright 2021-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -12,7 +12,7 @@ import ( "time" "github.com/spf13/cobra" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer" @@ -99,7 +99,7 @@ func runWhoami(output io.Writer, getClientset getConciergeClientsetFunc, flags * whoAmI, err := clientset.IdentityV1alpha1().WhoAmIRequests().Create(ctx, &identityv1alpha1.WhoAmIRequest{}, metav1.CreateOptions{}) if err != nil { hint := "" - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { hint = " (is the Pinniped WhoAmI API running and healthy?)" } return fmt.Errorf("could not complete WhoAmIRequest%s: %w", hint, err) diff --git a/cmd/pinniped/cmd/whoami_test.go b/cmd/pinniped/cmd/whoami_test.go index 728953510..e40bd15ca 100644 --- a/cmd/pinniped/cmd/whoami_test.go +++ b/cmd/pinniped/cmd/whoami_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" kubetesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/clientcmd" @@ -273,7 +273,7 @@ func TestWhoami(t *testing.T) { }, { name: "calling API fails because WhoAmI API is not installed", - callingAPIErr: errors.NewNotFound(identityv1alpha1.SchemeGroupVersion.WithResource("whoamirequests").GroupResource(), "whatever"), + callingAPIErr: apierrors.NewNotFound(identityv1alpha1.SchemeGroupVersion.WithResource("whoamirequests").GroupResource(), "whatever"), wantError: true, wantStderr: "Error: could not complete WhoAmIRequest (is the Pinniped WhoAmI API running and healthy?): whoamirequests.identity.concierge.pinniped.dev \"whatever\" not found\n", }, diff --git a/internal/clientcertissuer/issuer.go b/internal/clientcertissuer/issuer.go index 1efbc3e7e..f84f7beda 100644 --- a/internal/clientcertissuer/issuer.go +++ b/internal/clientcertissuer/issuer.go @@ -1,4 +1,4 @@ -// Copyright 2021-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package clientcertissuer @@ -8,7 +8,7 @@ import ( "strings" "time" - "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" "go.pinniped.dev/internal/constable" ) @@ -48,7 +48,7 @@ func (c ClientCertIssuers) IssueClientCertPEM(username string, groups []string, errs = append(errs, fmt.Errorf("%s failed to issue client cert: %w", issuer.Name(), err)) } - if err := errors.NewAggregate(errs); err != nil { + if err := utilerrors.NewAggregate(errs); err != nil { return nil, nil, err } diff --git a/internal/concierge/apiserver/apiserver.go b/internal/concierge/apiserver/apiserver.go index a43c82261..ad84f67b5 100644 --- a/internal/concierge/apiserver/apiserver.go +++ b/internal/concierge/apiserver/apiserver.go @@ -11,7 +11,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apiserver/pkg/registry/rest" genericapiserver "k8s.io/apiserver/pkg/server" @@ -105,7 +105,7 @@ func (c completedConfig) New() (*PinnipedServer, error) { ), ) } - if err := errors.NewAggregate(errs); err != nil { + if err := utilerrors.NewAggregate(errs); err != nil { return nil, fmt.Errorf("could not install API groups: %w", err) } diff --git a/internal/concierge/impersonator/impersonator.go b/internal/concierge/impersonator/impersonator.go index 062ae7aed..f67bb3108 100644 --- a/internal/concierge/impersonator/impersonator.go +++ b/internal/concierge/impersonator/impersonator.go @@ -26,7 +26,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/httpstream" utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/apimachinery/pkg/util/sets" @@ -349,7 +349,7 @@ func newInternal( if listener != nil { errs = append(errs, listener.Close()) } - return nil, errors.NewAggregate(errs) + return nil, utilerrors.NewAggregate(errs) } return result, nil } diff --git a/internal/concierge/impersonator/impersonator_test.go b/internal/concierge/impersonator/impersonator_test.go index 289a79bea..3a62071bc 100644 --- a/internal/concierge/impersonator/impersonator_test.go +++ b/internal/concierge/impersonator/impersonator_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/require" authenticationv1 "k8s.io/api/authentication/v1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme" "k8s.io/apimachinery/pkg/runtime" @@ -1010,7 +1010,7 @@ func TestImpersonator(t *testing.T) { probeBody, errProbe := rc.Get().AbsPath("/probe").DoRaw(ctx) if tt.anonymousAuthDisabled { - require.True(t, errors.IsUnauthorized(errProbe), errProbe) + require.True(t, apierrors.IsUnauthorized(errProbe), errProbe) require.Equal(t, `{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}`+"\n", string(probeBody)) } else { require.NoError(t, errProbe) @@ -1019,7 +1019,7 @@ func TestImpersonator(t *testing.T) { notTCRBody, errNotTCR := rc.Get().Resource("tokencredentialrequests").DoRaw(ctx) if tt.anonymousAuthDisabled { - require.True(t, errors.IsUnauthorized(errNotTCR), errNotTCR) + require.True(t, apierrors.IsUnauthorized(errNotTCR), errNotTCR) require.Equal(t, `{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}`+"\n", string(notTCRBody)) } else { require.NoError(t, errNotTCR) @@ -1028,7 +1028,7 @@ func TestImpersonator(t *testing.T) { ducksBody, errDucks := rc.Get().Resource("ducks").DoRaw(ctx) if tt.anonymousAuthDisabled { - require.True(t, errors.IsUnauthorized(errDucks), errDucks) + require.True(t, apierrors.IsUnauthorized(errDucks), errDucks) require.Equal(t, `{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}`+"\n", string(ducksBody)) } else { require.NoError(t, errDucks) @@ -1046,7 +1046,7 @@ func TestImpersonator(t *testing.T) { require.NoError(t, err) _, errBadCert := tcrBadCert.PinnipedConcierge.LoginV1alpha1().TokenCredentialRequests().Create(ctx, &loginv1alpha1.TokenCredentialRequest{}, metav1.CreateOptions{}) - require.True(t, errors.IsUnauthorized(errBadCert), errBadCert) + require.True(t, apierrors.IsUnauthorized(errBadCert), errBadCert) require.EqualError(t, errBadCert, "Unauthorized") }) } diff --git a/internal/controller/apicerts/apiservice_updater.go b/internal/controller/apicerts/apiservice_updater.go index 574d9c88b..f938b436e 100644 --- a/internal/controller/apicerts/apiservice_updater.go +++ b/internal/controller/apicerts/apiservice_updater.go @@ -1,4 +1,4 @@ -// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package apicerts @@ -6,7 +6,7 @@ package apicerts import ( "fmt" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" corev1informers "k8s.io/client-go/informers/core/v1" aggregatorclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset" @@ -53,7 +53,7 @@ func NewAPIServiceUpdaterController( func (c *apiServiceUpdaterController) Sync(ctx controllerlib.Context) error { // Try to get the secret from the informer cache. certSecret, err := c.secretInformer.Lister().Secrets(c.namespace).Get(c.certsSecretResourceName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf("failed to get %s/%s secret: %w", c.namespace, c.certsSecretResourceName, err) } diff --git a/internal/controller/apicerts/certs_expirer.go b/internal/controller/apicerts/certs_expirer.go index bb4a28f84..a6edbe62b 100644 --- a/internal/controller/apicerts/certs_expirer.go +++ b/internal/controller/apicerts/certs_expirer.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package apicerts @@ -10,7 +10,7 @@ import ( "time" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1informers "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes" @@ -74,7 +74,7 @@ func NewCertsExpirerController( // Sync implements controller.Syncer.Sync. func (c *certsExpirerController) Sync(ctx controllerlib.Context) error { secret, err := c.secretInformer.Lister().Secrets(c.namespace).Get(c.certsSecretResourceName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf("failed to get %s/%s secret: %w", c.namespace, c.certsSecretResourceName, err) } diff --git a/internal/controller/apicerts/certs_manager.go b/internal/controller/apicerts/certs_manager.go index d85514527..c99d5162d 100644 --- a/internal/controller/apicerts/certs_manager.go +++ b/internal/controller/apicerts/certs_manager.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package apicerts @@ -8,7 +8,7 @@ import ( "time" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1informers "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes" @@ -83,7 +83,7 @@ func NewCertsManagerController( func (c *certsManagerController) Sync(ctx controllerlib.Context) error { // Try to get the secret from the informer cache. _, err := c.secretInformer.Lister().Secrets(c.namespace).Get(c.certsSecretResourceName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf("failed to get %s/%s secret: %w", c.namespace, c.certsSecretResourceName, err) } diff --git a/internal/controller/apicerts/certs_observer.go b/internal/controller/apicerts/certs_observer.go index 704020f7b..631928afe 100644 --- a/internal/controller/apicerts/certs_observer.go +++ b/internal/controller/apicerts/certs_observer.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package apicerts @@ -6,7 +6,7 @@ package apicerts import ( "fmt" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" corev1informers "k8s.io/client-go/informers/core/v1" pinnipedcontroller "go.pinniped.dev/internal/controller" @@ -50,7 +50,7 @@ func NewCertsObserverController( func (c *certsObserverController) Sync(_ controllerlib.Context) error { // Try to get the secret from the informer cache. certSecret, err := c.secretInformer.Lister().Secrets(c.namespace).Get(c.certsSecretResourceName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf("failed to get %s/%s secret: %w", c.namespace, c.certsSecretResourceName, err) } diff --git a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller.go b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller.go index 30016836d..1159aa1da 100644 --- a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller.go +++ b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller.go @@ -21,7 +21,7 @@ import ( "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - errorsutil "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apiserver/pkg/apis/apiserver" "k8s.io/apiserver/pkg/authentication/authenticator" "k8s.io/apiserver/plugin/pkg/authenticator/token/oidc" @@ -229,7 +229,7 @@ func (c *jwtCacheFillerController) Sync(ctx controllerlib.Context) error { // object. The controller simply must wait for a user to correct before running again. // - Other errors, such as networking errors, etc. are the types of errors that should return here // and signal the controller to retry the sync loop. These may be corrected by machines. - return errorsutil.NewAggregate(errs) + return utilerrors.NewAggregate(errs) } func (c *jwtCacheFillerController) extractValueAsJWTAuthenticator(value authncache.Value) *cachedJWTAuthenticator { diff --git a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go index 2ad717a9f..284fd6389 100644 --- a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go +++ b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go @@ -14,9 +14,9 @@ import ( k8sauthv1beta1 "k8s.io/api/authentication/v1beta1" "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - errorsutil "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" k8snetutil "k8s.io/apimachinery/pkg/util/net" "k8s.io/apiserver/pkg/authentication/authenticator" "k8s.io/apiserver/plugin/pkg/authenticator/token/webhook" @@ -95,7 +95,7 @@ type webhookCacheFillerController struct { // Sync implements controllerlib.Syncer. func (c *webhookCacheFillerController) Sync(ctx controllerlib.Context) error { obj, err := c.webhooks.Lister().Get(ctx.Key.Name) - if err != nil && errors.IsNotFound(err) { + if err != nil && apierrors.IsNotFound(err) { c.log.Info("Sync() found that the WebhookAuthenticator does not exist yet or was deleted") return nil } @@ -141,7 +141,7 @@ func (c *webhookCacheFillerController) Sync(ctx controllerlib.Context) error { // object. The controller simply must wait for a user to correct before running again. // - other errors, such as networking errors, etc. are the types of errors that should return here // and signal the controller to retry the sync loop. These may be corrected by machines. - return errorsutil.NewAggregate(errs) + return utilerrors.NewAggregate(errs) } // newWebhookAuthenticator creates a webhook from the provided API server url and caBundle diff --git a/internal/controller/impersonatorconfig/impersonator_config.go b/internal/controller/impersonatorconfig/impersonator_config.go index 2a5af83c9..6edbfa82c 100644 --- a/internal/controller/impersonatorconfig/impersonator_config.go +++ b/internal/controller/impersonatorconfig/impersonator_config.go @@ -19,9 +19,8 @@ import ( "github.com/go-logr/logr" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/errors" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/intstr" utilruntime "k8s.io/apimachinery/pkg/util/runtime" @@ -221,7 +220,7 @@ func (c *impersonatorConfigController) Sync(syncCtx controllerlib.Context) error // recover on a following sync. func strategyReasonForError(err error) v1alpha1.StrategyReason { switch { - case k8serrors.IsConflict(err), k8serrors.IsAlreadyExists(err): + case apierrors.IsConflict(err), apierrors.IsAlreadyExists(err): return v1alpha1.PendingStrategyReason default: return v1alpha1.ErrorDuringSetupStrategyReason @@ -442,7 +441,7 @@ func (c *impersonatorConfigController) shouldHaveClusterIPService(config *v1alph func (c *impersonatorConfigController) serviceExists(serviceName string) (bool, *corev1.Service, error) { service, err := c.servicesInformer.Lister().Services(c.namespace).Get(serviceName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if notFound { return false, nil, nil } @@ -454,7 +453,7 @@ func (c *impersonatorConfigController) serviceExists(serviceName string) (bool, func (c *impersonatorConfigController) tlsSecretExists() (bool, *corev1.Secret, error) { secret, err := c.secretsInformer.Lister().Secrets(c.namespace).Get(c.tlsSecretName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if notFound { return false, nil, nil } @@ -481,7 +480,7 @@ func (c *impersonatorConfigController) ensureImpersonatorIsStarted(syncCtx contr // and we'll have a chance to restart the server. close(c.errorCh) // We don't want ensureImpersonatorIsStopped to block on reading this channel. stoppingErr := c.ensureImpersonatorIsStopped(false) - return errors.NewAggregate([]error{runningErr, stoppingErr}) + return utilerrors.NewAggregate([]error{runningErr, stoppingErr}) default: // Seems like it is still running, so nothing to do. return nil @@ -581,7 +580,7 @@ func (c *impersonatorConfigController) ensureLoadBalancerIsStopped(ctx context.C ResourceVersion: &service.ResourceVersion, }, }) - return utilerrors.FilterOut(err, k8serrors.IsNotFound) + return utilerrors.FilterOut(err, apierrors.IsNotFound) } func (c *impersonatorConfigController) ensureClusterIPServiceIsStarted(ctx context.Context, config *v1alpha1.ImpersonationProxySpec) error { @@ -626,7 +625,7 @@ func (c *impersonatorConfigController) ensureClusterIPServiceIsStopped(ctx conte ResourceVersion: &service.ResourceVersion, }, }) - return utilerrors.FilterOut(err, k8serrors.IsNotFound) + return utilerrors.FilterOut(err, apierrors.IsNotFound) } func (c *impersonatorConfigController) createOrUpdateService(ctx context.Context, desiredService *corev1.Service) error { @@ -654,7 +653,7 @@ func (c *impersonatorConfigController) createOrUpdateService(ctx context.Context // Get the Service from the informer, and create it if it does not already exist. existingService, err := c.servicesInformer.Lister().Services(c.namespace).Get(desiredService.Name) - if k8serrors.IsNotFound(err) { + if apierrors.IsNotFound(err) { log.Info("creating service for impersonation proxy") _, err := c.k8sClient.CoreV1().Services(c.namespace).Create(ctx, desiredService, metav1.CreateOptions{}) return err @@ -755,7 +754,7 @@ func (c *impersonatorConfigController) readExternalTLSSecret(externalTLSSecretNa func (c *impersonatorConfigController) ensureTLSSecret(ctx context.Context, nameInfo *certNameInfo, ca *certauthority.CA) error { secretFromInformer, err := c.secretsInformer.Lister().Secrets(c.namespace).Get(c.tlsSecretName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if !notFound && err != nil { return err } @@ -898,12 +897,12 @@ func (c *impersonatorConfigController) ensureTLSSecretIsCreatedAndLoaded(ctx con func (c *impersonatorConfigController) ensureCASecretIsCreated(ctx context.Context) (*certauthority.CA, error) { caSecret, err := c.secretsInformer.Lister().Secrets(c.namespace).Get(c.caSecretName) - if err != nil && !k8serrors.IsNotFound(err) { + if err != nil && !apierrors.IsNotFound(err) { return nil, err } var impersonationCA *certauthority.CA - if k8serrors.IsNotFound(err) { + if apierrors.IsNotFound(err) { impersonationCA, err = c.createCASecret(ctx) } else { crtBytes := caSecret.Data[caCrtKey] @@ -972,7 +971,7 @@ func (c *impersonatorConfigController) findTLSCertificateNameFromEndpointConfig( func (c *impersonatorConfigController) findTLSCertificateNameFromLoadBalancer() (*certNameInfo, error) { lb, err := c.servicesInformer.Lister().Services(c.namespace).Get(c.generatedLoadBalancerServiceName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if notFound { // We aren't ready and will try again later in this case. return &certNameInfo{ready: false}, nil @@ -1006,7 +1005,7 @@ func (c *impersonatorConfigController) findTLSCertificateNameFromLoadBalancer() func (c *impersonatorConfigController) findTLSCertificateNameFromClusterIPService() (*certNameInfo, error) { clusterIP, err := c.servicesInformer.Lister().Services(c.namespace).Get(c.generatedClusterIPServiceName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if notFound { // We aren't ready and will try again later in this case. return &certNameInfo{ready: false}, nil @@ -1103,7 +1102,7 @@ func (c *impersonatorConfigController) ensureTLSSecretIsRemoved(ctx context.Cont }) // it is okay if we tried to delete and we got a not found error. This probably means // another instance of the concierge got here first so there's nothing to delete. - return utilerrors.FilterOut(err, k8serrors.IsNotFound) + return utilerrors.FilterOut(err, apierrors.IsNotFound) } func (c *impersonatorConfigController) clearTLSSecret() { diff --git a/internal/controller/impersonatorconfig/impersonator_config_test.go b/internal/controller/impersonatorconfig/impersonator_config_test.go index a39b477af..9dad42e32 100644 --- a/internal/controller/impersonatorconfig/impersonator_config_test.go +++ b/internal/controller/impersonatorconfig/impersonator_config_test.go @@ -1,4 +1,4 @@ -// Copyright 2021-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package impersonatorconfig @@ -25,7 +25,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -3542,7 +3542,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addNodeWithRoleToTracker("worker", kubeAPIClient) kubeAPIClient.PrependReactor("create", "services", func(action coretesting.Action) (handled bool, ret runtime.Object, err error) { - return true, nil, k8serrors.NewAlreadyExists( + return true, nil, apierrors.NewAlreadyExists( action.GetResource().GroupResource(), action.(coretesting.CreateAction).GetObject().(*corev1.Service).Name, ) diff --git a/internal/controller/kubecertagent/kubecertagent.go b/internal/controller/kubecertagent/kubecertagent.go index 7afcdc147..2a441fc90 100644 --- a/internal/controller/kubecertagent/kubecertagent.go +++ b/internal/controller/kubecertagent/kubecertagent.go @@ -19,7 +19,7 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" @@ -396,7 +396,7 @@ func (c *agentController) createOrUpdateDeployment(ctx controllerlib.Context, ne // Try to get the existing Deployment, if it exists. existingDeployment, err := c.agentDeployments.Lister().Deployments(expectedDeployment.Namespace).Get(expectedDeployment.Name) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf("could not get deployments: %w", err) } diff --git a/internal/controller/kubecertagent/kubecertagent_test.go b/internal/controller/kubecertagent/kubecertagent_test.go index 1308e12a8..3f7e38010 100644 --- a/internal/controller/kubecertagent/kubecertagent_test.go +++ b/internal/controller/kubecertagent/kubecertagent_test.go @@ -15,7 +15,7 @@ import ( "go.uber.org/mock/gomock" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -1267,7 +1267,7 @@ func hasDeploymentSynced(client kubernetes.Interface, kubeInformers informers.Sh cachedDep, cachedErr := kubeInformers.Apps().V1().Deployments().Lister().Deployments("concierge"). Get("pinniped-concierge-kube-cert-agent") - if errors.IsNotFound(realErr) && errors.IsNotFound(cachedErr) { + if apierrors.IsNotFound(realErr) && apierrors.IsNotFound(cachedErr) { return } diff --git a/internal/controller/kubecertagent/legacypodcleaner.go b/internal/controller/kubecertagent/legacypodcleaner.go index 8c8a6cf92..8a776811e 100644 --- a/internal/controller/kubecertagent/legacypodcleaner.go +++ b/internal/controller/kubecertagent/legacypodcleaner.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package kubecertagent @@ -7,7 +7,7 @@ import ( "fmt" "github.com/go-logr/logr" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" corev1informers "k8s.io/client-go/informers/core/v1" @@ -44,7 +44,7 @@ func NewLegacyPodCleanerController( // avoid blind writes to the API agentPod, err := podClient.Get(ctx.Context, ctx.Key.Name, metav1.GetOptions{}) if err != nil { - if k8serrors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil } return fmt.Errorf("could not get legacy agent pod: %w", err) @@ -56,7 +56,7 @@ func NewLegacyPodCleanerController( ResourceVersion: &agentPod.ResourceVersion, }, }); err != nil { - if k8serrors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil } return fmt.Errorf("could not delete legacy agent pod: %w", err) diff --git a/internal/controller/kubecertagent/legacypodcleaner_test.go b/internal/controller/kubecertagent/legacypodcleaner_test.go index 843c2398e..3aacf6d96 100644 --- a/internal/controller/kubecertagent/legacypodcleaner_test.go +++ b/internal/controller/kubecertagent/legacypodcleaner_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/informers" @@ -111,7 +111,7 @@ func TestLegacyPodCleanerController(t *testing.T) { }, addKubeReactions: func(clientset *kubefake.Clientset) { clientset.PrependReactor("delete", "*", func(action coretesting.Action) (handled bool, ret runtime.Object, err error) { - return true, nil, k8serrors.NewNotFound(action.GetResource().GroupResource(), "") + return true, nil, apierrors.NewNotFound(action.GetResource().GroupResource(), "") }) }, wantDistinctErrors: []string{""}, @@ -129,7 +129,7 @@ func TestLegacyPodCleanerController(t *testing.T) { }, addKubeReactions: func(clientset *kubefake.Clientset) { clientset.PrependReactor("get", "*", func(action coretesting.Action) (handled bool, ret runtime.Object, err error) { - return true, nil, k8serrors.NewNotFound(action.GetResource().GroupResource(), "") + return true, nil, apierrors.NewNotFound(action.GetResource().GroupResource(), "") }) }, wantDistinctErrors: []string{""}, diff --git a/internal/controller/kubecertagent/pod_command_executor_test.go b/internal/controller/kubecertagent/pod_command_executor_test.go index 938fa16b4..d5e30d3c1 100644 --- a/internal/controller/kubecertagent/pod_command_executor_test.go +++ b/internal/controller/kubecertagent/pod_command_executor_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/client-go/rest" "go.pinniped.dev/internal/crypto/ptls" @@ -38,7 +38,7 @@ func TestSecureTLS(t *testing.T) { podCommandExecutor := NewPodCommandExecutor(client.JSONConfig, client.Kubernetes) got, err := podCommandExecutor.Exec(context.Background(), "podNamespace", "podName", "containerName", "command", "arg1", "arg2") - require.Equal(t, &errors.StatusError{}, err) + require.Equal(t, &apierrors.StatusError{}, err) require.Empty(t, got) require.True(t, sawRequest) diff --git a/internal/controller/supervisorconfig/federation_domain_watcher.go b/internal/controller/supervisorconfig/federation_domain_watcher.go index 9152d0f6b..643309bf4 100644 --- a/internal/controller/supervisorconfig/federation_domain_watcher.go +++ b/internal/controller/supervisorconfig/federation_domain_watcher.go @@ -13,11 +13,11 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/types" - errorsutil "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/utils/clock" @@ -185,7 +185,7 @@ func (c *federationDomainWatcherController) Sync(ctx controllerlib.Context) erro } } - return errorsutil.NewAggregate(errs) + return utilerrors.NewAggregate(errs) } func (c *federationDomainWatcherController) processAllFederationDomains( @@ -454,7 +454,7 @@ func (c *federationDomainWatcherController) findIDPsUIDByObjectRef(objectRef cor switch { case err == nil: idpResourceUID = foundIDP.GetUID() - case errors.IsNotFound(err): + case apierrors.IsNotFound(err): return "", false, nil default: return "", false, err // unexpected error from the informer diff --git a/internal/controller/supervisorconfig/generator/federation_domain_secrets.go b/internal/controller/supervisorconfig/generator/federation_domain_secrets.go index 528721f42..4b511ca6c 100644 --- a/internal/controller/supervisorconfig/generator/federation_domain_secrets.go +++ b/internal/controller/supervisorconfig/generator/federation_domain_secrets.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package generator @@ -9,7 +9,7 @@ import ( "reflect" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1informers "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes" @@ -75,7 +75,7 @@ func NewFederationDomainSecretsController( func (c *federationDomainSecretsController) Sync(ctx controllerlib.Context) error { federationDomain, err := c.federationDomainInformer.Lister().FederationDomains(ctx.Key.Namespace).Get(ctx.Key.Name) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf( "failed to get %s/%s FederationDomain: %w", @@ -149,7 +149,7 @@ func (c *federationDomainSecretsController) secretNeedsUpdate( ) (bool, *corev1.Secret, error) { // This FederationDomain says it has a secret associated with it. Let's try to get it from the cache. secret, err := c.secretInformer.Lister().Secrets(federationDomain.Namespace).Get(secretName) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return false, nil, fmt.Errorf("cannot get secret: %w", err) } @@ -174,7 +174,7 @@ func (c *federationDomainSecretsController) createOrUpdateSecret( secretClient := c.kubeClient.CoreV1().Secrets((*newSecret).Namespace) return retry.RetryOnConflict(retry.DefaultRetry, func() error { oldSecret, err := secretClient.Get(ctx, (*newSecret).Name, metav1.GetOptions{}) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf("failed to get secret %s/%s: %w", (*newSecret).Namespace, (*newSecret).Name, err) } diff --git a/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go b/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go index 18940f0e9..a72537af7 100644 --- a/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go +++ b/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -553,7 +553,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { once := sync.Once{} c.PrependReactor("update", "secrets", func(_ kubetesting.Action) (bool, runtime.Object, error) { var err error - once.Do(func() { err = k8serrors.NewConflict(secretGVR.GroupResource(), namespace, errors.New("some error")) }) + once.Do(func() { err = apierrors.NewConflict(secretGVR.GroupResource(), namespace, errors.New("some error")) }) return true, nil, err }) }, @@ -606,7 +606,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { once := sync.Once{} c.PrependReactor("update", "federationdomains", func(_ kubetesting.Action) (bool, runtime.Object, error) { var err error - once.Do(func() { err = k8serrors.NewConflict(secretGVR.GroupResource(), namespace, errors.New("some error")) }) + once.Do(func() { err = apierrors.NewConflict(secretGVR.GroupResource(), namespace, errors.New("some error")) }) return true, nil, err }) }, diff --git a/internal/controller/supervisorconfig/generator/supervisor_secrets.go b/internal/controller/supervisorconfig/generator/supervisor_secrets.go index bd01a9c70..516e2cf72 100644 --- a/internal/controller/supervisorconfig/generator/supervisor_secrets.go +++ b/internal/controller/supervisorconfig/generator/supervisor_secrets.go @@ -1,4 +1,4 @@ -// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package generator provides a supervisorSecretsController that can ensure existence of a generated secret. @@ -11,7 +11,7 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1informers "k8s.io/client-go/informers/core/v1" "k8s.io/client-go/kubernetes" @@ -75,7 +75,7 @@ func NewSupervisorSecretsController( // Sync implements controllerlib.Syncer.Sync(). func (c *supervisorSecretsController) Sync(ctx controllerlib.Context) error { secret, err := c.secretInformer.Lister().Secrets(ctx.Key.Namespace).Get(ctx.Key.Name) - isNotFound := k8serrors.IsNotFound(err) + isNotFound := apierrors.IsNotFound(err) if !isNotFound && err != nil { return fmt.Errorf("failed to list secret %s/%s: %w", ctx.Key.Namespace, ctx.Key.Name, err) } @@ -115,7 +115,7 @@ func (c *supervisorSecretsController) updateSecret(ctx context.Context, newSecre secrets := c.kubeClient.CoreV1().Secrets((*newSecret).Namespace) return retry.RetryOnConflict(retry.DefaultBackoff, func() error { currentSecret, err := secrets.Get(ctx, secretName, metav1.GetOptions{}) - isNotFound := k8serrors.IsNotFound(err) + isNotFound := apierrors.IsNotFound(err) if !isNotFound && err != nil { return fmt.Errorf("failed to get secret: %w", err) } diff --git a/internal/controller/supervisorconfig/generator/supervisor_secrets_test.go b/internal/controller/supervisorconfig/generator/supervisor_secrets_test.go index 1ac1e9473..53273f918 100644 --- a/internal/controller/supervisorconfig/generator/supervisor_secrets_test.go +++ b/internal/controller/supervisorconfig/generator/supervisor_secrets_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -306,7 +306,7 @@ func TestSupervisorSecretsControllerSync(t *testing.T) { client.PrependReactor("update", "secrets", func(action kubetesting.Action) (bool, runtime.Object, error) { var err error once.Do(func() { - err = k8serrors.NewConflict(secretsGVR.GroupResource(), generatedSecretName, errors.New("some error")) + err = apierrors.NewConflict(secretsGVR.GroupResource(), generatedSecretName, errors.New("some error")) }) return true, nil, err }) @@ -363,7 +363,7 @@ func TestSupervisorSecretsControllerSync(t *testing.T) { }, apiClient: func(t *testing.T, client *kubernetesfake.Clientset) { client.PrependReactor("get", "secrets", func(action kubetesting.Action) (bool, runtime.Object, error) { - return true, nil, k8serrors.NewNotFound(secretsGVR.GroupResource(), generatedSecretName) + return true, nil, apierrors.NewNotFound(secretsGVR.GroupResource(), generatedSecretName) }) client.PrependReactor("create", "secrets", func(action kubetesting.Action) (bool, runtime.Object, error) { return true, nil, nil @@ -382,7 +382,7 @@ func TestSupervisorSecretsControllerSync(t *testing.T) { }, apiClient: func(t *testing.T, client *kubernetesfake.Clientset) { client.PrependReactor("get", "secrets", func(action kubetesting.Action) (bool, runtime.Object, error) { - return true, nil, k8serrors.NewNotFound(secretsGVR.GroupResource(), generatedSecretName) + return true, nil, apierrors.NewNotFound(secretsGVR.GroupResource(), generatedSecretName) }) client.PrependReactor("create", "secrets", func(action kubetesting.Action) (bool, runtime.Object, error) { return true, nil, errors.New("some create error") diff --git a/internal/controller/supervisorconfig/jwks_writer.go b/internal/controller/supervisorconfig/jwks_writer.go index 965f586d3..a5918972d 100644 --- a/internal/controller/supervisorconfig/jwks_writer.go +++ b/internal/controller/supervisorconfig/jwks_writer.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package supervisorconfig @@ -14,7 +14,7 @@ import ( "github.com/go-jose/go-jose/v3" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" corev1informers "k8s.io/client-go/informers/core/v1" @@ -110,7 +110,7 @@ func NewJWKSWriterController( // Sync implements controllerlib.Syncer. func (c *jwksWriterController) Sync(ctx controllerlib.Context) error { federationDomain, err := c.federationDomainInformer.Lister().FederationDomains(ctx.Key.Namespace).Get(ctx.Key.Name) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf( "failed to get %s/%s FederationDomain: %w", @@ -176,7 +176,7 @@ func (c *jwksWriterController) secretNeedsUpdate(federationDomain *configv1alpha // This FederationDomain says it has a secret associated with it. Let's try to get it from the cache. secret, err := c.secretInformer.Lister().Secrets(federationDomain.Namespace).Get(federationDomain.Status.Secrets.JWKS.Name) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return false, fmt.Errorf("cannot get secret: %w", err) } @@ -254,7 +254,7 @@ func (c *jwksWriterController) createOrUpdateSecret( secretClient := c.kubeClient.CoreV1().Secrets(newSecret.Namespace) return retry.RetryOnConflict(retry.DefaultRetry, func() error { oldSecret, err := secretClient.Get(ctx, newSecret.Name, metav1.GetOptions{}) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { return fmt.Errorf("cannot get secret: %w", err) } diff --git a/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher.go b/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher.go index 9445fc343..dbea00ec8 100644 --- a/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher.go +++ b/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher.go @@ -1,4 +1,4 @@ -// Copyright 2022-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2022-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package oidcclientwatcher @@ -9,7 +9,7 @@ import ( "strings" "k8s.io/apimachinery/pkg/api/equality" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" corev1informers "k8s.io/client-go/informers/core/v1" @@ -94,7 +94,7 @@ func (c *oidcClientWatcherController) Sync(ctx controllerlib.Context) error { secret, err := c.secretInformer.Lister().Secrets(oidcClient.Namespace).Get(correspondingSecretName) if err != nil { - if !k8serrors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { // Anything other than a NotFound error is unexpected when reading from an informer. return fmt.Errorf("failed to get %s/%s secret: %w", oidcClient.Namespace, correspondingSecretName, err) } diff --git a/internal/controller/supervisorconfig/tls_cert_observer.go b/internal/controller/supervisorconfig/tls_cert_observer.go index 97c0b0c8e..49659e9f0 100644 --- a/internal/controller/supervisorconfig/tls_cert_observer.go +++ b/internal/controller/supervisorconfig/tls_cert_observer.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package supervisorconfig @@ -10,7 +10,7 @@ import ( "strings" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" corev1informers "k8s.io/client-go/informers/core/v1" @@ -112,7 +112,7 @@ func (c *tlsCertObserverController) Sync(ctx controllerlib.Context) error { if err != nil { c.issuerTLSCertSetter.SetDefaultTLSCert(nil) // It's okay if the default TLS cert Secret is not found (it is not required). - if !k8serrors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { // For any other error, log a message which is visible at the default log level. plog.Error("error loading TLS certificate from Secret for Supervisor default TLS cert", err, "defaultCertSecretName", c.defaultTLSCertificateSecretName, diff --git a/internal/federationdomain/clientregistry/clientregistry.go b/internal/federationdomain/clientregistry/clientregistry.go index d46809bb3..0345fb323 100644 --- a/internal/federationdomain/clientregistry/clientregistry.go +++ b/internal/federationdomain/clientregistry/clientregistry.go @@ -12,7 +12,7 @@ import ( coreosoidc "github.com/coreos/go-oidc/v3/oidc" "github.com/ory/fosite" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" @@ -95,7 +95,7 @@ func (m *ClientManager) GetClient(ctx context.Context, id string) (fosite.Client // Try to look up an OIDCClient with the given client ID (which will be the Name of the OIDCClient). oidcClient, err := m.oidcClientsClient.Get(ctx, id, metav1.GetOptions{}) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, fosite.ErrNotFound.WithDescription("no such client") } if err != nil { diff --git a/internal/fositestorage/accesstoken/accesstoken.go b/internal/fositestorage/accesstoken/accesstoken.go index c67b9cab7..b95e47c09 100644 --- a/internal/fositestorage/accesstoken/accesstoken.go +++ b/internal/fositestorage/accesstoken/accesstoken.go @@ -11,7 +11,7 @@ import ( "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" "go.pinniped.dev/internal/constable" @@ -114,7 +114,7 @@ func (a *accessTokenStorage) getSession(ctx context.Context, signature string) ( session := newValidEmptyAccessTokenSession() rv, err := a.storage.Get(ctx, signature, session) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, "", fosite.ErrNotFound.WithWrap(err).WithDebug(err.Error()) } diff --git a/internal/fositestorage/authorizationcode/authorizationcode.go b/internal/fositestorage/authorizationcode/authorizationcode.go index f1187ec83..5b19a217e 100644 --- a/internal/fositestorage/authorizationcode/authorizationcode.go +++ b/internal/fositestorage/authorizationcode/authorizationcode.go @@ -12,7 +12,7 @@ import ( "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" "go.pinniped.dev/internal/constable" @@ -130,7 +130,7 @@ func (a *authorizeCodeStorage) InvalidateAuthorizeCodeSession(ctx context.Contex session.Active = false if _, err := a.storage.Update(ctx, signature, rv, session); err != nil { - if errors.IsConflict(err) { + if apierrors.IsConflict(err) { return &errSerializationFailureWithCause{cause: err} } return err @@ -143,7 +143,7 @@ func (a *authorizeCodeStorage) getSession(ctx context.Context, signature string) session := NewValidEmptyAuthorizeCodeSession() rv, err := a.storage.Get(ctx, signature, session) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, "", fosite.ErrNotFound.WithWrap(err).WithDebug(err.Error()) } diff --git a/internal/fositestorage/openidconnect/openidconnect.go b/internal/fositestorage/openidconnect/openidconnect.go index a04bea4c3..c5c7a4a2d 100644 --- a/internal/fositestorage/openidconnect/openidconnect.go +++ b/internal/fositestorage/openidconnect/openidconnect.go @@ -11,7 +11,7 @@ import ( "github.com/ory/fosite" "github.com/ory/fosite/handler/openid" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" "go.pinniped.dev/internal/constable" @@ -104,7 +104,7 @@ func (a *openIDConnectRequestStorage) getSession(ctx context.Context, signature session := newValidEmptyOIDCSession() rv, err := a.storage.Get(ctx, signature, session) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, "", fosite.ErrNotFound.WithWrap(err).WithDebug(err.Error()) } diff --git a/internal/fositestorage/pkce/pkce.go b/internal/fositestorage/pkce/pkce.go index b0d371b6a..dda38208d 100644 --- a/internal/fositestorage/pkce/pkce.go +++ b/internal/fositestorage/pkce/pkce.go @@ -10,7 +10,7 @@ import ( "github.com/ory/fosite" "github.com/ory/fosite/handler/pkce" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" "go.pinniped.dev/internal/constable" @@ -87,7 +87,7 @@ func (a *pkceStorage) getSession(ctx context.Context, signature string) (*sessio session := newValidEmptyPKCESession() rv, err := a.storage.Get(ctx, signature, session) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, "", fosite.ErrNotFound.WithWrap(err).WithDebug(err.Error()) } diff --git a/internal/fositestorage/refreshtoken/refreshtoken.go b/internal/fositestorage/refreshtoken/refreshtoken.go index efc96071b..13389afc0 100644 --- a/internal/fositestorage/refreshtoken/refreshtoken.go +++ b/internal/fositestorage/refreshtoken/refreshtoken.go @@ -11,7 +11,7 @@ import ( "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" "go.pinniped.dev/internal/constable" @@ -120,7 +120,7 @@ func (a *refreshTokenStorage) getSession(ctx context.Context, signature string) session := newValidEmptyRefreshTokenSession() rv, err := a.storage.Get(ctx, signature, session) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, "", fosite.ErrNotFound.WithWrap(err).WithDebug(err.Error()) } diff --git a/internal/groupsuffix/groupsuffix.go b/internal/groupsuffix/groupsuffix.go index b2d3ccdd5..61a9c168c 100644 --- a/internal/groupsuffix/groupsuffix.go +++ b/internal/groupsuffix/groupsuffix.go @@ -10,7 +10,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/validation" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" @@ -189,5 +189,5 @@ func Validate(apiGroupSuffix string) error { errs = append(errs, constable.Error(errorString)) } - return errors.NewAggregate(errs) + return utilerrors.NewAggregate(errs) } diff --git a/internal/kubeclient/middleware.go b/internal/kubeclient/middleware.go index 4c5aa3226..eee9557e6 100644 --- a/internal/kubeclient/middleware.go +++ b/internal/kubeclient/middleware.go @@ -12,7 +12,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" ) type Middleware interface { @@ -119,7 +119,7 @@ func (r *request) mutateRequest(obj Object) (*mutationResult, error) { errs = append(errs, err) } } - if err := errors.NewAggregate(errs); err != nil { + if err := utilerrors.NewAggregate(errs); err != nil { return nil, fmt.Errorf("request mutation failed: %w", err) } @@ -148,7 +148,7 @@ func (r *request) mutateResponse(obj Object) (bool, error) { errs = append(errs, err) } } - if err := errors.NewAggregate(errs); err != nil { + if err := utilerrors.NewAggregate(errs); err != nil { return false, fmt.Errorf("response mutation failed: %w", err) } diff --git a/internal/localuserauthenticator/localuserauthenticator.go b/internal/localuserauthenticator/localuserauthenticator.go index d50688d66..33ee42b25 100644 --- a/internal/localuserauthenticator/localuserauthenticator.go +++ b/internal/localuserauthenticator/localuserauthenticator.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package localuserauthenticator provides a authentication webhook program. @@ -27,7 +27,7 @@ import ( "golang.org/x/crypto/bcrypt" authenticationv1beta1 "k8s.io/api/authentication/v1beta1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" k8sinformers "k8s.io/client-go/informers" corev1informers "k8s.io/client-go/informers/core/v1" @@ -114,7 +114,7 @@ func (w *webhook) ServeHTTP(rsp http.ResponseWriter, req *http.Request) { defer func() { _ = req.Body.Close() }() secret, err := w.secretInformer.Lister().Secrets(namespace).Get(username) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if err != nil && !notFound { plog.Debug("could not get secret", "err", err) rsp.WriteHeader(http.StatusInternalServerError) diff --git a/internal/oidcclientsecretstorage/oidcclientsecretstorage.go b/internal/oidcclientsecretstorage/oidcclientsecretstorage.go index 1cdba6549..d44d184d9 100644 --- a/internal/oidcclientsecretstorage/oidcclientsecretstorage.go +++ b/internal/oidcclientsecretstorage/oidcclientsecretstorage.go @@ -9,7 +9,7 @@ import ( "fmt" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" @@ -56,7 +56,7 @@ func New(secrets corev1client.SecretInterface) *OIDCClientSecretStorage { func (s *OIDCClientSecretStorage) Get(ctx context.Context, oidcClientUID types.UID) (string, []string, error) { clientSecret := &storedClientSecret{} rv, err := s.storage.Get(ctx, uidToName(oidcClientUID), clientSecret) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return "", nil, nil } if err != nil { @@ -107,7 +107,7 @@ func (s *OIDCClientSecretStorage) Set(ctx context.Context, resourceVersion, oidc // Returns nil,nil when the corev1.Secret was not found, as this is not an error for a client to not have any secrets yet. func (s *OIDCClientSecretStorage) GetStorageSecret(ctx context.Context, oidcClientUID types.UID) (*corev1.Secret, error) { secret, err := s.secrets.Get(ctx, s.GetName(oidcClientUID), metav1.GetOptions{}) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return nil, nil } if err != nil { diff --git a/internal/supervisor/apiserver/apiserver.go b/internal/supervisor/apiserver/apiserver.go index 703e61fb4..31f299a57 100644 --- a/internal/supervisor/apiserver/apiserver.go +++ b/internal/supervisor/apiserver/apiserver.go @@ -13,7 +13,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apiserver/pkg/registry/rest" genericapiserver "k8s.io/apiserver/pkg/server" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" @@ -109,7 +109,7 @@ func (c completedConfig) New() (*PinnipedServer, error) { ), ) } - if err := errors.NewAggregate(errs); err != nil { + if err := utilerrors.NewAggregate(errs); err != nil { return nil, fmt.Errorf("could not install API groups: %w", err) } diff --git a/internal/testutil/fakekubeapi/fakekubeapi.go b/internal/testutil/fakekubeapi/fakekubeapi.go index 0fb176b34..fc6b6d4c1 100644 --- a/internal/testutil/fakekubeapi/fakekubeapi.go +++ b/internal/testutil/fakekubeapi/fakekubeapi.go @@ -32,7 +32,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" kubescheme "k8s.io/client-go/kubernetes/scheme" restclient "k8s.io/client-go/rest" aggregatorclientscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" @@ -127,7 +127,7 @@ func decodeObj(r *http.Request) (runtime.Object, error) { } errs = append(errs, err) } - return nil, errors.NewAggregate(errs) + return nil, utilerrors.NewAggregate(errs) } func tryDecodeObj( diff --git a/test/integration/concierge_credentialrequest_test.go b/test/integration/concierge_credentialrequest_test.go index 9292f487c..cf3b84191 100644 --- a/test/integration/concierge_credentialrequest_test.go +++ b/test/integration/concierge_credentialrequest_test.go @@ -13,7 +13,7 @@ import ( "github.com/go-jose/go-jose/v3/jwt" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" @@ -176,7 +176,7 @@ func TestCredentialRequest_ShouldFailWhenRequestDoesNotIncludeToken_Parallel(t * ) require.Error(t, err) - statusError, isStatus := err.(*errors.StatusError) + statusError, isStatus := err.(*apierrors.StatusError) require.True(t, isStatus, testlib.Sdump(err)) require.Equal(t, 1, len(statusError.ErrStatus.Details.Causes)) diff --git a/test/integration/concierge_impersonation_proxy_test.go b/test/integration/concierge_impersonation_proxy_test.go index 28ed71704..8713769af 100644 --- a/test/integration/concierge_impersonation_proxy_test.go +++ b/test/integration/concierge_impersonation_proxy_test.go @@ -39,7 +39,7 @@ import ( corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/equality" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme" @@ -537,7 +537,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl // Make sure that the deleted ConfigMap shows up in the informer's cache. testlib.RequireEventually(t, func(requireEventually *require.Assertions) { _, err := informer.Lister().ConfigMaps(namespaceName).Get("configmap-3") - requireEventually.Truef(k8serrors.IsNotFound(err), "expected a NotFound error from get, got %v", err) + requireEventually.Truef(apierrors.IsNotFound(err), "expected a NotFound error from get, got %v", err) list, err := informer.Lister().ConfigMaps(namespaceName).List(configMapLabels.AsSelector()) requireEventually.NoError(err) @@ -579,7 +579,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl // request similar to the one above, except that it will also have an impersonation header. _, err = nestedImpersonationClient.Kubernetes.CoreV1().Secrets(env.ConciergeNamespace).Get(ctx, impersonationProxyTLSSecretName(env), metav1.GetOptions{}) // this user is not allowed to impersonate other users - require.True(t, k8serrors.IsForbidden(err), err) + require.True(t, apierrors.IsForbidden(err), err) require.EqualError(t, err, fmt.Sprintf( `users "other-user-to-impersonate" is forbidden: `+ `User "%s" cannot impersonate resource "users" in API group "" at the cluster scope: `+ @@ -628,7 +628,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl refreshCredential).PinnipedConcierge.IdentityV1alpha1().WhoAmIRequests(). Create(ctx, &identityv1alpha1.WhoAmIRequest{}, metav1.CreateOptions{}) // this user should not be able to impersonate extra - require.True(t, k8serrors.IsForbidden(err), err) + require.True(t, apierrors.IsForbidden(err), err) require.EqualError(t, err, fmt.Sprintf( `userextras.authentication.k8s.io "with a dangerous value" is forbidden: `+ `User "%s" cannot impersonate resource "userextras/some-fancy-key" in API group "authentication.k8s.io" at the cluster scope: `+ @@ -688,7 +688,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl _, err = nestedImpersonationClient.Kubernetes.CoreV1().Secrets(env.ConciergeNamespace).Get(ctx, impersonationProxyTLSSecretName(env), metav1.GetOptions{}) // the impersonated user lacks the RBAC to perform this call - require.True(t, k8serrors.IsForbidden(err), err) + require.True(t, apierrors.IsForbidden(err), err) require.EqualError(t, err, fmt.Sprintf( `secrets "%s" is forbidden: User "other-user-to-impersonate" cannot get resource "secrets" in API group "" in the namespace "%s": `+ `decision made by impersonation-proxy.concierge.pinniped.dev`, @@ -731,8 +731,8 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl _, err := nestedImpersonationClient.Kubernetes.CoreV1().Secrets(env.ConciergeNamespace).Get(ctx, impersonationProxyTLSSecretName(env), metav1.GetOptions{}) require.EqualError(t, err, "Internal error occurred: unimplemented functionality - unable to act as current user") - require.True(t, k8serrors.IsInternalError(err), err) - require.Equal(t, &k8serrors.StatusError{ + require.True(t, apierrors.IsInternalError(err), err) + require.Equal(t, &apierrors.StatusError{ ErrStatus: metav1.Status{ Status: metav1.StatusFailure, Code: http.StatusInternalServerError, @@ -768,8 +768,8 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl msg := `Internal Server Error: "/api/v1/namespaces/foo/secrets/bar": requested [{UID some-awesome-uid authentication.k8s.io/v1 }] without impersonating a user` full := fmt.Sprintf(`an error on the server (%q) has prevented the request from succeeding (get secrets bar)`, msg) require.EqualError(t, errUID, full) - require.True(t, k8serrors.IsInternalError(errUID), errUID) - require.Equal(t, &k8serrors.StatusError{ + require.True(t, apierrors.IsInternalError(errUID), errUID) + require.Equal(t, &apierrors.StatusError{ ErrStatus: metav1.Status{ Status: metav1.StatusFailure, Code: http.StatusInternalServerError, @@ -804,8 +804,8 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl _, err := testlib.NewKubeclient(t, nestedImpersonationUID).Kubernetes.CoreV1().Secrets(env.ConciergeNamespace).Get(ctx, impersonationProxyTLSSecretName(env), metav1.GetOptions{}) require.EqualError(t, err, "Internal error occurred: unimplemented functionality - unable to act as current user") - require.True(t, k8serrors.IsInternalError(err), err) - require.Equal(t, &k8serrors.StatusError{ + require.True(t, apierrors.IsInternalError(err), err) + require.Equal(t, &apierrors.StatusError{ ErrStatus: metav1.Status{ Status: metav1.StatusFailure, Code: http.StatusInternalServerError, @@ -833,7 +833,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl _, err := nestedImpersonationClient.IdentityV1alpha1().WhoAmIRequests(). Create(ctx, &identityv1alpha1.WhoAmIRequest{}, metav1.CreateOptions{}) // this SA is not yet allowed to impersonate SAs - require.True(t, k8serrors.IsForbidden(err), err) + require.True(t, apierrors.IsForbidden(err), err) require.EqualError(t, err, fmt.Sprintf( `serviceaccounts "root-ca-cert-publisher" is forbidden: `+ `User "%s" cannot impersonate resource "serviceaccounts" in API group "" in the namespace "kube-system": `+ @@ -910,7 +910,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl whoAmI, ) } else { - require.True(t, k8serrors.IsUnauthorized(err), testlib.Sdump(err)) + require.True(t, apierrors.IsUnauthorized(err), testlib.Sdump(err)) } // Test using a service account token. @@ -941,7 +941,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl expectedGroups := []string{"system:serviceaccounts", "system:serviceaccounts:" + namespaceName, "system:authenticated"} _, tokenRequestProbeErr := kubeClient.ServiceAccounts(namespaceName).CreateToken(ctx, saName, &authenticationv1.TokenRequest{}, metav1.CreateOptions{}) - if k8serrors.IsNotFound(tokenRequestProbeErr) && tokenRequestProbeErr.Error() == "the server could not find the requested resource" { + if apierrors.IsNotFound(tokenRequestProbeErr) && tokenRequestProbeErr.Error() == "the server could not find the requested resource" { return // stop test early since the token request API is not enabled on this cluster - other errors are caught below } @@ -979,7 +979,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl _, badAudErr := impersonationProxySABadAudPinnipedConciergeClient.IdentityV1alpha1().WhoAmIRequests(). Create(ctx, &identityv1alpha1.WhoAmIRequest{}, metav1.CreateOptions{}) - require.True(t, k8serrors.IsUnauthorized(badAudErr), testlib.Sdump(badAudErr)) + require.True(t, apierrors.IsUnauthorized(badAudErr), testlib.Sdump(badAudErr)) tokenRequest, err := kubeClient.ServiceAccounts(namespaceName).CreateToken(ctx, saName, &authenticationv1.TokenRequest{ Spec: authenticationv1.TokenRequestSpec{ @@ -1385,7 +1385,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl Authenticator: corev1.TypedLocalObjectReference{APIGroup: ptr.To("anything.pinniped.dev")}, }, }, metav1.CreateOptions{}) - require.True(t, k8serrors.IsInvalid(err), testlib.Sdump(err)) + require.True(t, apierrors.IsInvalid(err), testlib.Sdump(err)) require.Equal(t, `.login.concierge.pinniped.dev "" is invalid: spec.token.value: Required value: token must be supplied`, err.Error()) require.Equal(t, &loginv1alpha1.TokenCredentialRequest{}, tkr) }) @@ -1409,7 +1409,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl require.Equal(t, "ok", string(healthz)) healthzLog, errHealthzLog := impersonationProxyAdminRestClientAsAnonymous.Get().AbsPath("/healthz/log").DoRaw(ctx) - require.True(t, k8serrors.IsForbidden(errHealthzLog), "%s\n%s", testlib.Sdump(errHealthzLog), string(healthzLog)) + require.True(t, apierrors.IsForbidden(errHealthzLog), "%s\n%s", testlib.Sdump(errHealthzLog), string(healthzLog)) require.Equal(t, `{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"forbidden: User \"system:anonymous\" cannot get path \"/healthz/log\": decision made by impersonation-proxy.concierge.pinniped.dev","reason":"Forbidden","details":{},"code":403}`+"\n", string(healthzLog)) }) }) @@ -1440,7 +1440,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl pod, err := impersonationProxyAnonymousClient.Kubernetes.CoreV1().Pods(metav1.NamespaceSystem). Get(ctx, "does-not-matter", metav1.GetOptions{}) - require.True(t, k8serrors.IsForbidden(err), testlib.Sdump(err)) + require.True(t, apierrors.IsForbidden(err), testlib.Sdump(err)) require.EqualError(t, err, `pods "does-not-matter" is forbidden: User "system:anonymous" cannot get resource "pods" in API group "" in the namespace "kube-system": `+ `decision made by impersonation-proxy.concierge.pinniped.dev`, testlib.Sdump(err)) require.Equal(t, &corev1.Pod{}, pod) @@ -1479,7 +1479,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl parallelIfNotEKS(t) healthz, err := impersonationProxyAnonymousRestClient.Get().AbsPath("/healthz").DoRaw(ctx) - require.True(t, k8serrors.IsUnauthorized(err), testlib.Sdump(err)) + require.True(t, apierrors.IsUnauthorized(err), testlib.Sdump(err)) require.Equal(t, `{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}`+"\n", string(healthz)) }) @@ -1492,7 +1492,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl pod, err := impersonationProxyAnonymousClient.Kubernetes.CoreV1().Pods(metav1.NamespaceSystem). Get(ctx, "does-not-matter", metav1.GetOptions{}) - require.True(t, k8serrors.IsUnauthorized(err), testlib.Sdump(err)) + require.True(t, apierrors.IsUnauthorized(err), testlib.Sdump(err)) require.Equal(t, &corev1.Pod{}, pod) }) @@ -1505,7 +1505,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl whoAmI, err := impersonationProxyAnonymousClient.PinnipedConcierge.IdentityV1alpha1().WhoAmIRequests(). Create(ctx, &identityv1alpha1.WhoAmIRequest{}, metav1.CreateOptions{}) - require.True(t, k8serrors.IsUnauthorized(err), testlib.Sdump(err)) + require.True(t, apierrors.IsUnauthorized(err), testlib.Sdump(err)) require.Equal(t, &identityv1alpha1.WhoAmIRequest{}, whoAmI) }) }) @@ -1537,7 +1537,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl // sanity check default expected error message _, err := impersonationProxySSRRClient.Create(ctx, invalidSSRR, metav1.CreateOptions{}) - require.True(t, k8serrors.IsBadRequest(err), testlib.Sdump(err)) + require.True(t, apierrors.IsBadRequest(err), testlib.Sdump(err)) require.EqualError(t, err, "no namespace on request") // remove the impersonation proxy SA's permissions @@ -1581,11 +1581,11 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl case errCreate == nil: return false, fmt.Errorf("unexpected nil error for test user create invalid SSRR") - case k8serrors.IsBadRequest(errCreate) && errCreate.Error() == "no namespace on request": + case apierrors.IsBadRequest(errCreate) && errCreate.Error() == "no namespace on request": t.Log("waiting for impersonation proxy service account to lose impersonate permissions") return false, nil // RBAC change has not rolled out yet - case k8serrors.IsForbidden(errCreate) && errCreate.Error() == + case apierrors.IsForbidden(errCreate) && errCreate.Error() == `users "`+env.TestUser.ExpectedUsername+`" is forbidden: User "`+saFullName+ `" cannot impersonate resource "users" in API group "" at the cluster scope`: return true, nil // expected RBAC error @@ -1968,7 +1968,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl // when we disable the impersonator. testlib.RequireEventually(t, func(requireEventually *require.Assertions) { _, err := adminClient.CoreV1().Secrets(env.ConciergeNamespace).Get(ctx, impersonationProxyTLSSecretName(env), metav1.GetOptions{}) - requireEventually.Truef(k8serrors.IsNotFound(err), "expected NotFound error, got %v", err) + requireEventually.Truef(apierrors.IsNotFound(err), "expected NotFound error, got %v", err) }, 2*time.Minute, time.Second) // Check that the generated CA cert Secret was not deleted by the controller because it's supposed to keep this @@ -2301,7 +2301,7 @@ func updateCredentialIssuer(ctx context.Context, t *testing.T, env *testlib.Test func hasImpersonationProxyLoadBalancerService(ctx context.Context, env *testlib.TestEnv, client kubernetes.Interface) (bool, error) { service, err := client.CoreV1().Services(env.ConciergeNamespace).Get(ctx, impersonationProxyLoadBalancerName(env), metav1.GetOptions{}) - if k8serrors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return false, nil } if err != nil { diff --git a/test/integration/concierge_jwtauthenticator_status_test.go b/test/integration/concierge_jwtauthenticator_status_test.go index 24927f67f..dca246aff 100644 --- a/test/integration/concierge_jwtauthenticator_status_test.go +++ b/test/integration/concierge_jwtauthenticator_status_test.go @@ -11,7 +11,7 @@ import ( "time" "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" @@ -339,7 +339,7 @@ func TestConciergeJWTAuthenticatorCRDValidations_Parallel(t *testing.T) { t.Cleanup(func() { // delete if it exists delErr := jwtAuthenticatorClient.Delete(ctx, tt.jwtAuthenticator.Name, metav1.DeleteOptions{}) - if !errors.IsNotFound(delErr) { + if !apierrors.IsNotFound(delErr) { require.NoError(t, delErr) } }) diff --git a/test/integration/concierge_kubecertagent_test.go b/test/integration/concierge_kubecertagent_test.go index 5afc51baa..b306da99f 100644 --- a/test/integration/concierge_kubecertagent_test.go +++ b/test/integration/concierge_kubecertagent_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package integration @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/utils/ptr" @@ -133,7 +133,7 @@ func TestLegacyPodCleaner_Parallel(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) defer cancel() err := kubeClient.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{GracePeriodSeconds: ptr.To[int64](0)}) - if !k8serrors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { require.NoError(t, err, "failed to clean up fake legacy agent pod") } }) @@ -141,7 +141,7 @@ func TestLegacyPodCleaner_Parallel(t *testing.T) { // Expect the legacy-pod-cleaner controller to delete the pod. testlib.RequireEventuallyWithoutError(t, func() (bool, error) { _, err := kubeClient.CoreV1().Pods(pod.Namespace).Get(ctx, pod.Name, metav1.GetOptions{}) - if k8serrors.IsNotFound(err) { + if apierrors.IsNotFound(err) { t.Logf("fake legacy agent pod %s/%s was deleted as expected", pod.Namespace, pod.Name) return true, nil } diff --git a/test/integration/concierge_webhookauthenticator_status_test.go b/test/integration/concierge_webhookauthenticator_status_test.go index 68b019b17..6b1e1f937 100644 --- a/test/integration/concierge_webhookauthenticator_status_test.go +++ b/test/integration/concierge_webhookauthenticator_status_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" @@ -250,7 +250,7 @@ func TestConciergeWebhookAuthenticatorCRDValidations_Parallel(t *testing.T) { t.Cleanup(func() { // delete if it exists delErr := webhookAuthenticatorClient.Delete(ctx, tt.webhookAuthenticator.Name, metav1.DeleteOptions{}) - if !errors.IsNotFound(delErr) { + if !apierrors.IsNotFound(delErr) { require.NoError(t, delErr) } }) diff --git a/test/integration/concierge_whoami_test.go b/test/integration/concierge_whoami_test.go index 2b2aab212..3993a7984 100644 --- a/test/integration/concierge_whoami_test.go +++ b/test/integration/concierge_whoami_test.go @@ -18,7 +18,7 @@ import ( certificatesv1 "k8s.io/api/certificates/v1" certificatesv1beta1 "k8s.io/api/certificates/v1beta1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/rest" "k8s.io/client-go/util/cert" @@ -173,7 +173,7 @@ func TestWhoAmI_ServiceAccount_TokenRequest_Parallel(t *testing.T) { require.NoError(t, err) _, tokenRequestProbeErr := coreV1client.ServiceAccounts(ns.Name).CreateToken(ctx, sa.Name, &authenticationv1.TokenRequest{}, metav1.CreateOptions{}) - if errors.IsNotFound(tokenRequestProbeErr) && tokenRequestProbeErr.Error() == "the server could not find the requested resource" { + if apierrors.IsNotFound(tokenRequestProbeErr) && tokenRequestProbeErr.Error() == "the server could not find the requested resource" { return // stop test early since the token request API is not enabled on this cluster - other errors are caught below } @@ -210,7 +210,7 @@ func TestWhoAmI_ServiceAccount_TokenRequest_Parallel(t *testing.T) { _, badAudErr := testlib.NewKubeclient(t, saBadAudConfig).PinnipedConcierge.IdentityV1alpha1().WhoAmIRequests(). Create(ctx, &identityv1alpha1.WhoAmIRequest{}, metav1.CreateOptions{}) - require.True(t, errors.IsUnauthorized(badAudErr), testlib.Sdump(badAudErr)) + require.True(t, apierrors.IsUnauthorized(badAudErr), testlib.Sdump(badAudErr)) tokenRequest, err := coreV1client.ServiceAccounts(ns.Name).CreateToken(ctx, sa.Name, &authenticationv1.TokenRequest{ Spec: authenticationv1.TokenRequestSpec{ diff --git a/test/integration/kubeclient_test.go b/test/integration/kubeclient_test.go index 292b26852..a08fbed3f 100644 --- a/test/integration/kubeclient_test.go +++ b/test/integration/kubeclient_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package integration @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" @@ -98,7 +98,7 @@ func TestKubeClientOwnerRef(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() err := regularAggregationClient.ApiregistrationV1().APIServices().Delete(ctx, parentAPIService.Name, metav1.DeleteOptions{}) - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return } require.NoError(t, err) @@ -310,7 +310,7 @@ func isEventuallyDeleted(t *testing.T, f func() error) { switch { case err == nil: return false, nil - case errors.IsNotFound(err): + case apierrors.IsNotFound(err): return true, nil default: return false, err diff --git a/test/integration/supervisor_discovery_test.go b/test/integration/supervisor_discovery_test.go index e1ea9dec4..2d3d9ff5d 100644 --- a/test/integration/supervisor_discovery_test.go +++ b/test/integration/supervisor_discovery_test.go @@ -19,7 +19,7 @@ import ( "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/util/retry" @@ -376,7 +376,7 @@ func temporarilyRemoveAllFederationDomainsAndDefaultTLSCertSecret( // Also remove the supervisor's default TLS cert originalSecret, err := kubeClient.CoreV1().Secrets(ns).Get(ctx, defaultTLSCertSecretName, metav1.GetOptions{}) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) require.False(t, err != nil && !notFound, "unexpected error when getting %s", defaultTLSCertSecretName) if notFound { originalSecret = nil diff --git a/test/integration/supervisor_federationdomain_status_test.go b/test/integration/supervisor_federationdomain_status_test.go index 82c213bc5..79bf8eae8 100644 --- a/test/integration/supervisor_federationdomain_status_test.go +++ b/test/integration/supervisor_federationdomain_status_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/util/retry" "k8s.io/utils/ptr" @@ -914,7 +914,7 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { t.Cleanup(func() { // Delete it if it exists. delErr := fdClient.Delete(ctx, tt.fd.Name, metav1.DeleteOptions{}) - if !k8serrors.IsNotFound(delErr) { + if !apierrors.IsNotFound(delErr) { require.NoError(t, delErr) } }) diff --git a/test/integration/supervisor_oidc_client_test.go b/test/integration/supervisor_oidc_client_test.go index 0d0bc6ccb..29dffa227 100644 --- a/test/integration/supervisor_oidc_client_test.go +++ b/test/integration/supervisor_oidc_client_test.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" @@ -393,7 +393,7 @@ func TestOIDCClientStaticValidation_Parallel(t *testing.T) { }, fixWant: func(t *testing.T, err error, want string) string { // sort the error causes and use that to rebuild a sorted error message - statusErr := &errors.StatusError{} + statusErr := &apierrors.StatusError{} require.ErrorAs(t, err, &statusErr) require.Len(t, statusErr.ErrStatus.Details.Causes, 4) out := make([]string, 0, len(statusErr.ErrStatus.Details.Causes)) diff --git a/test/integration/supervisor_oidcclientsecret_test.go b/test/integration/supervisor_oidcclientsecret_test.go index 1eb38b77f..4f517e34f 100644 --- a/test/integration/supervisor_oidcclientsecret_test.go +++ b/test/integration/supervisor_oidcclientsecret_test.go @@ -15,7 +15,7 @@ import ( "github.com/stretchr/testify/require" "golang.org/x/crypto/bcrypt" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" @@ -916,7 +916,7 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { _, err := kubeClient.CoreV1().Secrets(oidcClient.Namespace). Get(cleanupCtx, oidcclientsecretstorage.New(nil).GetName(oidcClient.UID), metav1.GetOptions{}) requireEventually.Error(err, "deleting OIDCClient should result in deleting storage secrets") - requireEventually.True(k8serrors.IsNotFound(err), + requireEventually.True(apierrors.IsNotFound(err), "deleting OIDCClient should result in deleting storage secrets") }, 2*time.Minute, 250*time.Millisecond) }) @@ -984,7 +984,7 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { Get(ctx, oidcclientsecretstorage.New(nil).GetName(oidcClient.UID), metav1.GetOptions{}) if !hasSecretBeenGenerated { require.Error(t, getStorageSecretError, "expected not found error") - require.True(t, k8serrors.IsNotFound(getStorageSecretError), "expected not found error") + require.True(t, apierrors.IsNotFound(getStorageSecretError), "expected not found error") // no storage secret was created, so no reason to continue making assertions continue } diff --git a/test/integration/supervisor_storage_garbage_collection_test.go b/test/integration/supervisor_storage_garbage_collection_test.go index 6dd3efa66..c37013840 100644 --- a/test/integration/supervisor_storage_garbage_collection_test.go +++ b/test/integration/supervisor_storage_garbage_collection_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package integration @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" @@ -54,12 +54,12 @@ func TestStorageGarbageCollection_Parallel(t *testing.T) { slightlyLongerThanGCControllerFullResyncPeriod := 3*time.Minute + 30*time.Second testlib.RequireEventually(t, func(requireEventually *require.Assertions) { _, err := secrets.Get(ctx, secretAlreadyExpired.Name, metav1.GetOptions{}) - requireEventually.Truef(k8serrors.IsNotFound(err), "wanted a NotFound error but got %v", err) + requireEventually.Truef(apierrors.IsNotFound(err), "wanted a NotFound error but got %v", err) }, slightlyLongerThanGCControllerFullResyncPeriod, 250*time.Millisecond) testlib.RequireEventually(t, func(requireEventually *require.Assertions) { _, err := secrets.Get(ctx, secretWhichWillExpireBeforeTheTestEnds.Name, metav1.GetOptions{}) - requireEventually.Truef(k8serrors.IsNotFound(err), "wanted a NotFound error but got %v", err) + requireEventually.Truef(apierrors.IsNotFound(err), "wanted a NotFound error but got %v", err) }, slightlyLongerThanGCControllerFullResyncPeriod, 250*time.Millisecond) // The unexpired secret should not have been deleted within the timeframe of this test run. @@ -96,7 +96,7 @@ func updateSecretEveryTwoSeconds(stopCh chan struct{}, errCh chan error, secrets case updateErr == nil: // continue to next update - case k8serrors.IsConflict(updateErr), k8serrors.IsNotFound(updateErr): + case apierrors.IsConflict(updateErr), apierrors.IsNotFound(updateErr): select { case _, ok := <-stopCh: if !ok { // stopCh is closed meaning that test is already finished so these errors are expected @@ -121,7 +121,7 @@ func createSecret(ctx context.Context, t *testing.T, secrets corev1client.Secret ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() err := secrets.Delete(ctx, secret.Name, metav1.DeleteOptions{}) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) if !notFound { // it's okay if the Secret was already deleted, but other errors are cleanup failures require.NoError(t, err) diff --git a/test/integration/supervisor_storage_test.go b/test/integration/supervisor_storage_test.go index 9da514620..8bee33c5f 100644 --- a/test/integration/supervisor_storage_test.go +++ b/test/integration/supervisor_storage_test.go @@ -14,7 +14,7 @@ import ( "github.com/ory/fosite/compose" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "go.pinniped.dev/internal/federationdomain/clientregistry" @@ -85,7 +85,7 @@ func TestAuthorizeCodeStorage(t *testing.T) { // trying to create the session again fails because it already exists err = storage.CreateAuthorizeCodeSession(ctx, signature, session.Request) require.Error(t, err) - require.True(t, errors.IsAlreadyExists(err)) + require.True(t, apierrors.IsAlreadyExists(err)) // check that the data stored in Kube matches what we put in initialSecret, err := secrets.Get(ctx, name, metav1.GetOptions{}) diff --git a/test/testlib/client.go b/test/testlib/client.go index 9be61147a..406ff5cef 100644 --- a/test/testlib/client.go +++ b/test/testlib/client.go @@ -19,7 +19,7 @@ import ( corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1" - k8serrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" @@ -33,7 +33,7 @@ import ( configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" - supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" "go.pinniped.dev/internal/groupsuffix" "go.pinniped.dev/internal/kubeclient" @@ -80,13 +80,13 @@ func NewKubernetesClientset(t *testing.T) kubernetes.Interface { return NewKubeclient(t, NewClientConfig(t)).Kubernetes } -func NewSupervisorClientset(t *testing.T) supervisorclientset.Interface { +func NewSupervisorClientset(t *testing.T) pinnipedsupervisorclientset.Interface { t.Helper() return NewKubeclient(t, NewClientConfig(t)).PinnipedSupervisor } -func NewAnonymousSupervisorClientset(t *testing.T) supervisorclientset.Interface { +func NewAnonymousSupervisorClientset(t *testing.T) pinnipedsupervisorclientset.Interface { t.Helper() return NewKubeclient(t, NewAnonymousClientRestConfig(t)).PinnipedSupervisor @@ -380,7 +380,7 @@ func CreateTestFederationDomain( deleteCtx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() err := federationDomainsClient.Delete(deleteCtx, federationDomain.Name, metav1.DeleteOptions{}) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) // It's okay if it is not found, because it might have been deleted by another part of this test. if !notFound { require.NoErrorf(t, err, "could not cleanup test FederationDomain %s/%s", federationDomain.Namespace, federationDomain.Name) @@ -609,7 +609,7 @@ func CreateTestOIDCIdentityProviderWithObjectMeta(t *testing.T, spec idpv1alpha1 t.Cleanup(func() { t.Logf("cleaning up test OIDCIdentityProvider %s/%s", created.Namespace, created.Name) err := upstreams.Delete(context.Background(), created.Name, metav1.DeleteOptions{}) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) // It's okay if it is not found, because it might have been deleted by another part of this test. if !notFound { require.NoErrorf(t, err, "could not cleanup test OIDCIdentityProvider %s/%s", created.Namespace, created.Name) From e9252a9ee300d6afb7dc6eb9eda8fa8e7c7b43d0 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Sat, 11 May 2024 22:17:37 -0500 Subject: [PATCH 02/10] Enforce more imports - k8s.io/apimachinery/pkg/apis/meta/v1 - k8s.io/api/core/v1 - github.com/coreos/go-oidc/v3/oidc - github.com/ory/fosite/handler/oauth2 - go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1 --- .golangci.yaml | 13 ++ cmd/pinniped/cmd/kubeconfig.go | 6 +- cmd/pinniped/cmd/kubeconfig_test.go | 52 ++--- .../controller/authenticator/authenticator.go | 6 +- .../authenticator/authncache/cache_test.go | 4 +- .../cachecleaner/cachecleaner.go | 10 +- .../cachecleaner/cachecleaner_test.go | 18 +- .../jwtcachefiller/jwtcachefiller.go | 16 +- .../jwtcachefiller/jwtcachefiller_test.go | 196 ++++++++--------- .../webhookcachefiller/webhookcachefiller.go | 12 +- .../webhookcachefiller_test.go | 198 +++++++++--------- .../active_directory_upstream_watcher.go | 10 +- .../federation_domain_watcher.go | 6 +- .../generator/federation_domain_secrets.go | 6 +- .../supervisorconfig/jwks_writer.go | 6 +- .../clientregistry/clientregistry_test.go | 4 +- .../endpoints/tokenexchange/token_exchange.go | 12 +- .../federationdomain/storage/kube_storage.go | 4 +- .../strategy/dynamic_oauth2_hmac_strategy.go | 8 +- .../fositestorage/accesstoken/accesstoken.go | 4 +- .../authorizationcode/authorizationcode.go | 6 +- .../authorizationcode_test.go | 4 +- .../refreshtoken/refreshtoken.go | 4 +- .../fosite_storage_interface.go | 8 +- internal/groupsuffix/groupsuffix_test.go | 10 +- internal/supervisor/server/server.go | 4 +- internal/testutil/assertions.go | 6 +- .../testutil/conciergetestutil/tlstestutil.go | 6 +- .../testutil/kube_server_compatibility.go | 4 +- internal/upstreamoidc/upstreamoidc_test.go | 30 +-- pkg/conciergeclient/conciergeclient.go | 8 +- pkg/oidcclient/nonce/nonce_test.go | 10 +- test/integration/cli_test.go | 4 +- .../concierge_api_serving_certs_test.go | 4 +- test/integration/concierge_client_test.go | 4 +- .../concierge_credentialrequest_test.go | 12 +- .../concierge_impersonation_proxy_test.go | 4 +- .../concierge_jwtauthenticator_status_test.go | 72 +++---- ...cierge_webhookauthenticator_status_test.go | 60 +++--- test/integration/e2e_test.go | 44 ++-- test/integration/supervisor_warnings_test.go | 14 +- test/testlib/client.go | 30 +-- test/testlib/env.go | 38 ++-- 43 files changed, 496 insertions(+), 481 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 1504f4263..d4e5e5e77 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -100,3 +100,16 @@ linters-settings: alias: utilerrors - pkg: k8s.io/apimachinery/pkg/api/errors alias: apierrors + - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 + alias: metav1 + # k8s.io libs + - pkg: k8s.io/api/core/v1 + alias: corev1 + # OAuth2/OIDC/Fosite libs + - pkg: github.com/coreos/go-oidc/v3/oidc + alias: coreosoidc + - pkg: github.com/ory/fosite/handler/oauth2 + alias: fositeoauth2 + # Generated Pinniped libs + - pkg: go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1 + alias: authenticationv1alpha1 diff --git a/cmd/pinniped/cmd/kubeconfig.go b/cmd/pinniped/cmd/kubeconfig.go index 0265fab9f..85c04bbbc 100644 --- a/cmd/pinniped/cmd/kubeconfig.go +++ b/cmd/pinniped/cmd/kubeconfig.go @@ -25,7 +25,7 @@ import ( clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "k8s.io/utils/strings/slices" - conciergev1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" idpdiscoveryv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idpdiscovery/v1alpha1" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" @@ -477,7 +477,7 @@ func logStrategies(credentialIssuer *configv1alpha1.CredentialIssuer, log plog.M func discoverAuthenticatorParams(authenticator metav1.Object, flags *getKubeconfigParams, log plog.MinLogger) error { switch auth := authenticator.(type) { - case *conciergev1alpha1.WebhookAuthenticator: + case *authenticationv1alpha1.WebhookAuthenticator: // If the --concierge-authenticator-type/--concierge-authenticator-name flags were not set explicitly, set // them to point at the discovered WebhookAuthenticator. if flags.concierge.authenticatorType == "" && flags.concierge.authenticatorName == "" { @@ -485,7 +485,7 @@ func discoverAuthenticatorParams(authenticator metav1.Object, flags *getKubeconf flags.concierge.authenticatorType = "webhook" flags.concierge.authenticatorName = auth.Name } - case *conciergev1alpha1.JWTAuthenticator: + case *authenticationv1alpha1.JWTAuthenticator: // If the --concierge-authenticator-type/--concierge-authenticator-name flags were not set explicitly, set // them to point at the discovered JWTAuthenticator. if flags.concierge.authenticatorType == "" && flags.concierge.authenticatorName == "" { diff --git a/cmd/pinniped/cmd/kubeconfig_test.go b/cmd/pinniped/cmd/kubeconfig_test.go index 656d5126b..7a791c44f 100644 --- a/cmd/pinniped/cmd/kubeconfig_test.go +++ b/cmd/pinniped/cmd/kubeconfig_test.go @@ -20,7 +20,7 @@ import ( "k8s.io/client-go/tools/clientcmd" "k8s.io/utils/ptr" - conciergev1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" fakeconciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" @@ -64,12 +64,12 @@ func TestGetKubeconfig(t *testing.T) { } jwtAuthenticator := func(issuerCABundle string, issuerURL string) runtime.Object { - return &conciergev1alpha1.JWTAuthenticator{ + return &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}, - Spec: conciergev1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: issuerURL, Audience: "test-audience", - TLS: &conciergev1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte(issuerCABundle)), }, }, @@ -445,10 +445,10 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, - &conciergev1alpha1.JWTAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-1"}}, - &conciergev1alpha1.JWTAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-2"}}, - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-3"}}, - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-4"}}, + &authenticationv1alpha1.JWTAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-1"}}, + &authenticationv1alpha1.JWTAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-2"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-3"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-4"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -485,7 +485,7 @@ func TestGetKubeconfig(t *testing.T) { }}, }, }, - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -546,7 +546,7 @@ func TestGetKubeconfig(t *testing.T) { }, }, }, - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -571,7 +571,7 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -615,12 +615,12 @@ func TestGetKubeconfig(t *testing.T) { }}, }, }, - &conciergev1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}, - Spec: conciergev1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: issuerURL, Audience: "some-test-audience", - TLS: &conciergev1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: "invalid-base64", }, }, @@ -653,12 +653,12 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}, - Spec: conciergev1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: issuerURL, Audience: "some-test-audience.pinniped.dev-invalid-substring", - TLS: &conciergev1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte(issuerCABundle)), }, }, @@ -758,7 +758,7 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -1008,9 +1008,9 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}, - Spec: conciergev1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: issuerURL, Audience: "test-audience", }, @@ -1047,9 +1047,9 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}, - Spec: conciergev1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: issuerURL, Audience: "test-audience", }, @@ -1397,7 +1397,7 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -1461,7 +1461,7 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -1615,7 +1615,7 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, } }, oidcDiscoveryResponse: onlyIssuerOIDCDiscoveryResponse, @@ -3145,7 +3145,7 @@ func TestGetKubeconfig(t *testing.T) { conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ credentialIssuer(), - &conciergev1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, + &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { diff --git a/internal/controller/authenticator/authenticator.go b/internal/controller/authenticator/authenticator.go index 7623aecd9..59b1cc956 100644 --- a/internal/controller/authenticator/authenticator.go +++ b/internal/controller/authenticator/authenticator.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package authenticator contains helper code for dealing with *Authenticator CRDs. @@ -11,7 +11,7 @@ import ( "k8s.io/client-go/util/cert" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" ) // Closer is a type that can be closed idempotently. @@ -25,7 +25,7 @@ type Closer interface { // CABundle returns a PEM-encoded CA bundle from the provided spec. If the provided spec is nil, a // nil CA bundle will be returned. If the provided spec contains a CA bundle that is not properly // encoded, an error will be returned. -func CABundle(spec *auth1alpha1.TLSSpec) (*x509.CertPool, []byte, error) { +func CABundle(spec *authenticationv1alpha1.TLSSpec) (*x509.CertPool, []byte, error) { if spec == nil || len(spec.CertificateAuthorityData) == 0 { return nil, nil, nil } diff --git a/internal/controller/authenticator/authncache/cache_test.go b/internal/controller/authenticator/authncache/cache_test.go index f9dfec1ee..9d22caa07 100644 --- a/internal/controller/authenticator/authncache/cache_test.go +++ b/internal/controller/authenticator/authncache/cache_test.go @@ -17,7 +17,7 @@ import ( "k8s.io/apiserver/pkg/authentication/authenticator" "k8s.io/apiserver/pkg/authentication/user" - authv1alpha "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" loginapi "go.pinniped.dev/generated/latest/apis/concierge/login" "go.pinniped.dev/internal/mocks/mocktokenauthenticator" ) @@ -75,7 +75,7 @@ func TestAuthenticateTokenCredentialRequest(t *testing.T) { }, Spec: loginapi.TokenCredentialRequestSpec{ Authenticator: corev1.TypedLocalObjectReference{ - APIGroup: &authv1alpha.SchemeGroupVersion.Group, + APIGroup: &authenticationv1alpha1.SchemeGroupVersion.Group, Kind: "WebhookAuthenticator", Name: "test-name", }, diff --git a/internal/controller/authenticator/cachecleaner/cachecleaner.go b/internal/controller/authenticator/cachecleaner/cachecleaner.go index 9a789b279..772bd57c2 100644 --- a/internal/controller/authenticator/cachecleaner/cachecleaner.go +++ b/internal/controller/authenticator/cachecleaner/cachecleaner.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package cachecleaner implements a controller for garbage collecting authenticators from an authenticator cache. @@ -11,7 +11,7 @@ import ( "k8s.io/apimachinery/pkg/labels" "k8s.io/klog/v2" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" authinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions/authentication/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controller/authenticator" @@ -74,7 +74,7 @@ func (c *controller) Sync(_ controllerlib.Context) error { key := authncache.Key{ Name: webhook.Name, Kind: "WebhookAuthenticator", - APIGroup: auth1alpha1.SchemeGroupVersion.Group, + APIGroup: authenticationv1alpha1.SchemeGroupVersion.Group, } authenticatorSet[key] = true } @@ -82,14 +82,14 @@ func (c *controller) Sync(_ controllerlib.Context) error { key := authncache.Key{ Name: jwtAuthenticator.Name, Kind: "JWTAuthenticator", - APIGroup: auth1alpha1.SchemeGroupVersion.Group, + APIGroup: authenticationv1alpha1.SchemeGroupVersion.Group, } authenticatorSet[key] = true } // Delete any entries from the cache which are no longer in the cluster. for _, key := range c.cache.Keys() { - if key.APIGroup != auth1alpha1.SchemeGroupVersion.Group || (key.Kind != "WebhookAuthenticator" && key.Kind != "JWTAuthenticator") { + if key.APIGroup != authenticationv1alpha1.SchemeGroupVersion.Group || (key.Kind != "WebhookAuthenticator" && key.Kind != "JWTAuthenticator") { continue } if _, exists := authenticatorSet[key]; !exists { diff --git a/internal/controller/authenticator/cachecleaner/cachecleaner_test.go b/internal/controller/authenticator/cachecleaner/cachecleaner_test.go index 72636b8f7..c72068829 100644 --- a/internal/controller/authenticator/cachecleaner/cachecleaner_test.go +++ b/internal/controller/authenticator/cachecleaner/cachecleaner_test.go @@ -12,7 +12,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apiserver/pkg/authentication/authenticator" - authv1alpha "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" controllerAuthenticator "go.pinniped.dev/internal/controller/authenticator" @@ -65,12 +65,12 @@ func TestController(t *testing.T) { cache.Store(testJWTAuthenticatorKey1, nil) }, objects: []runtime.Object{ - &authv1alpha.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: testWebhookKey1.Name, }, }, - &authv1alpha.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: testJWTAuthenticatorKey1.Name, }, @@ -81,22 +81,22 @@ func TestController(t *testing.T) { { name: "authenticators not yet added", objects: []runtime.Object{ - &authv1alpha.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: testWebhookKey1.Name, }, }, - &authv1alpha.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: testWebhookKey2.Name, }, }, - &authv1alpha.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: testJWTAuthenticatorKey1.Name, }, }, - &authv1alpha.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: testJWTAuthenticatorKey2.Name, }, @@ -114,12 +114,12 @@ func TestController(t *testing.T) { cache.Store(testKeyUnknownType, nil) }, objects: []runtime.Object{ - &authv1alpha.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: testWebhookKey1.Name, }, }, - &authv1alpha.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: testJWTAuthenticatorKey1.Name, }, diff --git a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller.go b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller.go index 1159aa1da..02b8289a9 100644 --- a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller.go +++ b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller.go @@ -29,7 +29,7 @@ import ( "k8s.io/utils/clock" "k8s.io/utils/ptr" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" authinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions/authentication/v1alpha1" @@ -103,7 +103,7 @@ type tokenAuthenticatorCloser interface { type cachedJWTAuthenticator struct { authenticator.Token - spec *auth1alpha1.JWTAuthenticatorSpec + spec *authenticationv1alpha1.JWTAuthenticatorSpec cancel context.CancelFunc } @@ -161,7 +161,7 @@ func (c *jwtCacheFillerController) Sync(ctx controllerlib.Context) error { } cacheKey := authncache.Key{ - APIGroup: auth1alpha1.GroupName, + APIGroup: authenticationv1alpha1.GroupName, Kind: "JWTAuthenticator", Name: ctx.Key.Name, } @@ -245,7 +245,7 @@ func (c *jwtCacheFillerController) extractValueAsJWTAuthenticator(value authncac return jwtAuthenticator } -func (c *jwtCacheFillerController) validateTLS(tlsSpec *auth1alpha1.TLSSpec, conditions []*metav1.Condition) (*x509.CertPool, []*metav1.Condition, bool) { +func (c *jwtCacheFillerController) validateTLS(tlsSpec *authenticationv1alpha1.TLSSpec, conditions []*metav1.Condition) (*x509.CertPool, []*metav1.Condition, bool) { rootCAs, _, err := pinnipedauthenticator.CABundle(tlsSpec) if err != nil { msg := fmt.Sprintf("%s: %s", "invalid TLS configuration", err.Error()) @@ -504,7 +504,7 @@ func (c *jwtCacheFillerController) validateJWKSFetch(ctx context.Context, jwksUR } // newCachedJWTAuthenticator creates a jwt authenticator from the provided spec. -func (c *jwtCacheFillerController) newCachedJWTAuthenticator(client *http.Client, spec *auth1alpha1.JWTAuthenticatorSpec, keySet *coreosoidc.RemoteKeySet, conditions []*metav1.Condition, prereqOk bool) (*cachedJWTAuthenticator, []*metav1.Condition, error) { +func (c *jwtCacheFillerController) newCachedJWTAuthenticator(client *http.Client, spec *authenticationv1alpha1.JWTAuthenticatorSpec, keySet *coreosoidc.RemoteKeySet, conditions []*metav1.Condition, prereqOk bool) (*cachedJWTAuthenticator, []*metav1.Condition, error) { if !prereqOk { conditions = append(conditions, &metav1.Condition{ Type: typeAuthenticatorValid, @@ -580,13 +580,13 @@ func (c *jwtCacheFillerController) newCachedJWTAuthenticator(client *http.Client func (c *jwtCacheFillerController) updateStatus( ctx context.Context, - original *auth1alpha1.JWTAuthenticator, + original *authenticationv1alpha1.JWTAuthenticator, conditions []*metav1.Condition, ) error { updated := original.DeepCopy() if conditionsutil.HadErrorCondition(conditions) { - updated.Status.Phase = auth1alpha1.JWTAuthenticatorPhaseError + updated.Status.Phase = authenticationv1alpha1.JWTAuthenticatorPhaseError conditions = append(conditions, &metav1.Condition{ Type: typeReady, Status: metav1.ConditionFalse, @@ -594,7 +594,7 @@ func (c *jwtCacheFillerController) updateStatus( Message: "the JWTAuthenticator is not ready: see other conditions for details", }) } else { - updated.Status.Phase = auth1alpha1.JWTAuthenticatorPhaseReady + updated.Status.Phase = authenticationv1alpha1.JWTAuthenticatorPhaseReady conditions = append(conditions, &metav1.Condition{ Type: typeReady, Status: metav1.ConditionTrue, diff --git a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go index ca09c410b..97ecfd46d 100644 --- a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go +++ b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go @@ -33,7 +33,7 @@ import ( coretesting "k8s.io/client-go/testing" clocktesting "k8s.io/utils/clock/testing" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" "go.pinniped.dev/internal/controller/authenticator/authncache" @@ -216,72 +216,72 @@ func TestController(t *testing.T) { timeInThePast := time.Date(1111, time.January, 1, 1, 1, 1, 111111, time.Local) frozenTimeInThePast := metav1.NewTime(timeInThePast) - someJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + someJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: goodIssuer, Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), } - someJWTAuthenticatorSpecWithUsernameClaim := &auth1alpha1.JWTAuthenticatorSpec{ + someJWTAuthenticatorSpecWithUsernameClaim := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: goodIssuer, Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), - Claims: auth1alpha1.JWTTokenClaims{ + Claims: authenticationv1alpha1.JWTTokenClaims{ Username: "my-custom-username-claim", }, } - someJWTAuthenticatorSpecWithGroupsClaim := &auth1alpha1.JWTAuthenticatorSpec{ + someJWTAuthenticatorSpecWithGroupsClaim := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: goodIssuer, Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), - Claims: auth1alpha1.JWTTokenClaims{ + Claims: authenticationv1alpha1.JWTTokenClaims{ Groups: customGroupsClaim, }, } - otherJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + otherJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: someOtherIssuer, Audience: goodAudience, // Some random generated cert // Issuer: C=US, O=Pivotal // No SAN provided - TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURVVENDQWptZ0F3SUJBZ0lWQUpzNStTbVRtaTJXeUI0bGJJRXBXaUs5a1RkUE1BMEdDU3FHU0liM0RRRUIKQ3dVQU1COHhDekFKQmdOVkJBWVRBbFZUTVJBd0RnWURWUVFLREFkUWFYWnZkR0ZzTUI0WERUSXdNRFV3TkRFMgpNamMxT0ZvWERUSTBNRFV3TlRFMk1qYzFPRm93SHpFTE1Ba0dBMVVFQmhNQ1ZWTXhFREFPQmdOVkJBb01CMUJwCmRtOTBZV3d3Z2dFaU1BMEdDU3FHU0liM0RRRUJBUVVBQTRJQkR3QXdnZ0VLQW9JQkFRRERZWmZvWGR4Z2NXTEMKZEJtbHB5a0tBaG9JMlBuUWtsVFNXMno1cGcwaXJjOGFRL1E3MXZzMTRZYStmdWtFTGlvOTRZYWw4R01DdVFrbApMZ3AvUEE5N1VYelhQNDBpK25iNXcwRGpwWWd2dU9KQXJXMno2MFRnWE5NSFh3VHk4ME1SZEhpUFVWZ0VZd0JpCmtkNThzdEFVS1Y1MnBQTU1reTJjNy9BcFhJNmRXR2xjalUvaFBsNmtpRzZ5dEw2REtGYjJQRWV3MmdJM3pHZ2IKOFVVbnA1V05DZDd2WjNVY0ZHNXlsZEd3aGc3cnZ4U1ZLWi9WOEhCMGJmbjlxamlrSVcxWFM4dzdpUUNlQmdQMApYZWhKZmVITlZJaTJtZlczNlVQbWpMdnVKaGpqNDIrdFBQWndvdDkzdWtlcEgvbWpHcFJEVm9wamJyWGlpTUYrCkYxdnlPNGMxQWdNQkFBR2pnWU13Z1lBd0hRWURWUjBPQkJZRUZNTWJpSXFhdVkwajRVWWphWDl0bDJzby9LQ1IKTUI4R0ExVWRJd1FZTUJhQUZNTWJpSXFhdVkwajRVWWphWDl0bDJzby9LQ1JNQjBHQTFVZEpRUVdNQlFHQ0NzRwpBUVVGQndNQ0JnZ3JCZ0VGQlFjREFUQVBCZ05WSFJNQkFmOEVCVEFEQVFIL01BNEdBMVVkRHdFQi93UUVBd0lCCkJqQU5CZ2txaGtpRzl3MEJBUXNGQUFPQ0FRRUFYbEh4M2tIMDZwY2NDTDlEVE5qTnBCYnlVSytGd2R6T2IwWFYKcmpNaGtxdHVmdEpUUnR5T3hKZ0ZKNXhUR3pCdEtKamcrVU1pczBOV0t0VDBNWThVMU45U2c5SDl0RFpHRHBjVQpxMlVRU0Y4dXRQMVR3dnJIUzIrdzB2MUoxdHgrTEFiU0lmWmJCV0xXQ21EODUzRlVoWlFZekkvYXpFM28vd0p1CmlPUklMdUpNUk5vNlBXY3VLZmRFVkhaS1RTWnk3a25FcHNidGtsN3EwRE91eUFWdG9HVnlkb3VUR0FOdFhXK2YKczNUSTJjKzErZXg3L2RZOEJGQTFzNWFUOG5vZnU3T1RTTzdiS1kzSkRBUHZOeFQzKzVZUXJwNGR1Nmh0YUFMbAppOHNaRkhidmxpd2EzdlhxL3p1Y2JEaHEzQzBhZnAzV2ZwRGxwSlpvLy9QUUFKaTZLQT09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K"}, + TLS: &authenticationv1alpha1.TLSSpec{CertificateAuthorityData: "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURVVENDQWptZ0F3SUJBZ0lWQUpzNStTbVRtaTJXeUI0bGJJRXBXaUs5a1RkUE1BMEdDU3FHU0liM0RRRUIKQ3dVQU1COHhDekFKQmdOVkJBWVRBbFZUTVJBd0RnWURWUVFLREFkUWFYWnZkR0ZzTUI0WERUSXdNRFV3TkRFMgpNamMxT0ZvWERUSTBNRFV3TlRFMk1qYzFPRm93SHpFTE1Ba0dBMVVFQmhNQ1ZWTXhFREFPQmdOVkJBb01CMUJwCmRtOTBZV3d3Z2dFaU1BMEdDU3FHU0liM0RRRUJBUVVBQTRJQkR3QXdnZ0VLQW9JQkFRRERZWmZvWGR4Z2NXTEMKZEJtbHB5a0tBaG9JMlBuUWtsVFNXMno1cGcwaXJjOGFRL1E3MXZzMTRZYStmdWtFTGlvOTRZYWw4R01DdVFrbApMZ3AvUEE5N1VYelhQNDBpK25iNXcwRGpwWWd2dU9KQXJXMno2MFRnWE5NSFh3VHk4ME1SZEhpUFVWZ0VZd0JpCmtkNThzdEFVS1Y1MnBQTU1reTJjNy9BcFhJNmRXR2xjalUvaFBsNmtpRzZ5dEw2REtGYjJQRWV3MmdJM3pHZ2IKOFVVbnA1V05DZDd2WjNVY0ZHNXlsZEd3aGc3cnZ4U1ZLWi9WOEhCMGJmbjlxamlrSVcxWFM4dzdpUUNlQmdQMApYZWhKZmVITlZJaTJtZlczNlVQbWpMdnVKaGpqNDIrdFBQWndvdDkzdWtlcEgvbWpHcFJEVm9wamJyWGlpTUYrCkYxdnlPNGMxQWdNQkFBR2pnWU13Z1lBd0hRWURWUjBPQkJZRUZNTWJpSXFhdVkwajRVWWphWDl0bDJzby9LQ1IKTUI4R0ExVWRJd1FZTUJhQUZNTWJpSXFhdVkwajRVWWphWDl0bDJzby9LQ1JNQjBHQTFVZEpRUVdNQlFHQ0NzRwpBUVVGQndNQ0JnZ3JCZ0VGQlFjREFUQVBCZ05WSFJNQkFmOEVCVEFEQVFIL01BNEdBMVVkRHdFQi93UUVBd0lCCkJqQU5CZ2txaGtpRzl3MEJBUXNGQUFPQ0FRRUFYbEh4M2tIMDZwY2NDTDlEVE5qTnBCYnlVSytGd2R6T2IwWFYKcmpNaGtxdHVmdEpUUnR5T3hKZ0ZKNXhUR3pCdEtKamcrVU1pczBOV0t0VDBNWThVMU45U2c5SDl0RFpHRHBjVQpxMlVRU0Y4dXRQMVR3dnJIUzIrdzB2MUoxdHgrTEFiU0lmWmJCV0xXQ21EODUzRlVoWlFZekkvYXpFM28vd0p1CmlPUklMdUpNUk5vNlBXY3VLZmRFVkhaS1RTWnk3a25FcHNidGtsN3EwRE91eUFWdG9HVnlkb3VUR0FOdFhXK2YKczNUSTJjKzErZXg3L2RZOEJGQTFzNWFUOG5vZnU3T1RTTzdiS1kzSkRBUHZOeFQzKzVZUXJwNGR1Nmh0YUFMbAppOHNaRkhidmxpd2EzdlhxL3p1Y2JEaHEzQzBhZnAzV2ZwRGxwSlpvLy9QUUFKaTZLQT09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K"}, } - missingTLSJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + missingTLSJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: goodIssuer, Audience: goodAudience, } - invalidTLSJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + invalidTLSJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: someOtherIssuer, Audience: goodAudience, - TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: "invalid base64-encoded data"}, + TLS: &authenticationv1alpha1.TLSSpec{CertificateAuthorityData: "invalid base64-encoded data"}, } - invalidIssuerJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + invalidIssuerJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "https://.café .com/café/café/café/coffee", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), } - invalidIssuerSchemeJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + invalidIssuerSchemeJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "http://.café.com/café/café/café/coffee", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), } - validIssuerURLButDoesNotExistJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + validIssuerURLButDoesNotExistJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: goodIssuer + "/foo/bar/baz/shizzle", Audience: goodAudience, } - badIssuerJWKSURIJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + badIssuerJWKSURIJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: badIssuerInvalidJWKSURI, Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(badOIDCIssuerServerInvalidJWKSURI.TLS), } - badIssuerJWKSURISchemeJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + badIssuerJWKSURISchemeJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: badIssuerInvalidJWKSURIScheme, Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(badOIDCIssuerServerInvalidJWKSURIScheme.TLS), } - jwksFetchShouldFailJWTAuthenticatorSpec := &auth1alpha1.JWTAuthenticatorSpec{ + jwksFetchShouldFailJWTAuthenticatorSpec := &authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: jwksFetchShouldFailServer.URL, Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(jwksFetchShouldFailServer.TLS), @@ -617,12 +617,12 @@ func TestController(t *testing.T) { name: "Sync: valid and unchanged JWTAuthenticator: loop will preserve existing status conditions", syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -649,13 +649,13 @@ func TestController(t *testing.T) { name: "Sync: changed JWTAuthenticator: loop will update timestamps only on relevant statuses", syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", Generation: 1234, }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 1233), []metav1.Condition{ @@ -684,13 +684,13 @@ func TestController(t *testing.T) { }, }}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", Generation: 1234, }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 1234), []metav1.Condition{ @@ -714,7 +714,7 @@ func TestController(t *testing.T) { name: "Sync: valid JWTAuthenticator with CA: loop will complete successfully and update status conditions.", syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -732,12 +732,12 @@ func TestController(t *testing.T) { }, }}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -756,7 +756,7 @@ func TestController(t *testing.T) { name: "Sync: JWTAuthenticator with custom username claim: loop will complete successfully and update status conditions.", syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -774,12 +774,12 @@ func TestController(t *testing.T) { }, }}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpecWithUsernameClaim, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -799,7 +799,7 @@ func TestController(t *testing.T) { name: "Sync: JWTAuthenticator with custom groups claim: loop will complete successfully and update status conditions.", syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -817,12 +817,12 @@ func TestController(t *testing.T) { }, }}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpecWithGroupsClaim, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -845,7 +845,7 @@ func TestController(t *testing.T) { authncache.Key{ Name: "test-name", Kind: "JWTAuthenticator", - APIGroup: auth1alpha1.SchemeGroupVersion.Group, + APIGroup: authenticationv1alpha1.SchemeGroupVersion.Group, }, newCacheValue(t, *otherJWTAuthenticatorSpec, wantClose), ) @@ -853,7 +853,7 @@ func TestController(t *testing.T) { wantClose: true, syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -871,12 +871,12 @@ func TestController(t *testing.T) { }, }}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -898,7 +898,7 @@ func TestController(t *testing.T) { authncache.Key{ Name: "test-name", Kind: "JWTAuthenticator", - APIGroup: auth1alpha1.SchemeGroupVersion.Group, + APIGroup: authenticationv1alpha1.SchemeGroupVersion.Group, }, newCacheValue(t, *someJWTAuthenticatorSpec, wantClose), ) @@ -906,7 +906,7 @@ func TestController(t *testing.T) { wantClose: false, syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -939,14 +939,14 @@ func TestController(t *testing.T) { authncache.Key{ Name: "test-name", Kind: "JWTAuthenticator", - APIGroup: auth1alpha1.SchemeGroupVersion.Group, + APIGroup: authenticationv1alpha1.SchemeGroupVersion.Group, }, struct{ authenticator.Token }{}, ) }, syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -970,12 +970,12 @@ func TestController(t *testing.T) { }, }}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -994,7 +994,7 @@ func TestController(t *testing.T) { name: "Sync: valid JWTAuthenticator without CA: loop will fail to cache the authenticator, will write failed and unknown status conditions, and will enqueue resync", syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -1002,12 +1002,12 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *missingTLSJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1038,7 +1038,7 @@ func TestController(t *testing.T) { name: "validateTLS: JWTAuthenticator with invalid CA: loop will fail, will write failed and unknown status conditions, but will not enqueue a resync due to user config error", syncKey: controllerlib.Key{Name: "test-name"}, jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -1046,12 +1046,12 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *invalidTLSJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(someOtherIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1077,7 +1077,7 @@ func TestController(t *testing.T) { }, { name: "validateIssuer: parsing error (spec.issuer URL is invalid): loop will fail sync, will write failed and unknown status conditions, but will not enqueue a resync due to user config error", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -1086,12 +1086,12 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *invalidIssuerJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1116,7 +1116,7 @@ func TestController(t *testing.T) { }, { name: "validateIssuer: parsing error (spec.issuer URL has invalid scheme, requires https): loop will fail sync, will write failed and unknown conditions, but will not enqueue a resync due to user config error", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -1125,12 +1125,12 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *invalidIssuerSchemeJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1155,11 +1155,11 @@ func TestController(t *testing.T) { }, { name: "validateIssuer: issuer cannot include fragment: loop will fail sync, will write failed and unknown conditions, but will not enqueue a resync due to user config error", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "https://www.example.com/foo/bar/#do-not-include-fragment", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), @@ -1168,16 +1168,16 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "https://www.example.com/foo/bar/#do-not-include-fragment", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), }, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1202,11 +1202,11 @@ func TestController(t *testing.T) { }, { name: "validateIssuer: issuer cannot include query params: loop will fail sync, will write failed and unknown conditions, but will not enqueue a resync due to user config error", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "https://www.example.com/foo/bar/?query-params=not-allowed", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), @@ -1215,16 +1215,16 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "https://www.example.com/foo/bar/?query-params=not-allowed", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), }, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1249,11 +1249,11 @@ func TestController(t *testing.T) { }, { name: "validateIssuer: issuer cannot include .well-known in path: loop will fail sync, will write failed and unknown conditions, but will not enqueue a resync due to user config error", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "https://www.example.com/foo/bar/.well-known/openid-configuration", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), @@ -1262,16 +1262,16 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "https://www.example.com/foo/bar/.well-known/openid-configuration", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), }, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1296,7 +1296,7 @@ func TestController(t *testing.T) { }, { name: "validateProviderDiscovery: could not perform oidc discovery on provider issuer: loop will fail sync, will write failed and unknown conditions, and will enqueue new sync", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -1305,12 +1305,12 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *validIssuerURLButDoesNotExistJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1337,11 +1337,11 @@ func TestController(t *testing.T) { }, { name: "validateProviderDiscovery: excessively long errors truncated: loop will fail sync, will write failed and unknown conditions, and will enqueue new sync", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: goodIssuer + "/path/to/not/found", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), @@ -1350,16 +1350,16 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: goodIssuer + "/path/to/not/found", Audience: goodAudience, TLS: conciergetestutil.TLSSpecFromTLSConfig(goodOIDCIssuerServer.TLS), }, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1392,7 +1392,7 @@ func TestController(t *testing.T) { { name: "validateProviderJWKSURL: could not parse provider jwks_uri: loop will fail sync, will write failed and unknown conditions, and will enqueue new sync", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -1401,12 +1401,12 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *badIssuerJWKSURIJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1431,7 +1431,7 @@ func TestController(t *testing.T) { }, { name: "validateProviderJWKSURL: invalid scheme, requires 'https': loop will fail sync, will write failed and unknown conditions, and will enqueue new sync", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -1440,12 +1440,12 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *badIssuerJWKSURISchemeJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1473,7 +1473,7 @@ func TestController(t *testing.T) { { name: "validateJWKSFetch: could not fetch keys: loop will fail sync, will write failed and unknown status conditions, and will enqueue a resync", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -1482,12 +1482,12 @@ func TestController(t *testing.T) { }, syncKey: controllerlib.Key{Name: "test-name"}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *jwksFetchShouldFailJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1512,12 +1512,12 @@ func TestController(t *testing.T) { { name: "updateStatus: called with matching original and updated conditions: will not make request to update conditions", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -1545,12 +1545,12 @@ func TestController(t *testing.T) { { name: "updateStatus: called with different original and updated conditions: will make request to update conditions", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1573,12 +1573,12 @@ func TestController(t *testing.T) { }, }}, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -1595,12 +1595,12 @@ func TestController(t *testing.T) { { name: "updateStatus: when update request fails: error will enqueue a resync", jwtAuthenticators: []runtime.Object{ - &auth1alpha1.JWTAuthenticator{ + &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), []metav1.Condition{ @@ -1625,12 +1625,12 @@ func TestController(t *testing.T) { // This captures that there was an attempt to update to Ready, allHappyConditions, // but the wantSyncLoopErr indicates that there is a failure, so the JWTAuthenticator // remains with a bad phase and at least 1 sad condition - updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &auth1alpha1.JWTAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(jwtAuthenticatorsGVR, "", &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: *someJWTAuthenticatorSpec, - Status: auth1alpha1.JWTAuthenticatorStatus{ + Status: authenticationv1alpha1.JWTAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodIssuer, frozenMetav1Now, 0), Phase: "Ready", }, @@ -1742,7 +1742,7 @@ func TestController(t *testing.T) { // We expected the cache to have an entry, so pull that entry from the cache and test it. expectedCacheKey := authncache.Key{ - APIGroup: auth1alpha1.GroupName, + APIGroup: authenticationv1alpha1.GroupName, Kind: "JWTAuthenticator", Name: syncCtx.Key.Name, } @@ -2083,7 +2083,7 @@ func createJWT( return jwt } -func newCacheValue(t *testing.T, spec auth1alpha1.JWTAuthenticatorSpec, wantClose bool) authncache.Value { +func newCacheValue(t *testing.T, spec authenticationv1alpha1.JWTAuthenticatorSpec, wantClose bool) authncache.Value { t.Helper() wasClosed := false diff --git a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go index 284fd6389..58f256c33 100644 --- a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go +++ b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go @@ -24,7 +24,7 @@ import ( "k8s.io/klog/v2" "k8s.io/utils/clock" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" authinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions/authentication/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" @@ -126,7 +126,7 @@ func (c *webhookCacheFillerController) Sync(ctx controllerlib.Context) error { if !conditionsutil.HadErrorCondition(conditions) { c.cache.Store(authncache.Key{ - APIGroup: auth1alpha1.GroupName, + APIGroup: authenticationv1alpha1.GroupName, Kind: "WebhookAuthenticator", Name: ctx.Key.Name, }, webhookAuthenticator) @@ -264,7 +264,7 @@ func (c *webhookCacheFillerController) validateConnection(certPool *x509.CertPoo return conditions, nil } -func (c *webhookCacheFillerController) validateTLSBundle(tlsSpec *auth1alpha1.TLSSpec, conditions []*metav1.Condition) (*x509.CertPool, []byte, []*metav1.Condition, bool) { +func (c *webhookCacheFillerController) validateTLSBundle(tlsSpec *authenticationv1alpha1.TLSSpec, conditions []*metav1.Condition) (*x509.CertPool, []byte, []*metav1.Condition, bool) { rootCAs, pemBytes, err := pinnipedauthenticator.CABundle(tlsSpec) if err != nil { msg := fmt.Sprintf("%s: %s", "invalid TLS configuration", err.Error()) @@ -337,13 +337,13 @@ func (c *webhookCacheFillerController) validateEndpoint(endpoint string, conditi func (c *webhookCacheFillerController) updateStatus( ctx context.Context, - original *auth1alpha1.WebhookAuthenticator, + original *authenticationv1alpha1.WebhookAuthenticator, conditions []*metav1.Condition, ) error { updated := original.DeepCopy() if conditionsutil.HadErrorCondition(conditions) { - updated.Status.Phase = auth1alpha1.WebhookAuthenticatorPhaseError + updated.Status.Phase = authenticationv1alpha1.WebhookAuthenticatorPhaseError conditions = append(conditions, &metav1.Condition{ Type: typeReady, Status: metav1.ConditionFalse, @@ -351,7 +351,7 @@ func (c *webhookCacheFillerController) updateStatus( Message: "the WebhookAuthenticator is not ready: see other conditions for details", }) } else { - updated.Status.Phase = auth1alpha1.WebhookAuthenticatorPhaseReady + updated.Status.Phase = authenticationv1alpha1.WebhookAuthenticatorPhaseReady conditions = append(conditions, &metav1.Condition{ Type: typeReady, Status: metav1.ConditionTrue, diff --git a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go index 2c8564670..8711343e5 100644 --- a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go +++ b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go @@ -28,7 +28,7 @@ import ( clocktesting "k8s.io/utils/clock/testing" "k8s.io/utils/ptr" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" "go.pinniped.dev/internal/certauthority" @@ -139,34 +139,34 @@ func TestController(t *testing.T) { timeInThePast := time.Date(1111, time.January, 1, 1, 1, 1, 111111, time.Local) frozenTimeInThePast := metav1.NewTime(timeInThePast) - goodWebhookAuthenticatorSpecWithCA := auth1alpha1.WebhookAuthenticatorSpec{ + goodWebhookAuthenticatorSpecWithCA := authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: goodWebhookDefaultServingCertEndpoint, TLS: conciergetestutil.TLSSpecFromTLSConfig(hostGoodDefaultServingCertServer.TLS), } - localWithExampleDotComWeebhookAuthenticatorSpec := auth1alpha1.WebhookAuthenticatorSpec{ + localWithExampleDotComWeebhookAuthenticatorSpec := authenticationv1alpha1.WebhookAuthenticatorSpec{ // CA for example.com, TLS serving cert for example.com, but endpoint is still localhost Endpoint: hostLocalWithExampleDotComCertServer.URL, - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ // CA Bundle for example.com CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForExampleDotCom.Bundle()), }, } - goodWebhookAuthenticatorSpecWithoutCA := auth1alpha1.WebhookAuthenticatorSpec{ + goodWebhookAuthenticatorSpecWithoutCA := authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: goodWebhookDefaultServingCertEndpoint, - TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: ""}, + TLS: &authenticationv1alpha1.TLSSpec{CertificateAuthorityData: ""}, } - goodWebhookAuthenticatorSpecWith404Endpoint := auth1alpha1.WebhookAuthenticatorSpec{ + goodWebhookAuthenticatorSpecWith404Endpoint := authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: goodWebhookDefaultServingCertEndpointBut404, TLS: conciergetestutil.TLSSpecFromTLSConfig(hostGoodDefaultServingCertServer.TLS), } - badWebhookAuthenticatorSpecInvalidTLS := auth1alpha1.WebhookAuthenticatorSpec{ + badWebhookAuthenticatorSpecInvalidTLS := authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: goodWebhookDefaultServingCertEndpoint, - TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: "invalid base64-encoded data"}, + TLS: &authenticationv1alpha1.TLSSpec{CertificateAuthorityData: "invalid base64-encoded data"}, } - badWebhookAuthenticatorSpecGoodEndpointButUnknownCA := auth1alpha1.WebhookAuthenticatorSpec{ + badWebhookAuthenticatorSpecGoodEndpointButUnknownCA := authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: goodWebhookDefaultServingCertEndpoint, - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(pemServerCertForUnknownServer), }, } @@ -392,12 +392,12 @@ func TestController(t *testing.T) { name: "Sync: valid and unchanged WebhookAuthenticator: loop will preserve existing status conditions", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), Phase: "Ready", }, @@ -427,13 +427,13 @@ func TestController(t *testing.T) { name: "Sync: changed WebhookAuthenticator: loop will update timestamps only on relevant statuses", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", Generation: 1234, }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 1233), []metav1.Condition{ @@ -458,13 +458,13 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", Generation: 1234, }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 1234), []metav1.Condition{ @@ -487,7 +487,7 @@ func TestController(t *testing.T) { name: "Sync: valid WebhookAuthenticator with CA: will complete sync loop successfully with success conditions and ready phase", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -507,12 +507,12 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), Phase: "Ready", }, @@ -530,14 +530,14 @@ func TestController(t *testing.T) { name: "Sync: valid WebhookAuthenticator with IPV6 and CA: will complete sync loop successfully with success conditions and ready phase", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: func() auth1alpha1.WebhookAuthenticatorSpec { + Spec: func() authenticationv1alpha1.WebhookAuthenticatorSpec { ipv6 := goodWebhookAuthenticatorSpecWithCA.DeepCopy() ipv6.Endpoint = hostLocalIPv6Server.URL - ipv6.TLS = ptr.To(auth1alpha1.TLSSpec{ + ipv6.TLS = ptr.To(authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(ipv6CA), }) return *ipv6 @@ -557,19 +557,19 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: func() auth1alpha1.WebhookAuthenticatorSpec { + Spec: func() authenticationv1alpha1.WebhookAuthenticatorSpec { ipv6 := goodWebhookAuthenticatorSpecWithCA.DeepCopy() ipv6.Endpoint = hostLocalIPv6Server.URL - ipv6.TLS = ptr.To(auth1alpha1.TLSSpec{ + ipv6.TLS = ptr.To(authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(ipv6CA), }) return *ipv6 }(), - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(hostLocalIPv6Server.URL, frozenMetav1Now, 0), Phase: "Ready", }, @@ -587,7 +587,7 @@ func TestController(t *testing.T) { name: "Sync: valid WebhookAuthenticator without CA: loop will fail to cache the authenticator, will write failed and unknown status conditions, and will enqueue resync", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -595,12 +595,12 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWithoutCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), []metav1.Condition{ @@ -627,7 +627,7 @@ func TestController(t *testing.T) { name: "validateTLS: WebhookAuthenticator with invalid CA will fail sync loop and will report failed and unknown conditions and Error phase, but will not enqueue a resync due to user config error", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -635,12 +635,12 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: badWebhookAuthenticatorSpecInvalidTLS, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), []metav1.Condition{ @@ -666,24 +666,24 @@ func TestController(t *testing.T) { name: "validateEndpoint: parsing error (spec.endpoint URL is invalid) will fail sync loop and will report failed and unknown conditions and Error phase, but will not enqueue a resync due to user config error", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: badEndpointInvalidURL, }, }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: badEndpointInvalidURL, }, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), []metav1.Condition{ @@ -710,24 +710,24 @@ func TestController(t *testing.T) { name: "validateEndpoint: parsing error (spec.endpoint URL has invalid scheme, requires https) will fail sync loop, will write failed and unknown status conditions, but will not enqueue a resync due to user config error", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: badEndpointNoHTTPS, }, }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: badEndpointNoHTTPS, }, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), []metav1.Condition{ @@ -754,30 +754,30 @@ func TestController(t *testing.T) { name: "validateEndpoint: should error if endpoint cannot be parsed", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://[0:0:0:0:0:0:0:1]:69999/some/fake/path", - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://[0:0:0:0:0:0:0:1]:69999/some/fake/path", - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess("https://[0:0:0:0:0:0:0:1]:69999/some/fake/path", frozenMetav1Now, 0), []metav1.Condition{ @@ -803,7 +803,7 @@ func TestController(t *testing.T) { name: "validateConnection: CA does not validate serving certificate for host, the dialer will error, will fail sync loop, will write failed and unknown status conditions, but will not enqueue a resync due to user config error", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -812,12 +812,12 @@ func TestController(t *testing.T) { }, wantSyncLoopErr: testutil.WantExactErrorString("cannot dial server: tls: failed to verify certificate: x509: certificate signed by unknown authority"), wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: badWebhookAuthenticatorSpecGoodEndpointButUnknownCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), []metav1.Condition{ @@ -845,7 +845,7 @@ func TestController(t *testing.T) { name: "validateConnection: 404 endpoint on a valid server will still validate server certificate, will complete sync loop successfully with success conditions and ready phase", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, @@ -865,12 +865,12 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWith404Endpoint, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpointBut404, frozenMetav1Now, 0), Phase: "Ready", }, @@ -888,18 +888,18 @@ func TestController(t *testing.T) { name: "validateConnection: localhost hostname instead of 127.0.0.1 should still dial correctly as dialer should handle hostnames as well as IPv4", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: fmt.Sprintf("https://localhost:%s", localhostURL.Port()), - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ // CA Bundle for validating the server's certs CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAsHostname.Bundle()), }, }, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(fmt.Sprintf("https://localhost:%s", localhostURL.Port()), frozenMetav1Now, 0), Phase: "Ready", }, @@ -929,30 +929,30 @@ func TestController(t *testing.T) { name: "validateConnection: IPv6 address with port: should call dialer func with correct arguments", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://[0:0:0:0:0:0:0:1]:4242/some/fake/path", - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://[0:0:0:0:0:0:0:1]:4242/some/fake/path", - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess("https://[0:0:0:0:0:0:0:1]:4242/some/fake/path", frozenMetav1Now, 0), []metav1.Condition{ @@ -978,30 +978,30 @@ func TestController(t *testing.T) { name: "validateConnection: IPv6 address without port: should call dialer func with correct arguments", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://[0:0:0:0:0:0:0:1]/some/fake/path", - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://[0:0:0:0:0:0:0:1]/some/fake/path", - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess("https://[0:0:0:0:0:0:0:1]/some/fake/path", frozenMetav1Now, 0), []metav1.Condition{ @@ -1027,17 +1027,17 @@ func TestController(t *testing.T) { name: "validateConnection: localhost as IP address 127.0.0.1 should still dial correctly as dialer should handle hostnames as well as IPv4 and IPv6 addresses", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: hostAs127001WebhookServer.URL, - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(hostAs127001WebhookServer.URL, frozenMetav1Now, 0), Phase: "Ready", }, @@ -1067,24 +1067,24 @@ func TestController(t *testing.T) { name: "validateConnection: CA for example.com, serving cert for example.com, but endpoint 127.0.0.1 will fail to validate certificate and will fail sync loop and will report failed and unknown conditions and Error phase, but will not enqueue a resync due to user config error", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: localWithExampleDotComWeebhookAuthenticatorSpec, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(hostLocalWithExampleDotComCertServer.URL, frozenMetav1Now, 0), Phase: "Ready", }, }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: localWithExampleDotComWeebhookAuthenticatorSpec, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(hostLocalWithExampleDotComCertServer.URL, frozenMetav1Now, 0), []metav1.Condition{ @@ -1110,30 +1110,30 @@ func TestController(t *testing.T) { name: "validateConnection: IPv6 address without port or brackets: should succeed since IPv6 brackets are optional without port", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://0:0:0:0:0:0:0:1/some/fake/path", - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, - Spec: auth1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://0:0:0:0:0:0:0:1/some/fake/path", - TLS: &auth1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(caForLocalhostAs127001.Bundle()), }, }, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess("https://0:0:0:0:0:0:0:1/some/fake/path", frozenMetav1Now, 0), []metav1.Condition{ @@ -1159,12 +1159,12 @@ func TestController(t *testing.T) { name: "updateStatus: called with matching original and updated conditions: will not make request to update conditions", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), Phase: "Ready", }, @@ -1194,12 +1194,12 @@ func TestController(t *testing.T) { name: "updateStatus: called with different original and updated conditions: will make request to update conditions", syncKey: controllerlib.Key{Name: "test-name"}, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), []metav1.Condition{ @@ -1223,12 +1223,12 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), Phase: "Ready", }, @@ -1255,12 +1255,12 @@ func TestController(t *testing.T) { ) }, webhooks: []runtime.Object{ - &auth1alpha1.WebhookAuthenticator{ + &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: conditionstestutil.Replace( allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), []metav1.Condition{ @@ -1284,12 +1284,12 @@ func TestController(t *testing.T) { }, }, wantActions: func() []coretesting.Action { - updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &auth1alpha1.WebhookAuthenticator{ + updateStatusAction := coretesting.NewUpdateAction(webhookAuthenticatorGVR, "", &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: metav1.ObjectMeta{ Name: "test-name", }, Spec: goodWebhookAuthenticatorSpecWithCA, - Status: auth1alpha1.WebhookAuthenticatorStatus{ + Status: authenticationv1alpha1.WebhookAuthenticatorStatus{ Conditions: allHappyConditionsSuccess(goodWebhookDefaultServingCertEndpoint, frozenMetav1Now, 0), Phase: "Ready", }, diff --git a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go index 2a127d450..df86e06ac 100644 --- a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go +++ b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go @@ -1,4 +1,4 @@ -// Copyright 2021-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package activedirectoryupstreamwatcher implements a controller which watches ActiveDirectoryIdentityProviders. @@ -20,7 +20,7 @@ import ( corev1informers "k8s.io/client-go/informers/core/v1" "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" - supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controller/conditionsutil" @@ -232,7 +232,7 @@ type activeDirectoryWatcherController struct { cache UpstreamActiveDirectoryIdentityProviderICache validatedSettingsCache upstreamwatchers.ValidatedSettingsCacheI ldapDialer upstreamldap.LDAPDialer - client supervisorclientset.Interface + client pinnipedsupervisorclientset.Interface activeDirectoryIdentityProviderInformer idpinformers.ActiveDirectoryIdentityProviderInformer secretInformer corev1informers.SecretInformer } @@ -240,7 +240,7 @@ type activeDirectoryWatcherController struct { // New instantiates a new controllerlib.Controller which will populate the provided UpstreamActiveDirectoryIdentityProviderICache. func New( idpCache UpstreamActiveDirectoryIdentityProviderICache, - client supervisorclientset.Interface, + client pinnipedsupervisorclientset.Interface, activeDirectoryIdentityProviderInformer idpinformers.ActiveDirectoryIdentityProviderInformer, secretInformer corev1informers.SecretInformer, withInformer pinnipedcontroller.WithInformerOptionFunc, @@ -263,7 +263,7 @@ func newInternal( idpCache UpstreamActiveDirectoryIdentityProviderICache, validatedSettingsCache upstreamwatchers.ValidatedSettingsCacheI, ldapDialer upstreamldap.LDAPDialer, - client supervisorclientset.Interface, + client pinnipedsupervisorclientset.Interface, activeDirectoryIdentityProviderInformer idpinformers.ActiveDirectoryIdentityProviderInformer, secretInformer corev1informers.SecretInformer, withInformer pinnipedcontroller.WithInformerOptionFunc, diff --git a/internal/controller/supervisorconfig/federation_domain_watcher.go b/internal/controller/supervisorconfig/federation_domain_watcher.go index 643309bf4..9b41135bf 100644 --- a/internal/controller/supervisorconfig/federation_domain_watcher.go +++ b/internal/controller/supervisorconfig/federation_domain_watcher.go @@ -22,7 +22,7 @@ import ( "k8s.io/utils/clock" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" "go.pinniped.dev/internal/celtransformer" @@ -82,7 +82,7 @@ type federationDomainWatcherController struct { federationDomainsSetter FederationDomainsSetter apiGroup string clock clock.Clock - client supervisorclientset.Interface + client pinnipedsupervisorclientset.Interface federationDomainInformer configinformers.FederationDomainInformer oidcIdentityProviderInformer idpinformers.OIDCIdentityProviderInformer @@ -99,7 +99,7 @@ func NewFederationDomainWatcherController( federationDomainsSetter FederationDomainsSetter, apiGroupSuffix string, clock clock.Clock, - client supervisorclientset.Interface, + client pinnipedsupervisorclientset.Interface, federationDomainInformer configinformers.FederationDomainInformer, oidcIdentityProviderInformer idpinformers.OIDCIdentityProviderInformer, ldapIdentityProviderInformer idpinformers.LDAPIdentityProviderInformer, diff --git a/internal/controller/supervisorconfig/generator/federation_domain_secrets.go b/internal/controller/supervisorconfig/generator/federation_domain_secrets.go index 4b511ca6c..a8c9c6373 100644 --- a/internal/controller/supervisorconfig/generator/federation_domain_secrets.go +++ b/internal/controller/supervisorconfig/generator/federation_domain_secrets.go @@ -17,7 +17,7 @@ import ( "k8s.io/klog/v2" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controllerlib" @@ -28,7 +28,7 @@ type federationDomainSecretsController struct { secretHelper SecretHelper secretRefFunc func(domain *configv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference kubeClient kubernetes.Interface - pinnipedClient supervisorclientset.Interface + pinnipedClient pinnipedsupervisorclientset.Interface federationDomainInformer configinformers.FederationDomainInformer secretInformer corev1informers.SecretInformer } @@ -40,7 +40,7 @@ func NewFederationDomainSecretsController( secretHelper SecretHelper, secretRefFunc func(domain *configv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference, kubeClient kubernetes.Interface, - pinnipedClient supervisorclientset.Interface, + pinnipedClient pinnipedsupervisorclientset.Interface, secretInformer corev1informers.SecretInformer, federationDomainInformer configinformers.FederationDomainInformer, withInformer pinnipedcontroller.WithInformerOptionFunc, diff --git a/internal/controller/supervisorconfig/jwks_writer.go b/internal/controller/supervisorconfig/jwks_writer.go index a5918972d..df4666ba7 100644 --- a/internal/controller/supervisorconfig/jwks_writer.go +++ b/internal/controller/supervisorconfig/jwks_writer.go @@ -23,7 +23,7 @@ import ( "k8s.io/klog/v2" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controller/supervisorconfig/generator" @@ -60,7 +60,7 @@ func generateECKey(r io.Reader) (interface{}, error) { // secrets, both via a cache and via the API. type jwksWriterController struct { jwksSecretLabels map[string]string - pinnipedClient supervisorclientset.Interface + pinnipedClient pinnipedsupervisorclientset.Interface kubeClient kubernetes.Interface federationDomainInformer configinformers.FederationDomainInformer secretInformer corev1informers.SecretInformer @@ -71,7 +71,7 @@ type jwksWriterController struct { func NewJWKSWriterController( jwksSecretLabels map[string]string, kubeClient kubernetes.Interface, - pinnipedClient supervisorclientset.Interface, + pinnipedClient pinnipedsupervisorclientset.Interface, secretInformer corev1informers.SecretInformer, federationDomainInformer configinformers.FederationDomainInformer, withInformer pinnipedcontroller.WithInformerOptionFunc, diff --git a/internal/federationdomain/clientregistry/clientregistry_test.go b/internal/federationdomain/clientregistry/clientregistry_test.go index 1d8f20612..3484c6988 100644 --- a/internal/federationdomain/clientregistry/clientregistry_test.go +++ b/internal/federationdomain/clientregistry/clientregistry_test.go @@ -10,7 +10,7 @@ import ( "testing" "time" - "github.com/coreos/go-oidc/v3/oidc" + coreosoidc "github.com/coreos/go-oidc/v3/oidc" "github.com/ory/fosite" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -294,7 +294,7 @@ func requireEqualsPinnipedCLI(t *testing.T, c *Client) { require.Equal(t, []string{"http://127.0.0.1/callback"}, c.GetRedirectURIs()) require.Equal(t, fosite.Arguments{"authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:token-exchange"}, c.GetGrantTypes()) require.Equal(t, fosite.Arguments{"code"}, c.GetResponseTypes()) - require.Equal(t, fosite.Arguments{oidc.ScopeOpenID, oidc.ScopeOfflineAccess, "profile", "email", "pinniped:request-audience", "username", "groups"}, c.GetScopes()) + require.Equal(t, fosite.Arguments{coreosoidc.ScopeOpenID, coreosoidc.ScopeOfflineAccess, "profile", "email", "pinniped:request-audience", "username", "groups"}, c.GetScopes()) require.True(t, c.IsPublic()) require.Nil(t, c.GetAudience()) require.Nil(t, c.GetRequestURIs()) diff --git a/internal/federationdomain/endpoints/tokenexchange/token_exchange.go b/internal/federationdomain/endpoints/tokenexchange/token_exchange.go index 61a67e367..b3032be19 100644 --- a/internal/federationdomain/endpoints/tokenexchange/token_exchange.go +++ b/internal/federationdomain/endpoints/tokenexchange/token_exchange.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package tokenexchange @@ -9,7 +9,7 @@ import ( "strings" "github.com/ory/fosite" - "github.com/ory/fosite/handler/oauth2" + fositeoauth2 "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/handler/openid" "github.com/pkg/errors" @@ -30,16 +30,16 @@ type stsParams struct { func HandlerFactory(config fosite.Configurator, storage interface{}, strategy interface{}) interface{} { return &tokenExchangeHandler{ idTokenStrategy: strategy.(openid.OpenIDConnectTokenStrategy), - accessTokenStrategy: strategy.(oauth2.AccessTokenStrategy), - accessTokenStorage: storage.(oauth2.AccessTokenStorage), + accessTokenStrategy: strategy.(fositeoauth2.AccessTokenStrategy), + accessTokenStorage: storage.(fositeoauth2.AccessTokenStorage), fositeConfig: config, } } type tokenExchangeHandler struct { idTokenStrategy openid.OpenIDConnectTokenStrategy - accessTokenStrategy oauth2.AccessTokenStrategy - accessTokenStorage oauth2.AccessTokenStorage + accessTokenStrategy fositeoauth2.AccessTokenStrategy + accessTokenStorage fositeoauth2.AccessTokenStorage fositeConfig fosite.Configurator } diff --git a/internal/federationdomain/storage/kube_storage.go b/internal/federationdomain/storage/kube_storage.go index 3ffe1b0df..c75053ccb 100644 --- a/internal/federationdomain/storage/kube_storage.go +++ b/internal/federationdomain/storage/kube_storage.go @@ -8,7 +8,7 @@ import ( "time" "github.com/ory/fosite" - "github.com/ory/fosite/handler/oauth2" + fositeoauth2 "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/handler/openid" fositepkce "github.com/ory/fosite/handler/pkce" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" @@ -27,7 +27,7 @@ import ( type KubeStorage struct { clientManager fosite.ClientManager - authorizationCodeStorage oauth2.AuthorizeCodeStorage + authorizationCodeStorage fositeoauth2.AuthorizeCodeStorage pkceStorage fositepkce.PKCERequestStorage oidcStorage openid.OpenIDConnectRequestStorage accessTokenStorage accesstoken.RevocationStorage diff --git a/internal/federationdomain/strategy/dynamic_oauth2_hmac_strategy.go b/internal/federationdomain/strategy/dynamic_oauth2_hmac_strategy.go index 200dd41c9..ee432d439 100644 --- a/internal/federationdomain/strategy/dynamic_oauth2_hmac_strategy.go +++ b/internal/federationdomain/strategy/dynamic_oauth2_hmac_strategy.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package strategy @@ -9,7 +9,7 @@ import ( "github.com/ory/fosite" "github.com/ory/fosite/compose" - "github.com/ory/fosite/handler/oauth2" + fositeoauth2 "github.com/ory/fosite/handler/oauth2" errorsx "github.com/pkg/errors" "go.pinniped.dev/internal/federationdomain/storage" @@ -44,7 +44,7 @@ type DynamicOauth2HMACStrategy struct { keyFunc func() []byte } -var _ oauth2.CoreStrategy = &DynamicOauth2HMACStrategy{} +var _ fositeoauth2.CoreStrategy = &DynamicOauth2HMACStrategy{} func NewDynamicOauth2HMACStrategy( fositeConfig *fosite.Config, @@ -156,6 +156,6 @@ func (s *DynamicOauth2HMACStrategy) ValidateAuthorizeCode( return s.delegate().ValidateAuthorizeCode(ctx, requester, replacePrefix(token, pinAuthcodePrefix, oryAuthcodePrefix)) } -func (s *DynamicOauth2HMACStrategy) delegate() *oauth2.HMACSHAStrategy { +func (s *DynamicOauth2HMACStrategy) delegate() *fositeoauth2.HMACSHAStrategy { return compose.NewOAuth2HMACStrategy(storage.NewDynamicGlobalSecretConfig(s.fositeConfig, s.keyFunc)) } diff --git a/internal/fositestorage/accesstoken/accesstoken.go b/internal/fositestorage/accesstoken/accesstoken.go index b95e47c09..eda7ce925 100644 --- a/internal/fositestorage/accesstoken/accesstoken.go +++ b/internal/fositestorage/accesstoken/accesstoken.go @@ -9,7 +9,7 @@ import ( "time" "github.com/ory/fosite" - "github.com/ory/fosite/handler/oauth2" + fositeoauth2 "github.com/ory/fosite/handler/oauth2" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" @@ -39,7 +39,7 @@ const ( ) type RevocationStorage interface { - oauth2.AccessTokenStorage + fositeoauth2.AccessTokenStorage RevokeAccessToken(ctx context.Context, requestID string) error } diff --git a/internal/fositestorage/authorizationcode/authorizationcode.go b/internal/fositestorage/authorizationcode/authorizationcode.go index 5b19a217e..189a9ce35 100644 --- a/internal/fositestorage/authorizationcode/authorizationcode.go +++ b/internal/fositestorage/authorizationcode/authorizationcode.go @@ -10,7 +10,7 @@ import ( "time" "github.com/ory/fosite" - "github.com/ory/fosite/handler/oauth2" + fositeoauth2 "github.com/ory/fosite/handler/oauth2" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" @@ -39,7 +39,7 @@ const ( authorizeCodeStorageVersion = "7" ) -var _ oauth2.AuthorizeCodeStorage = &authorizeCodeStorage{} +var _ fositeoauth2.AuthorizeCodeStorage = &authorizeCodeStorage{} type authorizeCodeStorage struct { storage crud.Storage @@ -52,7 +52,7 @@ type Session struct { Version string `json:"version"` } -func New(secrets corev1client.SecretInterface, clock func() time.Time, sessionStorageLifetime timeouts.StorageLifetime) oauth2.AuthorizeCodeStorage { +func New(secrets corev1client.SecretInterface, clock func() time.Time, sessionStorageLifetime timeouts.StorageLifetime) fositeoauth2.AuthorizeCodeStorage { return &authorizeCodeStorage{storage: crud.New(TypeLabelValue, secrets, clock), lifetime: sessionStorageLifetime} } diff --git a/internal/fositestorage/authorizationcode/authorizationcode_test.go b/internal/fositestorage/authorizationcode/authorizationcode_test.go index f39e5580a..feba59615 100644 --- a/internal/fositestorage/authorizationcode/authorizationcode_test.go +++ b/internal/fositestorage/authorizationcode/authorizationcode_test.go @@ -18,7 +18,7 @@ import ( "github.com/go-jose/go-jose/v3" fuzz "github.com/google/gofuzz" "github.com/ory/fosite" - "github.com/ory/fosite/handler/oauth2" + fositeoauth2 "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/handler/openid" "github.com/ory/fosite/token/jwt" "github.com/pkg/errors" @@ -276,7 +276,7 @@ func TestCreateWithWrongRequesterDataTypes(t *testing.T) { require.EqualError(t, err, "requester's client must be of type clientregistry.Client") } -func makeTestSubject(lifetimeFunc timeouts.StorageLifetime) (context.Context, *fake.Clientset, corev1client.SecretInterface, oauth2.AuthorizeCodeStorage) { +func makeTestSubject(lifetimeFunc timeouts.StorageLifetime) (context.Context, *fake.Clientset, corev1client.SecretInterface, fositeoauth2.AuthorizeCodeStorage) { client := fake.NewSimpleClientset() secrets := client.CoreV1().Secrets(namespace) return context.Background(), diff --git a/internal/fositestorage/refreshtoken/refreshtoken.go b/internal/fositestorage/refreshtoken/refreshtoken.go index 13389afc0..0e74d7167 100644 --- a/internal/fositestorage/refreshtoken/refreshtoken.go +++ b/internal/fositestorage/refreshtoken/refreshtoken.go @@ -9,7 +9,7 @@ import ( "time" "github.com/ory/fosite" - "github.com/ory/fosite/handler/oauth2" + fositeoauth2 "github.com/ory/fosite/handler/oauth2" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" @@ -39,7 +39,7 @@ const ( ) type RevocationStorage interface { - oauth2.RefreshTokenStorage + fositeoauth2.RefreshTokenStorage RevokeRefreshToken(ctx context.Context, requestID string) error RevokeRefreshTokenMaybeGracePeriod(ctx context.Context, requestID string, signature string) error } diff --git a/internal/fositestoragei/fosite_storage_interface.go b/internal/fositestoragei/fosite_storage_interface.go index 408dfb28c..39ee4589d 100644 --- a/internal/fositestoragei/fosite_storage_interface.go +++ b/internal/fositestoragei/fosite_storage_interface.go @@ -1,11 +1,11 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package fositestoragei import ( "github.com/ory/fosite" - "github.com/ory/fosite/handler/oauth2" + fositeoauth2 "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/handler/openid" "github.com/ory/fosite/handler/pkce" ) @@ -14,8 +14,8 @@ import ( // Not having this interface makes it a pain to avoid cyclical test dependencies, so we'll define it. type AllFositeStorage interface { fosite.ClientManager - oauth2.CoreStorage - oauth2.TokenRevocationStorage + fositeoauth2.CoreStorage + fositeoauth2.TokenRevocationStorage openid.OpenIDConnectRequestStorage pkce.PKCERequestStorage } diff --git a/internal/groupsuffix/groupsuffix_test.go b/internal/groupsuffix/groupsuffix_test.go index bf7f3af4d..8a40084f5 100644 --- a/internal/groupsuffix/groupsuffix_test.go +++ b/internal/groupsuffix/groupsuffix_test.go @@ -14,7 +14,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" - authv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" "go.pinniped.dev/internal/kubeclient" @@ -154,11 +154,11 @@ func TestMiddlware(t *testing.T) { ) tokenCredentialRequestWithPinnipedAuthenticator := with( tokenCredentialRequest, - authenticatorAPIGroup(authv1alpha1.SchemeGroupVersion.Group), + authenticatorAPIGroup(authenticationv1alpha1.SchemeGroupVersion.Group), ) tokenCredentialRequestWithCustomAPIGroupAuthenticator := with( tokenCredentialRequest, - authenticatorAPIGroup(replaceGV(t, authv1alpha1.SchemeGroupVersion, newSuffix).Group), + authenticatorAPIGroup(replaceGV(t, authenticationv1alpha1.SchemeGroupVersion, newSuffix).Group), ) tokenCredentialRequestWithNewGroup := with( tokenCredentialRequest, @@ -166,11 +166,11 @@ func TestMiddlware(t *testing.T) { ) tokenCredentialRequestWithNewGroupAndPinnipedAuthenticator := with( tokenCredentialRequestWithNewGroup, - authenticatorAPIGroup(authv1alpha1.SchemeGroupVersion.Group), + authenticatorAPIGroup(authenticationv1alpha1.SchemeGroupVersion.Group), ) tokenCredentialRequestWithNewGroupAndCustomAPIGroupAuthenticator := with( tokenCredentialRequestWithNewGroup, - authenticatorAPIGroup(replaceGV(t, authv1alpha1.SchemeGroupVersion, newSuffix).Group), + authenticatorAPIGroup(replaceGV(t, authenticationv1alpha1.SchemeGroupVersion, newSuffix).Group), ) tests := []struct { diff --git a/internal/supervisor/server/server.go b/internal/supervisor/server/server.go index 7f3925c11..1be051b6e 100644 --- a/internal/supervisor/server/server.go +++ b/internal/supervisor/server/server.go @@ -39,7 +39,7 @@ import ( "k8s.io/utils/clock" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/typed/config/v1alpha1" supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" supervisoropenapi "go.pinniped.dev/generated/latest/client/supervisor/openapi" @@ -141,7 +141,7 @@ func prepareControllers( secretCache *secret.Cache, supervisorDeployment *appsv1.Deployment, kubeClient kubernetes.Interface, - pinnipedClient supervisorclientset.Interface, + pinnipedClient pinnipedsupervisorclientset.Interface, aggregatorClient aggregatorclient.Interface, kubeInformers k8sinformers.SharedInformerFactory, pinnipedInformers supervisorinformers.SharedInformerFactory, diff --git a/internal/testutil/assertions.go b/internal/testutil/assertions.go index ec4211c1d..e104f7a7b 100644 --- a/internal/testutil/assertions.go +++ b/internal/testutil/assertions.go @@ -12,7 +12,7 @@ import ( "time" "github.com/stretchr/testify/require" - v12 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" v1 "k8s.io/client-go/kubernetes/typed/core/v1" @@ -49,7 +49,7 @@ func RequireEqualContentType(t *testing.T, actual string, expected string) { func RequireNumberOfSecretsMatchingLabelSelector(t *testing.T, secrets v1.SecretInterface, labelSet labels.Set, expectedNumberOfSecrets int) { t.Helper() - storedAuthcodeSecrets, err := secrets.List(context.Background(), v12.ListOptions{ + storedAuthcodeSecrets, err := secrets.List(context.Background(), metav1.ListOptions{ LabelSelector: labelSet.String(), }) require.NoError(t, err) @@ -66,7 +66,7 @@ func RequireNumberOfSecretsExcludingLabelSelector(t *testing.T, secrets v1.Secre selector = selector.Add(*requirement) } - storedAuthcodeSecrets, err := secrets.List(context.Background(), v12.ListOptions{ + storedAuthcodeSecrets, err := secrets.List(context.Background(), metav1.ListOptions{ LabelSelector: selector.String(), }) require.NoError(t, err) diff --git a/internal/testutil/conciergetestutil/tlstestutil.go b/internal/testutil/conciergetestutil/tlstestutil.go index f99ba4e86..1f275c89f 100644 --- a/internal/testutil/conciergetestutil/tlstestutil.go +++ b/internal/testutil/conciergetestutil/tlstestutil.go @@ -8,10 +8,10 @@ import ( "encoding/base64" "encoding/pem" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" ) -func TLSSpecFromTLSConfig(tls *tls.Config) *auth1alpha1.TLSSpec { +func TLSSpecFromTLSConfig(tls *tls.Config) *authenticationv1alpha1.TLSSpec { pemData := make([]byte, 0) for _, certificate := range tls.Certificates { // this is the public part of the certificate, the private is the certificate.PrivateKey @@ -22,7 +22,7 @@ func TLSSpecFromTLSConfig(tls *tls.Config) *auth1alpha1.TLSSpec { })...) } } - return &auth1alpha1.TLSSpec{ + return &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(pemData), } } diff --git a/internal/testutil/kube_server_compatibility.go b/internal/testutil/kube_server_compatibility.go index f4a5275e0..91764e57f 100644 --- a/internal/testutil/kube_server_compatibility.go +++ b/internal/testutil/kube_server_compatibility.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" certificatesv1 "k8s.io/api/certificates/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/discovery" ) @@ -66,7 +66,7 @@ func CheckServiceAccountExtraFieldsAccountingForChangesInK8s1_30[M ~map[string]V t *testing.T, discoveryClient discovery.DiscoveryInterface, actualExtras M, - expectedPodValues *v1.Pod, + expectedPodValues *corev1.Pod, ) { t.Helper() diff --git a/internal/upstreamoidc/upstreamoidc_test.go b/internal/upstreamoidc/upstreamoidc_test.go index 904bf6b21..58f228fa8 100644 --- a/internal/upstreamoidc/upstreamoidc_test.go +++ b/internal/upstreamoidc/upstreamoidc_test.go @@ -16,7 +16,7 @@ import ( "time" "unsafe" - "github.com/coreos/go-oidc/v3/oidc" + coreosoidc "github.com/coreos/go-oidc/v3/oidc" "github.com/go-jose/go-jose/v3" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" @@ -108,7 +108,7 @@ func TestProviderConfig(t *testing.T) { wantToken oidctypes.Token rawClaims []byte - userInfo *oidc.UserInfo + userInfo *coreosoidc.UserInfo userInfoErr error wantUserInfoCalled bool }{ @@ -204,7 +204,7 @@ func TestProviderConfig(t *testing.T) { name: "user info sub error", returnIDTok: validIDToken, wantErr: "could not fetch user info claims: userinfo 'sub' claim (test-user-2) did not match id_token 'sub' claim (test-user)", - userInfo: &oidc.UserInfo{Subject: "test-user-2"}, + userInfo: &coreosoidc.UserInfo{Subject: "test-user-2"}, }, { name: "user info is not json", @@ -746,7 +746,7 @@ func TestProviderConfig(t *testing.T) { nonce nonce.Nonce requireIDToken bool requireUserInfo bool - userInfo *oidc.UserInfo + userInfo *coreosoidc.UserInfo rawClaims []byte userInfoErr error wantErr string @@ -1127,7 +1127,7 @@ func TestProviderConfig(t *testing.T) { wantToken oidctypes.Token rawClaims []byte - userInfo *oidc.UserInfo + userInfo *coreosoidc.UserInfo userInfoErr error wantUserInfoCalled bool }{ @@ -1260,7 +1260,7 @@ func TestProviderConfig(t *testing.T) { authCode: "valid", returnIDTok: validIDToken, wantErr: "could not fetch user info claims: userinfo 'sub' claim (test-user-2) did not match id_token 'sub' claim (test-user)", - userInfo: &oidc.UserInfo{Subject: "test-user-2"}, + userInfo: &coreosoidc.UserInfo{Subject: "test-user-2"}, }, { name: "user info is not json", @@ -1407,8 +1407,8 @@ func TestProviderConfig(t *testing.T) { }) } -// mockVerifier returns an *oidc.IDTokenVerifier that validates any correctly serialized JWT without doing much else. -func mockVerifier() *oidc.IDTokenVerifier { +// mockVerifier returns an *coreosoidc.IDTokenVerifier that validates any correctly serialized JWT without doing much else. +func mockVerifier() *coreosoidc.IDTokenVerifier { mockKeySet := mockkeyset.NewMockKeySet(gomock.NewController(nil)) mockKeySet.EXPECT().VerifySignature(gomock.Any(), gomock.Any()). AnyTimes(). @@ -1420,7 +1420,7 @@ func mockVerifier() *oidc.IDTokenVerifier { return jws.UnsafePayloadWithoutVerification(), nil }) - return oidc.NewVerifier("", mockKeySet, &oidc.Config{ + return coreosoidc.NewVerifier("", mockKeySet, &coreosoidc.Config{ SkipIssuerCheck: true, SkipExpiryCheck: true, SkipClientIDCheck: true, @@ -1430,17 +1430,19 @@ func mockVerifier() *oidc.IDTokenVerifier { type mockProvider struct { called bool rawClaims []byte - userInfo *oidc.UserInfo + userInfo *coreosoidc.UserInfo userInfoErr error } -func (m *mockProvider) Verifier(_ *oidc.Config) *oidc.IDTokenVerifier { return mockVerifier() } +func (m *mockProvider) Verifier(_ *coreosoidc.Config) *coreosoidc.IDTokenVerifier { + return mockVerifier() +} func (m *mockProvider) Claims(v interface{}) error { return json.Unmarshal(m.rawClaims, v) } -func (m *mockProvider) UserInfo(_ context.Context, tokenSource oauth2.TokenSource) (*oidc.UserInfo, error) { +func (m *mockProvider) UserInfo(_ context.Context, tokenSource oauth2.TokenSource) (*coreosoidc.UserInfo, error) { m.called = true token, err := tokenSource.Token() @@ -1454,8 +1456,8 @@ func (m *mockProvider) UserInfo(_ context.Context, tokenSource oauth2.TokenSourc return m.userInfo, m.userInfoErr } -func forceUserInfoWithClaims(subject string, claims string) *oidc.UserInfo { - userInfo := &oidc.UserInfo{Subject: subject} +func forceUserInfoWithClaims(subject string, claims string) *coreosoidc.UserInfo { + userInfo := &coreosoidc.UserInfo{Subject: subject} // this is some dark magic to set a private field claimsField := reflect.ValueOf(userInfo).Elem().FieldByName("claims") diff --git a/pkg/conciergeclient/conciergeclient.go b/pkg/conciergeclient/conciergeclient.go index 895089bd8..8c68c691d 100644 --- a/pkg/conciergeclient/conciergeclient.go +++ b/pkg/conciergeclient/conciergeclient.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package conciergeclient provides login helpers for the Pinniped concierge. @@ -18,7 +18,7 @@ import ( "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" "go.pinniped.dev/internal/constable" @@ -49,10 +49,10 @@ func WithAuthenticator(authType, authName string) Option { authenticator := corev1.TypedLocalObjectReference{Name: authName} switch strings.ToLower(authType) { case "webhook": - authenticator.APIGroup = &auth1alpha1.SchemeGroupVersion.Group + authenticator.APIGroup = &authenticationv1alpha1.SchemeGroupVersion.Group authenticator.Kind = "WebhookAuthenticator" case "jwt": - authenticator.APIGroup = &auth1alpha1.SchemeGroupVersion.Group + authenticator.APIGroup = &authenticationv1alpha1.SchemeGroupVersion.Group authenticator.Kind = "JWTAuthenticator" default: return fmt.Errorf(`invalid authenticator type: %q, supported values are "webhook" and "jwt"`, authType) diff --git a/pkg/oidcclient/nonce/nonce_test.go b/pkg/oidcclient/nonce/nonce_test.go index 0ba3a7ce9..2c3d79ec8 100644 --- a/pkg/oidcclient/nonce/nonce_test.go +++ b/pkg/oidcclient/nonce/nonce_test.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package nonce @@ -9,7 +9,7 @@ import ( "net/url" "testing" - "github.com/coreos/go-oidc/v3/oidc" + coreosoidc "github.com/coreos/go-oidc/v3/oidc" "github.com/stretchr/testify/require" "golang.org/x/oauth2" ) @@ -25,10 +25,10 @@ func TestNonce(t *testing.T) { require.NoError(t, err) require.Equal(t, n.String(), authCodeURL.Query().Get("nonce")) - require.Error(t, n.Validate(&oidc.IDToken{})) - require.NoError(t, n.Validate(&oidc.IDToken{Nonce: string(n)})) + require.Error(t, n.Validate(&coreosoidc.IDToken{})) + require.NoError(t, n.Validate(&coreosoidc.IDToken{Nonce: string(n)})) - err = n.Validate(&oidc.IDToken{Nonce: string(n) + "x"}) + err = n.Validate(&coreosoidc.IDToken{Nonce: string(n) + "x"}) require.Error(t, err) require.True(t, errors.As(err, &InvalidNonceError{})) require.Contains(t, err.Error(), string(n)+"x") diff --git a/test/integration/cli_test.go b/test/integration/cli_test.go index f3cf3b80c..ff32f5bea 100644 --- a/test/integration/cli_test.go +++ b/test/integration/cli_test.go @@ -26,7 +26,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/serializer" clientauthenticationv1beta1 "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1" - "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" identityv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/identity/v1alpha1" conciergescheme "go.pinniped.dev/internal/concierge/scheme" "go.pinniped.dev/pkg/oidcclient" @@ -43,7 +43,7 @@ func TestCLIGetKubeconfigStaticToken_Parallel(t *testing.T) { ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Minute) defer cancelFunc() - authenticator := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, v1alpha1.WebhookAuthenticatorPhaseReady) + authenticator := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, authenticationv1alpha1.WebhookAuthenticatorPhaseReady) // Build pinniped CLI. pinnipedExe := testlib.PinnipedCLIPath(t) diff --git a/test/integration/concierge_api_serving_certs_test.go b/test/integration/concierge_api_serving_certs_test.go index 7b35390ae..a91141265 100644 --- a/test/integration/concierge_api_serving_certs_test.go +++ b/test/integration/concierge_api_serving_certs_test.go @@ -12,7 +12,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" "go.pinniped.dev/internal/testutil" "go.pinniped.dev/test/testlib" @@ -83,7 +83,7 @@ func TestAPIServingCertificateAutoCreationAndRotation_Disruptive(t *testing.T) { // Create a testWebhook so we have a legitimate authenticator to pass to the // TokenCredentialRequest API. - testWebhook := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, v1alpha1.WebhookAuthenticatorPhaseReady) + testWebhook := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, authenticationv1alpha1.WebhookAuthenticatorPhaseReady) // Get the initial auto-generated version of the Secret. secret, err := kubeClient.CoreV1().Secrets(env.ConciergeNamespace).Get(ctx, defaultServingCertResourceName, metav1.GetOptions{}) diff --git a/test/integration/concierge_client_test.go b/test/integration/concierge_client_test.go index 6a7ffae76..7ea58ee97 100644 --- a/test/integration/concierge_client_test.go +++ b/test/integration/concierge_client_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" - "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" "go.pinniped.dev/internal/here" "go.pinniped.dev/pkg/conciergeclient" "go.pinniped.dev/test/testlib" @@ -59,7 +59,7 @@ func TestClient(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() - webhook := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, v1alpha1.WebhookAuthenticatorPhaseReady) + webhook := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, authenticationv1alpha1.WebhookAuthenticatorPhaseReady) // Use an invalid certificate/key to validate that the ServerVersion API fails like we assume. invalidClient := testlib.NewClientsetWithCertAndKey(t, testCert, testKey) diff --git a/test/integration/concierge_credentialrequest_test.go b/test/integration/concierge_credentialrequest_test.go index cf3b84191..491f745bc 100644 --- a/test/integration/concierge_credentialrequest_test.go +++ b/test/integration/concierge_credentialrequest_test.go @@ -17,7 +17,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" "go.pinniped.dev/test/testlib" ) @@ -33,7 +33,7 @@ func TestUnsuccessfulCredentialRequest_Parallel(t *testing.T) { loginv1alpha1.TokenCredentialRequestSpec{ Token: env.TestUser.Token, Authenticator: corev1.TypedLocalObjectReference{ - APIGroup: &auth1alpha1.SchemeGroupVersion.Group, + APIGroup: &authenticationv1alpha1.SchemeGroupVersion.Group, Kind: "WebhookAuthenticator", Name: "some-webhook-that-does-not-exist", }, @@ -62,7 +62,7 @@ func TestSuccessfulCredentialRequest_Browser(t *testing.T) { { name: "webhook", authenticator: func(ctx context.Context, t *testing.T) corev1.TypedLocalObjectReference { - return testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, auth1alpha1.WebhookAuthenticatorPhaseReady) + return testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, authenticationv1alpha1.WebhookAuthenticatorPhaseReady) }, token: func(t *testing.T) (string, string, []string) { return testlib.IntegrationEnv(t).TestUser.Token, env.TestUser.ExpectedUsername, env.TestUser.ExpectedGroups @@ -73,7 +73,7 @@ func TestSuccessfulCredentialRequest_Browser(t *testing.T) { authenticator: func(ctx context.Context, t *testing.T) corev1.TypedLocalObjectReference { authenticator := testlib.CreateTestJWTAuthenticatorForCLIUpstream(ctx, t) return corev1.TypedLocalObjectReference{ - APIGroup: &auth1alpha1.SchemeGroupVersion.Group, + APIGroup: &authenticationv1alpha1.SchemeGroupVersion.Group, Kind: "JWTAuthenticator", Name: authenticator.Name, } @@ -148,7 +148,7 @@ func TestFailedCredentialRequestWhenTheRequestIsValidButTheTokenDoesNotAuthentic // TokenCredentialRequest API. ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() - testWebhook := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, auth1alpha1.WebhookAuthenticatorPhaseReady) + testWebhook := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, authenticationv1alpha1.WebhookAuthenticatorPhaseReady) response, err := testlib.CreateTokenCredentialRequest(context.Background(), t, loginv1alpha1.TokenCredentialRequestSpec{Token: "not a good token", Authenticator: testWebhook}, @@ -169,7 +169,7 @@ func TestCredentialRequest_ShouldFailWhenRequestDoesNotIncludeToken_Parallel(t * // TokenCredentialRequest API. ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() - testWebhook := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, auth1alpha1.WebhookAuthenticatorPhaseReady) + testWebhook := testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, authenticationv1alpha1.WebhookAuthenticatorPhaseReady) response, err := testlib.CreateTokenCredentialRequest(context.Background(), t, loginv1alpha1.TokenCredentialRequestSpec{Token: "", Authenticator: testWebhook}, diff --git a/test/integration/concierge_impersonation_proxy_test.go b/test/integration/concierge_impersonation_proxy_test.go index 8713769af..98f6cd2f0 100644 --- a/test/integration/concierge_impersonation_proxy_test.go +++ b/test/integration/concierge_impersonation_proxy_test.go @@ -61,7 +61,7 @@ import ( "k8s.io/client-go/util/retry" "k8s.io/utils/ptr" - "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" conciergev1alpha "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" identityv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/identity/v1alpha1" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" @@ -121,7 +121,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl // Create a WebhookAuthenticator and prepare a TokenCredentialRequestSpec using the authenticator for use later. credentialRequestSpecWithWorkingCredentials := loginv1alpha1.TokenCredentialRequestSpec{ Token: env.TestUser.Token, - Authenticator: testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, v1alpha1.WebhookAuthenticatorPhaseReady), + Authenticator: testlib.CreateTestWebhookAuthenticator(ctx, t, &testlib.IntegrationEnv(t).TestWebhook, authenticationv1alpha1.WebhookAuthenticatorPhaseReady), } // The address of the ClusterIP service that points at the impersonation proxy's port (used when there is no load balancer). diff --git a/test/integration/concierge_jwtauthenticator_status_test.go b/test/integration/concierge_jwtauthenticator_status_test.go index dca246aff..8c77da8ac 100644 --- a/test/integration/concierge_jwtauthenticator_status_test.go +++ b/test/integration/concierge_jwtauthenticator_status_test.go @@ -14,7 +14,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" "go.pinniped.dev/test/testlib" ) @@ -31,13 +31,13 @@ func TestConciergeJWTAuthenticatorStatus_Parallel(t *testing.T) { name: "valid spec with no errors and all good status conditions and phase will result in a jwt authenticator that is ready", run: func(t *testing.T) { caBundleString := base64.StdEncoding.EncodeToString([]byte(env.SupervisorUpstreamOIDC.CABundle)) - jwtAuthenticator := testlib.CreateTestJWTAuthenticator(ctx, t, v1alpha1.JWTAuthenticatorSpec{ + jwtAuthenticator := testlib.CreateTestJWTAuthenticator(ctx, t, authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: env.SupervisorUpstreamOIDC.Issuer, Audience: "some-fake-audience", - TLS: &v1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: caBundleString, }, - }, v1alpha1.JWTAuthenticatorPhaseReady) + }, authenticationv1alpha1.JWTAuthenticatorPhaseReady) testlib.WaitForJWTAuthenticatorStatusConditions( ctx, t, @@ -49,13 +49,13 @@ func TestConciergeJWTAuthenticatorStatus_Parallel(t *testing.T) { name: "valid spec with invalid CA in TLS config will result in a jwt authenticator that is not ready", run: func(t *testing.T) { caBundleString := "invalid base64-encoded data" - jwtAuthenticator := testlib.CreateTestJWTAuthenticator(ctx, t, v1alpha1.JWTAuthenticatorSpec{ + jwtAuthenticator := testlib.CreateTestJWTAuthenticator(ctx, t, authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: env.SupervisorUpstreamOIDC.Issuer, Audience: "some-fake-audience", - TLS: &v1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: caBundleString, }, - }, v1alpha1.JWTAuthenticatorPhaseError) + }, authenticationv1alpha1.JWTAuthenticatorPhaseError) testlib.WaitForJWTAuthenticatorStatusConditions( ctx, t, @@ -102,16 +102,16 @@ func TestConciergeJWTAuthenticatorStatus_Parallel(t *testing.T) { name: "valid spec with valid CA in TLS config but does not match issuer server will result in a jwt authenticator that is not ready", run: func(t *testing.T) { caBundleString := "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURVVENDQWptZ0F3SUJBZ0lWQUpzNStTbVRtaTJXeUI0bGJJRXBXaUs5a1RkUE1BMEdDU3FHU0liM0RRRUIKQ3dVQU1COHhDekFKQmdOVkJBWVRBbFZUTVJBd0RnWURWUVFLREFkUWFYWnZkR0ZzTUI0WERUSXdNRFV3TkRFMgpNamMxT0ZvWERUSTBNRFV3TlRFMk1qYzFPRm93SHpFTE1Ba0dBMVVFQmhNQ1ZWTXhFREFPQmdOVkJBb01CMUJwCmRtOTBZV3d3Z2dFaU1BMEdDU3FHU0liM0RRRUJBUVVBQTRJQkR3QXdnZ0VLQW9JQkFRRERZWmZvWGR4Z2NXTEMKZEJtbHB5a0tBaG9JMlBuUWtsVFNXMno1cGcwaXJjOGFRL1E3MXZzMTRZYStmdWtFTGlvOTRZYWw4R01DdVFrbApMZ3AvUEE5N1VYelhQNDBpK25iNXcwRGpwWWd2dU9KQXJXMno2MFRnWE5NSFh3VHk4ME1SZEhpUFVWZ0VZd0JpCmtkNThzdEFVS1Y1MnBQTU1reTJjNy9BcFhJNmRXR2xjalUvaFBsNmtpRzZ5dEw2REtGYjJQRWV3MmdJM3pHZ2IKOFVVbnA1V05DZDd2WjNVY0ZHNXlsZEd3aGc3cnZ4U1ZLWi9WOEhCMGJmbjlxamlrSVcxWFM4dzdpUUNlQmdQMApYZWhKZmVITlZJaTJtZlczNlVQbWpMdnVKaGpqNDIrdFBQWndvdDkzdWtlcEgvbWpHcFJEVm9wamJyWGlpTUYrCkYxdnlPNGMxQWdNQkFBR2pnWU13Z1lBd0hRWURWUjBPQkJZRUZNTWJpSXFhdVkwajRVWWphWDl0bDJzby9LQ1IKTUI4R0ExVWRJd1FZTUJhQUZNTWJpSXFhdVkwajRVWWphWDl0bDJzby9LQ1JNQjBHQTFVZEpRUVdNQlFHQ0NzRwpBUVVGQndNQ0JnZ3JCZ0VGQlFjREFUQVBCZ05WSFJNQkFmOEVCVEFEQVFIL01BNEdBMVVkRHdFQi93UUVBd0lCCkJqQU5CZ2txaGtpRzl3MEJBUXNGQUFPQ0FRRUFYbEh4M2tIMDZwY2NDTDlEVE5qTnBCYnlVSytGd2R6T2IwWFYKcmpNaGtxdHVmdEpUUnR5T3hKZ0ZKNXhUR3pCdEtKamcrVU1pczBOV0t0VDBNWThVMU45U2c5SDl0RFpHRHBjVQpxMlVRU0Y4dXRQMVR3dnJIUzIrdzB2MUoxdHgrTEFiU0lmWmJCV0xXQ21EODUzRlVoWlFZekkvYXpFM28vd0p1CmlPUklMdUpNUk5vNlBXY3VLZmRFVkhaS1RTWnk3a25FcHNidGtsN3EwRE91eUFWdG9HVnlkb3VUR0FOdFhXK2YKczNUSTJjKzErZXg3L2RZOEJGQTFzNWFUOG5vZnU3T1RTTzdiS1kzSkRBUHZOeFQzKzVZUXJwNGR1Nmh0YUFMbAppOHNaRkhidmxpd2EzdlhxL3p1Y2JEaHEzQzBhZnAzV2ZwRGxwSlpvLy9QUUFKaTZLQT09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K" - jwtAuthenticator := testlib.CreateTestJWTAuthenticator(ctx, t, v1alpha1.JWTAuthenticatorSpec{ + jwtAuthenticator := testlib.CreateTestJWTAuthenticator(ctx, t, authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: env.SupervisorUpstreamOIDC.Issuer, Audience: "some-fake-audience", // Some random generated cert // Issuer: C=US, O=Pivotal // No SAN provided - TLS: &v1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: caBundleString, }, - }, v1alpha1.JWTAuthenticatorPhaseError) + }, authenticationv1alpha1.JWTAuthenticatorPhaseError) testlib.WaitForJWTAuthenticatorStatusConditions( ctx, t, @@ -159,13 +159,13 @@ func TestConciergeJWTAuthenticatorStatus_Parallel(t *testing.T) { run: func(t *testing.T) { caBundleString := base64.StdEncoding.EncodeToString([]byte(env.SupervisorUpstreamOIDC.CABundle)) fakeIssuerURL := "https://127.0.0.1:443/some-fake-issuer" - jwtAuthenticator := testlib.CreateTestJWTAuthenticator(ctx, t, v1alpha1.JWTAuthenticatorSpec{ + jwtAuthenticator := testlib.CreateTestJWTAuthenticator(ctx, t, authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: fakeIssuerURL, Audience: "some-fake-audience", - TLS: &v1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: caBundleString, }, - }, v1alpha1.JWTAuthenticatorPhaseError) + }, authenticationv1alpha1.JWTAuthenticatorPhaseError) testlib.WaitForJWTAuthenticatorStatusConditions( ctx, t, @@ -223,14 +223,14 @@ func TestConciergeJWTAuthenticatorCRDValidations_Parallel(t *testing.T) { objectMeta := testlib.ObjectMetaWithRandomName(t, "jwt-authenticator") tests := []struct { name string - jwtAuthenticator *v1alpha1.JWTAuthenticator + jwtAuthenticator *authenticationv1alpha1.JWTAuthenticator wantErr string }{ { name: "issuer can not be empty string", - jwtAuthenticator: &v1alpha1.JWTAuthenticator{ + jwtAuthenticator: &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: objectMeta, - Spec: v1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "", Audience: "fake-audience", }, @@ -240,9 +240,9 @@ func TestConciergeJWTAuthenticatorCRDValidations_Parallel(t *testing.T) { }, { name: "audience can not be empty string", - jwtAuthenticator: &v1alpha1.JWTAuthenticator{ + jwtAuthenticator: &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: objectMeta, - Spec: v1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "https://example.com", Audience: "", }, @@ -252,9 +252,9 @@ func TestConciergeJWTAuthenticatorCRDValidations_Parallel(t *testing.T) { }, { name: "issuer must be https", - jwtAuthenticator: &v1alpha1.JWTAuthenticator{ + jwtAuthenticator: &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: objectMeta, - Spec: v1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: "http://www.example.com", Audience: "foo", }, @@ -264,9 +264,9 @@ func TestConciergeJWTAuthenticatorCRDValidations_Parallel(t *testing.T) { }, { name: "minimum valid authenticator", - jwtAuthenticator: &v1alpha1.JWTAuthenticator{ + jwtAuthenticator: &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "jwtauthenticator"), - Spec: v1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: env.CLIUpstreamOIDC.Issuer, Audience: "foo", }, @@ -274,23 +274,23 @@ func TestConciergeJWTAuthenticatorCRDValidations_Parallel(t *testing.T) { }, { name: "valid authenticator can have empty claims block", - jwtAuthenticator: &v1alpha1.JWTAuthenticator{ + jwtAuthenticator: &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "jwtauthenticator"), - Spec: v1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: env.CLIUpstreamOIDC.Issuer, Audience: "foo", - Claims: v1alpha1.JWTTokenClaims{}, + Claims: authenticationv1alpha1.JWTTokenClaims{}, }, }, }, { name: "valid authenticator can have empty group claim and empty username claim", - jwtAuthenticator: &v1alpha1.JWTAuthenticator{ + jwtAuthenticator: &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "jwtauthenticator"), - Spec: v1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: env.CLIUpstreamOIDC.Issuer, Audience: "foo", - Claims: v1alpha1.JWTTokenClaims{ + Claims: authenticationv1alpha1.JWTTokenClaims{ Groups: "", Username: "", }, @@ -299,31 +299,31 @@ func TestConciergeJWTAuthenticatorCRDValidations_Parallel(t *testing.T) { }, { name: "valid authenticator can have empty TLS block", - jwtAuthenticator: &v1alpha1.JWTAuthenticator{ + jwtAuthenticator: &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "jwtauthenticator"), - Spec: v1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: env.CLIUpstreamOIDC.Issuer, Audience: "foo", - Claims: v1alpha1.JWTTokenClaims{ + Claims: authenticationv1alpha1.JWTTokenClaims{ Groups: "", Username: "", }, - TLS: &v1alpha1.TLSSpec{}, + TLS: &authenticationv1alpha1.TLSSpec{}, }, }, }, { name: "valid authenticator can have empty TLS CertificateAuthorityData", - jwtAuthenticator: &v1alpha1.JWTAuthenticator{ + jwtAuthenticator: &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "jwtauthenticator"), - Spec: v1alpha1.JWTAuthenticatorSpec{ + Spec: authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: env.CLIUpstreamOIDC.Issuer, Audience: "foo", - Claims: v1alpha1.JWTTokenClaims{ + Claims: authenticationv1alpha1.JWTTokenClaims{ Groups: "", Username: "", }, - TLS: &v1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: "pretend-this-is-a-certificate", }, }, diff --git a/test/integration/concierge_webhookauthenticator_status_test.go b/test/integration/concierge_webhookauthenticator_status_test.go index 6b1e1f937..2a68ec5fa 100644 --- a/test/integration/concierge_webhookauthenticator_status_test.go +++ b/test/integration/concierge_webhookauthenticator_status_test.go @@ -12,7 +12,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" "go.pinniped.dev/test/testlib" ) @@ -25,30 +25,30 @@ func TestConciergeWebhookAuthenticatorStatus_Parallel(t *testing.T) { tests := []struct { name string - spec func() *v1alpha1.WebhookAuthenticatorSpec - initialPhase v1alpha1.WebhookAuthenticatorPhase + spec func() *authenticationv1alpha1.WebhookAuthenticatorSpec + initialPhase authenticationv1alpha1.WebhookAuthenticatorPhase finalConditions []metav1.Condition run func(t *testing.T) }{ { name: "Basic test to see if the WebhookAuthenticator wakes up or not.", - spec: func() *v1alpha1.WebhookAuthenticatorSpec { + spec: func() *authenticationv1alpha1.WebhookAuthenticatorSpec { return &testlib.IntegrationEnv(t).TestWebhook }, - initialPhase: v1alpha1.WebhookAuthenticatorPhaseReady, + initialPhase: authenticationv1alpha1.WebhookAuthenticatorPhaseReady, finalConditions: allSuccessfulWebhookAuthenticatorConditions(), }, { name: "valid spec with invalid CA in TLS config will result in a WebhookAuthenticator that is not ready", - spec: func() *v1alpha1.WebhookAuthenticatorSpec { + spec: func() *authenticationv1alpha1.WebhookAuthenticatorSpec { caBundleString := "invalid base64-encoded data" webhookSpec := testEnv.TestWebhook.DeepCopy() - webhookSpec.TLS = &v1alpha1.TLSSpec{ + webhookSpec.TLS = &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: caBundleString, } return webhookSpec }, - initialPhase: v1alpha1.WebhookAuthenticatorPhaseError, + initialPhase: authenticationv1alpha1.WebhookAuthenticatorPhaseError, finalConditions: replaceSomeConditions( allSuccessfulWebhookAuthenticatorConditions(), []metav1.Condition{ @@ -78,14 +78,14 @@ func TestConciergeWebhookAuthenticatorStatus_Parallel(t *testing.T) { }, { name: "valid spec with valid CA in TLS config but does not match issuer server will result in a WebhookAuthenticator that is not ready", - spec: func() *v1alpha1.WebhookAuthenticatorSpec { + spec: func() *authenticationv1alpha1.WebhookAuthenticatorSpec { webhookSpec := testEnv.TestWebhook.DeepCopy() - webhookSpec.TLS = &v1alpha1.TLSSpec{ + webhookSpec.TLS = &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: caBundleSomePivotalCA, } return webhookSpec }, - initialPhase: v1alpha1.WebhookAuthenticatorPhaseError, + initialPhase: authenticationv1alpha1.WebhookAuthenticatorPhaseError, finalConditions: replaceSomeConditions( allSuccessfulWebhookAuthenticatorConditions(), []metav1.Condition{ @@ -110,15 +110,15 @@ func TestConciergeWebhookAuthenticatorStatus_Parallel(t *testing.T) { }, { name: "invalid with unresponsive endpoint will result in a WebhookAuthenticator that is not ready", - spec: func() *v1alpha1.WebhookAuthenticatorSpec { + spec: func() *authenticationv1alpha1.WebhookAuthenticatorSpec { webhookSpec := testEnv.TestWebhook.DeepCopy() - webhookSpec.TLS = &v1alpha1.TLSSpec{ + webhookSpec.TLS = &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: caBundleSomePivotalCA, } webhookSpec.Endpoint = "https://127.0.0.1:443/some-fake-endpoint" return webhookSpec }, - initialPhase: v1alpha1.WebhookAuthenticatorPhaseError, + initialPhase: authenticationv1alpha1.WebhookAuthenticatorPhaseError, finalConditions: replaceSomeConditions( allSuccessfulWebhookAuthenticatorConditions(), []metav1.Condition{ @@ -171,14 +171,14 @@ func TestConciergeWebhookAuthenticatorCRDValidations_Parallel(t *testing.T) { objectMeta := testlib.ObjectMetaWithRandomName(t, "webhook-authenticator") tests := []struct { name string - webhookAuthenticator *v1alpha1.WebhookAuthenticator + webhookAuthenticator *authenticationv1alpha1.WebhookAuthenticator wantErr string }{ { name: "endpoint can not be empty string", - webhookAuthenticator: &v1alpha1.WebhookAuthenticator{ + webhookAuthenticator: &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: objectMeta, - Spec: v1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "", }, }, @@ -187,9 +187,9 @@ func TestConciergeWebhookAuthenticatorCRDValidations_Parallel(t *testing.T) { }, { name: "endpoint must be https", - webhookAuthenticator: &v1alpha1.WebhookAuthenticator{ + webhookAuthenticator: &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: objectMeta, - Spec: v1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "http://www.example.com", }, }, @@ -198,30 +198,30 @@ func TestConciergeWebhookAuthenticatorCRDValidations_Parallel(t *testing.T) { }, { name: "minimum valid authenticator", - webhookAuthenticator: &v1alpha1.WebhookAuthenticator{ + webhookAuthenticator: &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "webhook"), - Spec: v1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://localhost/webhook-isnt-actually-here", }, }, }, { name: "valid authenticator can have empty TLS block", - webhookAuthenticator: &v1alpha1.WebhookAuthenticator{ + webhookAuthenticator: &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "webhook"), - Spec: v1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://localhost/webhook-isnt-actually-here", - TLS: &v1alpha1.TLSSpec{}, + TLS: &authenticationv1alpha1.TLSSpec{}, }, }, }, { name: "valid authenticator can have empty TLS CertificateAuthorityData", - webhookAuthenticator: &v1alpha1.WebhookAuthenticator{ + webhookAuthenticator: &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "jwtauthenticator"), - Spec: v1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://localhost/webhook-isnt-actually-here", - TLS: &v1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: "", }, }, @@ -230,11 +230,11 @@ func TestConciergeWebhookAuthenticatorCRDValidations_Parallel(t *testing.T) { { // since the CRD validations do not assess fitness of the value provided name: "valid authenticator can have TLS CertificateAuthorityData string that is an invalid certificate", - webhookAuthenticator: &v1alpha1.WebhookAuthenticator{ + webhookAuthenticator: &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "jwtauthenticator"), - Spec: v1alpha1.WebhookAuthenticatorSpec{ + Spec: authenticationv1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://localhost/webhook-isnt-actually-here", - TLS: &v1alpha1.TLSSpec{ + TLS: &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: "pretend-this-is-a-certificate", }, }, diff --git a/test/integration/e2e_test.go b/test/integration/e2e_test.go index b65d0a472..f81206ede 100644 --- a/test/integration/e2e_test.go +++ b/test/integration/e2e_test.go @@ -34,7 +34,7 @@ import ( utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/utils/ptr" - authv1alpha "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" supervisorclient "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/typed/config/v1alpha1" @@ -115,11 +115,11 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Create a JWTAuthenticator that will validate the tokens from the downstream issuer. // If the FederationDomain is not Ready, the JWTAuthenticator cannot be ready, either. clusterAudience := "test-cluster-" + testlib.RandHex(t, 8) - authenticator := testlib.CreateTestJWTAuthenticator(topSetupCtx, t, authv1alpha.JWTAuthenticatorSpec{ + authenticator := testlib.CreateTestJWTAuthenticator(topSetupCtx, t, authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: federationDomain.Spec.Issuer, Audience: clusterAudience, - TLS: &authv1alpha.TLSSpec{CertificateAuthorityData: testCABundleBase64}, - }, authv1alpha.JWTAuthenticatorPhaseError) + TLS: &authenticationv1alpha1.TLSSpec{CertificateAuthorityData: testCABundleBase64}, + }, authenticationv1alpha1.JWTAuthenticatorPhaseError) // Add an OIDC upstream IDP and try using it to authenticate during kubectl commands. t.Run("with Supervisor OIDC upstream IDP and browser flow with with form_post automatic authcode delivery to CLI", func(t *testing.T) { @@ -164,7 +164,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, }, idpv1alpha1.PhaseReady) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -250,7 +250,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, }, idpv1alpha1.PhaseReady) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -338,7 +338,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, }, idpv1alpha1.PhaseReady) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -462,7 +462,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, }, idpv1alpha1.PhaseReady) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -593,7 +593,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, }, idpv1alpha1.PhaseReady) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -666,7 +666,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, }, idpv1alpha1.PhaseReady) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -730,7 +730,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -789,7 +789,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -852,7 +852,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -923,7 +923,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndActiveDirectoryTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -982,7 +982,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndActiveDirectoryTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -1055,7 +1055,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -1110,7 +1110,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndActiveDirectoryTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -1165,7 +1165,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -1242,7 +1242,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Having one IDP should put the FederationDomain into a ready state. testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Create a ClusterRoleBinding to give our test user from the upstream read-only access to the cluster. testlib.CreateTestClusterRoleBinding(t, @@ -1276,7 +1276,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Having a second IDP should put the FederationDomain back into an error state until we tell it which one to use. testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseError) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Update the FederationDomain to use the two IDPs. federationDomainsClient := testlib.NewSupervisorClientset(t).ConfigV1alpha1().FederationDomains(env.SupervisorNamespace) @@ -1371,7 +1371,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // The FederationDomain should be valid after the above update. testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -1505,7 +1505,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, 20*time.Second, 250*time.Millisecond) // The FederationDomain should be valid after the above update. testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Log out so we can try fresh logins again. require.NoError(t, os.Remove(credentialCachePath)) diff --git a/test/integration/supervisor_warnings_test.go b/test/integration/supervisor_warnings_test.go index b07f0a73a..246bad365 100644 --- a/test/integration/supervisor_warnings_test.go +++ b/test/integration/supervisor_warnings_test.go @@ -24,7 +24,7 @@ import ( corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" - authv1alpha "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/certauthority" @@ -93,11 +93,11 @@ func TestSupervisorWarnings_Browser(t *testing.T) { // Create a JWTAuthenticator that will validate the tokens from the downstream issuer. // if the FederationDomain is not Ready, the JWTAuthenticator cannot be ready, either. clusterAudience := "test-cluster-" + testlib.RandHex(t, 8) - authenticator := testlib.CreateTestJWTAuthenticator(ctx, t, authv1alpha.JWTAuthenticatorSpec{ + authenticator := testlib.CreateTestJWTAuthenticator(ctx, t, authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: downstream.Spec.Issuer, Audience: clusterAudience, - TLS: &authv1alpha.TLSSpec{CertificateAuthorityData: testCABundleBase64}, - }, authv1alpha.JWTAuthenticatorPhaseError) + TLS: &authenticationv1alpha1.TLSSpec{CertificateAuthorityData: testCABundleBase64}, + }, authenticationv1alpha1.JWTAuthenticatorPhaseError) const ( yellowColor = "\u001b[33;1m" @@ -111,7 +111,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/ldap-test-refresh-sessions.yaml" @@ -259,7 +259,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { sAMAccountName := expectedUsername + "@" + env.SupervisorUpstreamActiveDirectory.Domain createdProvider := setupClusterForEndToEndActiveDirectoryTest(t, sAMAccountName, env) testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/ldap-test-refresh-sessions.yaml" @@ -421,7 +421,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { }, }, idpv1alpha1.PhaseReady) testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/ldap-test-refresh-sessions.yaml" diff --git a/test/testlib/client.go b/test/testlib/client.go index 406ff5cef..35f4c6d72 100644 --- a/test/testlib/client.go +++ b/test/testlib/client.go @@ -27,7 +27,7 @@ import ( aggregatorclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset" "k8s.io/utils/ptr" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" clientsecretv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/clientsecret/v1alpha1" configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" @@ -174,8 +174,8 @@ func NewKubeclient(t *testing.T, config *rest.Config) *kubeclient.Client { func CreateTestWebhookAuthenticator( ctx context.Context, t *testing.T, - webhookSpec *auth1alpha1.WebhookAuthenticatorSpec, - expectedStatus auth1alpha1.WebhookAuthenticatorPhase) corev1.TypedLocalObjectReference { + webhookSpec *authenticationv1alpha1.WebhookAuthenticatorSpec, + expectedStatus authenticationv1alpha1.WebhookAuthenticatorPhase) corev1.TypedLocalObjectReference { t.Helper() client := NewConciergeClientset(t) @@ -184,7 +184,7 @@ func CreateTestWebhookAuthenticator( createContext, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() - webhook, err := webhooks.Create(createContext, &auth1alpha1.WebhookAuthenticator{ + webhook, err := webhooks.Create(createContext, &authenticationv1alpha1.WebhookAuthenticator{ ObjectMeta: testObjectMeta(t, "webhook"), Spec: *webhookSpec, }, metav1.CreateOptions{}) @@ -205,7 +205,7 @@ func CreateTestWebhookAuthenticator( } return corev1.TypedLocalObjectReference{ - APIGroup: &auth1alpha1.SchemeGroupVersion.Group, + APIGroup: &authenticationv1alpha1.SchemeGroupVersion.Group, Kind: "WebhookAuthenticator", Name: webhook.Name, } @@ -215,7 +215,7 @@ func WaitForWebhookAuthenticatorStatusPhase( ctx context.Context, t *testing.T, webhookName string, - expectPhase auth1alpha1.WebhookAuthenticatorPhase) { + expectPhase authenticationv1alpha1.WebhookAuthenticatorPhase) { t.Helper() webhookAuthenticatorClientSet := NewConciergeClientset(t).AuthenticationV1alpha1().WebhookAuthenticators() @@ -256,25 +256,25 @@ func WaitForWebhookAuthenticatorStatusConditions(ctx context.Context, t *testing // deleted at the end of the current test's lifetime. // // CreateTestJWTAuthenticatorForCLIUpstream gets the OIDC issuer info from IntegrationEnv().CLIUpstreamOIDC. -func CreateTestJWTAuthenticatorForCLIUpstream(ctx context.Context, t *testing.T) *auth1alpha1.JWTAuthenticator { +func CreateTestJWTAuthenticatorForCLIUpstream(ctx context.Context, t *testing.T) *authenticationv1alpha1.JWTAuthenticator { t.Helper() testEnv := IntegrationEnv(t) - spec := auth1alpha1.JWTAuthenticatorSpec{ + spec := authenticationv1alpha1.JWTAuthenticatorSpec{ Issuer: testEnv.CLIUpstreamOIDC.Issuer, Audience: testEnv.CLIUpstreamOIDC.ClientID, // The default UsernameClaim is "username" but the upstreams that we use for // integration tests won't necessarily have that claim, so use "sub" here. - Claims: auth1alpha1.JWTTokenClaims{Username: "sub"}, + Claims: authenticationv1alpha1.JWTTokenClaims{Username: "sub"}, } // If the test upstream does not have a CA bundle specified, then don't configure one in the // JWTAuthenticator. Leaving TLSSpec set to nil will result in OIDC discovery using the OS's root // CA store. if testEnv.CLIUpstreamOIDC.CABundle != "" { - spec.TLS = &auth1alpha1.TLSSpec{ + spec.TLS = &authenticationv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte(testEnv.CLIUpstreamOIDC.CABundle)), } } - authenticator := CreateTestJWTAuthenticator(ctx, t, spec, auth1alpha1.JWTAuthenticatorPhaseReady) + authenticator := CreateTestJWTAuthenticator(ctx, t, spec, authenticationv1alpha1.JWTAuthenticatorPhaseReady) return authenticator } @@ -283,8 +283,8 @@ func CreateTestJWTAuthenticatorForCLIUpstream(ctx context.Context, t *testing.T) func CreateTestJWTAuthenticator( ctx context.Context, t *testing.T, - spec auth1alpha1.JWTAuthenticatorSpec, - expectedStatus auth1alpha1.JWTAuthenticatorPhase) *auth1alpha1.JWTAuthenticator { + spec authenticationv1alpha1.JWTAuthenticatorSpec, + expectedStatus authenticationv1alpha1.JWTAuthenticatorPhase) *authenticationv1alpha1.JWTAuthenticator { t.Helper() client := NewConciergeClientset(t) @@ -293,7 +293,7 @@ func CreateTestJWTAuthenticator( createContext, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() - jwtAuthenticator, err := jwtAuthenticators.Create(createContext, &auth1alpha1.JWTAuthenticator{ + jwtAuthenticator, err := jwtAuthenticators.Create(createContext, &authenticationv1alpha1.JWTAuthenticator{ ObjectMeta: testObjectMeta(t, "jwt-authenticator"), Spec: spec, }, metav1.CreateOptions{}) @@ -314,7 +314,7 @@ func CreateTestJWTAuthenticator( return jwtAuthenticator } -func WaitForJWTAuthenticatorStatusPhase(ctx context.Context, t *testing.T, jwtAuthenticatorName string, expectPhase auth1alpha1.JWTAuthenticatorPhase) { +func WaitForJWTAuthenticatorStatusPhase(ctx context.Context, t *testing.T, jwtAuthenticatorName string, expectPhase authenticationv1alpha1.JWTAuthenticatorPhase) { t.Helper() jwtAuthenticatorClientSet := NewConciergeClientset(t).AuthenticationV1alpha1().JWTAuthenticators() diff --git a/test/testlib/env.go b/test/testlib/env.go index 74ea0ae90..0998c2cfb 100644 --- a/test/testlib/env.go +++ b/test/testlib/env.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testlib @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/require" "sigs.k8s.io/yaml" - auth1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" ) type Capability string @@ -39,22 +39,22 @@ type TestEnv struct { skipPodRestartAssertions bool - ToolsNamespace string `json:"toolsNamespace"` - ConciergeNamespace string `json:"conciergeNamespace"` - SupervisorNamespace string `json:"supervisorNamespace"` - ConciergeAppName string `json:"conciergeAppName"` - SupervisorAppName string `json:"supervisorAppName"` - SupervisorCustomLabels map[string]string `json:"supervisorCustomLabels"` - ConciergeCustomLabels map[string]string `json:"conciergeCustomLabels"` - KubernetesDistribution KubeDistro `json:"kubernetesDistribution"` - Capabilities map[Capability]bool `json:"capabilities"` - TestWebhook auth1alpha1.WebhookAuthenticatorSpec `json:"testWebhook"` - SupervisorHTTPSAddress string `json:"supervisorHttpsAddress"` - SupervisorHTTPSIngressAddress string `json:"supervisorHttpsIngressAddress"` - SupervisorHTTPSIngressCABundle string `json:"supervisorHttpsIngressCABundle"` - Proxy string `json:"proxy"` - APIGroupSuffix string `json:"apiGroupSuffix"` - ShellContainerImage string `json:"shellContainer"` + ToolsNamespace string `json:"toolsNamespace"` + ConciergeNamespace string `json:"conciergeNamespace"` + SupervisorNamespace string `json:"supervisorNamespace"` + ConciergeAppName string `json:"conciergeAppName"` + SupervisorAppName string `json:"supervisorAppName"` + SupervisorCustomLabels map[string]string `json:"supervisorCustomLabels"` + ConciergeCustomLabels map[string]string `json:"conciergeCustomLabels"` + KubernetesDistribution KubeDistro `json:"kubernetesDistribution"` + Capabilities map[Capability]bool `json:"capabilities"` + TestWebhook authenticationv1alpha1.WebhookAuthenticatorSpec `json:"testWebhook"` + SupervisorHTTPSAddress string `json:"supervisorHttpsAddress"` + SupervisorHTTPSIngressAddress string `json:"supervisorHttpsIngressAddress"` + SupervisorHTTPSIngressCABundle string `json:"supervisorHttpsIngressCABundle"` + Proxy string `json:"proxy"` + APIGroupSuffix string `json:"apiGroupSuffix"` + ShellContainerImage string `json:"shellContainer"` TestUser struct { Token string `json:"token"` @@ -227,7 +227,7 @@ func loadEnvVars(t *testing.T, result *TestEnv) { result.TestWebhook.Endpoint = needEnv(t, "PINNIPED_TEST_WEBHOOK_ENDPOINT") result.SupervisorNamespace = needEnv(t, "PINNIPED_TEST_SUPERVISOR_NAMESPACE") result.SupervisorAppName = needEnv(t, "PINNIPED_TEST_SUPERVISOR_APP_NAME") - result.TestWebhook.TLS = &auth1alpha1.TLSSpec{CertificateAuthorityData: needEnv(t, "PINNIPED_TEST_WEBHOOK_CA_BUNDLE")} + result.TestWebhook.TLS = &authenticationv1alpha1.TLSSpec{CertificateAuthorityData: needEnv(t, "PINNIPED_TEST_WEBHOOK_CA_BUNDLE")} result.SupervisorHTTPSIngressAddress = os.Getenv("PINNIPED_TEST_SUPERVISOR_HTTPS_INGRESS_ADDRESS") result.SupervisorHTTPSAddress = needEnv(t, "PINNIPED_TEST_SUPERVISOR_HTTPS_ADDRESS") From bbe10004b46aea9e323b8e3a09a529af90a34a3b Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Sat, 11 May 2024 22:27:52 -0500 Subject: [PATCH 03/10] Enforce more imports - go.pinniped.dev/generated/latest/apis/supervisor/clientsecret/v1alpha1 - go.pinniped.dev/internal/concierge/scheme --- .golangci.yaml | 12 +- .../supervisor_oidcclientsecret_test.go | 152 +++++++++--------- 2 files changed, 85 insertions(+), 79 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index d4e5e5e77..b4157b109 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -96,20 +96,26 @@ linters-settings: no-unaliased: true # All packages explicitly listed below must be aliased no-extra-aliases: false # Allow other aliases than the ones explicitly listed below alias: + # k8s.io/apimachinery - pkg: k8s.io/apimachinery/pkg/util/errors alias: utilerrors - pkg: k8s.io/apimachinery/pkg/api/errors alias: apierrors - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 alias: metav1 - # k8s.io libs + # k8s.io - pkg: k8s.io/api/core/v1 alias: corev1 - # OAuth2/OIDC/Fosite libs + # OAuth2/OIDC/Fosite - pkg: github.com/coreos/go-oidc/v3/oidc alias: coreosoidc - pkg: github.com/ory/fosite/handler/oauth2 alias: fositeoauth2 - # Generated Pinniped libs + # Generated Pinniped - pkg: go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1 alias: authenticationv1alpha1 + - pkg: go.pinniped.dev/generated/latest/apis/supervisor/clientsecret/v1alpha1 + alias: clientsecretv1alpha1 + # Pinniped internal + - pkg: go.pinniped.dev/internal/concierge/scheme + alias: conciergescheme diff --git a/test/integration/supervisor_oidcclientsecret_test.go b/test/integration/supervisor_oidcclientsecret_test.go index 4f517e34f..85ce75762 100644 --- a/test/integration/supervisor_oidcclientsecret_test.go +++ b/test/integration/supervisor_oidcclientsecret_test.go @@ -19,7 +19,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" - "go.pinniped.dev/generated/latest/apis/supervisor/clientsecret/v1alpha1" + clientsecretv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/clientsecret/v1alpha1" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" "go.pinniped.dev/internal/here" "go.pinniped.dev/internal/oidcclientsecretstorage" @@ -273,7 +273,7 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { env := testlib.IntegrationEnv(t) type testRequest struct { - secretRequest *v1alpha1.OIDCClientSecretRequest + secretRequest *clientsecretv1alpha1.OIDCClientSecretRequest wantSecretCount int wantErr func(string) string } @@ -291,12 +291,12 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, @@ -310,24 +310,24 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 1, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, RevokeOldSecrets: false, }, @@ -342,24 +342,24 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 1, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, RevokeOldSecrets: true, }, @@ -374,12 +374,12 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: true, }, @@ -394,12 +394,12 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: false, }, @@ -414,24 +414,24 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 1, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: false, }, @@ -446,24 +446,24 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 1, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: true, }, @@ -478,24 +478,24 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 1, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, RevokeOldSecrets: true, }, @@ -511,72 +511,72 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 1, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 2, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 3, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 4, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 5, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, RevokeOldSecrets: true, }, @@ -593,72 +593,72 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 1, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 2, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 3, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 4, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 5, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: true, }, @@ -673,72 +673,72 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 1, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 2, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 3, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 4, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, wantSecretCount: 5, }, { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: env.SupervisorNamespace, }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, RevokeOldSecrets: false, }, @@ -756,11 +756,11 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "some-generate-name-prefix-", }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: true, }, @@ -780,11 +780,11 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-", }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: true, }, @@ -804,11 +804,11 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: "doesnt-contain-prefix", }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: true, }, @@ -828,12 +828,12 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: "some-other-namespace", }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, @@ -850,11 +850,11 @@ func TestCreateOIDCClientSecretRequest_Parallel(t *testing.T) { clientSecretRequests: func(name string) []testRequest { return []testRequest{ { - secretRequest: &v1alpha1.OIDCClientSecretRequest{ + secretRequest: &clientsecretv1alpha1.OIDCClientSecretRequest{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-client-that-does-not-exist", }, - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: false, RevokeOldSecrets: true, }, @@ -1035,8 +1035,8 @@ func TestOIDCClientSecretRequestUnauthenticated_Parallel(t *testing.T) { client := testlib.NewAnonymousSupervisorClientset(t) _, err := client.ClientsecretV1alpha1().OIDCClientSecretRequests(env.SupervisorNamespace).Create(ctx, - &v1alpha1.OIDCClientSecretRequest{ - Spec: v1alpha1.OIDCClientSecretRequestSpec{ + &clientsecretv1alpha1.OIDCClientSecretRequest{ + Spec: clientsecretv1alpha1.OIDCClientSecretRequestSpec{ GenerateNewSecret: true, }, }, metav1.CreateOptions{}) From f5116cddb4bb1a83490b0c81daec9dfa2554cc53 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Sat, 11 May 2024 22:44:42 -0500 Subject: [PATCH 04/10] Enable 'makezero' and 'prealloc' linters, and require 'any' instead of 'interface{}' Enforce importas: - go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1 - go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1 --- .golangci.yaml | 19 + .../main_test.go | 2 +- cmd/pinniped-server/main_test.go | 2 +- internal/celtransformer/celformer.go | 12 +- internal/celtransformer/celformer_test.go | 2 +- internal/concierge/scheme/scheme.go | 4 +- .../authenticator/authncache/cache.go | 4 +- .../authenticator/authncache/cache_test.go | 2 +- .../jwtcachefiller/jwtcachefiller_test.go | 86 ++-- .../webhookcachefiller_test.go | 20 +- .../impersonator_config_test.go | 6 +- .../active_directory_upstream_watcher.go | 22 +- .../active_directory_upstream_watcher_test.go | 242 +++++----- .../federation_domain_watcher.go | 34 +- .../federation_domain_watcher_test.go | 441 +++++++++--------- .../generator/federation_domain_secrets.go | 12 +- .../federation_domain_secrets_test.go | 48 +- .../generator/secret_helper.go | 22 +- .../generator/secret_helper_test.go | 26 +- .../supervisorconfig/jwks_observer_test.go | 60 +-- .../supervisorconfig/jwks_writer.go | 14 +- .../supervisorconfig/jwks_writer_test.go | 70 +-- .../ldap_upstream_watcher.go | 22 +- .../ldap_upstream_watcher_test.go | 142 +++--- .../oidcclientwatcher/oidc_client_watcher.go | 8 +- .../oidc_client_watcher_test.go | 344 +++++++------- .../oidc_upstream_watcher.go | 30 +- .../oidc_upstream_watcher_test.go | 334 ++++++------- .../tls_cert_observer_test.go | 48 +- .../upstreamwatchers/upstream_watchers.go | 8 +- .../supervisorstorage/garbage_collector.go | 4 +- internal/controllerinit/controllerinit.go | 4 +- internal/controllerlib/die.go | 4 +- internal/controllerlib/option.go | 10 +- internal/controllerlib/recorder.go | 4 +- internal/controllerlib/sync.go | 4 +- internal/crud/crud.go | 2 +- internal/dynamiccert/provider_test.go | 2 +- internal/execcredcache/execcredcache.go | 8 +- .../clientregistry/clientregistry.go | 10 +- .../clientregistry/clientregistry_test.go | 64 +-- .../downstreamsession/downstream_session.go | 2 +- .../federationdomain/dynamiccodec/codec.go | 6 +- .../endpoints/auth/auth_handler_test.go | 14 +- .../callback/callback_handler_test.go | 26 +- .../login/post_login_handler_test.go | 26 +- .../endpoints/token/token_handler.go | 2 +- .../endpoints/token/token_handler_test.go | 244 +++++----- .../endpoints/tokenexchange/token_exchange.go | 2 +- .../endpointsmanager/manager_test.go | 2 +- .../idtokenlifespan/idtoken_lifespan.go | 4 +- internal/federationdomain/oidc/oidc.go | 10 +- .../oidcclientvalidator.go | 18 +- .../resolvedprovider/resolved_provider.go | 10 +- .../resolvedldap/resolved_ldap_provider.go | 6 +- .../resolvedoidc/resolved_oidc_provider.go | 28 +- .../resolved_oidc_provider_test.go | 16 +- .../dynamic_open_id_connect_ecdsa_strategy.go | 4 +- .../accesstoken/accesstoken_test.go | 2 +- .../authorizationcode_test.go | 18 +- .../refreshtoken/refreshtoken_test.go | 2 +- internal/groupsuffix/groupsuffix_test.go | 24 +- internal/here/doc.go | 4 +- internal/httputil/httperr/httperr.go | 4 +- .../idtransform/identity_transformations.go | 8 +- .../identity_transformations_test.go | 18 +- internal/kubeclient/path_test.go | 14 +- .../oidcclientsecretstorage.go | 4 +- internal/plog/plog.go | 94 ++-- .../registry/clientsecretrequest/rest_test.go | 42 +- internal/secret/cache.go | 4 +- internal/supervisor/server/server.go | 8 +- internal/testutil/assertions.go | 2 +- internal/testutil/oidcclient.go | 34 +- .../session_storage_assertions.go | 8 +- .../testutil/oidctestutil/testoidcprovider.go | 6 +- internal/testutil/testlogger/stdr_copied.go | 28 +- internal/testutil/transcript_logger.go | 8 +- internal/upstreamoidc/upstreamoidc.go | 12 +- internal/upstreamoidc/upstreamoidc_test.go | 70 +-- internal/valuelesscontext/valuelesscontext.go | 4 +- pkg/oidcclient/filesession/cachefile_test.go | 4 +- pkg/oidcclient/login_test.go | 16 +- pkg/oidcclient/oidctypes/oidctypes.go | 4 +- test/integration/cli_test.go | 6 +- test/integration/e2e_test.go | 76 +-- test/integration/securetls_test.go | 2 +- test/integration/supervisor_discovery_test.go | 60 +-- ...supervisor_federationdomain_status_test.go | 210 ++++----- test/integration/supervisor_login_test.go | 226 ++++----- .../supervisor_oidcclientsecret_test.go | 8 +- test/integration/supervisor_secrets_test.go | 20 +- test/integration/supervisor_upstream_test.go | 32 +- test/integration/supervisor_warnings_test.go | 14 +- test/testlib/assertions.go | 12 +- test/testlib/browsertest/browsertest.go | 2 +- test/testlib/client.go | 22 +- test/testlib/spew.go | 4 +- 98 files changed, 1889 insertions(+), 1869 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index b4157b109..e067158c2 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -49,6 +49,9 @@ linters: # - canonicalheader Can't do this one since it alerts on valid headers such as X-XSS-Protection - spancheck - importas + - makezero + - prealloc + - gofmt issues: exclude-dirs: @@ -116,6 +119,22 @@ linters-settings: alias: authenticationv1alpha1 - pkg: go.pinniped.dev/generated/latest/apis/supervisor/clientsecret/v1alpha1 alias: clientsecretv1alpha1 + - pkg: go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1 + alias: supervisorconfigv1alpha1 + - pkg: go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1 + alias: idpv1alpha1 # Pinniped internal - pkg: go.pinniped.dev/internal/concierge/scheme alias: conciergescheme + gofmt: + # Simplify code: gofmt with `-s` option. + # Default: true + simplify: false + # Apply the rewrite rules to the source before reformatting. + # https://pkg.go.dev/cmd/gofmt + # Default: [] + rewrite-rules: + - pattern: 'interface{}' + replacement: 'any' + - pattern: 'a[b:len(a)]' + replacement: 'a[b:]' diff --git a/cmd/pinniped-concierge-kube-cert-agent/main_test.go b/cmd/pinniped-concierge-kube-cert-agent/main_test.go index ee8fe3732..ab3cd6fe0 100644 --- a/cmd/pinniped-concierge-kube-cert-agent/main_test.go +++ b/cmd/pinniped-concierge-kube-cert-agent/main_test.go @@ -94,7 +94,7 @@ func TestEntrypoint(t *testing.T) { var logBuf bytes.Buffer testLog := log.New(&logBuf, "", 0) exited := "exiting via fatal" - fail = func(format string, v ...interface{}) { + fail = func(format string, v ...any) { testLog.Printf(format, v...) panic(exited) } diff --git a/cmd/pinniped-server/main_test.go b/cmd/pinniped-server/main_test.go index ee9fe2f96..a66696b5f 100644 --- a/cmd/pinniped-server/main_test.go +++ b/cmd/pinniped-server/main_test.go @@ -42,7 +42,7 @@ func TestEntrypoint(t *testing.T) { var logBuf bytes.Buffer testLog := log.New(&logBuf, "", 0) exited := "exiting via fatal" - fail = func(err error, keysAndValues ...interface{}) { + fail = func(err error, keysAndValues ...any) { testLog.Print(err) if len(keysAndValues) > 0 { testLog.Print(keysAndValues...) diff --git a/internal/celtransformer/celformer.go b/internal/celtransformer/celformer.go index e88b5bfda..150a66671 100644 --- a/internal/celtransformer/celformer.go +++ b/internal/celtransformer/celformer.go @@ -1,4 +1,4 @@ -// Copyright 2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2023-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package celtransformer is an implementation of upstream-to-downstream identity transformations @@ -228,8 +228,8 @@ func (c *baseCompiledTransformation) evalProgram(ctx context.Context, username s // Evaluation is thread-safe and side effect free. Many inputs can be sent to the same cel.Program // and if fields are present in the input, but not referenced in the expression, they are ignored. - // The argument to Eval may either be an `interpreter.Activation` or a `map[string]interface{}`. - val, _, err := c.program.ContextEval(timeoutCtx, map[string]interface{}{ + // The argument to Eval may either be an `interpreter.Activation` or a `map[string]any`. + val, _, err := c.program.ContextEval(timeoutCtx, map[string]any{ usernameVariableName: username, groupsVariableName: groups, constStringVariableName: c.consts.StringConstants, @@ -311,15 +311,15 @@ type CELTransformationSource struct { Consts *TransformationConstants } -func (c *compiledUsernameTransformation) Source() interface{} { +func (c *compiledUsernameTransformation) Source() any { return &CELTransformationSource{Expr: c.sourceExpr, Consts: c.consts} } -func (c *compiledGroupsTransformation) Source() interface{} { +func (c *compiledGroupsTransformation) Source() any { return &CELTransformationSource{Expr: c.sourceExpr, Consts: c.consts} } -func (c *compiledAllowAuthenticationPolicy) Source() interface{} { +func (c *compiledAllowAuthenticationPolicy) Source() any { return &CELTransformationSource{Expr: c.sourceExpr, Consts: c.consts} } diff --git a/internal/celtransformer/celformer_test.go b/internal/celtransformer/celformer_test.go index bc84e65ff..3ee786f54 100644 --- a/internal/celtransformer/celformer_test.go +++ b/internal/celtransformer/celformer_test.go @@ -787,7 +787,7 @@ func TestTransformer(t *testing.T) { require.NoError(t, err) pipeline := idtransform.NewTransformationPipeline() - expectedPipelineSource := []interface{}{} + expectedPipelineSource := []any{} for _, transform := range tt.transforms { compiledTransform, err := transformer.CompileTransformation(transform, tt.consts) diff --git a/internal/concierge/scheme/scheme.go b/internal/concierge/scheme/scheme.go index 658b888f8..0fb9c2f2f 100644 --- a/internal/concierge/scheme/scheme.go +++ b/internal/concierge/scheme/scheme.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package scheme contains code to construct a proper runtime.Scheme for the Concierge aggregated @@ -75,7 +75,7 @@ func New(apiGroupSuffix string) (_ *runtime.Scheme, login, identity schema.Group // on incoming requests, restore the authenticator API group to the standard group // note that we are responsible for duplicating this logic for every external API version - scheme.AddTypeDefaultingFunc(&loginv1alpha1.TokenCredentialRequest{}, func(obj interface{}) { + scheme.AddTypeDefaultingFunc(&loginv1alpha1.TokenCredentialRequest{}, func(obj any) { credentialRequest := obj.(*loginv1alpha1.TokenCredentialRequest) if credentialRequest.Spec.Authenticator.APIGroup == nil { diff --git a/internal/controller/authenticator/authncache/cache.go b/internal/controller/authenticator/authncache/cache.go index 14366c395..9e2b15011 100644 --- a/internal/controller/authenticator/authncache/cache.go +++ b/internal/controller/authenticator/authncache/cache.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package authncache implements a cache of active authenticators. @@ -65,7 +65,7 @@ func (c *Cache) Delete(key Key) { // Keys currently stored in the cache. func (c *Cache) Keys() []Key { var result []Key - c.cache.Range(func(key, _ interface{}) bool { + c.cache.Range(func(key, _ any) bool { result = append(result, key.(Key)) return true }) diff --git a/internal/controller/authenticator/authncache/cache_test.go b/internal/controller/authenticator/authncache/cache_test.go index 9d22caa07..13c6de76b 100644 --- a/internal/controller/authenticator/authncache/cache_test.go +++ b/internal/controller/authenticator/authncache/cache_test.go @@ -184,7 +184,7 @@ func TestAuthenticateTokenCredentialRequest(t *testing.T) { type audienceFreeContext struct{} -func (audienceFreeContext) Matches(in interface{}) bool { +func (audienceFreeContext) Matches(in any) bool { ctx, isCtx := in.(context.Context) if !isCtx { return false diff --git a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go index 97ecfd46d..6126716b1 100644 --- a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go +++ b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go @@ -141,8 +141,8 @@ func TestController(t *testing.T) { builder := jwt.Signed(sig).Claims(claimsWithoutSubject) - builder = builder.Claims(map[string]interface{}{customGroupsClaim: distributedGroups}) - builder = builder.Claims(map[string]interface{}{"groups": distributedGroups}) + builder = builder.Claims(map[string]any{customGroupsClaim: distributedGroups}) + builder = builder.Claims(map[string]any{"groups": distributedGroups}) distributedClaimsJwt, err := builder.CompactSerialize() require.NoError(t, err) @@ -162,7 +162,7 @@ func TestController(t *testing.T) { builder := jwt.Signed(sig).Claims(claimsWithoutSubject) - builder = builder.Claims(map[string]interface{}{"some-other-claim": distributedGroups}) + builder = builder.Claims(map[string]any{"some-other-claim": distributedGroups}) distributedClaimsJwt, err := builder.CompactSerialize() require.NoError(t, err) @@ -634,7 +634,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -679,7 +679,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -727,7 +727,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -769,7 +769,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -812,7 +812,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -866,7 +866,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -919,7 +919,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "actual jwt authenticator and desired jwt authenticator are the same", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -965,7 +965,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -1530,7 +1530,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -1568,7 +1568,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -1648,7 +1648,7 @@ func TestController(t *testing.T) { "logger": "jwtcachefiller-controller", "message": "added new jwt authenticator", "issuer": goodIssuer, - "jwtAuthenticator": map[string]interface{}{ + "jwtAuthenticator": map[string]any{ "name": "test-name", }, }}, @@ -1791,13 +1791,13 @@ func TestController(t *testing.T) { NotBefore: jwt.NewNumericDate(time.Now().Add(-time.Hour)), IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Hour)), } - var groups interface{} + var groups any username := goodUsername if test.jwtClaims != nil { test.jwtClaims(&wellKnownClaims, &groups, &username) } - var signingKey interface{} = goodECSigningKey + var signingKey any = goodECSigningKey signingAlgo := goodECSigningAlgo signingKID := goodECSigningKeyID if test.jwtSignature != nil { @@ -1860,8 +1860,8 @@ func testTableForAuthenticateTokenTests( issuer string, ) []struct { name string - jwtClaims func(wellKnownClaims *jwt.Claims, groups *interface{}, username *string) - jwtSignature func(key *interface{}, algo *jose.SignatureAlgorithm, kid *string) + jwtClaims func(wellKnownClaims *jwt.Claims, groups *any, username *string) + jwtSignature func(key *any, algo *jose.SignatureAlgorithm, kid *string) wantResponse *authenticator.Response wantAuthenticated bool wantErr testutil.RequireErrorStringFunc @@ -1869,8 +1869,8 @@ func testTableForAuthenticateTokenTests( } { tests := []struct { name string - jwtClaims func(wellKnownClaims *jwt.Claims, groups *interface{}, username *string) - jwtSignature func(key *interface{}, algo *jose.SignatureAlgorithm, kid *string) + jwtClaims func(wellKnownClaims *jwt.Claims, groups *any, username *string) + jwtSignature func(key *any, algo *jose.SignatureAlgorithm, kid *string) wantResponse *authenticator.Response wantAuthenticated bool wantErr testutil.RequireErrorStringFunc @@ -1887,7 +1887,7 @@ func testTableForAuthenticateTokenTests( }, { name: "good token without groups and with RSA signature", - jwtSignature: func(key *interface{}, algo *jose.SignatureAlgorithm, kid *string) { + jwtSignature: func(key *any, algo *jose.SignatureAlgorithm, kid *string) { *key = goodRSASigningKey *algo = goodRSASigningAlgo *kid = goodRSASigningKeyID @@ -1901,7 +1901,7 @@ func testTableForAuthenticateTokenTests( }, { name: "good token with groups as array", - jwtClaims: func(_ *jwt.Claims, groups *interface{}, username *string) { + jwtClaims: func(_ *jwt.Claims, groups *any, username *string) { *groups = []string{group0, group1} }, wantResponse: &authenticator.Response{ @@ -1914,7 +1914,7 @@ func testTableForAuthenticateTokenTests( }, { name: "good token with good distributed groups", - jwtClaims: func(claims *jwt.Claims, groups *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, groups *any, username *string) { }, distributedGroupsClaimURL: issuer + "/claim_source", wantResponse: &authenticator.Response{ @@ -1927,21 +1927,21 @@ func testTableForAuthenticateTokenTests( }, { name: "distributed groups returns a 404", - jwtClaims: func(claims *jwt.Claims, groups *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, groups *any, username *string) { }, distributedGroupsClaimURL: issuer + "/not_found_claim_source", wantErr: testutil.WantMatchingErrorString(`oidc: could not expand distributed claims: while getting distributed claim "` + expectedGroupsClaim + `": error while getting distributed claim JWT: 404 Not Found`), }, { name: "distributed groups doesn't return the right claim", - jwtClaims: func(claims *jwt.Claims, groups *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, groups *any, username *string) { }, distributedGroupsClaimURL: issuer + "/wrong_claim_source", wantErr: testutil.WantMatchingErrorString(`oidc: could not expand distributed claims: jwt returned by distributed claim endpoint "` + issuer + `/wrong_claim_source" did not contain claim: `), }, { name: "good token with groups as string", - jwtClaims: func(_ *jwt.Claims, groups *interface{}, username *string) { + jwtClaims: func(_ *jwt.Claims, groups *any, username *string) { *groups = group0 }, wantResponse: &authenticator.Response{ @@ -1954,7 +1954,7 @@ func testTableForAuthenticateTokenTests( }, { name: "good token with nbf unset", - jwtClaims: func(claims *jwt.Claims, _ *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, _ *any, username *string) { claims.NotBefore = nil }, wantResponse: &authenticator.Response{ @@ -1966,14 +1966,14 @@ func testTableForAuthenticateTokenTests( }, { name: "bad token with groups as map", - jwtClaims: func(_ *jwt.Claims, groups *interface{}, username *string) { + jwtClaims: func(_ *jwt.Claims, groups *any, username *string) { *groups = map[string]string{"not an array": "or a string"} }, wantErr: testutil.WantMatchingErrorString("oidc: parse groups claim \"" + expectedGroupsClaim + "\": json: cannot unmarshal object into Go value of type string"), }, { name: "bad token with wrong issuer", - jwtClaims: func(claims *jwt.Claims, _ *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, _ *any, username *string) { claims.Issuer = "wrong-issuer" }, wantResponse: nil, @@ -1981,49 +1981,49 @@ func testTableForAuthenticateTokenTests( }, { name: "bad token with no audience", - jwtClaims: func(claims *jwt.Claims, _ *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, _ *any, username *string) { claims.Audience = nil }, wantErr: testutil.WantMatchingErrorString(`oidc: verify token: oidc: expected audience "some-audience" got \[\]`), }, { name: "bad token with wrong audience", - jwtClaims: func(claims *jwt.Claims, _ *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, _ *any, username *string) { claims.Audience = []string{"wrong-audience"} }, wantErr: testutil.WantMatchingErrorString(`oidc: verify token: oidc: expected audience "some-audience" got \["wrong-audience"\]`), }, { name: "bad token with nbf in the future", - jwtClaims: func(claims *jwt.Claims, _ *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, _ *any, username *string) { claims.NotBefore = jwt.NewNumericDate(time.Date(3020, 2, 3, 4, 5, 6, 7, time.UTC)) }, wantErr: testutil.WantMatchingErrorString(`oidc: verify token: oidc: current time .* before the nbf \(not before\) time: 3020-.*`), }, { name: "bad token with exp in past", - jwtClaims: func(claims *jwt.Claims, _ *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, _ *any, username *string) { claims.Expiry = jwt.NewNumericDate(time.Date(1, 2, 3, 4, 5, 6, 7, time.UTC)) }, wantErr: testutil.WantMatchingErrorString(`oidc: verify token: oidc: token is expired \(Token Expiry: .+`), }, { name: "bad token without exp", - jwtClaims: func(claims *jwt.Claims, _ *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, _ *any, username *string) { claims.Expiry = nil }, wantErr: testutil.WantMatchingErrorString(`oidc: verify token: oidc: token is expired \(Token Expiry: .+`), }, { name: "token does not have username claim", - jwtClaims: func(claims *jwt.Claims, _ *interface{}, username *string) { + jwtClaims: func(claims *jwt.Claims, _ *any, username *string) { *username = "" }, wantErr: testutil.WantMatchingErrorString(`oidc: parse username claims "` + expectedUsernameClaim + `": claim not present`), }, { name: "signing key is wrong", - jwtSignature: func(key *interface{}, algo *jose.SignatureAlgorithm, kid *string) { + jwtSignature: func(key *any, algo *jose.SignatureAlgorithm, kid *string) { var err error *key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(t, err) @@ -2033,7 +2033,7 @@ func testTableForAuthenticateTokenTests( }, { name: "signing algo is unsupported", - jwtSignature: func(key *interface{}, algo *jose.SignatureAlgorithm, kid *string) { + jwtSignature: func(key *any, algo *jose.SignatureAlgorithm, kid *string) { var err error *key, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) require.NoError(t, err) @@ -2048,12 +2048,12 @@ func testTableForAuthenticateTokenTests( func createJWT( t *testing.T, - signingKey interface{}, + signingKey any, signingAlgo jose.SignatureAlgorithm, kid string, claims *jwt.Claims, groupsClaim string, - groupsValue interface{}, + groupsValue any, distributedGroupsClaimURL string, usernameClaim string, usernameValue string, @@ -2068,14 +2068,14 @@ func createJWT( builder := jwt.Signed(sig).Claims(claims) if groupsValue != nil { - builder = builder.Claims(map[string]interface{}{groupsClaim: groupsValue}) + builder = builder.Claims(map[string]any{groupsClaim: groupsValue}) } if distributedGroupsClaimURL != "" { - builder = builder.Claims(map[string]interface{}{"_claim_names": map[string]string{groupsClaim: "src1"}}) - builder = builder.Claims(map[string]interface{}{"_claim_sources": map[string]interface{}{"src1": map[string]string{"endpoint": distributedGroupsClaimURL}}}) + builder = builder.Claims(map[string]any{"_claim_names": map[string]string{groupsClaim: "src1"}}) + builder = builder.Claims(map[string]any{"_claim_sources": map[string]any{"src1": map[string]string{"endpoint": distributedGroupsClaimURL}}}) } if usernameValue != "" { - builder = builder.Claims(map[string]interface{}{usernameClaim: usernameValue}) + builder = builder.Claims(map[string]any{usernameClaim: usernameValue}) } jwt, err := builder.CompactSerialize() require.NoError(t, err) diff --git a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go index 8711343e5..53da3ce83 100644 --- a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go +++ b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go @@ -410,7 +410,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": goodWebhookDefaultServingCertEndpoint, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -452,7 +452,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": goodWebhookDefaultServingCertEndpoint, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -501,7 +501,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": goodWebhookDefaultServingCertEndpoint, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -551,7 +551,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": hostLocalIPv6Server.URL, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -859,7 +859,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": goodWebhookDefaultServingCertEndpointBut404, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -912,7 +912,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": fmt.Sprintf("https://localhost:%s", localhostURL.Port()), - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -1050,7 +1050,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": hostAs127001WebhookServer.URL, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -1177,7 +1177,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": goodWebhookDefaultServingCertEndpoint, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -1217,7 +1217,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": goodWebhookDefaultServingCertEndpoint, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, @@ -1278,7 +1278,7 @@ func TestController(t *testing.T) { "logger": "webhookcachefiller-controller", "message": "added new webhook authenticator", "endpoint": goodWebhookDefaultServingCertEndpoint, - "webhook": map[string]interface{}{ + "webhook": map[string]any{ "name": "test-name", }, }, diff --git a/internal/controller/impersonatorconfig/impersonator_config_test.go b/internal/controller/impersonatorconfig/impersonator_config_test.go index 9dad42e32..f012ff9b2 100644 --- a/internal/controller/impersonatorconfig/impersonator_config_test.go +++ b/internal/controller/impersonatorconfig/impersonator_config_test.go @@ -715,7 +715,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { // If an object is added to the informer's client *before* the informer is started, then waiting is // not needed because the informer's initial "list" will pick up the object. var waitForObjectToAppearInInformer = func(obj kubeclient.Object, informer controllerlib.InformerGetter) { - var objFromInformer interface{} + var objFromInformer any var exists bool var err error assert.Eventually(t, func() bool { @@ -728,7 +728,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { } var waitForClusterScopedObjectToAppearInInformer = func(obj kubeclient.Object, informer controllerlib.InformerGetter) { - var objFromInformer interface{} + var objFromInformer any var exists bool var err error assert.Eventually(t, func() bool { @@ -742,7 +742,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { // See comment for waitForObjectToAppearInInformer above. var waitForObjectToBeDeletedFromInformer = func(resourceName string, informer controllerlib.InformerGetter) { - var objFromInformer interface{} + var objFromInformer any var exists bool var err error assert.Eventually(t, func() bool { diff --git a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go index df86e06ac..6b64a7add 100644 --- a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go +++ b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go @@ -19,7 +19,7 @@ import ( "k8s.io/apimachinery/pkg/labels" corev1informers "k8s.io/client-go/informers/core/v1" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" @@ -74,7 +74,7 @@ const ( ) type activeDirectoryUpstreamGenericLDAPImpl struct { - activeDirectoryIdentityProvider v1alpha1.ActiveDirectoryIdentityProvider + activeDirectoryIdentityProvider idpv1alpha1.ActiveDirectoryIdentityProvider } func (g *activeDirectoryUpstreamGenericLDAPImpl) Spec() upstreamwatchers.UpstreamGenericLDAPSpec { @@ -98,14 +98,14 @@ func (g *activeDirectoryUpstreamGenericLDAPImpl) Status() upstreamwatchers.Upstr } type activeDirectoryUpstreamGenericLDAPSpec struct { - activeDirectoryIdentityProvider v1alpha1.ActiveDirectoryIdentityProvider + activeDirectoryIdentityProvider idpv1alpha1.ActiveDirectoryIdentityProvider } func (s *activeDirectoryUpstreamGenericLDAPSpec) Host() string { return s.activeDirectoryIdentityProvider.Spec.Host } -func (s *activeDirectoryUpstreamGenericLDAPSpec) TLSSpec() *v1alpha1.TLSSpec { +func (s *activeDirectoryUpstreamGenericLDAPSpec) TLSSpec() *idpv1alpha1.TLSSpec { return s.activeDirectoryIdentityProvider.Spec.TLS } @@ -161,7 +161,7 @@ func (s *activeDirectoryUpstreamGenericLDAPSpec) DetectAndSetSearchBase(ctx cont } type activeDirectoryUpstreamGenericLDAPUserSearch struct { - userSearch v1alpha1.ActiveDirectoryIdentityProviderUserSearch + userSearch idpv1alpha1.ActiveDirectoryIdentityProviderUserSearch } func (u *activeDirectoryUpstreamGenericLDAPUserSearch) Base() string { @@ -190,7 +190,7 @@ func (u *activeDirectoryUpstreamGenericLDAPUserSearch) UIDAttribute() string { } type activeDirectoryUpstreamGenericLDAPGroupSearch struct { - groupSearch v1alpha1.ActiveDirectoryIdentityProviderGroupSearch + groupSearch idpv1alpha1.ActiveDirectoryIdentityProviderGroupSearch } func (g *activeDirectoryUpstreamGenericLDAPGroupSearch) Base() string { @@ -216,7 +216,7 @@ func (g *activeDirectoryUpstreamGenericLDAPGroupSearch) GroupNameAttribute() str } type activeDirectoryUpstreamGenericLDAPStatus struct { - activeDirectoryIdentityProvider v1alpha1.ActiveDirectoryIdentityProvider + activeDirectoryIdentityProvider idpv1alpha1.ActiveDirectoryIdentityProvider } func (s *activeDirectoryUpstreamGenericLDAPStatus) Conditions() []metav1.Condition { @@ -318,7 +318,7 @@ func (c *activeDirectoryWatcherController) Sync(ctx controllerlib.Context) error return nil } -func (c *activeDirectoryWatcherController) validateUpstream(ctx context.Context, upstream *v1alpha1.ActiveDirectoryIdentityProvider) (p upstreamprovider.UpstreamLDAPIdentityProviderI, requeue bool) { +func (c *activeDirectoryWatcherController) validateUpstream(ctx context.Context, upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) (p upstreamprovider.UpstreamLDAPIdentityProviderI, requeue bool) { spec := upstream.Spec adUpstreamImpl := &activeDirectoryUpstreamGenericLDAPImpl{activeDirectoryIdentityProvider: *upstream} @@ -364,15 +364,15 @@ func (c *activeDirectoryWatcherController) validateUpstream(ctx context.Context, return upstreamwatchers.EvaluateConditions(conditions, config) } -func (c *activeDirectoryWatcherController) updateStatus(ctx context.Context, upstream *v1alpha1.ActiveDirectoryIdentityProvider, conditions []*metav1.Condition) { +func (c *activeDirectoryWatcherController) updateStatus(ctx context.Context, upstream *idpv1alpha1.ActiveDirectoryIdentityProvider, conditions []*metav1.Condition) { log := plog.WithValues("namespace", upstream.Namespace, "name", upstream.Name) updated := upstream.DeepCopy() hadErrorCondition := conditionsutil.MergeIDPConditions(conditions, upstream.Generation, &updated.Status.Conditions, log) - updated.Status.Phase = v1alpha1.ActiveDirectoryPhaseReady + updated.Status.Phase = idpv1alpha1.ActiveDirectoryPhaseReady if hadErrorCondition { - updated.Status.Phase = v1alpha1.ActiveDirectoryPhaseError + updated.Status.Phase = idpv1alpha1.ActiveDirectoryPhaseError } if equality.Semantic.DeepEqual(upstream, updated) { diff --git a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher_test.go b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher_test.go index ed12e87d4..3b8aa9b2b 100644 --- a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher_test.go +++ b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher_test.go @@ -22,7 +22,7 @@ import ( "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/certauthority" @@ -106,7 +106,7 @@ func TestActiveDirectoryUpstreamWatcherControllerFilterActiveDirectoryIdentityPr }{ { name: "any ActiveDirectoryIdentityProvider", - idp: &v1alpha1.ActiveDirectoryIdentityProvider{ + idp: &idpv1alpha1.ActiveDirectoryIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Name: "some-name", Namespace: "some-namespace"}, }, wantAdd: true, @@ -176,32 +176,32 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { testCABundle := testCA.Bundle() testCABundleBase64Encoded := base64.StdEncoding.EncodeToString(testCABundle) - validUpstream := &v1alpha1.ActiveDirectoryIdentityProvider{ + validUpstream := &idpv1alpha1.ActiveDirectoryIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Name: testName, Namespace: testNamespace, Generation: 1234, UID: testResourceUID}, - Spec: v1alpha1.ActiveDirectoryIdentityProviderSpec{ + Spec: idpv1alpha1.ActiveDirectoryIdentityProviderSpec{ Host: testHost, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testCABundleBase64Encoded}, - Bind: v1alpha1.ActiveDirectoryIdentityProviderBind{SecretName: testBindSecretName}, - UserSearch: v1alpha1.ActiveDirectoryIdentityProviderUserSearch{ + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testCABundleBase64Encoded}, + Bind: idpv1alpha1.ActiveDirectoryIdentityProviderBind{SecretName: testBindSecretName}, + UserSearch: idpv1alpha1.ActiveDirectoryIdentityProviderUserSearch{ Base: testUserSearchBase, Filter: testUserSearchFilter, - Attributes: v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{ + Attributes: idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{ Username: testUserSearchUsernameAttrName, UID: testUserSearchUIDAttrName, }, }, - GroupSearch: v1alpha1.ActiveDirectoryIdentityProviderGroupSearch{ + GroupSearch: idpv1alpha1.ActiveDirectoryIdentityProviderGroupSearch{ Base: testGroupSearchBase, Filter: testGroupSearchFilter, UserAttributeForFilter: testGroupSearchUserAttributeForFilter, - Attributes: v1alpha1.ActiveDirectoryIdentityProviderGroupSearchAttributes{ + Attributes: idpv1alpha1.ActiveDirectoryIdentityProviderGroupSearchAttributes{ GroupName: testGroupSearchNameAttrName, }, SkipGroupRefresh: false, }, }, } - editedValidUpstream := func(editFunc func(*v1alpha1.ActiveDirectoryIdentityProvider)) *v1alpha1.ActiveDirectoryIdentityProvider { + editedValidUpstream := func(editFunc func(*idpv1alpha1.ActiveDirectoryIdentityProvider)) *idpv1alpha1.ActiveDirectoryIdentityProvider { deepCopy := validUpstream.DeepCopy() editFunc(deepCopy) return deepCopy @@ -373,7 +373,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { dialErrors map[string]error wantErr string wantResultingCache []*upstreamldap.ProviderConfig - wantResultingUpstreams []v1alpha1.ActiveDirectoryIdentityProvider + wantResultingUpstreams []idpv1alpha1.ActiveDirectoryIdentityProvider wantValidatedSettings map[string]upstreamwatchers.ValidatedSettings }{ { @@ -390,9 +390,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -413,9 +413,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { inputSecrets: []runtime.Object{}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ { @@ -441,9 +441,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ { @@ -468,9 +468,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ { @@ -488,15 +488,15 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "CertificateAuthorityData is not base64 encoded", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.TLS.CertificateAuthorityData = "this-is-not-base64-encoded" })}, inputSecrets: []runtime.Object{validBindUserSecret("")}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -514,15 +514,15 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "CertificateAuthorityData is not valid pem data", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.TLS.CertificateAuthorityData = base64.StdEncoding.EncodeToString([]byte("this is not pem data")) })}, inputSecrets: []runtime.Object{validBindUserSecret("")}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -540,7 +540,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "nil TLS configuration is valid", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.TLS = nil })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -578,9 +578,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -609,7 +609,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "sAMAccountName explicitly provided as group name attribute does not add an override", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.TLS = nil upstream.Spec.GroupSearch.Attributes.GroupName = "sAMAccountName" })}, @@ -648,9 +648,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -679,7 +679,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when TLS connection fails it tries to use StartTLS instead: without a specified port it automatically switches ports", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.Host = "ldap.example.com" // when the port is not specified, automatically switch ports for StartTLS })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -721,9 +721,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -761,7 +761,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when TLS connection fails it tries to use StartTLS instead: with a specified port it does not automatically switch ports", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.Host = "ldap.example.com:5678" // when the port is specified, do not automatically switch ports for StartTLS })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -802,9 +802,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -827,7 +827,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "non-nil TLS configuration with empty CertificateAuthorityData is valid", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.TLS.CertificateAuthorityData = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -865,9 +865,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -884,7 +884,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "one valid upstream and one invalid upstream updates the cache to include only the valid upstream", - inputUpstreams: []runtime.Object{validUpstream, editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{validUpstream, editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Name = "other-upstream" upstream.Generation = 42 upstream.Spec.Bind.SecretName = "non-existent-secret" @@ -898,10 +898,10 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "other-upstream", Generation: 42, UID: "other-uid"}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ { @@ -918,7 +918,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -948,9 +948,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -973,8 +973,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when testing the connection to the LDAP server fails, but later querying defaultsearchbase succeeds, then the upstream is still added to the cache anyway (treated like a warning)", - // Add to cache but not to validatedSettings so we recheck next time - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + // Add to cache, but not to validatedSettings, so we recheck next time + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.UserSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("")}, @@ -1016,9 +1016,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1041,7 +1041,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when testing the connection to the LDAP server fails, and querying defaultsearchbase fails, then the upstream is not added to the cache", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.UserSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("")}, @@ -1052,9 +1052,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(3) }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1077,7 +1077,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was already validated using TLS for the current resource generation and secret version, then do not validate it again and keep using TLS", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ activeDirectoryConnectionValidTrueCondition(1234, "4242"), @@ -1098,9 +1098,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { // Should not perform a test dial and bind. No mocking here means the test will fail if Bind() or Close() are called. }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -1119,7 +1119,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { name: "when the validated cache contains LDAP server info but the search base is empty, reload everything", // this is an invalid state that shouldn't happen now, but if it does we should consider the whole // validatedsettings cache invalid. - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ activeDirectoryConnectionValidTrueCondition(1234, "4242"), @@ -1165,9 +1165,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { "msDS-User-Account-Control-Computed": validComputedUserAccountControl, }}, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1189,7 +1189,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was already validated using TLS, and the search base was found, load TLS and search base info into the cache", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ activeDirectoryConnectionValidTrueCondition(1234, "4242"), @@ -1238,9 +1238,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1262,7 +1262,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was already validated using StartTLS for the current resource generation and secret version, then do not validate it again and keep using StartTLS", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ activeDirectoryConnectionValidTrueCondition(1234, "4242"), @@ -1283,9 +1283,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { // Should not perform a test dial and bind. No mocking here means the test will fail if Bind() or Close() are called. }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithStartTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -1302,7 +1302,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was validated for an older resource generation, then try to validate it again", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 // current generation upstream.Status.Conditions = []metav1.Condition{ activeDirectoryConnectionValidTrueCondition(1233, "4242"), // older spec generation! @@ -1324,9 +1324,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -1343,7 +1343,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection condition failed to update previously, then write the cached condition from the previous connection validation", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 // current generation upstream.Status.Conditions = []metav1.Condition{ activeDirectoryConnectionValidTrueCondition(1234, "4200"), // old version of the condition, as if the previous update of conditions had failed @@ -1364,9 +1364,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { // Should not perform a test dial and bind. No mocking here means the test will fail if Bind() or Close() are called. }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), // updated version of the condition using the cached condition value }, @@ -1383,7 +1383,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection validation previously failed for this resource generation, then try to validate it again", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ { @@ -1403,9 +1403,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -1422,7 +1422,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was already validated for this resource generation but the bind secret has changed, then try to validate it again", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ activeDirectoryConnectionValidTrueCondition(1234, "4241"), // same spec generation, old secret version @@ -1444,9 +1444,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -1463,11 +1463,11 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the input activedirectoryidentityprovider leaves user attributes blank, provide default values", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.UserSearch.Filter = "" upstream.Spec.GroupSearch.Filter = "" - upstream.Spec.GroupSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderGroupSearchAttributes{} + upstream.Spec.GroupSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderGroupSearchAttributes{} })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, setupMocks: func(conn *mockldapconn.MockConn) { @@ -1505,9 +1505,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -1524,8 +1524,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the input activedirectoryidentityprovider leaves user and group search base blank, query for defaultNamingContext", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.UserSearch.Base = "" upstream.Spec.GroupSearch.Base = "" })}, @@ -1565,9 +1565,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1589,8 +1589,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the input activedirectoryidentityprovider leaves user search base blank but provides group search base, query for defaultNamingContext", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.UserSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1629,9 +1629,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1653,8 +1653,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the input activedirectoryidentityprovider leaves group search base blank but provides user search base, query for defaultNamingContext", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.GroupSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1693,9 +1693,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1717,8 +1717,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the input activedirectoryidentityprovider leaves group search base blank and query for defaultNamingContext fails", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.GroupSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1729,9 +1729,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Search(expectedDefaultNamingContextSearch()).Return(nil, errors.New("some error")).Times(1) }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1745,8 +1745,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when query for defaultNamingContext returns empty string", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.GroupSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1765,9 +1765,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }}, nil).Times(1) }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1781,8 +1781,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when query for defaultNamingContext returns multiple entries", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.GroupSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1807,9 +1807,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }}, nil).Times(1) }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1823,8 +1823,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when query for defaultNamingContext returns no entries", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.GroupSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1836,9 +1836,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { Entries: []*ldap.Entry{}}, nil).Times(1) }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1852,12 +1852,12 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when search base was previously found but the bind secret has changed", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ searchBaseFoundInRootDSECondition(1234), } - upstream.Spec.UserSearch.Attributes = v1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} + upstream.Spec.UserSearch.Attributes = idpv1alpha1.ActiveDirectoryIdentityProviderUserSearchAttributes{} upstream.Spec.GroupSearch.Base = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1905,9 +1905,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testResourceUID, Generation: 1234}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1929,7 +1929,7 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, { name: "skipping group refresh is valid", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.ActiveDirectoryIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.ActiveDirectoryIdentityProvider) { upstream.Spec.GroupSearch.SkipGroupRefresh = true })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1968,9 +1968,9 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.ActiveDirectoryIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.ActiveDirectoryIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.ActiveDirectoryIdentityProviderStatus{ + Status: idpv1alpha1.ActiveDirectoryIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -2133,13 +2133,13 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { } } -func normalizeActiveDirectoryUpstreams(upstreams []v1alpha1.ActiveDirectoryIdentityProvider, now metav1.Time) []v1alpha1.ActiveDirectoryIdentityProvider { - result := make([]v1alpha1.ActiveDirectoryIdentityProvider, 0, len(upstreams)) +func normalizeActiveDirectoryUpstreams(upstreams []idpv1alpha1.ActiveDirectoryIdentityProvider, now metav1.Time) []idpv1alpha1.ActiveDirectoryIdentityProvider { + result := make([]idpv1alpha1.ActiveDirectoryIdentityProvider, 0, len(upstreams)) for _, u := range upstreams { normalized := u.DeepCopy() // We're only interested in comparing the status, so zero out the spec. - normalized.Spec = v1alpha1.ActiveDirectoryIdentityProviderSpec{} + normalized.Spec = idpv1alpha1.ActiveDirectoryIdentityProviderSpec{} // Round down the LastTransitionTime values to `now` if they were just updated. This makes // it much easier to encode assertions about the expected timestamps. diff --git a/internal/controller/supervisorconfig/federation_domain_watcher.go b/internal/controller/supervisorconfig/federation_domain_watcher.go index 9b41135bf..664f29e6f 100644 --- a/internal/controller/supervisorconfig/federation_domain_watcher.go +++ b/internal/controller/supervisorconfig/federation_domain_watcher.go @@ -21,7 +21,7 @@ import ( "k8s.io/apimachinery/pkg/util/sets" "k8s.io/utils/clock" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" @@ -190,10 +190,10 @@ func (c *federationDomainWatcherController) Sync(ctx controllerlib.Context) erro func (c *federationDomainWatcherController) processAllFederationDomains( ctx context.Context, - federationDomains []*configv1alpha1.FederationDomain, -) ([]*federationdomainproviders.FederationDomainIssuer, map[*configv1alpha1.FederationDomain][]*metav1.Condition, error) { + federationDomains []*supervisorconfigv1alpha1.FederationDomain, +) ([]*federationdomainproviders.FederationDomainIssuer, map[*supervisorconfigv1alpha1.FederationDomain][]*metav1.Condition, error) { federationDomainIssuers := make([]*federationdomainproviders.FederationDomainIssuer, 0) - fdToConditionsMap := map[*configv1alpha1.FederationDomain][]*metav1.Condition{} + fdToConditionsMap := map[*supervisorconfigv1alpha1.FederationDomain][]*metav1.Condition{} crossDomainConfigValidator := newCrossFederationDomainConfigValidator(federationDomains) for _, federationDomain := range federationDomains { @@ -222,7 +222,7 @@ func (c *federationDomainWatcherController) processAllFederationDomains( func (c *federationDomainWatcherController) makeFederationDomainIssuer( ctx context.Context, - federationDomain *configv1alpha1.FederationDomain, + federationDomain *supervisorconfigv1alpha1.FederationDomain, conditions []*metav1.Condition, ) (*federationdomainproviders.FederationDomainIssuer, []*metav1.Condition, error) { var err error @@ -246,7 +246,7 @@ func (c *federationDomainWatcherController) makeFederationDomainIssuer( } func (c *federationDomainWatcherController) makeLegacyFederationDomainIssuer( - federationDomain *configv1alpha1.FederationDomain, + federationDomain *supervisorconfigv1alpha1.FederationDomain, conditions []*metav1.Condition, ) (*federationdomainproviders.FederationDomainIssuer, []*metav1.Condition, error) { var defaultFederationDomainIdentityProvider *federationdomainproviders.FederationDomainIdentityProvider @@ -337,7 +337,7 @@ func (c *federationDomainWatcherController) makeLegacyFederationDomainIssuer( //nolint:funlen func (c *federationDomainWatcherController) makeFederationDomainIssuerWithExplicitIDPs( ctx context.Context, - federationDomain *configv1alpha1.FederationDomain, + federationDomain *supervisorconfigv1alpha1.FederationDomain, conditions []*metav1.Condition, ) (*federationdomainproviders.FederationDomainIssuer, []*metav1.Condition, error) { federationDomainIdentityProviders := []*federationdomainproviders.FederationDomainIdentityProvider{} @@ -464,7 +464,7 @@ func (c *federationDomainWatcherController) findIDPsUIDByObjectRef(objectRef cor func (c *federationDomainWatcherController) makeTransformationPipelineAndEvaluateExamplesForIdentityProvider( ctx context.Context, - idp configv1alpha1.FederationDomainIdentityProvider, + idp supervisorconfigv1alpha1.FederationDomainIdentityProvider, idpIndex int, validationErrorMessages *transformsValidationErrorMessages, ) (*idtransform.TransformationPipeline, bool, error) { @@ -490,7 +490,7 @@ func (c *federationDomainWatcherController) makeTransformationPipelineAndEvaluat } func (c *federationDomainWatcherController) makeTransformsConstantsForIdentityProvider( - idp configv1alpha1.FederationDomainIdentityProvider, + idp supervisorconfigv1alpha1.FederationDomainIdentityProvider, ) (*celtransformer.TransformationConstants, error) { consts := &celtransformer.TransformationConstants{ StringConstants: map[string]string{}, @@ -518,7 +518,7 @@ func (c *federationDomainWatcherController) makeTransformsConstantsForIdentityPr } func (c *federationDomainWatcherController) makeTransformationPipelineForIdentityProvider( - idp configv1alpha1.FederationDomainIdentityProvider, + idp supervisorconfigv1alpha1.FederationDomainIdentityProvider, idpIndex int, consts *celtransformer.TransformationConstants, ) (*idtransform.TransformationPipeline, string, error) { @@ -564,7 +564,7 @@ func (c *federationDomainWatcherController) makeTransformationPipelineForIdentit func (c *federationDomainWatcherController) evaluateExamplesForIdentityProvider( ctx context.Context, - idp configv1alpha1.FederationDomainIdentityProvider, + idp supervisorconfigv1alpha1.FederationDomainIdentityProvider, idpIndex int, pipeline *idtransform.TransformationPipeline, ) (bool, string) { @@ -662,7 +662,7 @@ func appendIdentityProviderObjectRefKindCondition(expectedKinds []string, badSuf func appendIdentityProvidersFoundCondition( idpNotFoundIndices []int, - federationDomainIdentityProviders []configv1alpha1.FederationDomainIdentityProvider, + federationDomainIdentityProviders []supervisorconfigv1alpha1.FederationDomainIdentityProvider, conditions []*metav1.Condition, ) []*metav1.Condition { if len(idpNotFoundIndices) != 0 { @@ -789,13 +789,13 @@ func appendIssuerURLValidCondition(err error, conditions []*metav1.Condition) [] func (c *federationDomainWatcherController) updateStatus( ctx context.Context, - federationDomain *configv1alpha1.FederationDomain, + federationDomain *supervisorconfigv1alpha1.FederationDomain, conditions []*metav1.Condition, ) error { updated := federationDomain.DeepCopy() if conditionsutil.HadErrorCondition(conditions) { - updated.Status.Phase = configv1alpha1.FederationDomainPhaseError + updated.Status.Phase = supervisorconfigv1alpha1.FederationDomainPhaseError conditions = append(conditions, &metav1.Condition{ Type: typeReady, Status: metav1.ConditionFalse, @@ -803,7 +803,7 @@ func (c *federationDomainWatcherController) updateStatus( Message: "the FederationDomain is not ready: see other conditions for details", }) } else { - updated.Status.Phase = configv1alpha1.FederationDomainPhaseReady + updated.Status.Phase = supervisorconfigv1alpha1.FederationDomainPhaseReady conditions = append(conditions, &metav1.Condition{ Type: typeReady, Status: metav1.ConditionTrue, @@ -858,7 +858,7 @@ func issuerURLToIssuerKey(issuerURL *url.URL) string { return fmt.Sprintf("%s://%s%s", issuerURL.Scheme, strings.ToLower(issuerURL.Host), issuerURL.Path) } -func (v *crossFederationDomainConfigValidator) Validate(federationDomain *configv1alpha1.FederationDomain, conditions []*metav1.Condition) []*metav1.Condition { +func (v *crossFederationDomainConfigValidator) Validate(federationDomain *supervisorconfigv1alpha1.FederationDomain, conditions []*metav1.Condition) []*metav1.Condition { issuerURL, urlParseErr := url.Parse(federationDomain.Spec.Issuer) if urlParseErr != nil { @@ -913,7 +913,7 @@ func (v *crossFederationDomainConfigValidator) Validate(federationDomain *config return conditions } -func newCrossFederationDomainConfigValidator(federationDomains []*configv1alpha1.FederationDomain) *crossFederationDomainConfigValidator { +func newCrossFederationDomainConfigValidator(federationDomains []*supervisorconfigv1alpha1.FederationDomain) *crossFederationDomainConfigValidator { // Make a map of issuer strings -> count of how many times we saw that issuer string. // This will help us complain when there are duplicate issuer strings. // Also make a helper function for forming keys into this map. diff --git a/internal/controller/supervisorconfig/federation_domain_watcher_test.go b/internal/controller/supervisorconfig/federation_domain_watcher_test.go index ade25e060..2190d533f 100644 --- a/internal/controller/supervisorconfig/federation_domain_watcher_test.go +++ b/internal/controller/supervisorconfig/federation_domain_watcher_test.go @@ -22,7 +22,7 @@ import ( clocktesting "k8s.io/utils/clock/testing" "k8s.io/utils/ptr" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" @@ -53,7 +53,7 @@ func TestFederationDomainWatcherControllerInformerFilters(t *testing.T) { }{ { name: "any FederationDomain changes", - obj: &configv1alpha1.FederationDomain{}, + obj: &supervisorconfigv1alpha1.FederationDomain{}, informer: federationDomainInformer, wantAdd: true, wantUpdate: true, @@ -123,8 +123,8 @@ func (f *fakeFederationDomainsSetter) SetFederationDomains(federationDomains ... } var federationDomainGVR = schema.GroupVersionResource{ - Group: configv1alpha1.SchemeGroupVersion.Group, - Version: configv1alpha1.SchemeGroupVersion.Version, + Group: supervisorconfigv1alpha1.SchemeGroupVersion.Group, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Resource: "federationdomains", } @@ -162,19 +162,19 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, } - federationDomain1 := &configv1alpha1.FederationDomain{ + federationDomain1 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{Issuer: "https://issuer1.com"}, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://issuer1.com"}, } - federationDomain2 := &configv1alpha1.FederationDomain{ + federationDomain2 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config2", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{Issuer: "https://issuer2.com"}, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://issuer2.com"}, } - invalidIssuerURLFederationDomain := &configv1alpha1.FederationDomain{ + invalidIssuerURLFederationDomain := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "invalid-config", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{Issuer: "https://invalid-issuer.com?some=query"}, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://invalid-issuer.com?some=query"}, } federationDomainIssuerWithIDPs := func(t *testing.T, fedDomainIssuer string, fdIDPs []*federationdomainproviders.FederationDomainIdentityProvider) *federationdomainproviders.FederationDomainIssuer { @@ -523,7 +523,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { inputObjects []runtime.Object configClient func(*pinnipedfake.Clientset) wantErr string - wantStatusUpdates []*configv1alpha1.FederationDomain + wantStatusUpdates []*supervisorconfigv1alpha1.FederationDomain wantFDIssuers []*federationdomainproviders.FederationDomainIssuer }{ { @@ -544,13 +544,13 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomainIssuerWithDefaultIDP(t, federationDomain1.Spec.Issuer, oidcIdentityProvider.ObjectMeta), federationDomainIssuerWithDefaultIDP(t, federationDomain2.Spec.Issuer, oidcIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(federationDomain1, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain1.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), ), expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -568,13 +568,13 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomainIssuerWithDefaultIDP(t, federationDomain1.Spec.Issuer, ldapIdentityProvider.ObjectMeta), federationDomainIssuerWithDefaultIDP(t, federationDomain2.Spec.Issuer, ldapIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(federationDomain1, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain1.Spec.Issuer, ldapIdentityProvider.Name, frozenMetav1Now, 123), ), expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, ldapIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -592,13 +592,13 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomainIssuerWithDefaultIDP(t, federationDomain1.Spec.Issuer, adIdentityProvider.ObjectMeta), federationDomainIssuerWithDefaultIDP(t, federationDomain2.Spec.Issuer, adIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(federationDomain1, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain1.Spec.Issuer, adIdentityProvider.Name, frozenMetav1Now, 123), ), expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, adIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -608,11 +608,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { "the out-of-date FederationDomain", inputObjects: []runtime.Object{ oidcIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: federationDomain1.Name, Namespace: federationDomain1.Namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{Issuer: federationDomain1.Spec.Issuer}, - Status: configv1alpha1.FederationDomainStatus{ - Phase: configv1alpha1.FederationDomainPhaseReady, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: federationDomain1.Spec.Issuer}, + Status: supervisorconfigv1alpha1.FederationDomainStatus{ + Phase: supervisorconfigv1alpha1.FederationDomainPhaseReady, Conditions: allHappyConditionsLegacyConfigurationSuccess(federationDomain1.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), }, }, @@ -622,10 +622,10 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomainIssuerWithDefaultIDP(t, federationDomain1.Spec.Issuer, oidcIdentityProvider.ObjectMeta), federationDomainIssuerWithDefaultIDP(t, federationDomain2.Spec.Issuer, oidcIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ // only one update, because the other FederationDomain already had the right status expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -634,11 +634,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "when the status of the FederationDomains is based on an old generation, it is updated", inputObjects: []runtime.Object{ oidcIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: federationDomain1.Name, Namespace: federationDomain1.Namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{Issuer: federationDomain1.Spec.Issuer}, - Status: configv1alpha1.FederationDomainStatus{ - Phase: configv1alpha1.FederationDomainPhaseReady, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: federationDomain1.Spec.Issuer}, + Status: supervisorconfigv1alpha1.FederationDomainStatus{ + Phase: supervisorconfigv1alpha1.FederationDomainPhaseReady, Conditions: allHappyConditionsLegacyConfigurationSuccess( federationDomain1.Spec.Issuer, oidcIdentityProvider.Name, @@ -651,10 +651,10 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{ federationDomainIssuerWithDefaultIDP(t, federationDomain1.Spec.Issuer, oidcIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ // only one update, because the other FederationDomain already had the right status expectedFederationDomainStatusUpdate(federationDomain1, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess( federationDomain1.Spec.Issuer, oidcIdentityProvider.Name, @@ -676,7 +676,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { "update", "federationdomains", func(action coretesting.Action) (bool, runtime.Object, error) { - fd := action.(coretesting.UpdateAction).GetObject().(*configv1alpha1.FederationDomain) + fd := action.(coretesting.UpdateAction).GetObject().(*supervisorconfigv1alpha1.FederationDomain) if fd.Name == federationDomain1.Name { return true, nil, errors.New("some update error") } @@ -689,13 +689,13 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomainIssuerWithDefaultIDP(t, federationDomain1.Spec.Issuer, oidcIdentityProvider.ObjectMeta), federationDomainIssuerWithDefaultIDP(t, federationDomain2.Spec.Issuer, oidcIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(federationDomain1, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain1.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), ), expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -712,9 +712,9 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { // only the valid FederationDomain federationDomainIssuerWithDefaultIDP(t, federationDomain2.Spec.Issuer, oidcIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(invalidIssuerURLFederationDomain, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), []metav1.Condition{ @@ -723,7 +723,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -741,7 +741,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { "update", "federationdomains", func(action coretesting.Action) (bool, runtime.Object, error) { - fd := action.(coretesting.UpdateAction).GetObject().(*configv1alpha1.FederationDomain) + fd := action.(coretesting.UpdateAction).GetObject().(*supervisorconfigv1alpha1.FederationDomain) if fd.Name == invalidIssuerURLFederationDomain.Name { return true, nil, errors.New("some update error") } @@ -754,9 +754,9 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { // only the valid FederationDomain federationDomainIssuerWithDefaultIDP(t, federationDomain2.Spec.Issuer, oidcIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(invalidIssuerURLFederationDomain, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), []metav1.Condition{ @@ -765,7 +765,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, oidcIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -774,29 +774,29 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "when there are FederationDomains with duplicate issuer strings these particular FederationDomains " + "will report error on IssuerUnique conditions", inputObjects: []runtime.Object{ - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "duplicate1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{Issuer: "https://iSSueR-duPlicAte.cOm/a"}, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://iSSueR-duPlicAte.cOm/a"}, }, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "duplicate2", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{Issuer: "https://issuer-duplicate.com/a"}, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://issuer-duplicate.com/a"}, }, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "not-duplicate", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{Issuer: "https://issuer-duplicate.com/A"}, // different path (paths are case-sensitive) + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://issuer-duplicate.com/A"}, // different path (paths are case-sensitive) }, oidcIdentityProvider, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{ federationDomainIssuerWithDefaultIDP(t, "https://issuer-duplicate.com/A", oidcIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "duplicate1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess("https://iSSueR-duPlicAte.cOm/a", oidcIdentityProvider.Name, frozenMetav1Now, 123), []metav1.Condition{ @@ -805,10 +805,10 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "duplicate2", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess("https://issuer-duplicate.com/a", oidcIdentityProvider.Name, frozenMetav1Now, 123), []metav1.Condition{ @@ -817,10 +817,10 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "not-duplicate", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess("https://issuer-duplicate.com/A", oidcIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -829,34 +829,34 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "when there are FederationDomains with the same issuer DNS hostname using different secretNames these " + "particular FederationDomains will report errors on OneTLSSecretPerIssuerHostname conditions", inputObjects: []runtime.Object{ - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "fd1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://iSSueR-duPlicAte-adDress.cOm/path1", - TLS: &configv1alpha1.FederationDomainTLSSpec{SecretName: "secret1"}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: "secret1"}, }, }, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "fd2", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ // Validation treats these as the same DNS hostname even though they have different port numbers, // because SNI information on the incoming requests is not going to include port numbers. Issuer: "https://issuer-duplicate-address.com:1234/path2", - TLS: &configv1alpha1.FederationDomainTLSSpec{SecretName: "secret2"}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: "secret2"}, }, }, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "differentIssuerAddressFederationDomain", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer-not-duplicate.com", - TLS: &configv1alpha1.FederationDomainTLSSpec{SecretName: "secret1"}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: "secret1"}, }, }, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "invalidIssuerURLFederationDomain", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: invalidIssuerURL, - TLS: &configv1alpha1.FederationDomainTLSSpec{SecretName: "secret1"}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: "secret1"}, }, }, oidcIdentityProvider, @@ -864,12 +864,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{ federationDomainIssuerWithDefaultIDP(t, "https://issuer-not-duplicate.com", oidcIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "fd1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess("https://iSSueR-duPlicAte-adDress.cOm/path1", oidcIdentityProvider.Name, frozenMetav1Now, 123), []metav1.Condition{ @@ -878,10 +878,10 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "fd2", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess("https://issuer-duplicate-address.com:1234/path2", oidcIdentityProvider.Name, frozenMetav1Now, 123), []metav1.Condition{ @@ -890,10 +890,10 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "invalidIssuerURLFederationDomain", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess(invalidIssuerURL, oidcIdentityProvider.Name, frozenMetav1Now, 123), []metav1.Condition{ @@ -904,10 +904,10 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "differentIssuerAddressFederationDomain", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess("https://issuer-not-duplicate.com", oidcIdentityProvider.Name, frozenMetav1Now, 123), ), }, @@ -919,9 +919,9 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomain2, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(federationDomain1, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess(federationDomain1.Spec.Issuer, "", frozenMetav1Now, 123), []metav1.Condition{ @@ -930,7 +930,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, "", frozenMetav1Now, 123), []metav1.Condition{ @@ -949,9 +949,9 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { adIdentityProvider, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(federationDomain1, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsLegacyConfigurationSuccess(federationDomain1.Spec.Issuer, "", frozenMetav1Now, 123), []metav1.Condition{ @@ -964,11 +964,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { name: "the federation domain specifies identity providers that cannot be found", inputObjects: []runtime.Object{ - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "cant-find-me", ObjectRef: corev1.TypedLocalObjectReference{ @@ -998,12 +998,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1025,11 +1025,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { oidcIdentityProvider, ldapIdentityProvider, adIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "can-find-me", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1078,12 +1078,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), ), }, @@ -1094,11 +1094,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { oidcIdentityProvider, ldapIdentityProvider, adIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "duplicate1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1152,12 +1152,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1173,11 +1173,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { oidcIdentityProvider, ldapIdentityProvider, adIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "name1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1215,12 +1215,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1243,11 +1243,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { oidcIdentityProvider, ldapIdentityProvider, adIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "name1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1277,12 +1277,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1301,11 +1301,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "the federation domain has transformation expressions which don't compile", inputObjects: []runtime.Object{ oidcIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "name1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1313,8 +1313,8 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIdentityProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: "this is not a valid cel expression"}, {Type: "groups/v1", Expression: "this is also not a valid cel expression"}, {Type: "username/v1", Expression: "username"}, // valid @@ -1327,12 +1327,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1364,11 +1364,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "the federation domain has transformation examples which don't pass", inputObjects: []runtime.Object{ oidcIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "name1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1376,18 +1376,18 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIdentityProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "policy/v1", Expression: `username == "ryan" || username == "rejectMeWithDefaultMessage"`, Message: "only ryan allowed"}, {Type: "policy/v1", Expression: `username != "rejectMeWithDefaultMessage"`}, // no message specified {Type: "username/v1", Expression: `"pre:" + username`}, {Type: "groups/v1", Expression: `groups.map(g, "pre:" + g)`}, }, - Examples: []configv1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { // this example should pass Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:ryan", Groups: []string{"pre:b", "pre:a", "pre:b", "pre:a"}, // order and repeats don't matter, treated like a set Rejected: false, @@ -1395,7 +1395,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, { // this example should pass Username: "other", - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "only ryan allowed", }, @@ -1403,7 +1403,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { // this example should fail because it expects the user to be rejected but the user was actually not rejected Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "this input is ignored in this case", }, @@ -1411,7 +1411,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { // this example should fail because it expects the user not to be rejected but they were actually rejected Username: "other", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:other", Groups: []string{"pre:a", "pre:b"}, Rejected: false, @@ -1420,7 +1420,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { // this example should fail because it expects the wrong rejection message Username: "other", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "wrong message", }, @@ -1429,14 +1429,14 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { // because the message assertions defaults to asserting the default rejection message Username: "rejectMeWithDefaultMessage", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, }, }, { // this example should fail because it expects both the wrong username and groups Username: "ryan", Groups: []string{"b", "a"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "wrong", Groups: []string{}, Rejected: false, @@ -1445,7 +1445,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { // this example should fail because it expects the wrong username only Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "wrong", Groups: []string{"pre:b", "pre:a"}, Rejected: false, @@ -1454,7 +1454,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { // this example should fail because it expects the wrong groups only Username: "ryan", Groups: []string{"b", "a"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:ryan", Groups: []string{"wrong2", "wrong1"}, Rejected: false, @@ -1463,7 +1463,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { // this example should fail because it does not expect anything but the auth actually was successful Username: "ryan", Groups: []string{"b", "a"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{}, + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{}, }, }, }, @@ -1473,12 +1473,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1528,11 +1528,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "the federation domain has transformation expressions that return illegal values with examples which exercise them", inputObjects: []runtime.Object{ oidcIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "name1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1540,25 +1540,25 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIdentityProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: `username == "ryan" ? "" : username`}, // not allowed to return an empty string as the transformed username }, - Examples: []configv1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { // every example which encounters an unexpected error should fail because the transformation pipeline returned an error Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{}, + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{}, }, { // every example which encounters an unexpected error should fail because the transformation pipeline returned an error Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{}, + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{}, }, { // this should pass Username: "other", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "other", Groups: []string{"a", "b"}, Rejected: false, @@ -1572,12 +1572,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1599,11 +1599,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "the federation domain has lots of errors including errors from multiple IDPs, which are all shown in the status conditions using IDP indices in the messages", inputObjects: []runtime.Object{ oidcIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://not-unique.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "not unique", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1611,19 +1611,19 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: "this will not be found", }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Constants: []configv1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "foo", Type: "string", StringValue: "bar"}, {Name: "bar", Type: "string", StringValue: "baz"}, }, - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: `username + ":suffix"`}, }, - Examples: []configv1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { // this should fail Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "this is wrong string", Groups: []string{"this is wrong string list"}, }, @@ -1631,7 +1631,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { // this should fail Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "this is also wrong string", Groups: []string{"this is also wrong string list"}, }, @@ -1646,19 +1646,19 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "this is wrong", Name: "foo", }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Constants: []configv1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "foo", Type: "string", StringValue: "bar"}, {Name: "bar", Type: "string", StringValue: "baz"}, }, - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: `username + ":suffix"`}, }, - Examples: []configv1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { // this should pass Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "ryan:suffix", Groups: []string{"a", "b"}, }, @@ -1666,7 +1666,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { { // this should fail Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "this is still wrong string", Groups: []string{"this is still wrong string list"}, }, @@ -1681,8 +1681,8 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: "foo", }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: `username`}, {Type: "username/v1", Expression: `this does not compile`}, {Type: "username/v1", Expression: `username`}, @@ -1693,11 +1693,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, }, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config2", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://not-unique.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "name1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1705,8 +1705,8 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIdentityProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: `username`}, {Type: "username/v1", Expression: `this still does not compile`}, {Type: "username/v1", Expression: `username`}, @@ -1719,12 +1719,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }, wantFDIssuers: []*federationdomainproviders.FederationDomainIssuer{}, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://not-unique.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1781,10 +1781,10 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }), ), expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config2", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseError, + supervisorconfigv1alpha1.FederationDomainPhaseError, conditionstestutil.Replace( allHappyConditionsSuccess("https://not-unique.com", frozenMetav1Now, 123), []metav1.Condition{ @@ -1813,11 +1813,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { inputObjects: []runtime.Object{ oidcIdentityProvider, ldapIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "name1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1825,22 +1825,22 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIdentityProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "policy/v1", Expression: `username == "ryan" || username == "rejectMeWithDefaultMessage"`, Message: "only ryan allowed"}, {Type: "policy/v1", Expression: `username != "rejectMeWithDefaultMessage"`}, // no message specified {Type: "username/v1", Expression: `"pre:" + username`}, {Type: "groups/v1", Expression: `groups.map(g, "pre:" + g)`}, }, - Constants: []configv1alpha1.FederationDomainTransformsConstant{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "str", Type: "string", StringValue: "abc"}, {Name: "strL", Type: "stringList", StringListValue: []string{"def"}}, }, - Examples: []configv1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:ryan", Groups: []string{"pre:b", "pre:a"}, Rejected: false, @@ -1848,21 +1848,21 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, { Username: "other", - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "only ryan allowed", }, }, { Username: "rejectMeWithDefaultMessage", - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, // Not specifying message is the same as expecting the default message. }, }, { Username: "rejectMeWithDefaultMessage", - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "authentication was rejected by a configured policy", // this is the default message }, @@ -1877,15 +1877,15 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "LDAPIdentityProvider", Name: ldapIdentityProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: `"pre:" + username`}, }, - Examples: []configv1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { Username: "ryan", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:ryan", Groups: []string{"b", "a"}, Rejected: false, @@ -1925,12 +1925,12 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { }, }), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate( - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, }, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsSuccess("https://issuer1.com", frozenMetav1Now, 123), ), }, @@ -1939,11 +1939,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "the federation domain specifies illegal const type, which shouldn't really happen since the CRD validates it", inputObjects: []runtime.Object{ oidcIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "can-find-me", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1951,8 +1951,8 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIdentityProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Constants: []configv1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ { Type: "this is illegal", }, @@ -1969,11 +1969,11 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { name: "the federation domain specifies illegal expression type, which shouldn't really happen since the CRD validates it", inputObjects: []runtime.Object{ oidcIdentityProvider, - &configv1alpha1.FederationDomain{ + &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{Name: "config1", Namespace: namespace, Generation: 123}, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://issuer1.com", - IdentityProviders: []configv1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "can-find-me", ObjectRef: corev1.TypedLocalObjectReference{ @@ -1981,8 +1981,8 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIdentityProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ { Type: "this is illegal", }, @@ -2079,7 +2079,7 @@ type comparableFederationDomainIssuer struct { type comparableFederationDomainIdentityProvider struct { DisplayName string UID types.UID - TransformsSource []interface{} + TransformsSource []any } func makeFederationDomainIdentityProviderComparable(fdi *federationdomainproviders.FederationDomainIdentityProvider) *comparableFederationDomainIdentityProvider { @@ -2096,9 +2096,10 @@ func makeFederationDomainIdentityProviderComparable(fdi *federationdomainprovide func convertToComparableType(fdis []*federationdomainproviders.FederationDomainIssuer) []*comparableFederationDomainIssuer { result := []*comparableFederationDomainIssuer{} for _, fdi := range fdis { - comparableFDIs := make([]*comparableFederationDomainIdentityProvider, len(fdi.IdentityProviders())) - for _, idp := range fdi.IdentityProviders() { - comparableFDIs = append(comparableFDIs, makeFederationDomainIdentityProviderComparable(idp)) + identityProviders := fdi.IdentityProviders() + comparableFDIs := make([]*comparableFederationDomainIdentityProvider, len(identityProviders)) + for i, idp := range fdi.IdentityProviders() { + comparableFDIs[i] = makeFederationDomainIdentityProviderComparable(idp) } converted := &comparableFederationDomainIssuer{ issuer: fdi.Issuer(), @@ -2111,15 +2112,15 @@ func convertToComparableType(fdis []*federationdomainproviders.FederationDomainI } func expectedFederationDomainStatusUpdate( - fd *configv1alpha1.FederationDomain, - phase configv1alpha1.FederationDomainPhase, + fd *supervisorconfigv1alpha1.FederationDomain, + phase supervisorconfigv1alpha1.FederationDomainPhase, conditions []metav1.Condition, -) *configv1alpha1.FederationDomain { +) *supervisorconfigv1alpha1.FederationDomain { fdCopy := fd.DeepCopy() // We don't care about the spec of a FederationDomain in an update status action, // so clear it out to make it easier to write expected values. - fdCopy.Spec = configv1alpha1.FederationDomainSpec{} + fdCopy.Spec = supervisorconfigv1alpha1.FederationDomainSpec{} fdCopy.Status.Phase = phase fdCopy.Status.Conditions = conditions @@ -2127,8 +2128,8 @@ func expectedFederationDomainStatusUpdate( return fdCopy } -func getFederationDomainStatusUpdates(t *testing.T, actions []coretesting.Action) []*configv1alpha1.FederationDomain { - federationDomains := []*configv1alpha1.FederationDomain{} +func getFederationDomainStatusUpdates(t *testing.T, actions []coretesting.Action) []*supervisorconfigv1alpha1.FederationDomain { + federationDomains := []*supervisorconfigv1alpha1.FederationDomain{} for _, action := range actions { updateAction, ok := action.(coretesting.UpdateAction) @@ -2136,14 +2137,14 @@ func getFederationDomainStatusUpdates(t *testing.T, actions []coretesting.Action require.Equal(t, federationDomainGVR, updateAction.GetResource(), "an update action should have updated a FederationDomain but updated something else") require.Equal(t, "status", updateAction.GetSubresource(), "an update action should have updated the status subresource but updated something else") - fd, ok := updateAction.GetObject().(*configv1alpha1.FederationDomain) + fd, ok := updateAction.GetObject().(*supervisorconfigv1alpha1.FederationDomain) require.True(t, ok, "failed to cast an action's object as a FederationDomain: %#v", updateAction.GetObject()) require.Equal(t, fd.Namespace, updateAction.GetNamespace(), "an update action might have been called on the wrong namespace for a FederationDomain") // We don't care about the spec of a FederationDomain in an update status action, // so clear it out to make it easier to write expected values. copyOfFD := fd.DeepCopy() - copyOfFD.Spec = configv1alpha1.FederationDomainSpec{} + copyOfFD.Spec = supervisorconfigv1alpha1.FederationDomainSpec{} federationDomains = append(federationDomains, copyOfFD) } @@ -2151,7 +2152,7 @@ func getFederationDomainStatusUpdates(t *testing.T, actions []coretesting.Action return federationDomains } -func sortFederationDomainsByName(federationDomains []*configv1alpha1.FederationDomain) { +func sortFederationDomainsByName(federationDomains []*supervisorconfigv1alpha1.FederationDomain) { sort.SliceStable(federationDomains, func(a, b int) bool { return federationDomains[a].GetName() < federationDomains[b].GetName() }) @@ -2231,7 +2232,7 @@ func TestTransformationPipelinesCanBeTestedForEqualityUsingSourceToMakeTestingEa equalPipeline := idtransform.NewTransformationPipeline() differentPipeline1 := idtransform.NewTransformationPipeline() differentPipeline2 := idtransform.NewTransformationPipeline() - expectedSourceList := []interface{}{} + expectedSourceList := []any{} for i, transform := range transforms { // Compile and append to a pipeline. diff --git a/internal/controller/supervisorconfig/generator/federation_domain_secrets.go b/internal/controller/supervisorconfig/generator/federation_domain_secrets.go index a8c9c6373..b4dae4fe2 100644 --- a/internal/controller/supervisorconfig/generator/federation_domain_secrets.go +++ b/internal/controller/supervisorconfig/generator/federation_domain_secrets.go @@ -16,7 +16,7 @@ import ( "k8s.io/client-go/util/retry" "k8s.io/klog/v2" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" @@ -26,7 +26,7 @@ import ( type federationDomainSecretsController struct { secretHelper SecretHelper - secretRefFunc func(domain *configv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference + secretRefFunc func(domain *supervisorconfigv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference kubeClient kubernetes.Interface pinnipedClient pinnipedsupervisorclientset.Interface federationDomainInformer configinformers.FederationDomainInformer @@ -38,7 +38,7 @@ type federationDomainSecretsController struct { // provides the parent/child mapping logic. func NewFederationDomainSecretsController( secretHelper SecretHelper, - secretRefFunc func(domain *configv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference, + secretRefFunc func(domain *supervisorconfigv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference, kubeClient kubernetes.Interface, pinnipedClient pinnipedsupervisorclientset.Interface, secretInformer corev1informers.SecretInformer, @@ -144,7 +144,7 @@ func (c *federationDomainSecretsController) Sync(ctx controllerlib.Context) erro // secretNeedsUpdate returns whether or not the Secret, with name secretName, for the federationDomain param // needs to be updated. It returns the existing secret as its second argument. func (c *federationDomainSecretsController) secretNeedsUpdate( - federationDomain *configv1alpha1.FederationDomain, + federationDomain *supervisorconfigv1alpha1.FederationDomain, secretName string, ) (bool, *corev1.Secret, error) { // This FederationDomain says it has a secret associated with it. Let's try to get it from the cache. @@ -168,7 +168,7 @@ func (c *federationDomainSecretsController) secretNeedsUpdate( func (c *federationDomainSecretsController) createOrUpdateSecret( ctx context.Context, - federationDomain *configv1alpha1.FederationDomain, + federationDomain *supervisorconfigv1alpha1.FederationDomain, newSecret **corev1.Secret, ) error { secretClient := c.kubeClient.CoreV1().Secrets((*newSecret).Namespace) @@ -207,7 +207,7 @@ func (c *federationDomainSecretsController) createOrUpdateSecret( func (c *federationDomainSecretsController) updateFederationDomainStatus( ctx context.Context, - newFederationDomain *configv1alpha1.FederationDomain, + newFederationDomain *supervisorconfigv1alpha1.FederationDomain, ) error { federationDomainClient := c.pinnipedClient.ConfigV1alpha1().FederationDomains(newFederationDomain.Namespace) return retry.RetryOnConflict(retry.DefaultRetry, func() error { diff --git a/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go b/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go index a72537af7..8abd82f58 100644 --- a/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go +++ b/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go @@ -22,7 +22,7 @@ import ( kubernetesfake "k8s.io/client-go/kubernetes/fake" kubetesting "k8s.io/client-go/testing" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" @@ -72,7 +72,7 @@ func TestFederationDomainControllerFilterSecret(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Name: "some-name", Controller: boolPtr(true), }, @@ -88,7 +88,7 @@ func TestFederationDomainControllerFilterSecret(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", Name: "some-name", }, @@ -104,7 +104,7 @@ func TestFederationDomainControllerFilterSecret(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", Name: "some-name", Controller: boolPtr(true), @@ -128,7 +128,7 @@ func TestFederationDomainControllerFilterSecret(t *testing.T) { Kind: "UnrelatedKind", }, { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", Name: "some-name", Controller: boolPtr(true), @@ -149,7 +149,7 @@ func TestFederationDomainControllerFilterSecret(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", Name: "some-name", Controller: boolPtr(true), @@ -214,7 +214,7 @@ func TestNewFederationDomainSecretsControllerFilterFederationDomain(t *testing.T tests := []struct { name string - federationDomain configv1alpha1.FederationDomain + federationDomain supervisorconfigv1alpha1.FederationDomain wantAdd bool wantUpdate bool wantDelete bool @@ -222,7 +222,7 @@ func TestNewFederationDomainSecretsControllerFilterFederationDomain(t *testing.T }{ { name: "anything goes", - federationDomain: configv1alpha1.FederationDomain{}, + federationDomain: supervisorconfigv1alpha1.FederationDomain{}, wantAdd: true, wantUpdate: true, wantDelete: true, @@ -260,7 +260,7 @@ func TestNewFederationDomainSecretsControllerFilterFederationDomain(t *testing.T withInformer.WithInformer, ) - unrelated := configv1alpha1.FederationDomain{} + unrelated := supervisorconfigv1alpha1.FederationDomain{} filter := withInformer.GetFilterForInformer(federationDomainInformer) require.Equal(t, test.wantAdd, filter.Add(test.federationDomain.DeepCopy())) require.Equal(t, test.wantUpdate, filter.Update(&unrelated, test.federationDomain.DeepCopy())) @@ -285,8 +285,8 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { ) federationDomainGVR := schema.GroupVersionResource{ - Group: configv1alpha1.SchemeGroupVersion.Group, - Version: configv1alpha1.SchemeGroupVersion.Version, + Group: supervisorconfigv1alpha1.SchemeGroupVersion.Group, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Resource: "federationdomains", } @@ -296,7 +296,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { Resource: "secrets", } - goodFederationDomain := &configv1alpha1.FederationDomain{ + goodFederationDomain := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: federationDomainName, Namespace: namespace, @@ -359,7 +359,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { tests := []struct { name string - storage func(**configv1alpha1.FederationDomain, **corev1.Secret) + storage func(**supervisorconfigv1alpha1.FederationDomain, **corev1.Secret) client func(*pinnipedfake.Clientset, *kubernetesfake.Clientset) secretHelper func(*mocksecrethelper.MockSecretHelper) wantFederationDomainActions []kubetesting.Action @@ -368,20 +368,20 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { }{ { name: "FederationDomain does not exist and secret does not exist", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *federationDomain = nil *s = nil }, }, { name: "FederationDomain does not exist and secret exists", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *federationDomain = nil }, }, { name: "FederationDomain exists and secret does not exist", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *s = nil }, secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { @@ -399,7 +399,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { }, { name: "FederationDomain exists and secret does not exist and upon updating FederationDomain we learn a new status field has been set", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *s = nil }, secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { @@ -422,7 +422,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { }, { name: "FederationDomain exists and secret does not exist and upon updating FederationDomain we learn all status fields have been set", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *s = nil }, secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { @@ -444,7 +444,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { }, { name: "FederationDomain exists and invalid secret exists", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *s = invalidSecret.DeepCopy() }, secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { @@ -505,7 +505,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { }, { name: "FederationDomain exists and secret does not exist and creating secret fails", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *s = nil }, secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { @@ -541,7 +541,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { }, { name: "FederationDomain exists and invalid secret exists and updating secret fails due to conflict", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *s = invalidSecret.DeepCopy() }, secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { @@ -570,7 +570,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { }, { name: "FederationDomain exists and invalid secret exists and getting FederationDomain fails", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *s = invalidSecret.DeepCopy() }, secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { @@ -594,7 +594,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { }, { name: "FederationDomain exists and invalid secret exists and updating FederationDomain fails due to conflict", - storage: func(federationDomain **configv1alpha1.FederationDomain, s **corev1.Secret) { + storage: func(federationDomain **supervisorconfigv1alpha1.FederationDomain, s **corev1.Secret) { *s = invalidSecret.DeepCopy() }, secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { @@ -673,7 +673,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { c := NewFederationDomainSecretsController( secretHelper, - func(fd *configv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference { + func(fd *supervisorconfigv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference { return &fd.Secrets.TokenSigningKey }, kubeAPIClient, diff --git a/internal/controller/supervisorconfig/generator/secret_helper.go b/internal/controller/supervisorconfig/generator/secret_helper.go index 3b5a32d86..58f4d4887 100644 --- a/internal/controller/supervisorconfig/generator/secret_helper.go +++ b/internal/controller/supervisorconfig/generator/secret_helper.go @@ -11,7 +11,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" ) // SecretHelper describes an object that can Generate() a Secret and determine whether a Secret @@ -20,9 +20,9 @@ import ( // A SecretHelper has a NamePrefix() that can be used to identify it from other SecretHelper instances. type SecretHelper interface { NamePrefix() string - Generate(*configv1alpha1.FederationDomain) (*corev1.Secret, error) - IsValid(*configv1alpha1.FederationDomain, *corev1.Secret) bool - ObserveActiveSecretAndUpdateParentFederationDomain(*configv1alpha1.FederationDomain, *corev1.Secret) *configv1alpha1.FederationDomain + Generate(*supervisorconfigv1alpha1.FederationDomain) (*corev1.Secret, error) + IsValid(*supervisorconfigv1alpha1.FederationDomain, *corev1.Secret) bool + ObserveActiveSecretAndUpdateParentFederationDomain(*supervisorconfigv1alpha1.FederationDomain, *corev1.Secret) *supervisorconfigv1alpha1.FederationDomain Handles(metav1.Object) bool } @@ -89,7 +89,7 @@ type symmetricSecretHelper struct { func (s *symmetricSecretHelper) NamePrefix() string { return s.namePrefix } // Generate implements SecretHelper.Generate(). -func (s *symmetricSecretHelper) Generate(parent *configv1alpha1.FederationDomain) (*corev1.Secret, error) { +func (s *symmetricSecretHelper) Generate(parent *supervisorconfigv1alpha1.FederationDomain) (*corev1.Secret, error) { key := make([]byte, symmetricKeySize) if _, err := s.rand.Read(key); err != nil { return nil, err @@ -102,8 +102,8 @@ func (s *symmetricSecretHelper) Generate(parent *configv1alpha1.FederationDomain Labels: s.labels, OwnerReferences: []metav1.OwnerReference{ *metav1.NewControllerRef(parent, schema.GroupVersionKind{ - Group: configv1alpha1.SchemeGroupVersion.Group, - Version: configv1alpha1.SchemeGroupVersion.Version, + Group: supervisorconfigv1alpha1.SchemeGroupVersion.Group, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Kind: federationDomainKind, }), }, @@ -116,7 +116,7 @@ func (s *symmetricSecretHelper) Generate(parent *configv1alpha1.FederationDomain } // IsValid implements SecretHelper.IsValid(). -func (s *symmetricSecretHelper) IsValid(parent *configv1alpha1.FederationDomain, secret *corev1.Secret) bool { +func (s *symmetricSecretHelper) IsValid(parent *supervisorconfigv1alpha1.FederationDomain, secret *corev1.Secret) bool { if !metav1.IsControlledBy(secret, parent) { return false } @@ -138,9 +138,9 @@ func (s *symmetricSecretHelper) IsValid(parent *configv1alpha1.FederationDomain, // ObserveActiveSecretAndUpdateParentFederationDomain implements SecretHelper.ObserveActiveSecretAndUpdateParentFederationDomain(). func (s *symmetricSecretHelper) ObserveActiveSecretAndUpdateParentFederationDomain( - federationDomain *configv1alpha1.FederationDomain, + federationDomain *supervisorconfigv1alpha1.FederationDomain, secret *corev1.Secret, -) *configv1alpha1.FederationDomain { +) *supervisorconfigv1alpha1.FederationDomain { s.updateCacheFunc(federationDomain.Spec.Issuer, secret.Data[symmetricSecretDataKey]) switch s.secretUsage { @@ -189,6 +189,6 @@ func IsFederationDomainSecretOfType(obj metav1.Object, secretType corev1.SecretT func isFederationDomainControllee(obj metav1.Object) bool { controller := metav1.GetControllerOf(obj) return controller != nil && - controller.APIVersion == configv1alpha1.SchemeGroupVersion.String() && + controller.APIVersion == supervisorconfigv1alpha1.SchemeGroupVersion.String() && controller.Kind == federationDomainKind } diff --git a/internal/controller/supervisorconfig/generator/secret_helper_test.go b/internal/controller/supervisorconfig/generator/secret_helper_test.go index 7750ad4b5..11abe85ba 100644 --- a/internal/controller/supervisorconfig/generator/secret_helper_test.go +++ b/internal/controller/supervisorconfig/generator/secret_helper_test.go @@ -12,7 +12,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" ) const keyWith32Bytes = "0123456789abcdef0123456789abcdef" @@ -24,13 +24,13 @@ func TestSymmetricSecretHelper(t *testing.T) { name string secretUsage SecretUsage wantSecretType corev1.SecretType - wantSetFederationDomainField func(*configv1alpha1.FederationDomain) string + wantSetFederationDomainField func(*supervisorconfigv1alpha1.FederationDomain) string }{ { name: "token signing key", secretUsage: SecretUsageTokenSigningKey, wantSecretType: "secrets.pinniped.dev/federation-domain-token-signing-key", - wantSetFederationDomainField: func(federationDomain *configv1alpha1.FederationDomain) string { + wantSetFederationDomainField: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string { return federationDomain.Status.Secrets.TokenSigningKey.Name }, }, @@ -38,7 +38,7 @@ func TestSymmetricSecretHelper(t *testing.T) { name: "state signing key", secretUsage: SecretUsageStateSigningKey, wantSecretType: "secrets.pinniped.dev/federation-domain-state-signing-key", - wantSetFederationDomainField: func(federationDomain *configv1alpha1.FederationDomain) string { + wantSetFederationDomainField: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string { return federationDomain.Status.Secrets.StateSigningKey.Name }, }, @@ -46,7 +46,7 @@ func TestSymmetricSecretHelper(t *testing.T) { name: "state encryption key", secretUsage: SecretUsageStateEncryptionKey, wantSecretType: "secrets.pinniped.dev/federation-domain-state-encryption-key", - wantSetFederationDomainField: func(federationDomain *configv1alpha1.FederationDomain) string { + wantSetFederationDomainField: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string { return federationDomain.Status.Secrets.StateEncryptionKey.Name }, }, @@ -74,7 +74,7 @@ func TestSymmetricSecretHelper(t *testing.T) { }, ) - parent := &configv1alpha1.FederationDomain{ + parent := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ UID: "some-uid", Namespace: "some-namespace", @@ -89,8 +89,8 @@ func TestSymmetricSecretHelper(t *testing.T) { Labels: labels, OwnerReferences: []metav1.OwnerReference{ *metav1.NewControllerRef(parent, schema.GroupVersionKind{ - Group: configv1alpha1.SchemeGroupVersion.Group, - Version: configv1alpha1.SchemeGroupVersion.Version, + Group: supervisorconfigv1alpha1.SchemeGroupVersion.Group, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Kind: "FederationDomain", }), }, @@ -124,7 +124,7 @@ func TestSymmetricSecretHelperIsValid(t *testing.T) { name string secretUsage SecretUsage child func(*corev1.Secret) - parent func(*configv1alpha1.FederationDomain) + parent func(*supervisorconfigv1alpha1.FederationDomain) want bool }{ { @@ -167,7 +167,7 @@ func TestSymmetricSecretHelperIsValid(t *testing.T) { child: func(s *corev1.Secret) { s.Type = FederationDomainTokenSigningKeyType }, - parent: func(federationDomain *configv1alpha1.FederationDomain) { + parent: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) { federationDomain.UID = "wrong" }, want: false, @@ -184,7 +184,7 @@ func TestSymmetricSecretHelperIsValid(t *testing.T) { t.Run(test.name, func(t *testing.T) { h := NewSymmetricSecretHelper("none of these args matter", nil, nil, test.secretUsage, nil) - parent := &configv1alpha1.FederationDomain{ + parent := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "some-parent-name", Namespace: "some-namespace", @@ -197,8 +197,8 @@ func TestSymmetricSecretHelperIsValid(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ *metav1.NewControllerRef(parent, schema.GroupVersionKind{ - Group: configv1alpha1.SchemeGroupVersion.Group, - Version: configv1alpha1.SchemeGroupVersion.Version, + Group: supervisorconfigv1alpha1.SchemeGroupVersion.Group, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Kind: "FederationDomain", }), }, diff --git a/internal/controller/supervisorconfig/jwks_observer_test.go b/internal/controller/supervisorconfig/jwks_observer_test.go index c56e03fad..60d8cbb91 100644 --- a/internal/controller/supervisorconfig/jwks_observer_test.go +++ b/internal/controller/supervisorconfig/jwks_observer_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package supervisorconfig @@ -17,7 +17,7 @@ import ( k8sinformers "k8s.io/client-go/informers" kubernetesfake "k8s.io/client-go/kubernetes/fake" - "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" @@ -82,13 +82,13 @@ func TestJWKSObserverControllerInformerFilters(t *testing.T) { when("watching FederationDomain objects", func() { var ( subject controllerlib.Filter - provider, otherProvider *v1alpha1.FederationDomain + provider, otherProvider *supervisorconfigv1alpha1.FederationDomain ) it.Before(func() { subject = federationDomainInformerFilter - provider = &v1alpha1.FederationDomain{ObjectMeta: metav1.ObjectMeta{Name: "any-name", Namespace: "any-namespace"}} - otherProvider = &v1alpha1.FederationDomain{ObjectMeta: metav1.ObjectMeta{Name: "any-other-name", Namespace: "any-other-namespace"}} + provider = &supervisorconfigv1alpha1.FederationDomain{ObjectMeta: metav1.ObjectMeta{Name: "any-name", Namespace: "any-namespace"}} + otherProvider = &supervisorconfigv1alpha1.FederationDomain{ObjectMeta: metav1.ObjectMeta{Name: "any-other-name", Namespace: "any-other-namespace"}} }) when("any FederationDomain changes", func() { @@ -204,78 +204,78 @@ func TestJWKSObserverControllerSync(t *testing.T) { ) it.Before(func() { - federationDomainWithoutSecret1 := &v1alpha1.FederationDomain{ + federationDomainWithoutSecret1 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "no-secret-federationdomain1", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: "https://no-secret-issuer1.com"}, - Status: v1alpha1.FederationDomainStatus{}, // no Secrets.JWKS field + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://no-secret-issuer1.com"}, + Status: supervisorconfigv1alpha1.FederationDomainStatus{}, // no Secrets.JWKS field } - federationDomainWithoutSecret2 := &v1alpha1.FederationDomain{ + federationDomainWithoutSecret2 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "no-secret-federationdomain2", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: "https://no-secret-issuer2.com"}, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://no-secret-issuer2.com"}, // no Status field } - federationDomainWithBadSecret := &v1alpha1.FederationDomain{ + federationDomainWithBadSecret := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "bad-secret-federationdomain", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: "https://bad-secret-issuer.com"}, - Status: v1alpha1.FederationDomainStatus{ - Secrets: v1alpha1.FederationDomainSecrets{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://bad-secret-issuer.com"}, + Status: supervisorconfigv1alpha1.FederationDomainStatus{ + Secrets: supervisorconfigv1alpha1.FederationDomainSecrets{ JWKS: corev1.LocalObjectReference{Name: "bad-secret-name"}, }, }, } - federationDomainWithBadJWKSSecret := &v1alpha1.FederationDomain{ + federationDomainWithBadJWKSSecret := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "bad-jwks-secret-federationdomain", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: "https://bad-jwks-secret-issuer.com"}, - Status: v1alpha1.FederationDomainStatus{ - Secrets: v1alpha1.FederationDomainSecrets{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://bad-jwks-secret-issuer.com"}, + Status: supervisorconfigv1alpha1.FederationDomainStatus{ + Secrets: supervisorconfigv1alpha1.FederationDomainSecrets{ JWKS: corev1.LocalObjectReference{Name: "bad-jwks-secret-name"}, }, }, } - federationDomainWithBadActiveJWKSecret := &v1alpha1.FederationDomain{ + federationDomainWithBadActiveJWKSecret := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "bad-active-jwk-secret-federationdomain", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: "https://bad-active-jwk-secret-issuer.com"}, - Status: v1alpha1.FederationDomainStatus{ - Secrets: v1alpha1.FederationDomainSecrets{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://bad-active-jwk-secret-issuer.com"}, + Status: supervisorconfigv1alpha1.FederationDomainStatus{ + Secrets: supervisorconfigv1alpha1.FederationDomainSecrets{ JWKS: corev1.LocalObjectReference{Name: "bad-active-jwk-secret-name"}, }, }, } - federationDomainWithGoodSecret1 := &v1alpha1.FederationDomain{ + federationDomainWithGoodSecret1 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "good-secret-federationdomain1", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: "https://issuer-with-good-secret1.com"}, - Status: v1alpha1.FederationDomainStatus{ - Secrets: v1alpha1.FederationDomainSecrets{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://issuer-with-good-secret1.com"}, + Status: supervisorconfigv1alpha1.FederationDomainStatus{ + Secrets: supervisorconfigv1alpha1.FederationDomainSecrets{ JWKS: corev1.LocalObjectReference{Name: "good-jwks-secret-name1"}, }, }, } - federationDomainWithGoodSecret2 := &v1alpha1.FederationDomain{ + federationDomainWithGoodSecret2 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "good-secret-federationdomain2", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: "https://issuer-with-good-secret2.com"}, - Status: v1alpha1.FederationDomainStatus{ - Secrets: v1alpha1.FederationDomainSecrets{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://issuer-with-good-secret2.com"}, + Status: supervisorconfigv1alpha1.FederationDomainStatus{ + Secrets: supervisorconfigv1alpha1.FederationDomainSecrets{ JWKS: corev1.LocalObjectReference{Name: "good-jwks-secret-name2"}, }, }, diff --git a/internal/controller/supervisorconfig/jwks_writer.go b/internal/controller/supervisorconfig/jwks_writer.go index df4666ba7..8379796e5 100644 --- a/internal/controller/supervisorconfig/jwks_writer.go +++ b/internal/controller/supervisorconfig/jwks_writer.go @@ -22,7 +22,7 @@ import ( "k8s.io/client-go/util/retry" "k8s.io/klog/v2" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" @@ -52,7 +52,7 @@ const ( // generateKey is stubbed out for the purpose of testing. The default behavior is to generate an EC key. var generateKey = generateECKey //nolint:gochecknoglobals -func generateECKey(r io.Reader) (interface{}, error) { +func generateECKey(r io.Reader) (any, error) { return ecdsa.GenerateKey(elliptic.P256(), r) } @@ -168,7 +168,7 @@ func (c *jwksWriterController) Sync(ctx controllerlib.Context) error { return nil } -func (c *jwksWriterController) secretNeedsUpdate(federationDomain *configv1alpha1.FederationDomain) (bool, error) { +func (c *jwksWriterController) secretNeedsUpdate(federationDomain *supervisorconfigv1alpha1.FederationDomain) (bool, error) { if federationDomain.Status.Secrets.JWKS.Name == "" { // If the FederationDomain says it doesn't have a secret associated with it, then let's create one. return true, nil @@ -193,7 +193,7 @@ func (c *jwksWriterController) secretNeedsUpdate(federationDomain *configv1alpha return false, nil } -func (c *jwksWriterController) generateSecret(federationDomain *configv1alpha1.FederationDomain) (*corev1.Secret, error) { +func (c *jwksWriterController) generateSecret(federationDomain *supervisorconfigv1alpha1.FederationDomain) (*corev1.Secret, error) { // Note! This is where we could potentially add more handling of FederationDomain spec fields which tell us how // this FederationDomain should sign and verify ID tokens (e.g., hardcoded token secret, gRPC // connection to KMS, etc). @@ -231,8 +231,8 @@ func (c *jwksWriterController) generateSecret(federationDomain *configv1alpha1.F Labels: c.jwksSecretLabels, OwnerReferences: []metav1.OwnerReference{ *metav1.NewControllerRef(federationDomain, schema.GroupVersionKind{ - Group: configv1alpha1.SchemeGroupVersion.Group, - Version: configv1alpha1.SchemeGroupVersion.Version, + Group: supervisorconfigv1alpha1.SchemeGroupVersion.Group, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Kind: federationDomainKind, }), }, @@ -284,7 +284,7 @@ func (c *jwksWriterController) createOrUpdateSecret( func (c *jwksWriterController) updateFederationDomainStatus( ctx context.Context, - newFederationDomain *configv1alpha1.FederationDomain, + newFederationDomain *supervisorconfigv1alpha1.FederationDomain, ) error { federationDomainClient := c.pinnipedClient.ConfigV1alpha1().FederationDomains(newFederationDomain.Namespace) return retry.RetryOnConflict(retry.DefaultRetry, func() error { diff --git a/internal/controller/supervisorconfig/jwks_writer_test.go b/internal/controller/supervisorconfig/jwks_writer_test.go index 0f395f01c..247f6df56 100644 --- a/internal/controller/supervisorconfig/jwks_writer_test.go +++ b/internal/controller/supervisorconfig/jwks_writer_test.go @@ -22,7 +22,7 @@ import ( kubernetesfake "k8s.io/client-go/kubernetes/fake" kubetesting "k8s.io/client-go/testing" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" @@ -71,7 +71,7 @@ func TestJWKSWriterControllerFilterSecret(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Name: "some-name", Controller: boolPtr(true), }, @@ -87,7 +87,7 @@ func TestJWKSWriterControllerFilterSecret(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", Name: "some-name", }, @@ -103,7 +103,7 @@ func TestJWKSWriterControllerFilterSecret(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", Name: "some-name", Controller: boolPtr(true), @@ -127,7 +127,7 @@ func TestJWKSWriterControllerFilterSecret(t *testing.T) { Kind: "UnrelatedKind", }, { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", Name: "some-name", Controller: boolPtr(true), @@ -148,7 +148,7 @@ func TestJWKSWriterControllerFilterSecret(t *testing.T) { Namespace: "some-namespace", OwnerReferences: []metav1.OwnerReference{ { - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", Name: "some-name", Controller: boolPtr(true), @@ -204,7 +204,7 @@ func TestJWKSWriterControllerFilterFederationDomain(t *testing.T) { tests := []struct { name string - federationDomain configv1alpha1.FederationDomain + federationDomain supervisorconfigv1alpha1.FederationDomain wantAdd bool wantUpdate bool wantDelete bool @@ -212,7 +212,7 @@ func TestJWKSWriterControllerFilterFederationDomain(t *testing.T) { }{ { name: "anything goes", - federationDomain: configv1alpha1.FederationDomain{}, + federationDomain: supervisorconfigv1alpha1.FederationDomain{}, wantAdd: true, wantUpdate: true, wantDelete: true, @@ -241,7 +241,7 @@ func TestJWKSWriterControllerFilterFederationDomain(t *testing.T) { withInformer.WithInformer, ) - unrelated := configv1alpha1.FederationDomain{} + unrelated := supervisorconfigv1alpha1.FederationDomain{} filter := withInformer.GetFilterForInformer(federationDomainInformer) require.Equal(t, test.wantAdd, filter.Add(test.federationDomain.DeepCopy())) require.Equal(t, test.wantUpdate, filter.Update(&unrelated, test.federationDomain.DeepCopy())) @@ -265,18 +265,18 @@ func TestJWKSWriterControllerSync(t *testing.T) { require.NoError(t, err) federationDomainGVR := schema.GroupVersionResource{ - Group: configv1alpha1.SchemeGroupVersion.Group, - Version: configv1alpha1.SchemeGroupVersion.Version, + Group: supervisorconfigv1alpha1.SchemeGroupVersion.Group, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Resource: "federationdomains", } - goodFederationDomain := &configv1alpha1.FederationDomain{ + goodFederationDomain := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "good-federationDomain", Namespace: namespace, UID: "good-federationDomain-uid", }, - Spec: configv1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://some-issuer.com", }, } @@ -332,7 +332,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { secrets []*corev1.Secret configKubeClient func(*kubernetesfake.Clientset) configPinnipedClient func(*pinnipedfake.Clientset) - federationDomains []*configv1alpha1.FederationDomain + federationDomains []*supervisorconfigv1alpha1.FederationDomain generateKeyErr error wantGenerateKeyCount int wantSecretActions []kubetesting.Action @@ -342,7 +342,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "new federationDomain with no secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, wantGenerateKeyCount: 1, @@ -358,7 +358,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "federationDomain without status with existing secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, secrets: []*corev1.Secret{ @@ -376,7 +376,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "existing federationDomain with no secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, wantGenerateKeyCount: 1, @@ -391,7 +391,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "existing federationDomain with existing secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -406,7 +406,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "missing jwk in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -424,7 +424,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "missing jwks in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -442,7 +442,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "wrong type in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -460,7 +460,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "invalid jwk JSON in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -478,7 +478,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "invalid jwks JSON in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -496,7 +496,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "public jwk in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -514,7 +514,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "private jwks in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -532,7 +532,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "invalid jwk key in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -550,7 +550,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "invalid jwks key in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -568,7 +568,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "missing active jwks in secret", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, secrets: []*corev1.Secret{ @@ -586,7 +586,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "generate key fails", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomainWithStatus, }, generateKeyErr: errors.New("some generate error"), @@ -595,7 +595,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "get secret fails", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, configKubeClient: func(client *kubernetesfake.Clientset) { @@ -608,7 +608,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "create secret fails", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, configKubeClient: func(client *kubernetesfake.Clientset) { @@ -621,7 +621,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "update secret fails", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, secrets: []*corev1.Secret{ @@ -637,7 +637,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "get FederationDomain fails", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, configPinnipedClient: func(client *pinnipedfake.Clientset) { @@ -650,7 +650,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { { name: "update federationDomain fails", key: controllerlib.Key{Namespace: goodFederationDomain.Namespace, Name: goodFederationDomain.Name}, - federationDomains: []*configv1alpha1.FederationDomain{ + federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, configPinnipedClient: func(client *pinnipedfake.Clientset) { @@ -665,7 +665,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { t.Run(test.name, func(t *testing.T) { // We shouldn't run this test in parallel since it messes with a global function (generateKey). generateKeyCount := 0 - generateKey = func(_ io.Reader) (interface{}, error) { + generateKey = func(_ io.Reader) (any, error) { generateKeyCount++ return goodKey, test.generateKeyErr } diff --git a/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher.go b/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher.go index f8a027144..9d7ff8f72 100644 --- a/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher.go +++ b/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher.go @@ -13,7 +13,7 @@ import ( "k8s.io/apimachinery/pkg/labels" corev1informers "k8s.io/client-go/informers/core/v1" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" @@ -30,7 +30,7 @@ const ( ) type ldapUpstreamGenericLDAPImpl struct { - ldapIdentityProvider v1alpha1.LDAPIdentityProvider + ldapIdentityProvider idpv1alpha1.LDAPIdentityProvider } func (g *ldapUpstreamGenericLDAPImpl) Spec() upstreamwatchers.UpstreamGenericLDAPSpec { @@ -54,14 +54,14 @@ func (g *ldapUpstreamGenericLDAPImpl) Status() upstreamwatchers.UpstreamGenericL } type ldapUpstreamGenericLDAPSpec struct { - ldapIdentityProvider v1alpha1.LDAPIdentityProvider + ldapIdentityProvider idpv1alpha1.LDAPIdentityProvider } func (s *ldapUpstreamGenericLDAPSpec) Host() string { return s.ldapIdentityProvider.Spec.Host } -func (s *ldapUpstreamGenericLDAPSpec) TLSSpec() *v1alpha1.TLSSpec { +func (s *ldapUpstreamGenericLDAPSpec) TLSSpec() *idpv1alpha1.TLSSpec { return s.ldapIdentityProvider.Spec.TLS } @@ -84,7 +84,7 @@ func (s *ldapUpstreamGenericLDAPSpec) DetectAndSetSearchBase(_ context.Context, } type ldapUpstreamGenericLDAPUserSearch struct { - userSearch v1alpha1.LDAPIdentityProviderUserSearch + userSearch idpv1alpha1.LDAPIdentityProviderUserSearch } func (u *ldapUpstreamGenericLDAPUserSearch) Base() string { @@ -104,7 +104,7 @@ func (u *ldapUpstreamGenericLDAPUserSearch) UIDAttribute() string { } type ldapUpstreamGenericLDAPGroupSearch struct { - groupSearch v1alpha1.LDAPIdentityProviderGroupSearch + groupSearch idpv1alpha1.LDAPIdentityProviderGroupSearch } func (g *ldapUpstreamGenericLDAPGroupSearch) Base() string { @@ -124,7 +124,7 @@ func (g *ldapUpstreamGenericLDAPGroupSearch) GroupNameAttribute() string { } type ldapUpstreamGenericLDAPStatus struct { - ldapIdentityProvider v1alpha1.LDAPIdentityProvider + ldapIdentityProvider idpv1alpha1.LDAPIdentityProvider } func (s *ldapUpstreamGenericLDAPStatus) Conditions() []metav1.Condition { @@ -226,7 +226,7 @@ func (c *ldapWatcherController) Sync(ctx controllerlib.Context) error { return nil } -func (c *ldapWatcherController) validateUpstream(ctx context.Context, upstream *v1alpha1.LDAPIdentityProvider) (p upstreamprovider.UpstreamLDAPIdentityProviderI, requeue bool) { +func (c *ldapWatcherController) validateUpstream(ctx context.Context, upstream *idpv1alpha1.LDAPIdentityProvider) (p upstreamprovider.UpstreamLDAPIdentityProviderI, requeue bool) { spec := upstream.Spec config := &upstreamldap.ProviderConfig{ @@ -256,15 +256,15 @@ func (c *ldapWatcherController) validateUpstream(ctx context.Context, upstream * return upstreamwatchers.EvaluateConditions(conditions, config) } -func (c *ldapWatcherController) updateStatus(ctx context.Context, upstream *v1alpha1.LDAPIdentityProvider, conditions []*metav1.Condition) { +func (c *ldapWatcherController) updateStatus(ctx context.Context, upstream *idpv1alpha1.LDAPIdentityProvider, conditions []*metav1.Condition) { log := plog.WithValues("namespace", upstream.Namespace, "name", upstream.Name) updated := upstream.DeepCopy() hadErrorCondition := conditionsutil.MergeIDPConditions(conditions, upstream.Generation, &updated.Status.Conditions, log) - updated.Status.Phase = v1alpha1.LDAPPhaseReady + updated.Status.Phase = idpv1alpha1.LDAPPhaseReady if hadErrorCondition { - updated.Status.Phase = v1alpha1.LDAPPhaseError + updated.Status.Phase = idpv1alpha1.LDAPPhaseError } if equality.Semantic.DeepEqual(upstream, updated) { diff --git a/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher_test.go b/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher_test.go index 1e871858a..b42068912 100644 --- a/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher_test.go +++ b/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher_test.go @@ -21,7 +21,7 @@ import ( "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/certauthority" @@ -105,7 +105,7 @@ func TestLDAPUpstreamWatcherControllerFilterLDAPIdentityProviders(t *testing.T) }{ { name: "any LDAPIdentityProvider", - idp: &v1alpha1.LDAPIdentityProvider{ + idp: &idpv1alpha1.LDAPIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Name: "some-name", Namespace: "some-namespace"}, }, wantAdd: true, @@ -175,37 +175,37 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { testCABundle := testCA.Bundle() testCABundleBase64Encoded := base64.StdEncoding.EncodeToString(testCABundle) - validUpstream := &v1alpha1.LDAPIdentityProvider{ + validUpstream := &idpv1alpha1.LDAPIdentityProvider{ ObjectMeta: metav1.ObjectMeta{ Name: testName, Namespace: testNamespace, Generation: 1234, UID: testResourceUID, }, - Spec: v1alpha1.LDAPIdentityProviderSpec{ + Spec: idpv1alpha1.LDAPIdentityProviderSpec{ Host: testHost, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testCABundleBase64Encoded}, - Bind: v1alpha1.LDAPIdentityProviderBind{SecretName: testBindSecretName}, - UserSearch: v1alpha1.LDAPIdentityProviderUserSearch{ + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testCABundleBase64Encoded}, + Bind: idpv1alpha1.LDAPIdentityProviderBind{SecretName: testBindSecretName}, + UserSearch: idpv1alpha1.LDAPIdentityProviderUserSearch{ Base: testUserSearchBase, Filter: testUserSearchFilter, - Attributes: v1alpha1.LDAPIdentityProviderUserSearchAttributes{ + Attributes: idpv1alpha1.LDAPIdentityProviderUserSearchAttributes{ Username: testUserSearchUsernameAttrName, UID: testUserSearchUIDAttrName, }, }, - GroupSearch: v1alpha1.LDAPIdentityProviderGroupSearch{ + GroupSearch: idpv1alpha1.LDAPIdentityProviderGroupSearch{ Base: testGroupSearchBase, Filter: testGroupSearchFilter, UserAttributeForFilter: testGroupSearchUserAttributeForFilter, - Attributes: v1alpha1.LDAPIdentityProviderGroupSearchAttributes{ + Attributes: idpv1alpha1.LDAPIdentityProviderGroupSearchAttributes{ GroupName: testGroupSearchNameAttrName, }, SkipGroupRefresh: false, }, }, } - editedValidUpstream := func(editFunc func(*v1alpha1.LDAPIdentityProvider)) *v1alpha1.LDAPIdentityProvider { + editedValidUpstream := func(editFunc func(*idpv1alpha1.LDAPIdentityProvider)) *idpv1alpha1.LDAPIdentityProvider { deepCopy := validUpstream.DeepCopy() editFunc(deepCopy) return deepCopy @@ -303,7 +303,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { dialErrors map[string]error wantErr string wantResultingCache []*upstreamldap.ProviderConfig - wantResultingUpstreams []v1alpha1.LDAPIdentityProvider + wantResultingUpstreams []idpv1alpha1.LDAPIdentityProvider wantValidatedSettings map[string]upstreamwatchers.ValidatedSettings }{ { @@ -320,9 +320,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -342,9 +342,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { inputSecrets: []runtime.Object{}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ { @@ -370,9 +370,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ { @@ -397,9 +397,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ { @@ -417,15 +417,15 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "CertificateAuthorityData is not base64 encoded", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Spec.TLS.CertificateAuthorityData = "this-is-not-base64-encoded" })}, inputSecrets: []runtime.Object{validBindUserSecret("")}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -443,15 +443,15 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "CertificateAuthorityData is not valid pem data", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Spec.TLS.CertificateAuthorityData = base64.StdEncoding.EncodeToString([]byte("this is not pem data")) })}, inputSecrets: []runtime.Object{validBindUserSecret("")}, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -469,7 +469,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "nil TLS configuration is valid", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Spec.TLS = nil })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -501,9 +501,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -530,7 +530,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when TLS connection fails it tries to use StartTLS instead: without a specified port it automatically switches ports", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Spec.Host = "ldap.example.com" // when the port is not specified, automatically switch ports for StartTLS })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -566,9 +566,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -604,7 +604,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when TLS connection fails it tries to use StartTLS instead: with a specified port it does not automatically switch ports", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Spec.Host = "ldap.example.com:5678" // when the port is specified, do not automatically switch ports for StartTLS })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -639,9 +639,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -663,7 +663,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "non-nil TLS configuration with empty CertificateAuthorityData is valid", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Spec.TLS.CertificateAuthorityData = "" })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -695,9 +695,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -713,7 +713,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "one valid upstream and one invalid upstream updates the cache to include only the valid upstream", - inputUpstreams: []runtime.Object{validUpstream, editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{validUpstream, editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Name = "other-upstream" upstream.Generation = 42 upstream.Spec.Bind.SecretName = "non-existent-secret" @@ -727,10 +727,10 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "other-upstream", Generation: 42, UID: "other-uid"}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ { @@ -747,7 +747,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -774,9 +774,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, wantErr: controllerlib.ErrSyntheticRequeue.Error(), wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -798,7 +798,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was already validated using TLS for the current resource generation and secret version, then do not validate it again and keep using TLS", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ ldapConnectionValidTrueCondition(1234, "4242"), @@ -817,9 +817,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { // Should not perform a test dial and bind. No mocking here means the test will fail if Bind() or Close() are called. }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -835,7 +835,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was already validated using StartTLS for the current resource generation and secret version, then do not validate it again and keep using StartTLS", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ ldapConnectionValidTrueCondition(1234, "4242"), @@ -854,9 +854,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { // Should not perform a test dial and bind. No mocking here means the test will fail if Bind() or Close() are called. }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithStartTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -872,7 +872,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was validated for an older resource generation, then try to validate it again", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Generation = 1234 // current generation upstream.Status.Conditions = []metav1.Condition{ ldapConnectionValidTrueCondition(1233, "4242"), // older spec generation! @@ -892,9 +892,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -910,7 +910,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection condition failed to update previously, then write the cached condition from the previous connection validation", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Generation = 1234 // current generation upstream.Status.Conditions = []metav1.Condition{ ldapConnectionValidTrueCondition(1234, "4200"), // old version of the condition, as if the previous update of conditions had failed @@ -930,9 +930,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { // Should not perform a test dial and bind. No mocking here means the test will fail if Bind() or Close() are called. }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), // updated version of the condition using the cached condition value }, @@ -948,7 +948,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection validation previously failed for this resource generation, then try to validate it again", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ { @@ -968,9 +968,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -987,7 +987,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { { name: "when the validated settings cache is incomplete, then try to validate it again", // this shouldn't happen, but if it does, just throw it out and try again. - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ { @@ -1011,9 +1011,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -1029,7 +1029,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, { name: "when the LDAP server connection was already validated for this resource generation but the bind secret has changed, then try to validate it again", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Generation = 1234 upstream.Status.Conditions = []metav1.Condition{ ldapConnectionValidTrueCondition(1234, "4241"), // same spec generation, old secret version @@ -1049,9 +1049,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { conn.EXPECT().Close().Times(1) }, wantResultingCache: []*upstreamldap.ProviderConfig{providerConfigForValidUpstreamWithTLS}, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: allConditionsTrue(1234, "4242"), }, @@ -1066,7 +1066,7 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }}}, { name: "skipping group refresh is valid", - inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *v1alpha1.LDAPIdentityProvider) { + inputUpstreams: []runtime.Object{editedValidUpstream(func(upstream *idpv1alpha1.LDAPIdentityProvider) { upstream.Spec.GroupSearch.SkipGroupRefresh = true })}, inputSecrets: []runtime.Object{validBindUserSecret("4242")}, @@ -1099,9 +1099,9 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { }, }, }, - wantResultingUpstreams: []v1alpha1.LDAPIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.LDAPIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testResourceUID}, - Status: v1alpha1.LDAPIdentityProviderStatus{ + Status: idpv1alpha1.LDAPIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ bindSecretValidTrueCondition(1234), @@ -1226,13 +1226,13 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { } } -func normalizeLDAPUpstreams(upstreams []v1alpha1.LDAPIdentityProvider, now metav1.Time) []v1alpha1.LDAPIdentityProvider { - result := make([]v1alpha1.LDAPIdentityProvider, 0, len(upstreams)) +func normalizeLDAPUpstreams(upstreams []idpv1alpha1.LDAPIdentityProvider, now metav1.Time) []idpv1alpha1.LDAPIdentityProvider { + result := make([]idpv1alpha1.LDAPIdentityProvider, 0, len(upstreams)) for _, u := range upstreams { normalized := u.DeepCopy() // We're only interested in comparing the status, so zero out the spec. - normalized.Spec = v1alpha1.LDAPIdentityProviderSpec{} + normalized.Spec = idpv1alpha1.LDAPIdentityProviderSpec{} // Round down the LastTransitionTime values to `now` if they were just updated. This makes // it much easier to encode assertions about the expected timestamps. diff --git a/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher.go b/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher.go index dbea00ec8..01f630171 100644 --- a/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher.go +++ b/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher.go @@ -14,7 +14,7 @@ import ( "k8s.io/apimachinery/pkg/labels" corev1informers "k8s.io/client-go/informers/core/v1" - "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configInformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" @@ -127,7 +127,7 @@ func (c *oidcClientWatcherController) Sync(ctx controllerlib.Context) error { func (c *oidcClientWatcherController) updateStatus( ctx context.Context, - upstream *v1alpha1.OIDCClient, + upstream *supervisorconfigv1alpha1.OIDCClient, conditions []*metav1.Condition, totalClientSecrets int, ) error { @@ -136,9 +136,9 @@ func (c *oidcClientWatcherController) updateStatus( hadErrorCondition := conditionsutil.MergeConfigConditions(conditions, upstream.Generation, &updated.Status.Conditions, plog.New(), metav1.Now()) - updated.Status.Phase = v1alpha1.OIDCClientPhaseReady + updated.Status.Phase = supervisorconfigv1alpha1.OIDCClientPhaseReady if hadErrorCondition { - updated.Status.Phase = v1alpha1.OIDCClientPhaseError + updated.Status.Phase = supervisorconfigv1alpha1.OIDCClientPhaseError } updated.Status.TotalClientSecrets = int32(totalClientSecrets) diff --git a/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher_test.go b/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher_test.go index d13bad387..7e4aadf9a 100644 --- a/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher_test.go +++ b/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher_test.go @@ -16,7 +16,7 @@ import ( k8sinformers "k8s.io/client-go/informers" kubernetesfake "k8s.io/client-go/kubernetes/fake" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" @@ -93,14 +93,14 @@ func TestOIDCClientWatcherControllerFilterOIDCClient(t *testing.T) { tests := []struct { name string - oidcClient configv1alpha1.OIDCClient + oidcClient supervisorconfigv1alpha1.OIDCClient wantAdd bool wantUpdate bool wantDelete bool }{ { name: "name has client.oauth.pinniped.dev- prefix", - oidcClient: configv1alpha1.OIDCClient{ + oidcClient: supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Name: "client.oauth.pinniped.dev-foo"}, }, wantAdd: true, @@ -109,7 +109,7 @@ func TestOIDCClientWatcherControllerFilterOIDCClient(t *testing.T) { }, { name: "name does not have client.oauth.pinniped.dev- prefix", - oidcClient: configv1alpha1.OIDCClient{ + oidcClient: supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Name: "something.oauth.pinniped.dev-foo"}, }, wantAdd: false, @@ -118,7 +118,7 @@ func TestOIDCClientWatcherControllerFilterOIDCClient(t *testing.T) { }, { name: "other names without any particular pinniped.dev prefixes", - oidcClient: configv1alpha1.OIDCClient{ + oidcClient: supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Name: "something"}, }, wantAdd: false, @@ -147,7 +147,7 @@ func TestOIDCClientWatcherControllerFilterOIDCClient(t *testing.T) { withInformer.WithInformer, ) - unrelated := configv1alpha1.OIDCClient{} + unrelated := supervisorconfigv1alpha1.OIDCClient{} filter := withInformer.GetFilterForInformer(oidcClientsInformer) require.Equal(t, tt.wantAdd, filter.Add(&tt.oidcClient)) require.Equal(t, tt.wantUpdate, filter.Update(&unrelated, &tt.oidcClient)) @@ -251,7 +251,7 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { inputObjects []runtime.Object inputSecrets []runtime.Object wantErr string - wantResultingOIDCClients []configv1alpha1.OIDCClient + wantResultingOIDCClients []supervisorconfigv1alpha1.OIDCClient wantAPIActions int }{ { @@ -260,37 +260,37 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "OIDCClient with wrong prefix is ignored", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "wrong-prefix-name", Generation: 1234, UID: testUID}, }}, wantAPIActions: 0, // no updates - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "wrong-prefix-name", Generation: 1234, UID: testUID}, }}, }, { name: "successfully validate minimal OIDCClient and one client secret stored (while ignoring client with wrong prefix)", inputObjects: []runtime.Object{ - &configv1alpha1.OIDCClient{ + &supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "wrong-prefix-name", Generation: 1234, UID: testUID}, }, - &configv1alpha1.OIDCClient{ + &supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, }, }, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "wrong-prefix-name", Generation: 1234, UID: testUID}, }, { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -304,18 +304,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate minimal OIDCClient and two client secrets stored", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost, testutil.HashedPassword2AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -328,13 +328,13 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "an already validated OIDCClient does not have its conditions updated when everything is still valid", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(earlier, 1234), @@ -346,9 +346,9 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 0, // no updates - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(earlier, 1234), @@ -361,14 +361,14 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "missing required minimum settings and missing client secret storage", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{}, }}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ sadAllowedGrantTypesCondition(now, 1234, `"authorization_code" must always be included in "allowedGrantTypes"`), @@ -380,18 +380,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "client secret storage exists but cannot be read", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUIDWithWrongVersion(t, testNamespace, testUID)}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -403,18 +403,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "client secret storage exists but does not contain any client secrets", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -427,11 +427,11 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "client secret storage exists but some of the client secrets are invalid bcrypt hashes", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, }}, inputSecrets: []runtime.Object{ @@ -439,9 +439,9 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { []string{testutil.HashedPassword1AtSupervisorMinCost, testutil.HashedPassword1JustBelowSupervisorMinCost, testutil.HashedPassword1InvalidFormat}), }, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -458,24 +458,24 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { { name: "can operate on multiple at a time, e.g. one is valid one another is missing required minimum settings", inputObjects: []runtime.Object{ - &configv1alpha1.OIDCClient{ + &supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "client.oauth.pinniped.dev-test1", Generation: 1234, UID: "uid1"}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, }, - &configv1alpha1.OIDCClient{ + &supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "client.oauth.pinniped.dev-test2", Generation: 4567, UID: "uid2"}, - Spec: configv1alpha1.OIDCClientSpec{}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{}, }, }, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, "uid1", []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 2, // one update for each OIDCClient - wantResultingOIDCClients: []configv1alpha1.OIDCClient{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "client.oauth.pinniped.dev-test1", Generation: 1234, UID: "uid1"}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -487,7 +487,7 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "client.oauth.pinniped.dev-test2", Generation: 4567, UID: "uid2"}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ sadAllowedGrantTypesCondition(now, 4567, `"authorization_code" must always be included in "allowedGrantTypes"`), @@ -501,14 +501,14 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "a previously invalid OIDCClient has its spec changed to become valid so the conditions are updated", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 4567, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, // was invalid on previous run of controller which observed an old generation at an earlier time - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ sadAllowedGrantTypesCondition(earlier, 1234, `"authorization_code" must always be included in "allowedGrantTypes"`), @@ -520,10 +520,10 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 4567, UID: testUID}, // status was updated to reflect the current generation at the current time - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 4567), @@ -536,18 +536,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "refresh_token must be included in allowedGrantTypes when offline_access is included in allowedScopes", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access"}, }, }}, wantAPIActions: 1, // one update inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ sadAllowedGrantTypesCondition(now, 1234, `"refresh_token" must be included in "allowedGrantTypes" when "offline_access" is included in "allowedScopes"`), @@ -560,18 +560,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "multiple errors on allowedScopes and allowedGrantTypes", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"pinniped:request-audience"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"pinniped:request-audience"}, }, }}, wantAPIActions: 1, // one update inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ sadAllowedGrantTypesCondition(now, 1234, @@ -589,18 +589,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "another combination of multiple errors on allowedScopes and allowedGrantTypes", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"urn:ietf:params:oauth:grant-type:token-exchange"}, - AllowedScopes: []configv1alpha1.Scope{"offline_access"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"urn:ietf:params:oauth:grant-type:token-exchange"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"offline_access"}, }, }}, wantAPIActions: 1, // one update inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ sadAllowedGrantTypesCondition(now, 1234, @@ -617,18 +617,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "urn:ietf:params:oauth:grant-type:token-exchange must be included in allowedGrantTypes when pinniped:request-audience is included in allowedScopes", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "pinniped:request-audience", "username", "groups"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "pinniped:request-audience", "username", "groups"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ sadAllowedGrantTypesCondition(now, 1234, `"urn:ietf:params:oauth:grant-type:token-exchange" must be included in "allowedGrantTypes" when "pinniped:request-audience" is included in "allowedScopes"`), @@ -641,18 +641,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "offline_access must be included in allowedScopes when refresh_token is included in allowedGrantTypes", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -665,18 +665,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "username and groups must also be included in allowedScopes when pinniped:request-audience is included in allowedScopes: both missing", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "pinniped:request-audience"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "pinniped:request-audience"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -689,18 +689,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "username and groups must also be included in allowedScopes when pinniped:request-audience is included in allowedScopes: username missing", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "pinniped:request-audience", "groups"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "pinniped:request-audience", "groups"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -713,18 +713,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "username and groups must also be included in allowedScopes when pinniped:request-audience is included in allowedScopes: groups missing", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "pinniped:request-audience", "username"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "pinniped:request-audience", "username"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -737,18 +737,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "pinniped:request-audience must be included in allowedScopes when urn:ietf:params:oauth:grant-type:token-exchange is included in allowedGrantTypes", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange"}, - AllowedScopes: []configv1alpha1.Scope{"openid"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -761,18 +761,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate an OIDCClient with all allowedGrantTypes and all allowedScopes", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -785,18 +785,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate an OIDCClient for offline access without kube API access without username/groups", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -809,18 +809,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate an OIDCClient for offline access without kube API access with username", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "username"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -833,18 +833,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate an OIDCClient for offline access without kube API access with groups", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "groups"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "groups"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -857,18 +857,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate an OIDCClient for offline access without kube API access with both username and groups", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "username", "groups"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username", "groups"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -881,18 +881,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate an OIDCClient without offline access without kube API access with username", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "username"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "username"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -905,18 +905,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate an OIDCClient without offline access without kube API access with groups", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "username"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "username"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -929,18 +929,18 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { }, { name: "successfully validate an OIDCClient without offline access without kube API access with both username and groups", - inputObjects: []runtime.Object{&configv1alpha1.OIDCClient{ + inputObjects: []runtime.Object{&supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "username", "groups"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "username", "groups"}, }, }}, inputSecrets: []runtime.Object{testutil.OIDCClientSecretStorageSecretForUID(t, testNamespace, testUID, []string{testutil.HashedPassword1AtSupervisorMinCost})}, wantAPIActions: 1, // one update - wantResultingOIDCClients: []configv1alpha1.OIDCClient{{ + wantResultingOIDCClients: []supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: configv1alpha1.OIDCClientStatus{ + Status: supervisorconfigv1alpha1.OIDCClientStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAllowedGrantTypesCondition(now, 1234), @@ -995,13 +995,13 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { } } -func normalizeOIDCClients(oidcClients []configv1alpha1.OIDCClient, now metav1.Time) []configv1alpha1.OIDCClient { - result := make([]configv1alpha1.OIDCClient, 0, len(oidcClients)) +func normalizeOIDCClients(oidcClients []supervisorconfigv1alpha1.OIDCClient, now metav1.Time) []supervisorconfigv1alpha1.OIDCClient { + result := make([]supervisorconfigv1alpha1.OIDCClient, 0, len(oidcClients)) for _, u := range oidcClients { normalized := u.DeepCopy() // We're only interested in comparing the status, so zero out the spec. - normalized.Spec = configv1alpha1.OIDCClientSpec{} + normalized.Spec = supervisorconfigv1alpha1.OIDCClientSpec{} // Round down the LastTransitionTime values to `now` if they were just updated. This makes // it much easier to encode assertions about the expected timestamps. diff --git a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher.go b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher.go index 396df85dc..6a624bf58 100644 --- a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher.go +++ b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher.go @@ -25,7 +25,7 @@ import ( "k8s.io/apimachinery/pkg/util/sets" corev1informers "k8s.io/client-go/informers/core/v1" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" @@ -102,7 +102,7 @@ type lruValidatorCacheEntry struct { client *http.Client } -func (c *lruValidatorCache) getProvider(spec *v1alpha1.OIDCIdentityProviderSpec) (*coreosoidc.Provider, *http.Client) { +func (c *lruValidatorCache) getProvider(spec *idpv1alpha1.OIDCIdentityProviderSpec) (*coreosoidc.Provider, *http.Client) { if result, ok := c.cache.Get(c.cacheKey(spec)); ok { entry := result.(*lruValidatorCacheEntry) return entry.provider, entry.client @@ -110,11 +110,11 @@ func (c *lruValidatorCache) getProvider(spec *v1alpha1.OIDCIdentityProviderSpec) return nil, nil } -func (c *lruValidatorCache) putProvider(spec *v1alpha1.OIDCIdentityProviderSpec, provider *coreosoidc.Provider, client *http.Client) { +func (c *lruValidatorCache) putProvider(spec *idpv1alpha1.OIDCIdentityProviderSpec, provider *coreosoidc.Provider, client *http.Client) { c.cache.Set(c.cacheKey(spec), &lruValidatorCacheEntry{provider: provider, client: client}, oidcValidatorCacheTTL) } -func (c *lruValidatorCache) cacheKey(spec *v1alpha1.OIDCIdentityProviderSpec) interface{} { +func (c *lruValidatorCache) cacheKey(spec *idpv1alpha1.OIDCIdentityProviderSpec) any { var key struct{ issuer, caBundle string } key.issuer = spec.Issuer if spec.TLS != nil { @@ -130,8 +130,8 @@ type oidcWatcherController struct { oidcIdentityProviderInformer idpinformers.OIDCIdentityProviderInformer secretInformer corev1informers.SecretInformer validatorCache interface { - getProvider(*v1alpha1.OIDCIdentityProviderSpec) (*coreosoidc.Provider, *http.Client) - putProvider(*v1alpha1.OIDCIdentityProviderSpec, *coreosoidc.Provider, *http.Client) + getProvider(*idpv1alpha1.OIDCIdentityProviderSpec) (*coreosoidc.Provider, *http.Client) + putProvider(*idpv1alpha1.OIDCIdentityProviderSpec, *coreosoidc.Provider, *http.Client) } } @@ -191,9 +191,9 @@ func (c *oidcWatcherController) Sync(ctx controllerlib.Context) error { return nil } -// validateUpstream validates the provided v1alpha1.OIDCIdentityProvider and returns the validated configuration as a -// provider.UpstreamOIDCIdentityProvider. As a side effect, it also updates the status of the v1alpha1.OIDCIdentityProvider. -func (c *oidcWatcherController) validateUpstream(ctx controllerlib.Context, upstream *v1alpha1.OIDCIdentityProvider) *upstreamoidc.ProviderConfig { +// validateUpstream validates the provided idpv1alpha1.OIDCIdentityProvider and returns the validated configuration as a +// provider.UpstreamOIDCIdentityProvider. As a side effect, it also updates the status of the idpv1alpha1.OIDCIdentityProvider. +func (c *oidcWatcherController) validateUpstream(ctx controllerlib.Context, upstream *idpv1alpha1.OIDCIdentityProvider) *upstreamoidc.ProviderConfig { authorizationConfig := upstream.Spec.AuthorizationConfig additionalAuthcodeAuthorizeParameters := map[string]string{} @@ -261,7 +261,7 @@ func (c *oidcWatcherController) validateUpstream(ctx controllerlib.Context, upst } // validateSecret validates the .spec.client.secretName field and returns the appropriate ClientCredentialsValid condition. -func (c *oidcWatcherController) validateSecret(upstream *v1alpha1.OIDCIdentityProvider, result *upstreamoidc.ProviderConfig) *metav1.Condition { +func (c *oidcWatcherController) validateSecret(upstream *idpv1alpha1.OIDCIdentityProvider, result *upstreamoidc.ProviderConfig) *metav1.Condition { secretName := upstream.Spec.Client.SecretName // Fetch the Secret from informer cache. @@ -309,7 +309,7 @@ func (c *oidcWatcherController) validateSecret(upstream *v1alpha1.OIDCIdentityPr } // validateIssuer validates the .spec.issuer field, performs OIDC discovery, and returns the appropriate OIDCDiscoverySucceeded condition. -func (c *oidcWatcherController) validateIssuer(ctx context.Context, upstream *v1alpha1.OIDCIdentityProvider, result *upstreamoidc.ProviderConfig) *metav1.Condition { +func (c *oidcWatcherController) validateIssuer(ctx context.Context, upstream *idpv1alpha1.OIDCIdentityProvider, result *upstreamoidc.ProviderConfig) *metav1.Condition { // Get the provider and HTTP Client from cache if possible. discoveredProvider, httpClient := c.validatorCache.getProvider(&upstream.Spec) @@ -408,15 +408,15 @@ func (c *oidcWatcherController) validateIssuer(ctx context.Context, upstream *v1 } } -func (c *oidcWatcherController) updateStatus(ctx context.Context, upstream *v1alpha1.OIDCIdentityProvider, conditions []*metav1.Condition) { +func (c *oidcWatcherController) updateStatus(ctx context.Context, upstream *idpv1alpha1.OIDCIdentityProvider, conditions []*metav1.Condition) { log := c.log.WithValues("namespace", upstream.Namespace, "name", upstream.Name) updated := upstream.DeepCopy() hadErrorCondition := conditionsutil.MergeIDPConditions(conditions, upstream.Generation, &updated.Status.Conditions, log) - updated.Status.Phase = v1alpha1.PhaseReady + updated.Status.Phase = idpv1alpha1.PhaseReady if hadErrorCondition { - updated.Status.Phase = v1alpha1.PhaseError + updated.Status.Phase = idpv1alpha1.PhaseError } if equality.Semantic.DeepEqual(upstream, updated) { @@ -432,7 +432,7 @@ func (c *oidcWatcherController) updateStatus(ctx context.Context, upstream *v1al } } -func getClient(upstream *v1alpha1.OIDCIdentityProvider) (*http.Client, error) { +func getClient(upstream *idpv1alpha1.OIDCIdentityProvider) (*http.Client, error) { if upstream.Spec.TLS == nil || upstream.Spec.TLS.CertificateAuthorityData == "" { return defaultClientShortTimeout(nil), nil } diff --git a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go index 5810e272d..4221eb968 100644 --- a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go +++ b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go @@ -23,7 +23,7 @@ import ( "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/certauthority" @@ -140,7 +140,7 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { testAdditionalScopes = []string{"scope1", "scope2", "scope3"} testExpectedScopes = []string{"openid", "scope1", "scope2", "scope3"} testDefaultExpectedScopes = []string{"openid", "offline_access", "email", "profile"} - testAdditionalParams = []v1alpha1.Parameter{{Name: "prompt", Value: "consent"}, {Name: "foo", Value: "bar"}} + testAdditionalParams = []idpv1alpha1.Parameter{{Name: "prompt", Value: "consent"}, {Name: "foo", Value: "bar"}} testExpectedAdditionalParams = map[string]string{"prompt": "consent", "foo": "bar"} testClientID = "test-oidc-client-id" testClientSecret = "test-oidc-client-secret" @@ -156,19 +156,19 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { wantErr string wantLogs []string wantResultingCache []*oidctestutil.TestUpstreamOIDCIdentityProvider - wantResultingUpstreams []v1alpha1.OIDCIdentityProvider + wantResultingUpstreams []idpv1alpha1.OIDCIdentityProvider }{ { name: "no upstreams", }, { name: "missing secret", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{}, @@ -180,9 +180,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="secret \"test-client-secret\" not found" "name"="test-name" "namespace"="test-namespace" "reason"="SecretNotFound" "type"="ClientCredentialsValid"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -206,12 +206,12 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "secret has wrong type", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -227,9 +227,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="referenced Secret \"test-client-secret\" has wrong type \"some-other-type\" (should be \"secrets.pinniped.dev/oidc-client\")" "name"="test-name" "namespace"="test-namespace" "reason"="SecretWrongType" "type"="ClientCredentialsValid"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -253,12 +253,12 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "secret is missing key", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -273,9 +273,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="referenced Secret \"test-client-secret\" is missing required keys [\"clientID\" \"clientSecret\"]" "name"="test-name" "namespace"="test-namespace" "reason"="SecretMissingKeys" "type"="ClientCredentialsValid"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -299,14 +299,14 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "TLS CA bundle is invalid base64", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "test-name"}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{ + TLS: &idpv1alpha1.TLSSpec{ CertificateAuthorityData: "invalid-base64", }, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -322,9 +322,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="spec.certificateAuthorityData is invalid: illegal base64 data at input byte 7" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidTLSConfig" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -348,14 +348,14 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "TLS CA bundle does not have any certificates", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "test-name"}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{ + TLS: &idpv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte("not-a-pem-ca-bundle")), }, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -371,9 +371,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="spec.certificateAuthorityData is invalid: no certificates found" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidTLSConfig" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -397,11 +397,11 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "issuer is invalid URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: "%invalid-url-that-is-really-really-long-nanananananananannanananan-batman-nanananananananananananananana-batman-lalalalalalalalalal-batman-weeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -417,9 +417,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="failed to parse issuer URL: parse \"%invalid-url-that-is-really-really-long-nanananananananannanananan-batman-nanananananananananananananana-batman-lalalalalalalalalal-batman-weeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\": invalid URL escape \"%in\"" "name"="test-name" "namespace"="test-namespace" "reason"="Unreachable" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -443,11 +443,11 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "issuer is insecure http URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: strings.Replace(testIssuerURL, "https", "http", 1), - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -463,9 +463,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="issuer URL '` + strings.Replace(testIssuerURL, "https", "http", 1) + `' must have \"https\" scheme, not \"http\"" "name"="test-name" "namespace"="test-namespace" "reason"="Unreachable" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -489,11 +489,11 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "issuer contains a query param", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "?sub=foo", - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -509,9 +509,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="issuer URL '` + testIssuerURL + "?sub=foo" + `' cannot contain query or fragment component" "name"="test-name" "namespace"="test-namespace" "reason"="Unreachable" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -535,11 +535,11 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "issuer contains a fragment", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "#fragment", - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -555,9 +555,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="issuer URL '` + testIssuerURL + "#fragment" + `' cannot contain query or fragment component" "name"="test-name" "namespace"="test-namespace" "reason"="Unreachable" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -581,12 +581,12 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { }, { name: "really long issuer with invalid CA bundle", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/valid-url-that-is-really-really-long-nanananananananannanananan-batman-nanananananananananananananana-batman-lalalalalalalalalal-batman-weeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: wrongCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: wrongCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -603,9 +603,9 @@ func TestOIDCUpstreamWatcherControllerSync(t *testing.T) { `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="failed to perform OIDC discovery against \"` + testIssuerURL + `/valid-url-that-is-really-really-long-nanananananananannanananan-batman-nanananananananananananananana-batman-lalalalalalalalalal-batman-weeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\":\nGet \"` + testIssuerURL + `/valid-url-that-is-really-really-long-nanananananananannanananan-batman-nanananananananananananananana-batman-lalalalalalalalalal-batman-weeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee/.well-known/openid-configuration\": tls: failed to verify certificate: x509: certificate signed by unknown authority" "name"="test-name" "namespace"="test-namespace" "reason"="Unreachable" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -630,12 +630,12 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "issuer returns invalid authorize URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/invalid", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -651,9 +651,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="failed to parse authorization endpoint URL: parse \"%\": invalid URL escape \"%\"" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidResponse" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -677,12 +677,12 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "issuer returns invalid revocation URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/invalid-revocation-url", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -698,9 +698,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="failed to parse revocation endpoint URL: parse \"%\": invalid URL escape \"%\"" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidResponse" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -724,12 +724,12 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "issuer returns insecure authorize URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/insecure", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -745,9 +745,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="authorization endpoint URL 'http://example.com/authorize' must have \"https\" scheme, not \"http\"" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidResponse" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -771,12 +771,12 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "issuer returns insecure revocation URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/insecure-revocation-url", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -792,9 +792,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="revocation endpoint URL 'http://example.com/revoke' must have \"https\" scheme, not \"http\"" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidResponse" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -818,12 +818,12 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "issuer returns insecure token URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/insecure-token-url", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -839,9 +839,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="token endpoint URL 'http://example.com/token' must have \"https\" scheme, not \"http\"" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidResponse" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -865,12 +865,12 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "issuer returns no token URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/missing-token-url", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -886,9 +886,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="token endpoint URL '' must have \"https\" scheme, not \"\"" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidResponse" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -912,12 +912,12 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "issuer returns no auth URL", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/missing-auth-url", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -933,9 +933,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="authorization endpoint URL '' must have \"https\" scheme, not \"\"" "name"="test-name" "namespace"="test-namespace" "reason"="InvalidResponse" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -959,19 +959,19 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "upstream with error becomes valid", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "test-name", UID: testUID}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, - AuthorizationConfig: v1alpha1.OIDCAuthorizationConfig{ + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, + AuthorizationConfig: idpv1alpha1.OIDCAuthorizationConfig{ AdditionalScopes: append(testAdditionalScopes, "xyz", "openid"), // adds openid unnecessarily AllowPasswordGrant: true, }, - Claims: v1alpha1.OIDCClaims{Groups: testGroupsClaim, Username: testUsernameClaim}, + Claims: idpv1alpha1.OIDCClaims{Groups: testGroupsClaim, Username: testUsernameClaim}, }, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ {Type: "ClientCredentialsValid", Status: "False", LastTransitionTime: earlier, Reason: "SomeError1", Message: "some previous error 1"}, @@ -1004,9 +1004,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana ResourceUID: testUID, }, }, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, UID: testUID}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -1018,15 +1018,15 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "existing valid upstream with default authorizationConfig", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, - Claims: v1alpha1.OIDCClaims{Groups: testGroupsClaim, Username: testUsernameClaim}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, + Claims: idpv1alpha1.OIDCClaims{Groups: testGroupsClaim, Username: testUsernameClaim}, }, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidConditionEarlier, @@ -1060,9 +1060,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana ResourceUID: testUID, }, }, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ {Type: "AdditionalAuthorizeParametersValid", Status: "True", LastTransitionTime: earlier, Reason: "Success", Message: "additionalAuthorizeParameters parameter names are allowed", ObservedGeneration: 1234}, @@ -1074,15 +1074,15 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "existing valid upstream with no revocation endpoint in the discovery document", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/valid-without-revocation", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, - Claims: v1alpha1.OIDCClaims{Groups: testGroupsClaim, Username: testUsernameClaim}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, + Claims: idpv1alpha1.OIDCClaims{Groups: testGroupsClaim, Username: testUsernameClaim}, }, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidConditionEarlier, @@ -1116,9 +1116,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana ResourceUID: testUID, }, }, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ {Type: "AdditionalAuthorizeParametersValid", Status: "True", LastTransitionTime: earlier, Reason: "Success", Message: "additionalAuthorizeParameters parameter names are allowed", ObservedGeneration: 1234}, @@ -1130,18 +1130,18 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "existing valid upstream with additionalScopes set to override the default", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, - Claims: v1alpha1.OIDCClaims{Groups: testGroupsClaim, Username: testUsernameClaim}, - AuthorizationConfig: v1alpha1.OIDCAuthorizationConfig{ + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, + Claims: idpv1alpha1.OIDCClaims{Groups: testGroupsClaim, Username: testUsernameClaim}, + AuthorizationConfig: idpv1alpha1.OIDCAuthorizationConfig{ AdditionalScopes: testAdditionalScopes, }, }, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidConditionEarlier, @@ -1175,9 +1175,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana ResourceUID: testUID, }, }, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ {Type: "AdditionalAuthorizeParametersValid", Status: "True", LastTransitionTime: earlier, Reason: "Success", Message: "additionalAuthorizeParameters parameter names are allowed", ObservedGeneration: 1234}, @@ -1189,18 +1189,18 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "existing valid upstream with trailing slash and more optional settings", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/ends-with-slash/", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, - AuthorizationConfig: v1alpha1.OIDCAuthorizationConfig{ + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, + AuthorizationConfig: idpv1alpha1.OIDCAuthorizationConfig{ AdditionalScopes: testAdditionalScopes, AdditionalAuthorizeParameters: testAdditionalParams, AllowPasswordGrant: true, }, - Claims: v1alpha1.OIDCClaims{ + Claims: idpv1alpha1.OIDCClaims{ Groups: testGroupsClaim, Username: testUsernameClaim, AdditionalClaimMappings: map[string]string{ @@ -1208,7 +1208,7 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, }, }, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidConditionEarlier, @@ -1244,9 +1244,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana ResourceUID: testUID, }, }, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Ready", Conditions: []metav1.Condition{ {Type: "AdditionalAuthorizeParametersValid", Status: "True", LastTransitionTime: earlier, Reason: "Success", Message: "additionalAuthorizeParameters parameter names are allowed", ObservedGeneration: 1234}, @@ -1258,14 +1258,14 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "has disallowed additionalAuthorizeParams keys", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL, - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, - AuthorizationConfig: v1alpha1.OIDCAuthorizationConfig{ - AdditionalAuthorizeParameters: []v1alpha1.Parameter{ + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, + AuthorizationConfig: idpv1alpha1.OIDCAuthorizationConfig{ + AdditionalAuthorizeParameters: []idpv1alpha1.Parameter{ {Name: "response_type", Value: "foo"}, {Name: "scope", Value: "foo"}, {Name: "client_id", Value: "foo"}, @@ -1293,9 +1293,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="the following additionalAuthorizeParameters are not allowed: response_type,scope,client_id,state,nonce,code_challenge,code_challenge_method,redirect_uri,hd" "name"="test-name" "namespace"="test-namespace" "reason"="DisallowedParameterName" "type"="AdditionalAuthorizeParametersValid"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ {Type: "AdditionalAuthorizeParametersValid", Status: "False", LastTransitionTime: now, Reason: "DisallowedParameterName", @@ -1309,12 +1309,12 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana }, { name: "issuer is invalid URL, missing trailing slash when the OIDC discovery endpoint returns the URL with a trailing slash", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/ends-with-slash", // this does not end with slash when it should, thus this is an error case - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -1331,9 +1331,9 @@ Get "` + testIssuerURL + `/valid-url-that-is-really-really-long-nananananananana `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="failed to perform OIDC discovery against \"` + testIssuerURL + `/ends-with-slash\":\noidc: issuer did not match the issuer returned by provider, expected \"` + testIssuerURL + `/ends-with-slash\" got \"` + testIssuerURL + `/ends-with-slash/\"" "name"="test-name" "namespace"="test-namespace" "reason"="Unreachable" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -1358,12 +1358,12 @@ oidc: issuer did not match the issuer returned by provider, expected "` + testIs }, { name: "issuer is invalid URL, extra trailing slash", - inputUpstreams: []runtime.Object{&v1alpha1.OIDCIdentityProvider{ + inputUpstreams: []runtime.Object{&idpv1alpha1.OIDCIdentityProvider{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Spec: v1alpha1.OIDCIdentityProviderSpec{ + Spec: idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: testIssuerURL + "/", - TLS: &v1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, - Client: v1alpha1.OIDCClient{SecretName: testSecretName}, + TLS: &idpv1alpha1.TLSSpec{CertificateAuthorityData: testIssuerCABase64}, + Client: idpv1alpha1.OIDCClient{SecretName: testSecretName}, }, }}, inputSecrets: []runtime.Object{&corev1.Secret{ @@ -1380,9 +1380,9 @@ oidc: issuer did not match the issuer returned by provider, expected "` + testIs `oidc-upstream-observer "msg"="found failing condition" "error"="OIDCIdentityProvider has a failing condition" "message"="failed to perform OIDC discovery against \"` + testIssuerURL + `/\":\noidc: issuer did not match the issuer returned by provider, expected \"` + testIssuerURL + `/\" got \"` + testIssuerURL + `\"" "name"="test-name" "namespace"="test-namespace" "reason"="Unreachable" "type"="OIDCDiscoverySucceeded"`, }, wantResultingCache: []*oidctestutil.TestUpstreamOIDCIdentityProvider{}, - wantResultingUpstreams: []v1alpha1.OIDCIdentityProvider{{ + wantResultingUpstreams: []idpv1alpha1.OIDCIdentityProvider{{ ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName}, - Status: v1alpha1.OIDCIdentityProviderStatus{ + Status: idpv1alpha1.OIDCIdentityProviderStatus{ Phase: "Error", Conditions: []metav1.Condition{ happyAdditionalAuthorizeParametersValidCondition, @@ -1504,13 +1504,13 @@ func unwrapTransport(t *testing.T, rt http.RoundTripper) *http.Transport { } } -func normalizeOIDCUpstreams(upstreams []v1alpha1.OIDCIdentityProvider, now metav1.Time) []v1alpha1.OIDCIdentityProvider { - result := make([]v1alpha1.OIDCIdentityProvider, 0, len(upstreams)) +func normalizeOIDCUpstreams(upstreams []idpv1alpha1.OIDCIdentityProvider, now metav1.Time) []idpv1alpha1.OIDCIdentityProvider { + result := make([]idpv1alpha1.OIDCIdentityProvider, 0, len(upstreams)) for _, u := range upstreams { normalized := u.DeepCopy() // We're only interested in comparing the status, so zero out the spec. - normalized.Spec = v1alpha1.OIDCIdentityProviderSpec{} + normalized.Spec = idpv1alpha1.OIDCIdentityProviderSpec{} // Round down the LastTransitionTime values to `now` if they were just updated. This makes // it much easier to encode assertions about the expected timestamps. diff --git a/internal/controller/supervisorconfig/tls_cert_observer_test.go b/internal/controller/supervisorconfig/tls_cert_observer_test.go index e104204c6..01a33e865 100644 --- a/internal/controller/supervisorconfig/tls_cert_observer_test.go +++ b/internal/controller/supervisorconfig/tls_cert_observer_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package supervisorconfig @@ -18,7 +18,7 @@ import ( k8sinformers "k8s.io/client-go/informers" kubernetesfake "k8s.io/client-go/kubernetes/fake" - "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" @@ -83,13 +83,13 @@ func TestTLSCertObserverControllerInformerFilters(t *testing.T) { when("watching FederationDomain objects", func() { var ( subject controllerlib.Filter - provider, otherProvider *v1alpha1.FederationDomain + provider, otherProvider *supervisorconfigv1alpha1.FederationDomain ) it.Before(func() { subject = federationDomainInformerFilter - provider = &v1alpha1.FederationDomain{ObjectMeta: metav1.ObjectMeta{Name: "any-name", Namespace: "any-namespace"}} - otherProvider = &v1alpha1.FederationDomain{ObjectMeta: metav1.ObjectMeta{Name: "any-other-name", Namespace: "any-other-namespace"}} + provider = &supervisorconfigv1alpha1.FederationDomain{ObjectMeta: metav1.ObjectMeta{Name: "any-name", Namespace: "any-namespace"}} + otherProvider = &supervisorconfigv1alpha1.FederationDomain{ObjectMeta: metav1.ObjectMeta{Name: "any-other-name", Namespace: "any-other-namespace"}} }) when("any FederationDomain changes", func() { @@ -219,75 +219,75 @@ func TestTLSCertObserverControllerSync(t *testing.T) { it.Before(func() { var err error - federationDomainWithoutSecret1 := &v1alpha1.FederationDomain{ + federationDomainWithoutSecret1 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "no-secret-federationdomain1", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: "https://no-secret-issuer1.com"}, // no SNICertificateSecretName field + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: "https://no-secret-issuer1.com"}, // no SNICertificateSecretName field } - federationDomainWithoutSecret2 := &v1alpha1.FederationDomain{ + federationDomainWithoutSecret2 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "no-secret-federationdomain2", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://no-secret-issuer2.com", - TLS: &v1alpha1.FederationDomainTLSSpec{SecretName: ""}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: ""}, }, } - federationDomainWithBadSecret := &v1alpha1.FederationDomain{ + federationDomainWithBadSecret := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "bad-secret-federationdomain", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://bad-secret-issuer.com", - TLS: &v1alpha1.FederationDomainTLSSpec{SecretName: "bad-tls-secret-name"}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: "bad-tls-secret-name"}, }, } // Also add one with a URL that cannot be parsed to make sure that the controller is not confused by invalid URLs. invalidIssuerURL := ":/host//path" _, err = url.Parse(invalidIssuerURL) //nolint:staticcheck // Yes, this URL is intentionally invalid. r.Error(err) - federationDomainWithBadIssuer := &v1alpha1.FederationDomain{ + federationDomainWithBadIssuer := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "bad-issuer-federationdomain", Namespace: installedInNamespace, }, - Spec: v1alpha1.FederationDomainSpec{Issuer: invalidIssuerURL}, + Spec: supervisorconfigv1alpha1.FederationDomainSpec{Issuer: invalidIssuerURL}, } - federationDomainWithGoodSecret1 := &v1alpha1.FederationDomain{ + federationDomainWithGoodSecret1 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "good-secret-federationdomain1", Namespace: installedInNamespace, }, // Issuer hostname should be treated in a case-insensitive way and SNI ignores port numbers. Test without a port number. - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://www.iSSuer-wiTh-goOd-secRet1.cOm/path", - TLS: &v1alpha1.FederationDomainTLSSpec{SecretName: "good-tls-secret-name1"}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: "good-tls-secret-name1"}, }, } - federationDomainWithGoodSecret2 := &v1alpha1.FederationDomain{ + federationDomainWithGoodSecret2 := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "good-secret-federationdomain2", Namespace: installedInNamespace, }, // Issuer hostname should be treated in a case-insensitive way and SNI ignores port numbers. Test with a port number. - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://www.issUEr-WIth-gOOd-seCret2.com:1234/path", - TLS: &v1alpha1.FederationDomainTLSSpec{SecretName: "good-tls-secret-name2"}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: "good-tls-secret-name2"}, }, } - federationDomainWithIPv6Issuer := &v1alpha1.FederationDomain{ + federationDomainWithIPv6Issuer := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "ipv6-issuer-federationdomain", Namespace: installedInNamespace, }, // Issuer hostname should be treated correctly when it is an IPv6 address. Test with a port number. - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://[2001:db8::1]:1234/path", - TLS: &v1alpha1.FederationDomainTLSSpec{SecretName: "good-tls-secret-name1"}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: "good-tls-secret-name1"}, }, } testCrt1 := readTestFile("testdata/test.crt") diff --git a/internal/controller/supervisorconfig/upstreamwatchers/upstream_watchers.go b/internal/controller/supervisorconfig/upstreamwatchers/upstream_watchers.go index 0417463fa..7d3d4f738 100644 --- a/internal/controller/supervisorconfig/upstreamwatchers/upstream_watchers.go +++ b/internal/controller/supervisorconfig/upstreamwatchers/upstream_watchers.go @@ -1,4 +1,4 @@ -// Copyright 2021-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package upstreamwatchers @@ -14,7 +14,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1informers "k8s.io/client-go/informers/core/v1" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/constable" "go.pinniped.dev/internal/federationdomain/upstreamprovider" "go.pinniped.dev/internal/plog" @@ -110,7 +110,7 @@ type UpstreamGenericLDAPIDP interface { type UpstreamGenericLDAPSpec interface { Host() string - TLSSpec() *v1alpha1.TLSSpec + TLSSpec() *idpv1alpha1.TLSSpec BindSecretName() string UserSearch() UpstreamGenericLDAPUserSearch GroupSearch() UpstreamGenericLDAPGroupSearch @@ -135,7 +135,7 @@ type UpstreamGenericLDAPStatus interface { Conditions() []metav1.Condition } -func ValidateTLSConfig(tlsSpec *v1alpha1.TLSSpec, config *upstreamldap.ProviderConfig) *metav1.Condition { +func ValidateTLSConfig(tlsSpec *idpv1alpha1.TLSSpec, config *upstreamldap.ProviderConfig) *metav1.Condition { if tlsSpec == nil { return validTLSCondition(noTLSConfigurationMessage) } diff --git a/internal/controller/supervisorstorage/garbage_collector.go b/internal/controller/supervisorstorage/garbage_collector.go index bd791f8ba..26285d53c 100644 --- a/internal/controller/supervisorstorage/garbage_collector.go +++ b/internal/controller/supervisorstorage/garbage_collector.go @@ -278,8 +278,8 @@ func (c *garbageCollectorController) tryRevokeUpstreamOIDCToken(ctx context.Cont return nil } -func logKV(secret *corev1.Secret) []interface{} { - return []interface{}{ +func logKV(secret *corev1.Secret) []any { + return []any{ "secretName", secret.Name, "secretNamespace", secret.Namespace, "secretType", string(secret.Type), diff --git a/internal/controllerinit/controllerinit.go b/internal/controllerinit/controllerinit.go index 825817e49..8129d65aa 100644 --- a/internal/controllerinit/controllerinit.go +++ b/internal/controllerinit/controllerinit.go @@ -72,8 +72,8 @@ func unsyncedInformers(status map[reflect.Type]bool) []string { return names } -func anyToFullname(any interface{}) string { - typ := reflect.TypeOf(any) +func anyToFullname(a any) string { + typ := reflect.TypeOf(a) return typeToFullname(typ) } diff --git a/internal/controllerlib/die.go b/internal/controllerlib/die.go index 1c4c6b412..9ee60d919 100644 --- a/internal/controllerlib/die.go +++ b/internal/controllerlib/die.go @@ -1,11 +1,11 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package controllerlib type die string -func crash(i interface{}) { +func crash(i any) { mustDie, ok := i.(die) if ok { panic(string(mustDie)) diff --git a/internal/controllerlib/option.go b/internal/controllerlib/option.go index 894a13665..f74958268 100644 --- a/internal/controllerlib/option.go +++ b/internal/controllerlib/option.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package controllerlib @@ -60,7 +60,7 @@ func WithInformer(getter InformerGetter, filter Filter, opt InformerOption) Opti } _, err := informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { object := metaOrDie(obj) if filter.Add(object) { plog.Debug("handling add", @@ -73,7 +73,7 @@ func WithInformer(getter InformerGetter, filter Filter, opt InformerOption) Opti c.add(filter, object) } }, - UpdateFunc: func(oldObj, newObj interface{}) { + UpdateFunc: func(oldObj, newObj any) { oldObject := metaOrDie(oldObj) newObject := metaOrDie(newObj) if filter.Update(oldObject, newObject) { @@ -87,7 +87,7 @@ func WithInformer(getter InformerGetter, filter Filter, opt InformerOption) Opti c.add(filter, newObject) } }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { accessor, err := meta.Accessor(obj) if err != nil { tombstone, ok := obj.(cache.DeletedFinalStateUnknown) @@ -146,7 +146,7 @@ func toOnceOpt(opt Option) Option { } } -func metaOrDie(obj interface{}) metav1.Object { +func metaOrDie(obj any) metav1.Object { accessor, err := meta.Accessor(obj) if err != nil { panic(err) // this should never happen diff --git a/internal/controllerlib/recorder.go b/internal/controllerlib/recorder.go index b329c5b68..c6ba7674d 100644 --- a/internal/controllerlib/recorder.go +++ b/internal/controllerlib/recorder.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package controllerlib @@ -16,7 +16,7 @@ var _ events.EventRecorder = klogRecorder{} type klogRecorder struct{} -func (n klogRecorder) Eventf(regarding runtime.Object, related runtime.Object, eventtype, reason, action, note string, args ...interface{}) { +func (n klogRecorder) Eventf(regarding runtime.Object, related runtime.Object, eventtype, reason, action, note string, args ...any) { plog.Debug("recording event", "regarding", regarding, "related", related, diff --git a/internal/controllerlib/sync.go b/internal/controllerlib/sync.go index 27a5a5a91..fb127c5ec 100644 --- a/internal/controllerlib/sync.go +++ b/internal/controllerlib/sync.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package controllerlib @@ -34,7 +34,7 @@ type Key struct { Name string // TODO determine if it makes sense to add a field like: - // Extra interface{} + // Extra any // This would allow a custom ParentFunc to pass extra data through to the Syncer // The boxed type would have to be comparable (i.e. usable as a map key) } diff --git a/internal/crud/crud.go b/internal/crud/crud.go index 03aff68e8..dfe9c7e72 100644 --- a/internal/crud/crud.go +++ b/internal/crud/crud.go @@ -48,7 +48,7 @@ type Storage interface { GetName(signature string) string } -type JSON interface{} // document that we need valid JSON types +type JSON any // document that we need valid JSON types func New(resource string, secrets corev1client.SecretInterface, clock func() time.Time) Storage { return &secretsStorage{ diff --git a/internal/dynamiccert/provider_test.go b/internal/dynamiccert/provider_test.go index 3c661d963..08212cb6b 100644 --- a/internal/dynamiccert/provider_test.go +++ b/internal/dynamiccert/provider_test.go @@ -244,4 +244,4 @@ func TestNewServingCert(t *testing.T) { type fakeT struct{} -func (fakeT) Errorf(string, ...interface{}) {} +func (fakeT) Errorf(string, ...any) {} diff --git a/internal/execcredcache/execcredcache.go b/internal/execcredcache/execcredcache.go index 1ab90e0dc..d68ae7113 100644 --- a/internal/execcredcache/execcredcache.go +++ b/internal/execcredcache/execcredcache.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package execcredcache implements a cache for Kubernetes ExecCredential data. @@ -50,7 +50,7 @@ func New(path string) *Cache { } } -func (c *Cache) Get(key interface{}) *clientauthenticationv1beta1.ExecCredential { +func (c *Cache) Get(key any) *clientauthenticationv1beta1.ExecCredential { // If the cache file does not exist, exit immediately with no error log if _, err := os.Stat(c.path); errors.Is(err, os.ErrNotExist) { return nil @@ -80,7 +80,7 @@ func (c *Cache) Get(key interface{}) *clientauthenticationv1beta1.ExecCredential return result } -func (c *Cache) Put(key interface{}, cred *clientauthenticationv1beta1.ExecCredential) { +func (c *Cache) Put(key any, cred *clientauthenticationv1beta1.ExecCredential) { // Create the cache directory if it does not exist. if err := os.MkdirAll(filepath.Dir(c.path), 0700); err != nil && !errors.Is(err, os.ErrExist) { c.errReporter(fmt.Errorf("could not create credential cache directory: %w", err)) @@ -111,7 +111,7 @@ func (c *Cache) Put(key interface{}, cred *clientauthenticationv1beta1.ExecCrede }) } -func jsonSHA256Hex(key interface{}) string { +func jsonSHA256Hex(key any) string { hash := sha256.New() if err := json.NewEncoder(hash).Encode(key); err != nil { panic(err) diff --git a/internal/federationdomain/clientregistry/clientregistry.go b/internal/federationdomain/clientregistry/clientregistry.go index 0345fb323..421436c72 100644 --- a/internal/federationdomain/clientregistry/clientregistry.go +++ b/internal/federationdomain/clientregistry/clientregistry.go @@ -15,7 +15,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" supervisorclient "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/typed/config/v1alpha1" "go.pinniped.dev/internal/federationdomain/oidcclientvalidator" @@ -179,7 +179,7 @@ func PinnipedCLI() *Client { } } -func oidcClientCRToFositeClient(oidcClient *configv1alpha1.OIDCClient, clientSecrets []string) *Client { +func oidcClientCRToFositeClient(oidcClient *supervisorconfigv1alpha1.OIDCClient, clientSecrets []string) *Client { // Allow the user to optionally override the default timeouts for these clients. idTokenLifetimeOverrideInSeconds := oidcClient.Spec.TokenLifetimes.IDTokenSeconds var idTokenLifetime time.Duration @@ -215,7 +215,7 @@ func oidcClientCRToFositeClient(oidcClient *configv1alpha1.OIDCClient, clientSec } } -func scopesToArguments(scopes []configv1alpha1.Scope) fosite.Arguments { +func scopesToArguments(scopes []supervisorconfigv1alpha1.Scope) fosite.Arguments { a := make(fosite.Arguments, len(scopes)) for i, scope := range scopes { a[i] = string(scope) @@ -223,7 +223,7 @@ func scopesToArguments(scopes []configv1alpha1.Scope) fosite.Arguments { return a } -func grantTypesToArguments(grantTypes []configv1alpha1.GrantType) fosite.Arguments { +func grantTypesToArguments(grantTypes []supervisorconfigv1alpha1.GrantType) fosite.Arguments { a := make(fosite.Arguments, len(grantTypes)) for i, grantType := range grantTypes { a[i] = string(grantType) @@ -231,7 +231,7 @@ func grantTypesToArguments(grantTypes []configv1alpha1.GrantType) fosite.Argumen return a } -func redirectURIsToStrings(uris []configv1alpha1.RedirectURI) []string { +func redirectURIsToStrings(uris []supervisorconfigv1alpha1.RedirectURI) []string { s := make([]string, len(uris)) for i, uri := range uris { s[i] = string(uri) diff --git a/internal/federationdomain/clientregistry/clientregistry_test.go b/internal/federationdomain/clientregistry/clientregistry_test.go index 3484c6988..be2612bce 100644 --- a/internal/federationdomain/clientregistry/clientregistry_test.go +++ b/internal/federationdomain/clientregistry/clientregistry_test.go @@ -20,7 +20,7 @@ import ( coretesting "k8s.io/client-go/testing" "k8s.io/utils/ptr" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" "go.pinniped.dev/internal/federationdomain/oidcclientvalidator" "go.pinniped.dev/internal/oidcclientsecretstorage" @@ -39,7 +39,7 @@ func TestClientManager(t *testing.T) { tests := []struct { name string secrets []*corev1.Secret - oidcClients []*configv1alpha1.OIDCClient + oidcClients []*supervisorconfigv1alpha1.OIDCClient addKubeReactions func(client *fake.Clientset) addSupervisorReactions func(client *supervisorfake.Clientset) run func(t *testing.T, subject *ClientManager) @@ -62,7 +62,7 @@ func TestClientManager(t *testing.T) { }, { name: "find pinniped-cli client when some dynamic clients also exist", - oidcClients: []*configv1alpha1.OIDCClient{ + oidcClients: []*supervisorconfigv1alpha1.OIDCClient{ {ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}}, }, run: func(t *testing.T, subject *ClientManager) { @@ -74,7 +74,7 @@ func TestClientManager(t *testing.T) { }, { name: "client not found", - oidcClients: []*configv1alpha1.OIDCClient{ + oidcClients: []*supervisorconfigv1alpha1.OIDCClient{ {ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}}, }, run: func(t *testing.T, subject *ClientManager) { @@ -89,13 +89,13 @@ func TestClientManager(t *testing.T) { }, { name: "find a dynamic client when its storage secret does not exist (client is invalid because is has no client secret)", - oidcClients: []*configv1alpha1.OIDCClient{ + oidcClients: []*supervisorconfigv1alpha1.OIDCClient{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - AllowedRedirectURIs: []configv1alpha1.RedirectURI{"http://localhost:80", "https://foobar.com/callback"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{"http://localhost:80", "https://foobar.com/callback"}, }, }, }, @@ -107,13 +107,13 @@ func TestClientManager(t *testing.T) { }, { name: "find a dynamic client which is invalid due to its spec", - oidcClients: []*configv1alpha1.OIDCClient{ + oidcClients: []*supervisorconfigv1alpha1.OIDCClient{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code"}, - AllowedScopes: []configv1alpha1.Scope{}, // at least "openid" is required here, so this makes the client invalid - AllowedRedirectURIs: []configv1alpha1.RedirectURI{"http://localhost:80"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{}, // at least "openid" is required here, so this makes the client invalid + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{"http://localhost:80"}, }, }, }, @@ -128,13 +128,13 @@ func TestClientManager(t *testing.T) { }, { name: "find a dynamic client which somehow does not have the required prefix in its name, just in case, although should not be possible since prefix is a validation on the CRD", - oidcClients: []*configv1alpha1.OIDCClient{ + oidcClients: []*supervisorconfigv1alpha1.OIDCClient{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: "does-not-have-prefix", Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - AllowedRedirectURIs: []configv1alpha1.RedirectURI{"http://localhost:80", "https://foobar.com/callback"}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{"http://localhost:80", "https://foobar.com/callback"}, }, }, }, @@ -166,7 +166,7 @@ func TestClientManager(t *testing.T) { }, { name: "when there is an unexpected error getting the storage secret for the OIDCClient", - oidcClients: []*configv1alpha1.OIDCClient{ + oidcClients: []*supervisorconfigv1alpha1.OIDCClient{ {ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}}, }, addKubeReactions: func(client *fake.Clientset) { @@ -182,14 +182,14 @@ func TestClientManager(t *testing.T) { }, { name: "find a valid dynamic client without an ID token lifetime configuration", - oidcClients: []*configv1alpha1.OIDCClient{ + oidcClients: []*supervisorconfigv1alpha1.OIDCClient{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - AllowedRedirectURIs: []configv1alpha1.RedirectURI{"http://localhost:80", "https://foobar.com/callback"}, - TokenLifetimes: configv1alpha1.OIDCClientTokenLifetimes{IDTokenSeconds: nil}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{"http://localhost:80", "https://foobar.com/callback"}, + TokenLifetimes: supervisorconfigv1alpha1.OIDCClientTokenLifetimes{IDTokenSeconds: nil}, }, }, { @@ -217,14 +217,14 @@ func TestClientManager(t *testing.T) { }, { name: "find a valid dynamic client with an ID token lifetime configuration", - oidcClients: []*configv1alpha1.OIDCClient{ + oidcClients: []*supervisorconfigv1alpha1.OIDCClient{ { ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, Name: testName, Generation: 1234, UID: testUID}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "username", "groups"}, - AllowedRedirectURIs: []configv1alpha1.RedirectURI{"http://localhost:8080"}, - TokenLifetimes: configv1alpha1.OIDCClientTokenLifetimes{IDTokenSeconds: ptr.To[int32](4242)}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username", "groups"}, + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{"http://localhost:8080"}, + TokenLifetimes: supervisorconfigv1alpha1.OIDCClientTokenLifetimes{IDTokenSeconds: ptr.To[int32](4242)}, }, }, { diff --git a/internal/federationdomain/downstreamsession/downstream_session.go b/internal/federationdomain/downstreamsession/downstream_session.go index 6c4c9ec35..cf97cfdeb 100644 --- a/internal/federationdomain/downstreamsession/downstream_session.go +++ b/internal/federationdomain/downstreamsession/downstream_session.go @@ -73,7 +73,7 @@ func NewPinnipedSession( Custom: customSessionData, } - extras := map[string]interface{}{} + extras := map[string]any{} extras[oidcapi.IDTokenClaimAuthorizedParty] = c.ClientID diff --git a/internal/federationdomain/dynamiccodec/codec.go b/internal/federationdomain/dynamiccodec/codec.go index 36e9a8e92..797011a15 100644 --- a/internal/federationdomain/dynamiccodec/codec.go +++ b/internal/federationdomain/dynamiccodec/codec.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package dynamiccodec provides a type that can encode information using a just-in-time signing and @@ -41,12 +41,12 @@ func New(lifespan time.Duration, signingKeyFunc, encryptionKeyFunc KeyFunc) *Cod } // Encode implements oidc.Encode(). -func (c *Codec) Encode(name string, value interface{}) (string, error) { +func (c *Codec) Encode(name string, value any) (string, error) { return c.delegate().Encode(name, value) } // Decode implements oidc.Decode(). -func (c *Codec) Decode(name string, value string, into interface{}) error { +func (c *Codec) Decode(name string, value string, into any) error { return c.delegate().Decode(name, value, into) } diff --git a/internal/federationdomain/endpoints/auth/auth_handler_test.go b/internal/federationdomain/endpoints/auth/auth_handler_test.go index 81918abc8..8d2a3d297 100644 --- a/internal/federationdomain/endpoints/auth/auth_handler_test.go +++ b/internal/federationdomain/endpoints/auth/auth_handler_test.go @@ -673,7 +673,7 @@ func TestAuthorizationEndpoint(t *testing.T) { //nolint:gocyclo wantUnnecessaryStoredRecords int wantPasswordGrantCall *expectedPasswordGrant wantDownstreamCustomSessionData *psession.CustomSessionData - wantDownstreamAdditionalClaims map[string]interface{} + wantDownstreamAdditionalClaims map[string]any } tests := []testCase{ { @@ -929,7 +929,7 @@ func TestAuthorizationEndpoint(t *testing.T) { //nolint:gocyclo "downstreamMissingClaim": "upstreamMissingClaim", }). WithIDTokenClaim("upstreamCustomClaim", "i am a claim value"). - WithIDTokenClaim("upstreamOtherClaim", []interface{}{"hello", true}). + WithIDTokenClaim("upstreamOtherClaim", []any{"hello", true}). Build()), method: http.MethodGet, path: happyGetRequestPathForOIDCPasswordGrantUpstream, @@ -949,9 +949,9 @@ func TestAuthorizationEndpoint(t *testing.T) { //nolint:gocyclo wantDownstreamPKCEChallenge: downstreamPKCEChallenge, wantDownstreamPKCEChallengeMethod: downstreamPKCEChallengeMethod, wantDownstreamCustomSessionData: expectedHappyOIDCPasswordGrantCustomSession, - wantDownstreamAdditionalClaims: map[string]interface{}{ + wantDownstreamAdditionalClaims: map[string]any{ "downstreamCustomClaim": "i am a claim value", - "downstreamOtherClaim": []interface{}{"hello", true}, + "downstreamOtherClaim": []any{"hello", true}, }, }, { @@ -2961,7 +2961,7 @@ func TestAuthorizationEndpoint(t *testing.T) { //nolint:gocyclo name: "OIDC upstream password grant: upstream IDP's configured groups claim in the ID token is a slice of interfaces", idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( passwordGrantUpstreamOIDCIdentityProviderBuilder(). - WithIDTokenClaim(oidcUpstreamGroupsClaim, []interface{}{"group1", "group2"}).Build(), + WithIDTokenClaim(oidcUpstreamGroupsClaim, []any{"group1", "group2"}).Build(), ), method: http.MethodGet, path: happyGetRequestPathForOIDCPasswordGrantUpstream, @@ -3169,7 +3169,7 @@ func TestAuthorizationEndpoint(t *testing.T) { //nolint:gocyclo { name: "OIDC upstream password grant: upstream ID token contains groups claim where one element is invalid", idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( - passwordGrantUpstreamOIDCIdentityProviderBuilder().WithIDTokenClaim(oidcUpstreamGroupsClaim, []interface{}{"foo", 7}).Build(), + passwordGrantUpstreamOIDCIdentityProviderBuilder().WithIDTokenClaim(oidcUpstreamGroupsClaim, []any{"foo", 7}).Build(), ), method: http.MethodGet, path: happyGetRequestPathForOIDCPasswordGrantUpstream, @@ -3638,7 +3638,7 @@ type errorReturningEncoder struct { oidc.Codec } -func (*errorReturningEncoder) Encode(_ string, _ interface{}) (string, error) { +func (*errorReturningEncoder) Encode(_ string, _ any) (string, error) { return "", fmt.Errorf("some encoding error") } diff --git a/internal/federationdomain/endpoints/callback/callback_handler_test.go b/internal/federationdomain/endpoints/callback/callback_handler_test.go index d0aa3a6b8..0743c46a4 100644 --- a/internal/federationdomain/endpoints/callback/callback_handler_test.go +++ b/internal/federationdomain/endpoints/callback/callback_handler_test.go @@ -19,7 +19,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" "go.pinniped.dev/internal/federationdomain/endpoints/jwks" "go.pinniped.dev/internal/federationdomain/oidc" @@ -204,7 +204,7 @@ func TestCallbackEndpoint(t *testing.T) { wantDownstreamPKCEChallenge string wantDownstreamPKCEChallengeMethod string wantDownstreamCustomSessionData *psession.CustomSessionData - wantDownstreamAdditionalClaims map[string]interface{} + wantDownstreamAdditionalClaims map[string]any wantAuthcodeExchangeCall *expectedAuthcodeExchange }{ @@ -277,7 +277,7 @@ func TestCallbackEndpoint(t *testing.T) { performedByUpstreamName: happyUpstreamIDPName, args: happyExchangeAndValidateTokensArgs, }, - wantDownstreamAdditionalClaims: map[string]interface{}{ + wantDownstreamAdditionalClaims: map[string]any{ "downstreamCustomClaim": "i am a claim value", "downstreamOtherClaim": "other claim value", }, @@ -720,7 +720,7 @@ func TestCallbackEndpoint(t *testing.T) { { name: "upstream IDP's configured groups claim in the ID token is a slice of interfaces", idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( - happyUpstream().WithIDTokenClaim(oidcUpstreamGroupsClaim, []interface{}{"group1", "group2"}).Build(), + happyUpstream().WithIDTokenClaim(oidcUpstreamGroupsClaim, []any{"group1", "group2"}).Build(), ), method: http.MethodGet, path: newRequestPath().WithState(happyState).String(), @@ -813,8 +813,8 @@ func TestCallbackEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude username scope) - []configv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude username scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -856,8 +856,8 @@ func TestCallbackEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) - []configv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -1092,8 +1092,8 @@ func TestCallbackEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude username scope) - []configv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude username scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -1121,8 +1121,8 @@ func TestCallbackEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) - []configv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -1482,7 +1482,7 @@ func TestCallbackEndpoint(t *testing.T) { { name: "upstream ID token contains groups claim where one element is invalid", idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( - happyUpstream().WithIDTokenClaim(oidcUpstreamGroupsClaim, []interface{}{"foo", 7}).Build(), + happyUpstream().WithIDTokenClaim(oidcUpstreamGroupsClaim, []any{"foo", 7}).Build(), ), method: http.MethodGet, path: newRequestPath().WithState(happyState).String(), diff --git a/internal/federationdomain/endpoints/login/post_login_handler_test.go b/internal/federationdomain/endpoints/login/post_login_handler_test.go index 8d1c3112e..cf97c7aa1 100644 --- a/internal/federationdomain/endpoints/login/post_login_handler_test.go +++ b/internal/federationdomain/endpoints/login/post_login_handler_test.go @@ -17,7 +17,7 @@ import ( "k8s.io/apiserver/pkg/authentication/user" "k8s.io/client-go/kubernetes/fake" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" "go.pinniped.dev/internal/authenticators" "go.pinniped.dev/internal/celtransformer" @@ -613,8 +613,8 @@ func TestPostLoginEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude username scope) - []configv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude username scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -647,8 +647,8 @@ func TestPostLoginEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) - []configv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -691,8 +691,8 @@ func TestPostLoginEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) - []configv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -1051,8 +1051,8 @@ func TestPostLoginEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude username scope) - []configv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude username scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -1071,8 +1071,8 @@ func TestPostLoginEndpoint(t *testing.T) { kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { oidcClient, secret := testutil.OIDCClientAndStorageSecret(t, "some-namespace", downstreamDynamicClientID, downstreamDynamicClientUID, - []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) - []configv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed + []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) + []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed downstreamRedirectURI, nil, []string{testutil.HashedPassword1AtGoMinCost}, oidcclientvalidator.Validate) require.NoError(t, supervisorClient.Tracker().Add(oidcClient)) require.NoError(t, kubeClient.Tracker().Add(secret)) @@ -1185,7 +1185,7 @@ func TestPostLoginEndpoint(t *testing.T) { tt.wantDownstreamClient, tt.wantDownstreamRedirectURI, tt.wantDownstreamCustomSessionData, - map[string]interface{}{}, + map[string]any{}, ) case tt.wantRedirectToLoginPageError != "": // Expecting an error redirect to the login UI page. @@ -1221,7 +1221,7 @@ func TestPostLoginEndpoint(t *testing.T) { tt.wantDownstreamClient, tt.wantDownstreamRedirectURI, tt.wantDownstreamCustomSessionData, - map[string]interface{}{}, + map[string]any{}, ) default: require.Failf(t, "test should have expected a redirect or form body", diff --git a/internal/federationdomain/endpoints/token/token_handler.go b/internal/federationdomain/endpoints/token/token_handler.go index f9d31a7f2..1653a3cd0 100644 --- a/internal/federationdomain/endpoints/token/token_handler.go +++ b/internal/federationdomain/endpoints/token/token_handler.go @@ -298,7 +298,7 @@ func validateAndGetDownstreamGroupsFromSession(session *psession.PinnipedSession if downstreamGroupsInterface == nil { return nil, errorsx.WithStack(errMissingUpstreamSessionInternalError()) } - downstreamGroupsInterfaceList, ok := downstreamGroupsInterface.([]interface{}) + downstreamGroupsInterfaceList, ok := downstreamGroupsInterface.([]any) if !ok { return nil, errorsx.WithStack(errMissingUpstreamSessionInternalError()) } diff --git a/internal/federationdomain/endpoints/token/token_handler_test.go b/internal/federationdomain/endpoints/token/token_handler_test.go index 799990fdd..91362d651 100644 --- a/internal/federationdomain/endpoints/token/token_handler_test.go +++ b/internal/federationdomain/endpoints/token/token_handler_test.go @@ -41,7 +41,7 @@ import ( "k8s.io/utils/ptr" "k8s.io/utils/strings/slices" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" "go.pinniped.dev/internal/celtransformer" "go.pinniped.dev/internal/crud" @@ -291,7 +291,7 @@ type tokenEndpointResponseExpectedValues struct { wantUpstreamOIDCValidateTokenCall *expectedUpstreamValidateTokens wantCustomSessionDataStored *psession.CustomSessionData wantWarnings []RecordedWarning - wantAdditionalClaims map[string]interface{} + wantAdditionalClaims map[string]any // The expected lifetime of the ID tokens issued by authcode exchange and refresh, but not token exchange. // When zero, will assume that the test wants the default value for ID token lifetime. wantIDTokenLifetimeSeconds int @@ -377,10 +377,10 @@ func TestTokenEndpointAuthcodeExchange(t *testing.T) { authcodeExchange: authcodeExchangeInputs{ modifyAuthRequest: func(r *http.Request) { r.Form.Set("scope", "openid profile email username groups") }, modifySession: func(session *psession.PinnipedSession) { - session.IDTokenClaims().Extra["additionalClaims"] = map[string]interface{}{ + session.IDTokenClaims().Extra["additionalClaims"] = map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999, "upstreamObj": map[string]string{ @@ -396,13 +396,13 @@ func TestTokenEndpointAuthcodeExchange(t *testing.T) { wantGrantedScopes: []string{"openid", "username", "groups"}, wantUsername: goodUsername, wantGroups: goodGroups, - wantAdditionalClaims: map[string]interface{}{ + wantAdditionalClaims: map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999.0, // note: this is deserialized as float64 - "upstreamObj": map[string]interface{}{ + "upstreamObj": map[string]any{ "name": "value", }, }, @@ -460,10 +460,10 @@ func TestTokenEndpointAuthcodeExchange(t *testing.T) { }, modifyTokenRequest: modifyAuthcodeTokenRequestWithDynamicClientAuth, modifySession: func(session *psession.PinnipedSession) { - session.IDTokenClaims().Extra["additionalClaims"] = map[string]interface{}{ + session.IDTokenClaims().Extra["additionalClaims"] = map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999, "upstreamObj": map[string]string{ @@ -479,13 +479,13 @@ func TestTokenEndpointAuthcodeExchange(t *testing.T) { wantGrantedScopes: []string{"openid", "pinniped:request-audience", "username", "groups"}, wantUsername: goodUsername, wantGroups: goodGroups, - wantAdditionalClaims: map[string]interface{}{ + wantAdditionalClaims: map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999.0, // note: this is deserialized as float64 - "upstreamObj": map[string]interface{}{ + "upstreamObj": map[string]any{ "name": "value", }, }, @@ -967,7 +967,7 @@ func TestTokenEndpointWhenAuthcodeIsUsedTwice(t *testing.T) { // Authcode exchange doesn't use the upstream provider cache, so just pass an empty cache. subject, rsp, authCode, _, secrets, oauthStore := exchangeAuthcodeForTokens(t, test.authcodeExchange, testidplister.NewUpstreamIDPListerBuilder().BuildFederationDomainIdentityProvidersListerFinder(), test.kubeResources) - var parsedResponseBody map[string]interface{} + var parsedResponseBody map[string]any require.NoError(t, json.Unmarshal(rsp.Body.Bytes(), &parsedResponseBody)) // Second call - should be unsuccessful since auth code was already used. @@ -1074,10 +1074,10 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn authRequest.Form.Set("scope", "openid pinniped:request-audience username groups") }, modifySession: func(session *psession.PinnipedSession) { - session.IDTokenClaims().Extra["additionalClaims"] = map[string]interface{}{ + session.IDTokenClaims().Extra["additionalClaims"] = map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999, "upstreamObj": map[string]string{ @@ -1093,13 +1093,13 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn wantGrantedScopes: []string{"openid", "pinniped:request-audience", "username", "groups"}, wantUsername: goodUsername, wantGroups: goodGroups, - wantAdditionalClaims: map[string]interface{}{ + wantAdditionalClaims: map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999.0, // note: this is deserialized as float64 - "upstreamObj": map[string]interface{}{ + "upstreamObj": map[string]any{ "name": "value", }, }, @@ -1169,10 +1169,10 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn authRequest.Form.Set("scope", "openid pinniped:request-audience username groups") }, modifySession: func(session *psession.PinnipedSession) { - session.IDTokenClaims().Extra["additionalClaims"] = map[string]interface{}{ + session.IDTokenClaims().Extra["additionalClaims"] = map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999, "upstreamObj": map[string]string{ @@ -1189,13 +1189,13 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn wantGrantedScopes: []string{"openid", "pinniped:request-audience", "username", "groups"}, wantUsername: goodUsername, wantGroups: goodGroups, - wantAdditionalClaims: map[string]interface{}{ + wantAdditionalClaims: map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999.0, // note: this is deserialized as float64 - "upstreamObj": map[string]interface{}{ + "upstreamObj": map[string]any{ "name": "value", }, }, @@ -1242,12 +1242,12 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn name: "dynamic client lacks the required urn:ietf:params:oauth:grant-type:token-exchange grant type", kubeResources: func(t *testing.T, supervisorClient *supervisorfake.Clientset, kubeClient *fake.Clientset) { namespace, clientID, clientUID, redirectURI := "some-namespace", dynamicClientID, dynamicClientUID, goodRedirectURI - oidcClient := &configv1alpha1.OIDCClient{ + oidcClient := &supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: clientID, Generation: 1, UID: types.UID(clientUID)}, - Spec: configv1alpha1.OIDCClientSpec{ - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // does not have the grant type - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "username", "groups"}, // would be invalid if it also asked for pinniped:request-audience since it lacks the grant type - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(redirectURI)}, + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // does not have the grant type + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username", "groups"}, // would be invalid if it also asked for pinniped:request-audience since it lacks the grant type + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(redirectURI)}, }, } secret := testutil.OIDCClientSecretStorageSecretForUID(t, namespace, clientUID, []string{testutil.HashedPassword1AtGoMinCost, testutil.HashedPassword2AtGoMinCost}) @@ -1645,7 +1645,7 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn // Authcode exchange doesn't use the upstream provider cache, so just pass an empty cache. subject, rsp, _, _, secrets, storage := exchangeAuthcodeForTokens(t, test.authcodeExchange, testidplister.NewUpstreamIDPListerBuilder().BuildFederationDomainIdentityProvidersListerFinder(), test.kubeResources) - var parsedAuthcodeExchangeResponseBody map[string]interface{} + var parsedAuthcodeExchangeResponseBody map[string]any require.NoError(t, json.Unmarshal(rsp.Body.Bytes(), &parsedAuthcodeExchangeResponseBody)) request := happyTokenExchangeRequest(test.requestedAudience, parsedAuthcodeExchangeResponseBody["access_token"].(string)) @@ -1681,7 +1681,7 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn require.Equal(t, test.wantStatus, rsp.Code) testutil.RequireEqualContentType(t, rsp.Header().Get("Content-Type"), "application/json") - var parsedResponseBody map[string]interface{} + var parsedResponseBody map[string]any require.NoError(t, json.Unmarshal(rsp.Body.Bytes(), &parsedResponseBody)) if rsp.Code != http.StatusOK { @@ -1700,7 +1700,7 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn return } - claimsOfFirstIDToken := map[string]interface{}{} + claimsOfFirstIDToken := map[string]any{} originalIDToken := parsedAuthcodeExchangeResponseBody["id_token"].(string) firstIDTokenDecoded, _ := josejwt.ParseSigned(originalIDToken) err = firstIDTokenDecoded.UnsafeClaimsWithoutVerification(&claimsOfFirstIDToken) @@ -1713,7 +1713,7 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn // Parse the returned token. parsedJWT, err := jose.ParseSigned(parsedResponseBody["access_token"].(string)) require.NoError(t, err) - var tokenClaims map[string]interface{} + var tokenClaims map[string]any require.NoError(t, json.Unmarshal(parsedJWT.UnsafePayloadWithoutVerification(), &tokenClaims)) // Make sure that these are the only fields in the token. @@ -1751,7 +1751,7 @@ func TestTokenEndpointTokenExchange(t *testing.T) { // tests for grant_type "urn if len(test.authcodeExchange.want.wantAdditionalClaims) > 0 { require.Equal(t, test.authcodeExchange.want.wantAdditionalClaims, tokenClaims["additionalClaims"]) } - additionalClaims, ok := tokenClaims["additionalClaims"].(map[string]interface{}) + additionalClaims, ok := tokenClaims["additionalClaims"].(map[string]any) if ok && tokenClaims["additionalClaims"] != nil { require.True(t, len(additionalClaims) > 0, "additionalClaims may never be present and empty in the id token") } @@ -1995,7 +1995,7 @@ func TestRefreshGrant(t *testing.T) { return want } - happyRefreshTokenResponseForOpenIDAndOfflineAccessWithAdditionalClaims := func(wantCustomSessionDataStored *psession.CustomSessionData, expectToValidateToken *oauth2.Token, wantAdditionalClaims map[string]interface{}) tokenEndpointResponseExpectedValues { + happyRefreshTokenResponseForOpenIDAndOfflineAccessWithAdditionalClaims := func(wantCustomSessionDataStored *psession.CustomSessionData, expectToValidateToken *oauth2.Token, wantAdditionalClaims map[string]any) tokenEndpointResponseExpectedValues { want := happyRefreshTokenResponseForOpenIDAndOfflineAccess(wantCustomSessionDataStored, expectToValidateToken) want.wantAdditionalClaims = wantAdditionalClaims return want @@ -2030,7 +2030,7 @@ func TestRefreshGrant(t *testing.T) { refreshedUpstreamTokensWithIDAndRefreshTokens := func() *oauth2.Token { return refreshedUpstreamTokensWithRefreshTokenWithoutIDToken(). - WithExtra(map[string]interface{}{"id_token": oidcUpstreamRefreshedIDToken}) + WithExtra(map[string]any{"id_token": oidcUpstreamRefreshedIDToken}) } refreshedUpstreamTokensWithIDTokenWithoutRefreshToken := func() *oauth2.Token { @@ -2103,7 +2103,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -2121,7 +2121,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -2156,7 +2156,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{}, + Claims: map[string]any{}, }, }).WithRefreshedTokens(refreshedUpstreamTokensWithRefreshTokenWithoutIDToken()). WithTransformsForFederationDomain(prefixUsernameAndGroupsPipeline).Build()), @@ -2195,7 +2195,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -2235,7 +2235,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -2275,7 +2275,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -2284,10 +2284,10 @@ func TestRefreshGrant(t *testing.T) { customSessionData: initialUpstreamOIDCRefreshTokenCustomSessionData(), modifyAuthRequest: func(r *http.Request) { r.Form.Set("scope", "openid offline_access username groups") }, modifySession: func(session *psession.PinnipedSession) { - session.IDTokenClaims().Extra["additionalClaims"] = map[string]interface{}{ + session.IDTokenClaims().Extra["additionalClaims"] = map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999, "upstreamObj": map[string]string{ @@ -2304,13 +2304,13 @@ func TestRefreshGrant(t *testing.T) { wantCustomSessionDataStored: initialUpstreamOIDCRefreshTokenCustomSessionData(), wantUsername: goodUsername, wantGroups: goodGroups, - wantAdditionalClaims: map[string]interface{}{ + wantAdditionalClaims: map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999.0, // note: this is deserialized as float64 - "upstreamObj": map[string]interface{}{ + "upstreamObj": map[string]any{ "name": "value", }, }, @@ -2320,13 +2320,13 @@ func TestRefreshGrant(t *testing.T) { want: happyRefreshTokenResponseForOpenIDAndOfflineAccessWithAdditionalClaims( upstreamOIDCCustomSessionDataWithNewRefreshToken(oidcUpstreamRefreshedRefreshToken), refreshedUpstreamTokensWithIDAndRefreshTokens(), - map[string]interface{}{ + map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999.0, // note: this is deserialized as float64 - "upstreamObj": map[string]interface{}{ + "upstreamObj": map[string]any{ "name": "value", }, }, @@ -2338,7 +2338,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -2366,7 +2366,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -2402,7 +2402,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -2415,10 +2415,10 @@ func TestRefreshGrant(t *testing.T) { r.Form.Set("scope", "openid offline_access username groups") }, modifySession: func(session *psession.PinnipedSession) { - session.IDTokenClaims().Extra["additionalClaims"] = map[string]interface{}{ + session.IDTokenClaims().Extra["additionalClaims"] = map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999, "upstreamObj": map[string]string{ @@ -2436,13 +2436,13 @@ func TestRefreshGrant(t *testing.T) { wantCustomSessionDataStored: initialUpstreamOIDCRefreshTokenCustomSessionData(), wantUsername: goodUsername, wantGroups: goodGroups, - wantAdditionalClaims: map[string]interface{}{ + wantAdditionalClaims: map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999.0, // note: this is deserialized as float64 - "upstreamObj": map[string]interface{}{ + "upstreamObj": map[string]any{ "name": "value", }, }, @@ -2453,13 +2453,13 @@ func TestRefreshGrant(t *testing.T) { want: withWantDynamicClientID(happyRefreshTokenResponseForOpenIDAndOfflineAccessWithAdditionalClaims( upstreamOIDCCustomSessionDataWithNewRefreshToken(oidcUpstreamRefreshedRefreshToken), refreshedUpstreamTokensWithIDAndRefreshTokens(), - map[string]interface{}{ + map[string]any{ "upstreamString": "string value", "upstreamBool": true, - "upstreamArray": []interface{}{"hello", true}, + "upstreamArray": []any{"hello", true}, "upstreamFloat": 42.0, "upstreamInt": 999.0, // note: this is deserialized as float64 - "upstreamObj": map[string]interface{}{ + "upstreamObj": map[string]any{ "name": "value", }, }, @@ -2471,7 +2471,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithUsernameClaim("username-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "some-claim": "some-value", "sub": goodUpstreamSubject, "username-claim": goodUsername, @@ -2518,7 +2518,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithUsernameClaim("username-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "some-claim": "some-value", "sub": goodUpstreamSubject, "username-claim": goodUsername, @@ -2539,7 +2539,7 @@ func TestRefreshGrant(t *testing.T) { upstreamOIDCIdentityProviderBuilder().WithUsernameClaim("username-claim"). WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "some-claim": "some-value", "sub": goodUpstreamSubject, "username-claim": goodUsername, @@ -2582,7 +2582,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{}, + Claims: map[string]any{}, }, }).WithRefreshedTokens(refreshedUpstreamTokensWithRefreshTokenWithoutIDToken()).Build()), authcodeExchange: authcodeExchangeInputs{ @@ -2619,7 +2619,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{}, + Claims: map[string]any{}, }, }).WithRefreshedTokens(refreshedUpstreamTokensWithRefreshTokenWithoutIDToken()).Build()), authcodeExchange: happyAuthcodeExchangeInputsForOIDCUpstream, @@ -2643,7 +2643,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, "my-groups-claim": []string{"new-group1", "new-group2", "new-group3"}, // refreshed claims includes updated groups }, @@ -2674,7 +2674,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, "my-groups-claim": []string{"new-group1", "new-group2", "new-group3"}, // refreshed claims includes updated groups }, @@ -2708,13 +2708,13 @@ func TestRefreshGrant(t *testing.T) { }, }, { - name: "happy path refresh grant when the upstream refresh returns new group memberships (as interface{} types) from the merged ID token and userinfo results, it updates groups", + name: "happy path refresh grant when the upstream refresh returns new group memberships (as any types) from the merged ID token and userinfo results, it updates groups", idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, - "my-groups-claim": []interface{}{"new-group1", "new-group2", "new-group3"}, // refreshed claims includes updated groups + "my-groups-claim": []any{"new-group1", "new-group2", "new-group3"}, // refreshed claims includes updated groups }, }, }).WithRefreshedTokens(refreshedUpstreamTokensWithIDAndRefreshTokens()).Build()), @@ -2743,7 +2743,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, "my-groups-claim": []string{}, // refreshed groups claims is updated to be an empty list }, @@ -2773,7 +2773,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, // "my-groups-claim" is omitted from the refreshed claims }, @@ -2934,7 +2934,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, "my-groups-claim": []string{"new-group1", "new-group2", "new-group3"}, // refreshed claims includes updated groups }, @@ -2981,7 +2981,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, "my-groups-claim": []string{"new-group1", "new-group2", "new-group3"}, // refreshed claims includes updated groups }, @@ -3031,7 +3031,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, "my-groups-claim": []string{"new-group1", "new-group2", "new-group3"}, // refreshed claims includes updated groups }, @@ -3134,7 +3134,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithGroupsClaim("my-groups-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, "my-groups-claim": nil, }, @@ -3155,7 +3155,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -3173,7 +3173,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -3194,7 +3194,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -3238,7 +3238,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -3389,7 +3389,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -3410,7 +3410,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -3441,7 +3441,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": goodUpstreamSubject, }, }, @@ -3765,7 +3765,7 @@ func TestRefreshGrant(t *testing.T) { // This is the current format of the errors returned by the production code version of ValidateTokenAndMergeWithUserInfo, see ValidateTokenAndMergeWithUserInfo in upstreamoidc.go WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": "something-different", }, }, @@ -3791,7 +3791,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "some-claim": "some-value", }, }, @@ -3816,7 +3816,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithUsernameClaim("username-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "some-claim": "some-value", "sub": goodUpstreamSubject, "username-claim": "some-changed-username", @@ -3843,7 +3843,7 @@ func TestRefreshGrant(t *testing.T) { idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( upstreamOIDCIdentityProviderBuilder().WithUsernameClaim("username-claim").WithValidatedAndMergedWithUserInfoTokens(&oidctypes.Token{ IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{ + Claims: map[string]any{ "some-claim": "some-value", "sub": goodUpstreamSubject, "iss": "some-changed-issuer", @@ -4529,7 +4529,7 @@ func TestRefreshGrant(t *testing.T) { // just populating a secret in storage. subject, rsp, authCode, jwtSigningKey, secrets, oauthStore := exchangeAuthcodeForTokens(t, test.authcodeExchange, test.idps.BuildFederationDomainIdentityProvidersListerFinder(), test.kubeResources) - var parsedAuthcodeExchangeResponseBody map[string]interface{} + var parsedAuthcodeExchangeResponseBody map[string]any require.NoError(t, json.Unmarshal(rsp.Body.Bytes(), &parsedAuthcodeExchangeResponseBody)) // Performing an authcode exchange should not have caused any upstream refresh, which should only @@ -4614,7 +4614,7 @@ func TestRefreshGrant(t *testing.T) { if test.refreshRequest.want.wantStatus == http.StatusOK { wantIDToken := slices.Contains(test.refreshRequest.want.wantSuccessBodyFields, "id_token") - var parsedRefreshResponseBody map[string]interface{} + var parsedRefreshResponseBody map[string]any require.NoError(t, json.Unmarshal(refreshResponse.Body.Bytes(), &parsedRefreshResponseBody)) // Check that we got back new tokens. @@ -4630,12 +4630,12 @@ func TestRefreshGrant(t *testing.T) { require.Equal(t, parsedAuthcodeExchangeResponseBody["scope"].(string), parsedRefreshResponseBody["scope"].(string)) if wantIDToken { - var claimsOfFirstIDToken map[string]interface{} + var claimsOfFirstIDToken map[string]any firstIDTokenDecoded, _ := josejwt.ParseSigned(parsedAuthcodeExchangeResponseBody["id_token"].(string)) err := firstIDTokenDecoded.UnsafeClaimsWithoutVerification(&claimsOfFirstIDToken) require.NoError(t, err) - var claimsOfSecondIDToken map[string]interface{} + var claimsOfSecondIDToken map[string]any secondIDTokenDecoded, _ := josejwt.ParseSigned(parsedRefreshResponseBody["id_token"].(string)) err = secondIDTokenDecoded.UnsafeClaimsWithoutVerification(&claimsOfSecondIDToken) require.NoError(t, err) @@ -4658,13 +4658,13 @@ func TestRefreshGrant(t *testing.T) { } } -func requireClaimsAreNotEqual(t *testing.T, claimName string, claimsOfTokenA map[string]interface{}, claimsOfTokenB map[string]interface{}) { +func requireClaimsAreNotEqual(t *testing.T, claimName string, claimsOfTokenA map[string]any, claimsOfTokenB map[string]any) { require.NotEmpty(t, claimsOfTokenA[claimName]) require.NotEmpty(t, claimsOfTokenB[claimName]) require.NotEqual(t, claimsOfTokenA[claimName], claimsOfTokenB[claimName]) } -func requireClaimsAreEqual(t *testing.T, claimName string, claimsOfTokenA map[string]interface{}, claimsOfTokenB map[string]interface{}) { +func requireClaimsAreEqual(t *testing.T, claimName string, claimsOfTokenA map[string]any, claimsOfTokenB map[string]any) { require.NotEmpty(t, claimsOfTokenA[claimName]) require.NotEmpty(t, claimsOfTokenB[claimName]) require.Equal(t, claimsOfTokenA[claimName], claimsOfTokenB[claimName]) @@ -4776,7 +4776,7 @@ func requireTokenEndpointBehavior( if test.wantStatus == http.StatusOK { require.NotNil(t, test.wantSuccessBodyFields, "problem with test table setup: wanted success but did not specify expected response body") - var parsedResponseBody map[string]interface{} + var parsedResponseBody map[string]any require.NoError(t, json.Unmarshal(tokenEndpointResponse.Body.Bytes(), &parsedResponseBody)) require.ElementsMatch(t, test.wantSuccessBodyFields, getMapKeys(parsedResponseBody)) @@ -4949,7 +4949,7 @@ func simulateAuthEndpointHavingAlreadyRun( Subject: goodSubject, RequestedAt: goodRequestedAtTime, AuthTime: goodAuthTime, - Extra: map[string]interface{}{}, + Extra: map[string]any{}, }, Subject: "", // not used, note that the authorization and callback endpoints do not set this Username: "", // not used, note that the authorization and callback endpoints do not set this @@ -5033,7 +5033,7 @@ func requireInvalidAuthCodeStorage( func requireValidRefreshTokenStorage( t *testing.T, - body map[string]interface{}, + body map[string]any, storage fositeoauth2.CoreStorage, wantClientID string, wantRequestedScopes []string, @@ -5041,7 +5041,7 @@ func requireValidRefreshTokenStorage( wantUsername string, wantGroups []string, wantCustomSessionData *psession.CustomSessionData, - wantAdditionalClaims map[string]interface{}, + wantAdditionalClaims map[string]any, secrets v1.SecretInterface, requestTime time.Time, ) { @@ -5080,7 +5080,7 @@ func requireValidRefreshTokenStorage( func requireValidAccessTokenStorage( t *testing.T, - body map[string]interface{}, + body map[string]any, storage fositeoauth2.CoreStorage, wantClientID string, wantRequestedScopes []string, @@ -5088,7 +5088,7 @@ func requireValidAccessTokenStorage( wantUsername string, wantGroups []string, wantCustomSessionData *psession.CustomSessionData, - wantAdditionalClaims map[string]interface{}, + wantAdditionalClaims map[string]any, secrets v1.SecretInterface, requestTime time.Time, ) { @@ -5146,7 +5146,7 @@ func requireValidAccessTokenStorage( func requireInvalidAccessTokenStorage( t *testing.T, - body map[string]interface{}, + body map[string]any, storage fositeoauth2.CoreStorage, ) { t.Helper() @@ -5191,7 +5191,7 @@ func requireValidStoredRequest( wantUsername string, wantGroups []string, wantCustomSessionData *psession.CustomSessionData, - wantAdditionalClaims map[string]interface{}, + wantAdditionalClaims map[string]any, requestTime time.Time, ) { t.Helper() @@ -5216,7 +5216,7 @@ func requireValidStoredRequest( require.Equal(t, goodSubject, claims.Subject) // Our custom claims from the authorize endpoint should still be set. - expectedExtra := map[string]interface{}{} + expectedExtra := map[string]any{} if wantUsername != "" { expectedExtra["username"] = wantUsername } @@ -5310,13 +5310,13 @@ func requireGarbageCollectTimeInDelta(t *testing.T, tokenString string, typeLabe func requireValidIDToken( t *testing.T, - body map[string]interface{}, + body map[string]any, jwtSigningKey *ecdsa.PrivateKey, wantClientID string, wantNonceValueInIDToken bool, wantUsernameInIDToken string, wantGroupsInIDToken []string, - wantAdditionalClaims map[string]interface{}, + wantAdditionalClaims map[string]any, wantIDTokenLifetimeSeconds int, actualAccessToken string, requestTime time.Time, @@ -5332,19 +5332,19 @@ func requireValidIDToken( token := oidctestutil.VerifyECDSAIDToken(t, goodIssuer, wantClientID, jwtSigningKey, idTokenString) var claims struct { - Subject string `json:"sub"` - Audience []string `json:"aud"` - Issuer string `json:"iss"` - JTI string `json:"jti"` - Nonce string `json:"nonce"` - AccessTokenHash string `json:"at_hash"` - ExpiresAt int64 `json:"exp"` - IssuedAt int64 `json:"iat"` - RequestedAt int64 `json:"rat"` - AuthTime int64 `json:"auth_time"` - Groups []string `json:"groups"` - Username string `json:"username"` - AdditionalClaims map[string]interface{} `json:"additionalClaims"` + Subject string `json:"sub"` + Audience []string `json:"aud"` + Issuer string `json:"iss"` + JTI string `json:"jti"` + Nonce string `json:"nonce"` + AccessTokenHash string `json:"at_hash"` + ExpiresAt int64 `json:"exp"` + IssuedAt int64 `json:"iat"` + RequestedAt int64 `json:"rat"` + AuthTime int64 `json:"auth_time"` + Groups []string `json:"groups"` + Username string `json:"username"` + AdditionalClaims map[string]any `json:"additionalClaims"` } idTokenFields := []string{"sub", "aud", "iss", "jti", "auth_time", "exp", "iat", "rat", "azp", "at_hash"} @@ -5362,7 +5362,7 @@ func requireValidIDToken( } // make sure that these are the only fields in the token - var m map[string]interface{} + var m map[string]any require.NoError(t, token.Claims(&m)) require.ElementsMatch(t, idTokenFields, getMapKeys(m)) @@ -5378,7 +5378,7 @@ func requireValidIDToken( require.Equal(t, goodIssuer, claims.Issuer) require.NotEmpty(t, claims.JTI) require.Equal(t, wantAdditionalClaims, claims.AdditionalClaims) - require.NotEqual(t, map[string]interface{}{}, claims.AdditionalClaims, "additionalClaims may never be present and empty in the id token") + require.NotEqual(t, map[string]any{}, claims.AdditionalClaims, "additionalClaims may never be present and empty in the id token") if wantNonceValueInIDToken { require.Equal(t, goodNonce, claims.Nonce) @@ -5415,7 +5415,7 @@ func deepCopyRequestForm(r *http.Request) *http.Request { return &http.Request{Form: copied} } -func getMapKeys(m map[string]interface{}) []string { +func getMapKeys(m map[string]any) []string { keys := make([]string, 0) for key := range m { keys = append(keys, key) @@ -5423,8 +5423,8 @@ func getMapKeys(m map[string]interface{}) []string { return keys } -func toSliceOfInterface(s []string) []interface{} { - r := make([]interface{}, len(s)) +func toSliceOfInterface(s []string) []any { + r := make([]any, len(s)) for i := range s { r[i] = s[i] } diff --git a/internal/federationdomain/endpoints/tokenexchange/token_exchange.go b/internal/federationdomain/endpoints/tokenexchange/token_exchange.go index b3032be19..cd48157b6 100644 --- a/internal/federationdomain/endpoints/tokenexchange/token_exchange.go +++ b/internal/federationdomain/endpoints/tokenexchange/token_exchange.go @@ -27,7 +27,7 @@ type stsParams struct { requestedAudience string } -func HandlerFactory(config fosite.Configurator, storage interface{}, strategy interface{}) interface{} { +func HandlerFactory(config fosite.Configurator, storage any, strategy any) any { return &tokenExchangeHandler{ idTokenStrategy: strategy.(openid.OpenIDConnectTokenStrategy), accessTokenStrategy: strategy.(fositeoauth2.AccessTokenStrategy), diff --git a/internal/federationdomain/endpointsmanager/manager_test.go b/internal/federationdomain/endpointsmanager/manager_test.go index dc8d84091..794602fcf 100644 --- a/internal/federationdomain/endpointsmanager/manager_test.go +++ b/internal/federationdomain/endpointsmanager/manager_test.go @@ -247,7 +247,7 @@ func TestManager(t *testing.T) { // Minimal check to ensure that the right endpoint was called r.Equal(http.StatusOK, recorder.Code, "unexpected response:", recorder) - var body map[string]interface{} + var body map[string]any r.NoError(json.Unmarshal(recorder.Body.Bytes(), &body)) r.Contains(body, "id_token") r.Contains(body, "access_token") diff --git a/internal/federationdomain/idtokenlifespan/idtoken_lifespan.go b/internal/federationdomain/idtokenlifespan/idtoken_lifespan.go index 919d41a99..00e9711fc 100644 --- a/internal/federationdomain/idtokenlifespan/idtoken_lifespan.go +++ b/internal/federationdomain/idtokenlifespan/idtoken_lifespan.go @@ -19,7 +19,7 @@ const idTokenLifetimeOverrideKey contextKey = iota // OpenIDConnectExplicitFactory is similar to the function of the same name in the fosite compose package, // except it allows wrapping the IDTokenLifespanProvider. -func OpenIDConnectExplicitFactory(config fosite.Configurator, storage interface{}, strategy interface{}) interface{} { +func OpenIDConnectExplicitFactory(config fosite.Configurator, storage any, strategy any) any { openIDConnectExplicitHandler := compose.OpenIDConnectExplicitFactory(config, storage, strategy).(*openid.OpenIDConnectExplicitHandler) // Overwrite the config with a wrapper around the fosite.IDTokenLifespanProvider. openIDConnectExplicitHandler.Config = &contextAwareIDTokenLifespanProvider{DelegateConfig: config} @@ -28,7 +28,7 @@ func OpenIDConnectExplicitFactory(config fosite.Configurator, storage interface{ // OpenIDConnectRefreshFactory is similar to the function of the same name in the fosite compose package, // except it allows wrapping the IDTokenLifespanProvider. -func OpenIDConnectRefreshFactory(config fosite.Configurator, _ interface{}, strategy interface{}) interface{} { +func OpenIDConnectRefreshFactory(config fosite.Configurator, _ any, strategy any) any { openIDConnectRefreshHandler := compose.OpenIDConnectRefreshFactory(config, nil, strategy).(*openid.OpenIDConnectRefreshHandler) // Overwrite the config with a wrapper around the fosite.IDTokenLifespanProvider. openIDConnectRefreshHandler.Config = &contextAwareIDTokenLifespanProvider{DelegateConfig: config} diff --git a/internal/federationdomain/oidc/oidc.go b/internal/federationdomain/oidc/oidc.go index 2e07a65f6..88354159f 100644 --- a/internal/federationdomain/oidc/oidc.go +++ b/internal/federationdomain/oidc/oidc.go @@ -76,12 +76,12 @@ const ( // Encoder is the encoding side of the securecookie.Codec interface. type Encoder interface { - Encode(name string, value interface{}) (string, error) + Encode(name string, value any) (string, error) } // Decoder is the decoding side of the securecookie.Codec interface. type Decoder interface { - Decode(name, value string, into interface{}) error + Decode(name, value string, into any) error } // Codec is both the encoding and decoding sides of the securecookie.Codec interface. It is @@ -225,7 +225,7 @@ func DefaultOIDCTimeoutsConfiguration() timeouts.Configuration { } func FositeOauth2Helper( - oauthStore interface{}, + oauthStore any, issuer string, hmacSecretOfLengthAtLeast32Func func() []byte, jwksProvider jwks.DynamicJWKSProvider, @@ -293,9 +293,9 @@ func FositeOauth2Helper( // plog.Info("some error", FositeErrorForLog(err)...) // ... // } -func FositeErrorForLog(err error) []interface{} { +func FositeErrorForLog(err error) []any { rfc6749Error := fosite.ErrorToRFC6749Error(err) - keysAndValues := make([]interface{}, 0) + keysAndValues := make([]any, 0) keysAndValues = append(keysAndValues, "name") keysAndValues = append(keysAndValues, rfc6749Error.Error()) // Error() returns the ErrorField keysAndValues = append(keysAndValues, "status") diff --git a/internal/federationdomain/oidcclientvalidator/oidcclientvalidator.go b/internal/federationdomain/oidcclientvalidator/oidcclientvalidator.go index c69cbb7cb..3058f24ea 100644 --- a/internal/federationdomain/oidcclientvalidator/oidcclientvalidator.go +++ b/internal/federationdomain/oidcclientvalidator/oidcclientvalidator.go @@ -1,4 +1,4 @@ -// Copyright 2022-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2022-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package oidcclientvalidator @@ -11,7 +11,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" "go.pinniped.dev/internal/oidcclientsecretstorage" ) @@ -37,7 +37,7 @@ const ( // get the validation error for that case. It returns a bool to indicate if the client is valid, // along with a slice of conditions containing more details, and the list of client secrets in the // case that the client was valid. -func Validate(oidcClient *v1alpha1.OIDCClient, secret *corev1.Secret, minBcryptCost int) (bool, []*metav1.Condition, []string) { +func Validate(oidcClient *supervisorconfigv1alpha1.OIDCClient, secret *corev1.Secret, minBcryptCost int) (bool, []*metav1.Condition, []string) { conds := make([]*metav1.Condition, 0, 3) conds, clientSecrets := validateSecret(secret, conds, minBcryptCost) @@ -55,7 +55,7 @@ func Validate(oidcClient *v1alpha1.OIDCClient, secret *corev1.Secret, minBcryptC } // validateAllowedScopes checks if allowedScopes is valid on the OIDCClient. -func validateAllowedScopes(oidcClient *v1alpha1.OIDCClient, conditions []*metav1.Condition) []*metav1.Condition { +func validateAllowedScopes(oidcClient *supervisorconfigv1alpha1.OIDCClient, conditions []*metav1.Condition) []*metav1.Condition { m := make([]string, 0, 4) if !allowedScopesContains(oidcClient, oidcapi.ScopeOpenID) { @@ -95,7 +95,7 @@ func validateAllowedScopes(oidcClient *v1alpha1.OIDCClient, conditions []*metav1 } // validateAllowedGrantTypes checks if allowedGrantTypes is valid on the OIDCClient. -func validateAllowedGrantTypes(oidcClient *v1alpha1.OIDCClient, conditions []*metav1.Condition) []*metav1.Condition { +func validateAllowedGrantTypes(oidcClient *supervisorconfigv1alpha1.OIDCClient, conditions []*metav1.Condition) []*metav1.Condition { m := make([]string, 0, 3) if !allowedGrantTypesContains(oidcClient, oidcapi.GrantTypeAuthorizationCode) { @@ -207,18 +207,18 @@ func validateSecret(secret *corev1.Secret, conditions []*metav1.Condition, minBc return conditions, storedClientSecrets } -func allowedGrantTypesContains(haystack *v1alpha1.OIDCClient, needle string) bool { +func allowedGrantTypesContains(haystack *supervisorconfigv1alpha1.OIDCClient, needle string) bool { for _, hay := range haystack.Spec.AllowedGrantTypes { - if hay == v1alpha1.GrantType(needle) { + if hay == supervisorconfigv1alpha1.GrantType(needle) { return true } } return false } -func allowedScopesContains(haystack *v1alpha1.OIDCClient, needle string) bool { +func allowedScopesContains(haystack *supervisorconfigv1alpha1.OIDCClient, needle string) bool { for _, hay := range haystack.Spec.AllowedScopes { - if hay == v1alpha1.Scope(needle) { + if hay == supervisorconfigv1alpha1.Scope(needle) { return true } } diff --git a/internal/federationdomain/resolvedprovider/resolved_provider.go b/internal/federationdomain/resolvedprovider/resolved_provider.go index df3bca8f9..226564245 100644 --- a/internal/federationdomain/resolvedprovider/resolved_provider.go +++ b/internal/federationdomain/resolvedprovider/resolved_provider.go @@ -40,7 +40,7 @@ type Identity struct { // The portion of the user's session data which is specific to the upstream identity provider type. // Refer to the fields of psession.CustomSessionData whose types are specific to an identity provider type. // Must not be nil. - IDPSpecificSessionData interface{} + IDPSpecificSessionData any } // IdentityLoginExtras are additional information that an identity provider may choose to determine @@ -49,7 +49,7 @@ type Identity struct { // refreshes. Its fields are optional and may be nil. type IdentityLoginExtras struct { // The downstream additional claims determined for this user in an identity provider-specific way, if any. - DownstreamAdditionalClaims map[string]interface{} + DownstreamAdditionalClaims map[string]any // Login warnings to show the user after they exchange their downstream authcode, if any. Warnings []string @@ -76,7 +76,7 @@ type RefreshedIdentity struct { // Refer to the fields of psession.CustomSessionData whose types are specific to an identity provider type. // Set this to be the potentially updated IDP-specific session data. If no updates were required, then // set this to nil. - IDPSpecificSessionData interface{} + IDPSpecificSessionData any } // UpstreamAuthorizeRequestState is the state capturing the downstream authorization request, used as a parameter to @@ -117,7 +117,7 @@ type FederationDomainResolvedIdentityProvider interface { // of the field which is specific to the upstream identity provider type. If the session's field is // nil, then return nil. // Refer to the fields of psession.CustomSessionData whose types are specific to an identity provider type. - CloneIDPSpecificSessionDataFromSession(session *psession.CustomSessionData) interface{} + CloneIDPSpecificSessionDataFromSession(session *psession.CustomSessionData) any // ApplyIDPSpecificSessionDataToSession assigns the IDP-specific portion of the session data into a session. // The IDP-specific session data provided to this function will be from an Identity that was returned by @@ -125,7 +125,7 @@ type FederationDomainResolvedIdentityProvider interface { // assumptions about the type of idpSpecificSessionData for casting, based upon how it chooses to return // IDPSpecificSessionData in Identity structs. If the given session already has any IDP-specific session // data, it should be overwritten by this function. - ApplyIDPSpecificSessionDataToSession(session *psession.CustomSessionData, idpSpecificSessionData interface{}) + ApplyIDPSpecificSessionDataToSession(session *psession.CustomSessionData, idpSpecificSessionData any) // UpstreamAuthorizeRedirectURL returns the URL to which the user's browser can be redirected to continue // the downstream browser-based authorization flow. Returned errors should be of type fosite.RFC6749Error. diff --git a/internal/federationdomain/resolvedprovider/resolvedldap/resolved_ldap_provider.go b/internal/federationdomain/resolvedprovider/resolvedldap/resolved_ldap_provider.go index c8fea641c..aab159eb1 100644 --- a/internal/federationdomain/resolvedprovider/resolvedldap/resolved_ldap_provider.go +++ b/internal/federationdomain/resolvedprovider/resolvedldap/resolved_ldap_provider.go @@ -64,7 +64,7 @@ func (p *FederationDomainResolvedLDAPIdentityProvider) GetTransforms() *idtransf return p.Transforms } -func (p *FederationDomainResolvedLDAPIdentityProvider) CloneIDPSpecificSessionDataFromSession(session *psession.CustomSessionData) interface{} { +func (p *FederationDomainResolvedLDAPIdentityProvider) CloneIDPSpecificSessionDataFromSession(session *psession.CustomSessionData) any { switch p.GetSessionProviderType() { case psession.ProviderTypeLDAP: if session.LDAP == nil { @@ -83,7 +83,7 @@ func (p *FederationDomainResolvedLDAPIdentityProvider) CloneIDPSpecificSessionDa } } -func (p *FederationDomainResolvedLDAPIdentityProvider) ApplyIDPSpecificSessionDataToSession(session *psession.CustomSessionData, idpSpecificSessionData interface{}) { +func (p *FederationDomainResolvedLDAPIdentityProvider) ApplyIDPSpecificSessionDataToSession(session *psession.CustomSessionData, idpSpecificSessionData any) { if p.GetSessionProviderType() == psession.ProviderTypeActiveDirectory { session.ActiveDirectory = idpSpecificSessionData.(*psession.ActiveDirectorySessionData) return @@ -139,7 +139,7 @@ func (p *FederationDomainResolvedLDAPIdentityProvider) Login( upstreamUsername := authenticateResponse.User.GetName() upstreamGroups := authenticateResponse.User.GetGroups() - var sessionData interface{} + var sessionData any switch p.GetSessionProviderType() { case psession.ProviderTypeLDAP: sessionData = &psession.LDAPSessionData{ diff --git a/internal/federationdomain/resolvedprovider/resolvedoidc/resolved_oidc_provider.go b/internal/federationdomain/resolvedprovider/resolvedoidc/resolved_oidc_provider.go index 1258e292c..21d155a4b 100644 --- a/internal/federationdomain/resolvedprovider/resolvedoidc/resolved_oidc_provider.go +++ b/internal/federationdomain/resolvedprovider/resolvedoidc/resolved_oidc_provider.go @@ -86,14 +86,14 @@ func (p *FederationDomainResolvedOIDCIdentityProvider) GetTransforms() *idtransf return p.Transforms } -func (p *FederationDomainResolvedOIDCIdentityProvider) CloneIDPSpecificSessionDataFromSession(session *psession.CustomSessionData) interface{} { +func (p *FederationDomainResolvedOIDCIdentityProvider) CloneIDPSpecificSessionDataFromSession(session *psession.CustomSessionData) any { if session.OIDC == nil { return nil } return session.OIDC.Clone() } -func (p *FederationDomainResolvedOIDCIdentityProvider) ApplyIDPSpecificSessionDataToSession(session *psession.CustomSessionData, idpSpecificSessionData interface{}) { +func (p *FederationDomainResolvedOIDCIdentityProvider) ApplyIDPSpecificSessionDataToSession(session *psession.CustomSessionData, idpSpecificSessionData any) { session.OIDC = idpSpecificSessionData.(*psession.OIDCSessionData) } @@ -325,7 +325,7 @@ func (p *FederationDomainResolvedOIDCIdentityProvider) UpstreamRefresh( } func validateUpstreamSubjectAndIssuerUnchangedSinceInitialLogin( - mergedClaims map[string]interface{}, + mergedClaims map[string]any, s *psession.OIDCSessionData, providerName string, providerType psession.ProviderType, @@ -361,7 +361,7 @@ func validateUpstreamSubjectAndIssuerUnchangedSinceInitialLogin( return nil } -func getString(m map[string]interface{}, key string) (string, bool) { +func getString(m map[string]any, key string) (string, bool) { val, ok := m[key].(string) return val, ok } @@ -386,7 +386,7 @@ func makeDownstreamOIDCSessionData( const pleaseCheck = "please check configuration of OIDCIdentityProvider and the client in the " + "upstream provider's API/UI and try to get a refresh token if possible" - logKV := []interface{}{ + logKV := []any{ "upstreamName", oidcUpstream.GetName(), "scopes", oidcUpstream.GetScopes(), "additionalParams", oidcUpstream.GetAdditionalAuthcodeParams(), @@ -425,7 +425,7 @@ func makeDownstreamOIDCSessionData( // getIdentityFromUpstreamIDToken returns the mapped subject, username, and group names, in that order. func getIdentityFromUpstreamIDToken( upstreamIDPConfig upstreamprovider.UpstreamOIDCIdentityProviderI, - idTokenClaims map[string]interface{}, + idTokenClaims map[string]any, idpDisplayName string, ) (string, string, []string, error) { subject, username, err := getDownstreamSubjectAndUpstreamUsernameFromUpstreamIDToken(upstreamIDPConfig, idTokenClaims, idpDisplayName) @@ -444,9 +444,9 @@ func getIdentityFromUpstreamIDToken( // mapAdditionalClaimsFromUpstreamIDToken returns the additionalClaims mapped from the upstream token, if any. func mapAdditionalClaimsFromUpstreamIDToken( upstreamIDPConfig upstreamprovider.UpstreamOIDCIdentityProviderI, - idTokenClaims map[string]interface{}, -) map[string]interface{} { - mapped := make(map[string]interface{}, len(upstreamIDPConfig.GetAdditionalClaimMappings())) + idTokenClaims map[string]any, +) map[string]any { + mapped := make(map[string]any, len(upstreamIDPConfig.GetAdditionalClaimMappings())) for downstreamClaimName, upstreamClaimName := range upstreamIDPConfig.GetAdditionalClaimMappings() { upstreamClaimValue, ok := idTokenClaims[upstreamClaimName] if !ok { @@ -464,7 +464,7 @@ func mapAdditionalClaimsFromUpstreamIDToken( func getDownstreamSubjectAndUpstreamUsernameFromUpstreamIDToken( upstreamIDPConfig upstreamprovider.UpstreamOIDCIdentityProviderI, - idTokenClaims map[string]interface{}, + idTokenClaims map[string]any, idpDisplayName string, ) (string, string, error) { // The spec says the "sub" claim is only unique per issuer, @@ -516,7 +516,7 @@ func getDownstreamSubjectAndUpstreamUsernameFromUpstreamIDToken( return subject, username, nil } -func extractStringClaimValue(claimName string, upstreamIDPName string, idTokenClaims map[string]interface{}) (string, error) { +func extractStringClaimValue(claimName string, upstreamIDPName string, idTokenClaims map[string]any) (string, error) { value, ok := idTokenClaims[claimName] if !ok { plog.Warning( @@ -560,7 +560,7 @@ func mappedUsernameFromUpstreamOIDCSubject(upstreamIssuerAsString string, upstre // in the provided map of claims. It returns an error when the claim exists but its value cannot be parsed. func getGroupsFromUpstreamIDToken( upstreamIDPConfig upstreamprovider.UpstreamOIDCIdentityProviderI, - idTokenClaims map[string]interface{}, + idTokenClaims map[string]any, ) ([]string, error) { groupsClaimName := upstreamIDPConfig.GetGroupsClaim() if groupsClaimName == "" { @@ -590,7 +590,7 @@ func getGroupsFromUpstreamIDToken( return groupsAsArray, nil } -func extractGroups(groupsAsInterface interface{}) ([]string, bool) { +func extractGroups(groupsAsInterface any) ([]string, bool) { groupsAsString, okAsString := groupsAsInterface.(string) if okAsString { return []string{groupsAsString}, true @@ -601,7 +601,7 @@ func extractGroups(groupsAsInterface interface{}) ([]string, bool) { return groupsAsStringArray, true } - groupsAsInterfaceArray, okAsArray := groupsAsInterface.([]interface{}) + groupsAsInterfaceArray, okAsArray := groupsAsInterface.([]any) if !okAsArray { return nil, false } diff --git a/internal/federationdomain/resolvedprovider/resolvedoidc/resolved_oidc_provider_test.go b/internal/federationdomain/resolvedprovider/resolvedoidc/resolved_oidc_provider_test.go index 2ab0654b6..88c0df5f1 100644 --- a/internal/federationdomain/resolvedprovider/resolvedoidc/resolved_oidc_provider_test.go +++ b/internal/federationdomain/resolvedprovider/resolvedoidc/resolved_oidc_provider_test.go @@ -15,18 +15,18 @@ func TestMapAdditionalClaimsFromUpstreamIDToken(t *testing.T) { tests := []struct { name string additionalClaimMappings map[string]string - upstreamClaims map[string]interface{} - wantClaims map[string]interface{} + upstreamClaims map[string]any + wantClaims map[string]any }{ { name: "happy path", additionalClaimMappings: map[string]string{ "email": "notification_email", }, - upstreamClaims: map[string]interface{}{ + upstreamClaims: map[string]any{ "notification_email": "test@example.com", }, - wantClaims: map[string]interface{}{ + wantClaims: map[string]any{ "email": "test@example.com", }, }, @@ -35,20 +35,20 @@ func TestMapAdditionalClaimsFromUpstreamIDToken(t *testing.T) { additionalClaimMappings: map[string]string{ "email": "email", }, - upstreamClaims: map[string]interface{}{}, - wantClaims: map[string]interface{}{}, + upstreamClaims: map[string]any{}, + wantClaims: map[string]any{}, }, { name: "complex", additionalClaimMappings: map[string]string{ "complex": "complex", }, - upstreamClaims: map[string]interface{}{ + upstreamClaims: map[string]any{ "complex": map[string]string{ "subClaim": "subValue", }, }, - wantClaims: map[string]interface{}{ + wantClaims: map[string]any{ "complex": map[string]string{ "subClaim": "subValue", }, diff --git a/internal/federationdomain/strategy/dynamic_open_id_connect_ecdsa_strategy.go b/internal/federationdomain/strategy/dynamic_open_id_connect_ecdsa_strategy.go index 463a450c4..15711b4eb 100644 --- a/internal/federationdomain/strategy/dynamic_open_id_connect_ecdsa_strategy.go +++ b/internal/federationdomain/strategy/dynamic_open_id_connect_ecdsa_strategy.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package strategy @@ -69,7 +69,7 @@ func (s *DynamicOpenIDConnectECDSAStrategy) GenerateIDToken( return "", fosite.ErrServerError.WithWrap(constable.Error("JWK must be of type ecdsa")) } - keyGetter := func(context.Context) (interface{}, error) { + keyGetter := func(context.Context) (any, error) { return key, nil } strategy := compose.NewOpenIDConnectStrategy(keyGetter, s.fositeConfig) diff --git a/internal/fositestorage/accesstoken/accesstoken_test.go b/internal/fositestorage/accesstoken/accesstoken_test.go index 2091fc175..a20061e71 100644 --- a/internal/fositestorage/accesstoken/accesstoken_test.go +++ b/internal/fositestorage/accesstoken/accesstoken_test.go @@ -335,7 +335,7 @@ func TestReadFromSecret(t *testing.T) { Username: "snorlax", Subject: "panda", Claims: &jwt.IDTokenClaims{JTI: "xyz"}, - Headers: &jwt.Headers{Extra: map[string]interface{}{"myheader": "foo"}}, + Headers: &jwt.Headers{Extra: map[string]any{"myheader": "foo"}}, }, Custom: &psession.CustomSessionData{ Username: "fake-username", diff --git a/internal/fositestorage/authorizationcode/authorizationcode_test.go b/internal/fositestorage/authorizationcode/authorizationcode_test.go index feba59615..3427303d1 100644 --- a/internal/fositestorage/authorizationcode/authorizationcode_test.go +++ b/internal/fositestorage/authorizationcode/authorizationcode_test.go @@ -324,24 +324,24 @@ func TestFuzzAndJSONNewValidEmptyAuthorizeCodeSession(t *testing.T) { *fs = pinnipedSession }, - // these types contain an interface{} that we need to handle + // these types contain an any that we need to handle // this is safe because we explicitly provide the PinnipedSession concrete type - func(value *map[string]interface{}, c fuzz.Continue) { + func(value *map[string]any, c fuzz.Continue) { // cover all the JSON data types just in case - *value = map[string]interface{}{ + *value = map[string]any{ randString(c): float64(c.Intn(1 << 32)), - randString(c): map[string]interface{}{ - randString(c): []interface{}{float64(c.Intn(1 << 32))}, - randString(c): map[string]interface{}{ + randString(c): map[string]any{ + randString(c): []any{float64(c.Intn(1 << 32))}, + randString(c): map[string]any{ randString(c): nil, - randString(c): map[string]interface{}{ + randString(c): map[string]any{ randString(c): c.RandBool(), }, }, }, } }, - // JWK contains an interface{} Key that we need to handle + // JWK contains an any Key that we need to handle // this is safe because JWK explicitly implements JSON marshalling and unmarshalling func(jwk *jose.JSONWebKey, c fuzz.Continue) { key, _, err := ed25519.GenerateKey(c) @@ -471,7 +471,7 @@ func TestReadFromSecret(t *testing.T) { Username: "snorlax", Subject: "panda", Claims: &jwt.IDTokenClaims{JTI: "xyz"}, - Headers: &jwt.Headers{Extra: map[string]interface{}{"myheader": "foo"}}, + Headers: &jwt.Headers{Extra: map[string]any{"myheader": "foo"}}, }, Custom: &psession.CustomSessionData{ Username: "fake-username", diff --git a/internal/fositestorage/refreshtoken/refreshtoken_test.go b/internal/fositestorage/refreshtoken/refreshtoken_test.go index dc369a15b..37718bd9c 100644 --- a/internal/fositestorage/refreshtoken/refreshtoken_test.go +++ b/internal/fositestorage/refreshtoken/refreshtoken_test.go @@ -392,7 +392,7 @@ func TestReadFromSecret(t *testing.T) { Username: "snorlax", Subject: "panda", Claims: &jwt.IDTokenClaims{JTI: "xyz"}, - Headers: &jwt.Headers{Extra: map[string]interface{}{"myheader": "foo"}}, + Headers: &jwt.Headers{Extra: map[string]any{"myheader": "foo"}}, }, Custom: &psession.CustomSessionData{ Username: "fake-username", diff --git a/internal/groupsuffix/groupsuffix_test.go b/internal/groupsuffix/groupsuffix_test.go index 8a40084f5..10e554cbe 100644 --- a/internal/groupsuffix/groupsuffix_test.go +++ b/internal/groupsuffix/groupsuffix_test.go @@ -16,7 +16,7 @@ import ( authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" "go.pinniped.dev/internal/kubeclient" "go.pinniped.dev/internal/testutil" ) @@ -66,14 +66,14 @@ func TestMiddlware(t *testing.T) { } var ok bool - pinnipedOwner := &configv1alpha1.FederationDomain{ + pinnipedOwner := &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: metav1.ObjectMeta{ Name: "some-name", UID: "some-uid", }, } - pinnipedOwnerGVK := configv1alpha1.SchemeGroupVersion.WithKind("FederationDomain") - pinnipedOwnerWithNewGroupGVK := configv1alpha1.SchemeGroupVersion.WithKind("FederationDomain") + pinnipedOwnerGVK := supervisorconfigv1alpha1.SchemeGroupVersion.WithKind("FederationDomain") + pinnipedOwnerWithNewGroupGVK := supervisorconfigv1alpha1.SchemeGroupVersion.WithKind("FederationDomain") pinnipedOwnerWithNewGroupGVK.Group, ok = Replace(pinnipedOwnerWithNewGroupGVK.Group, newSuffix) require.True(t, ok) podWithPinnipedOwner := &corev1.Pod{ @@ -105,9 +105,9 @@ func TestMiddlware(t *testing.T) { }, } - federationDomainWithPinnipedOwner := &configv1alpha1.FederationDomain{ + federationDomainWithPinnipedOwner := &supervisorconfigv1alpha1.FederationDomain{ TypeMeta: metav1.TypeMeta{ - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "FederationDomain", }, ObjectMeta: metav1.ObjectMeta{ @@ -119,9 +119,9 @@ func TestMiddlware(t *testing.T) { }, }, } - federationDomainWithNewGroupAndPinnipedOwner := &configv1alpha1.FederationDomain{ + federationDomainWithNewGroupAndPinnipedOwner := &supervisorconfigv1alpha1.FederationDomain{ TypeMeta: metav1.TypeMeta{ - APIVersion: replaceGV(t, configv1alpha1.SchemeGroupVersion, newSuffix).String(), + APIVersion: replaceGV(t, supervisorconfigv1alpha1.SchemeGroupVersion, newSuffix).String(), Kind: "FederationDomain", }, ObjectMeta: metav1.ObjectMeta{ @@ -133,9 +133,9 @@ func TestMiddlware(t *testing.T) { }, }, } - federationDomainWithNewGroupAndPinnipedOwnerWithNewGroup := &configv1alpha1.FederationDomain{ + federationDomainWithNewGroupAndPinnipedOwnerWithNewGroup := &supervisorconfigv1alpha1.FederationDomain{ TypeMeta: metav1.TypeMeta{ - APIVersion: replaceGV(t, configv1alpha1.SchemeGroupVersion, newSuffix).String(), + APIVersion: replaceGV(t, supervisorconfigv1alpha1.SchemeGroupVersion, newSuffix).String(), Kind: "FederationDomain", }, ObjectMeta: metav1.ObjectMeta{ @@ -308,7 +308,7 @@ func TestMiddlware(t *testing.T) { rt: (&testutil.RoundTrip{}). WithVerb(kubeclient.VerbCreate). WithNamespace("some-namespace"). - WithResource(configv1alpha1.SchemeGroupVersion.WithResource("federationdomains")), + WithResource(supervisorconfigv1alpha1.SchemeGroupVersion.WithResource("federationdomains")), requestObj: federationDomainWithPinnipedOwner, responseObj: federationDomainWithNewGroupAndPinnipedOwnerWithNewGroup, wantMutateRequests: 2, @@ -323,7 +323,7 @@ func TestMiddlware(t *testing.T) { rt: (&testutil.RoundTrip{}). WithVerb(kubeclient.VerbUpdate). WithNamespace("some-namespace"). - WithResource(configv1alpha1.SchemeGroupVersion.WithResource("federationdomains")), + WithResource(supervisorconfigv1alpha1.SchemeGroupVersion.WithResource("federationdomains")), requestObj: federationDomainWithPinnipedOwner, responseObj: federationDomainWithNewGroupAndPinnipedOwnerWithNewGroup, wantMutateRequests: 2, diff --git a/internal/here/doc.go b/internal/here/doc.go index 1d576718a..fd947bd57 100644 --- a/internal/here/doc.go +++ b/internal/here/doc.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package here @@ -18,6 +18,6 @@ func Doc(s string) string { return strings.ReplaceAll(heredoc.Doc(s), tab, fourSpaces) } -func Docf(raw string, args ...interface{}) string { +func Docf(raw string, args ...any) string { return strings.ReplaceAll(heredoc.Docf(raw, args...), tab, fourSpaces) } diff --git a/internal/httputil/httperr/httperr.go b/internal/httputil/httperr/httperr.go index 1fb21cb76..0f07ca731 100644 --- a/internal/httputil/httperr/httperr.go +++ b/internal/httputil/httperr/httperr.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package httperr contains some helpers for nicer error handling in http.Handler implementations. @@ -21,7 +21,7 @@ func New(code int, msg string) error { } // Newf returns a Responder that emits the given HTTP status code and fmt.Sprintf formatted message. -func Newf(code int, format string, args ...interface{}) error { +func Newf(code int, format string, args ...any) error { return httpErr{code: code, msg: fmt.Sprintf(format, args...)} } diff --git a/internal/idtransform/identity_transformations.go b/internal/idtransform/identity_transformations.go index 2518b8e24..d8f2d3306 100644 --- a/internal/idtransform/identity_transformations.go +++ b/internal/idtransform/identity_transformations.go @@ -1,4 +1,4 @@ -// Copyright 2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2023-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package idtransform defines upstream-to-downstream identity transformations which could be @@ -28,7 +28,7 @@ type IdentityTransformation interface { // Source returns some representation of the original source code of the transformation, which is // useful for tests to be able to check that a compiled transformation came from the right source. - Source() interface{} + Source() any } // TransformationPipeline is a list of identity transforms, which can be evaluated in order against some given input @@ -89,8 +89,8 @@ func (p *TransformationPipeline) Evaluate(ctx context.Context, username string, return accumulatedResult, nil } -func (p *TransformationPipeline) Source() []interface{} { - result := []interface{}{} +func (p *TransformationPipeline) Source() []any { + result := []any{} for _, transform := range p.transforms { result = append(result, transform.Source()) } diff --git a/internal/idtransform/identity_transformations_test.go b/internal/idtransform/identity_transformations_test.go index e1db0a321..051df6681 100644 --- a/internal/idtransform/identity_transformations_test.go +++ b/internal/idtransform/identity_transformations_test.go @@ -22,7 +22,7 @@ func (a fakeNoopTransformer) Evaluate(_ctx context.Context, username string, gro }, nil } -func (a fakeNoopTransformer) Source() interface{} { +func (a fakeNoopTransformer) Source() any { return nil // not needed for this test } @@ -37,7 +37,7 @@ func (a fakeNilGroupTransformer) Evaluate(_ctx context.Context, username string, }, nil } -func (a fakeNilGroupTransformer) Source() interface{} { +func (a fakeNilGroupTransformer) Source() any { return nil // not needed for this test } @@ -56,7 +56,7 @@ func (a fakeAppendStringTransformer) Evaluate(_ctx context.Context, username str }, nil } -func (a fakeAppendStringTransformer) Source() interface{} { +func (a fakeAppendStringTransformer) Source() any { return nil // not needed for this test } @@ -71,7 +71,7 @@ func (a fakeDeleteUsernameAndGroupsTransformer) Evaluate(_ctx context.Context, _ }, nil } -func (a fakeDeleteUsernameAndGroupsTransformer) Source() interface{} { +func (a fakeDeleteUsernameAndGroupsTransformer) Source() any { return nil // not needed for this test } @@ -90,7 +90,7 @@ func (a fakeAuthenticationDisallowedTransformer) Evaluate(_ctx context.Context, }, nil } -func (a fakeAuthenticationDisallowedTransformer) Source() interface{} { +func (a fakeAuthenticationDisallowedTransformer) Source() any { return nil // not needed for this test } @@ -100,7 +100,7 @@ func (a fakeErrorTransformer) Evaluate(_ctx context.Context, _username string, _ return &TransformationResult{}, errors.New("unexpected catastrophic error") } -func (a fakeErrorTransformer) Source() interface{} { +func (a fakeErrorTransformer) Source() any { return nil // not needed for this test } @@ -112,7 +112,7 @@ func (a fakeTransformerWithSource) Evaluate(_ctx context.Context, _username stri return nil, nil // not needed for this test } -func (a fakeTransformerWithSource) Source() interface{} { +func (a fakeTransformerWithSource) Source() any { return a.source } @@ -334,6 +334,6 @@ func TestTransformationSource(t *testing.T) { pipeline.AppendTransformation(transform) } - require.Equal(t, []interface{}{"foo", "bar", "baz"}, pipeline.Source()) - require.NotEqual(t, []interface{}{"foo", "something-else", "baz"}, pipeline.Source()) + require.Equal(t, []any{"foo", "bar", "baz"}, pipeline.Source()) + require.NotEqual(t, []any{"foo", "something-else", "baz"}, pipeline.Source()) } diff --git a/internal/kubeclient/path_test.go b/internal/kubeclient/path_test.go index a2e39200c..dbe3c549b 100644 --- a/internal/kubeclient/path_test.go +++ b/internal/kubeclient/path_test.go @@ -17,7 +17,7 @@ import ( genericapirequest "k8s.io/apiserver/pkg/endpoints/request" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" ) func Test_updatePathNewGVK(t *testing.T) { @@ -92,12 +92,12 @@ func Test_updatePathNewGVK(t *testing.T) { { name: "namespace-scoped list path", args: args{ - reqURL: mustParse(t, "https://walrus.tld/apis/"+configv1alpha1.SchemeGroupVersion.String()+"/namespaces/default/federationdomains"), + reqURL: mustParse(t, "https://walrus.tld/apis/"+supervisorconfigv1alpha1.SchemeGroupVersion.String()+"/namespaces/default/federationdomains"), result: &mutationResult{ - origGVK: configv1alpha1.SchemeGroupVersion.WithKind("FederationDomain"), + origGVK: supervisorconfigv1alpha1.SchemeGroupVersion.WithKind("FederationDomain"), newGVK: schema.GroupVersionKind{ Group: "config.supervisor.tuna.io", - Version: configv1alpha1.SchemeGroupVersion.Version, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Kind: "FederationDomain", }, gvkChanged: true, @@ -110,12 +110,12 @@ func Test_updatePathNewGVK(t *testing.T) { { name: "namespace-scoped get path", args: args{ - reqURL: mustParse(t, "https://walrus.tld/apis/"+configv1alpha1.SchemeGroupVersion.String()+"/namespaces/default/federationdomains/some-name"), + reqURL: mustParse(t, "https://walrus.tld/apis/"+supervisorconfigv1alpha1.SchemeGroupVersion.String()+"/namespaces/default/federationdomains/some-name"), result: &mutationResult{ - origGVK: configv1alpha1.SchemeGroupVersion.WithKind("FederationDomain"), + origGVK: supervisorconfigv1alpha1.SchemeGroupVersion.WithKind("FederationDomain"), newGVK: schema.GroupVersionKind{ Group: "config.supervisor.tuna.io", - Version: configv1alpha1.SchemeGroupVersion.Version, + Version: supervisorconfigv1alpha1.SchemeGroupVersion.Version, Kind: "FederationDomain", }, gvkChanged: true, diff --git a/internal/oidcclientsecretstorage/oidcclientsecretstorage.go b/internal/oidcclientsecretstorage/oidcclientsecretstorage.go index d44d184d9..fac274628 100644 --- a/internal/oidcclientsecretstorage/oidcclientsecretstorage.go +++ b/internal/oidcclientsecretstorage/oidcclientsecretstorage.go @@ -14,7 +14,7 @@ import ( "k8s.io/apimachinery/pkg/types" corev1client "k8s.io/client-go/kubernetes/typed/core/v1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" "go.pinniped.dev/internal/constable" "go.pinniped.dev/internal/crud" ) @@ -84,7 +84,7 @@ func (s *OIDCClientSecretStorage) Set(ctx context.Context, resourceVersion, oidc // Setup an owner reference for garbage collection purposes. When the OIDCClient is deleted, then this // corresponding client secret storage secret should also be automatically deleted (by Kube garbage collection). ownerReferences := []metav1.OwnerReference{{ - APIVersion: configv1alpha1.SchemeGroupVersion.String(), + APIVersion: supervisorconfigv1alpha1.SchemeGroupVersion.String(), Kind: "OIDCClient", Name: oidcClientName, UID: oidcClientUID, diff --git a/internal/plog/plog.go b/internal/plog/plog.go index 9b722fe52..713887cf3 100644 --- a/internal/plog/plog.go +++ b/internal/plog/plog.go @@ -39,18 +39,18 @@ const errorKey = "error" // this matches zapr's default for .Error calls (which // If test assertions are desired, Logger should be passed in as an input. New should be used as the // production implementation and TestLogger should be used to write test assertions. type Logger interface { - Error(msg string, err error, keysAndValues ...interface{}) - Warning(msg string, keysAndValues ...interface{}) - WarningErr(msg string, err error, keysAndValues ...interface{}) - Info(msg string, keysAndValues ...interface{}) - InfoErr(msg string, err error, keysAndValues ...interface{}) - Debug(msg string, keysAndValues ...interface{}) - DebugErr(msg string, err error, keysAndValues ...interface{}) - Trace(msg string, keysAndValues ...interface{}) - TraceErr(msg string, err error, keysAndValues ...interface{}) - All(msg string, keysAndValues ...interface{}) - Always(msg string, keysAndValues ...interface{}) - WithValues(keysAndValues ...interface{}) Logger + Error(msg string, err error, keysAndValues ...any) + Warning(msg string, keysAndValues ...any) + WarningErr(msg string, err error, keysAndValues ...any) + Info(msg string, keysAndValues ...any) + InfoErr(msg string, err error, keysAndValues ...any) + Debug(msg string, keysAndValues ...any) + DebugErr(msg string, err error, keysAndValues ...any) + Trace(msg string, keysAndValues ...any) + TraceErr(msg string, err error, keysAndValues ...any) + All(msg string, keysAndValues ...any) + Always(msg string, keysAndValues ...any) + WithValues(keysAndValues ...any) Logger WithName(name string) Logger // does not include Fatal on purpose because that is not a method you should be using @@ -62,7 +62,7 @@ type Logger interface { // MinLogger is the overlap between Logger and logr.Logger. type MinLogger interface { - Info(msg string, keysAndValues ...interface{}) + Info(msg string, keysAndValues ...any) } var _ Logger = pLogger{} @@ -77,82 +77,82 @@ func New() Logger { return pLogger{} } -func (p pLogger) Error(msg string, err error, keysAndValues ...interface{}) { +func (p pLogger) Error(msg string, err error, keysAndValues ...any) { p.logr().WithCallDepth(p.depth+1).Error(err, msg, keysAndValues...) } -func (p pLogger) warningDepth(msg string, depth int, keysAndValues ...interface{}) { +func (p pLogger) warningDepth(msg string, depth int, keysAndValues ...any) { if p.logr().V(klogLevelWarning).Enabled() { // klog's structured logging has no concept of a warning (i.e. no WarningS function) // Thus we use info at log level zero as a proxy // klog's info logs have an I prefix and its warning logs have a W prefix // Since we lose the W prefix by using InfoS, just add a key to make these easier to find - keysAndValues = append([]interface{}{"warning", true}, keysAndValues...) + keysAndValues = append([]any{"warning", true}, keysAndValues...) p.logr().V(klogLevelWarning).WithCallDepth(depth+1).Info(msg, keysAndValues...) } } -func (p pLogger) Warning(msg string, keysAndValues ...interface{}) { +func (p pLogger) Warning(msg string, keysAndValues ...any) { p.warningDepth(msg, p.depth+1, keysAndValues...) } -func (p pLogger) WarningErr(msg string, err error, keysAndValues ...interface{}) { - p.warningDepth(msg, p.depth+1, append([]interface{}{errorKey, err}, keysAndValues...)...) +func (p pLogger) WarningErr(msg string, err error, keysAndValues ...any) { + p.warningDepth(msg, p.depth+1, append([]any{errorKey, err}, keysAndValues...)...) } -func (p pLogger) infoDepth(msg string, depth int, keysAndValues ...interface{}) { +func (p pLogger) infoDepth(msg string, depth int, keysAndValues ...any) { if p.logr().V(KlogLevelInfo).Enabled() { p.logr().V(KlogLevelInfo).WithCallDepth(depth+1).Info(msg, keysAndValues...) } } -func (p pLogger) Info(msg string, keysAndValues ...interface{}) { +func (p pLogger) Info(msg string, keysAndValues ...any) { p.infoDepth(msg, p.depth+1, keysAndValues...) } -func (p pLogger) InfoErr(msg string, err error, keysAndValues ...interface{}) { - p.infoDepth(msg, p.depth+1, append([]interface{}{errorKey, err}, keysAndValues...)...) +func (p pLogger) InfoErr(msg string, err error, keysAndValues ...any) { + p.infoDepth(msg, p.depth+1, append([]any{errorKey, err}, keysAndValues...)...) } -func (p pLogger) debugDepth(msg string, depth int, keysAndValues ...interface{}) { +func (p pLogger) debugDepth(msg string, depth int, keysAndValues ...any) { if p.logr().V(KlogLevelDebug).Enabled() { p.logr().V(KlogLevelDebug).WithCallDepth(depth+1).Info(msg, keysAndValues...) } } -func (p pLogger) Debug(msg string, keysAndValues ...interface{}) { +func (p pLogger) Debug(msg string, keysAndValues ...any) { p.debugDepth(msg, p.depth+1, keysAndValues...) } -func (p pLogger) DebugErr(msg string, err error, keysAndValues ...interface{}) { - p.debugDepth(msg, p.depth+1, append([]interface{}{errorKey, err}, keysAndValues...)...) +func (p pLogger) DebugErr(msg string, err error, keysAndValues ...any) { + p.debugDepth(msg, p.depth+1, append([]any{errorKey, err}, keysAndValues...)...) } -func (p pLogger) traceDepth(msg string, depth int, keysAndValues ...interface{}) { +func (p pLogger) traceDepth(msg string, depth int, keysAndValues ...any) { if p.logr().V(KlogLevelTrace).Enabled() { p.logr().V(KlogLevelTrace).WithCallDepth(depth+1).Info(msg, keysAndValues...) } } -func (p pLogger) Trace(msg string, keysAndValues ...interface{}) { +func (p pLogger) Trace(msg string, keysAndValues ...any) { p.traceDepth(msg, p.depth+1, keysAndValues...) } -func (p pLogger) TraceErr(msg string, err error, keysAndValues ...interface{}) { - p.traceDepth(msg, p.depth+1, append([]interface{}{errorKey, err}, keysAndValues...)...) +func (p pLogger) TraceErr(msg string, err error, keysAndValues ...any) { + p.traceDepth(msg, p.depth+1, append([]any{errorKey, err}, keysAndValues...)...) } -func (p pLogger) All(msg string, keysAndValues ...interface{}) { +func (p pLogger) All(msg string, keysAndValues ...any) { if p.logr().V(klogLevelAll).Enabled() { p.logr().V(klogLevelAll).WithCallDepth(p.depth+1).Info(msg, keysAndValues...) } } -func (p pLogger) Always(msg string, keysAndValues ...interface{}) { +func (p pLogger) Always(msg string, keysAndValues ...any) { p.logr().WithCallDepth(p.depth+1).Info(msg, keysAndValues...) } -func (p pLogger) WithValues(keysAndValues ...interface{}) Logger { +func (p pLogger) WithValues(keysAndValues ...any) Logger { if len(keysAndValues) == 0 { return p } @@ -197,51 +197,51 @@ func (p pLogger) logr() logr.Logger { var logger = New().withDepth(1) //nolint:gochecknoglobals -func Error(msg string, err error, keysAndValues ...interface{}) { +func Error(msg string, err error, keysAndValues ...any) { logger.Error(msg, err, keysAndValues...) } -func Warning(msg string, keysAndValues ...interface{}) { +func Warning(msg string, keysAndValues ...any) { logger.Warning(msg, keysAndValues...) } -func WarningErr(msg string, err error, keysAndValues ...interface{}) { +func WarningErr(msg string, err error, keysAndValues ...any) { logger.WarningErr(msg, err, keysAndValues...) } -func Info(msg string, keysAndValues ...interface{}) { +func Info(msg string, keysAndValues ...any) { logger.Info(msg, keysAndValues...) } -func InfoErr(msg string, err error, keysAndValues ...interface{}) { +func InfoErr(msg string, err error, keysAndValues ...any) { logger.InfoErr(msg, err, keysAndValues...) } -func Debug(msg string, keysAndValues ...interface{}) { +func Debug(msg string, keysAndValues ...any) { logger.Debug(msg, keysAndValues...) } -func DebugErr(msg string, err error, keysAndValues ...interface{}) { +func DebugErr(msg string, err error, keysAndValues ...any) { logger.DebugErr(msg, err, keysAndValues...) } -func Trace(msg string, keysAndValues ...interface{}) { +func Trace(msg string, keysAndValues ...any) { logger.Trace(msg, keysAndValues...) } -func TraceErr(msg string, err error, keysAndValues ...interface{}) { +func TraceErr(msg string, err error, keysAndValues ...any) { logger.TraceErr(msg, err, keysAndValues...) } -func All(msg string, keysAndValues ...interface{}) { +func All(msg string, keysAndValues ...any) { logger.All(msg, keysAndValues...) } -func Always(msg string, keysAndValues ...interface{}) { +func Always(msg string, keysAndValues ...any) { logger.Always(msg, keysAndValues...) } -func WithValues(keysAndValues ...interface{}) Logger { +func WithValues(keysAndValues ...any) Logger { // this looks weird but it is the same as New().WithValues(keysAndValues...) because it returns a new logger rooted at the call site return logger.withDepth(-1).WithValues(keysAndValues...) } @@ -251,7 +251,7 @@ func WithName(name string) Logger { return logger.withDepth(-1).WithName(name) } -func Fatal(err error, keysAndValues ...interface{}) { +func Fatal(err error, keysAndValues ...any) { logger.Error("unrecoverable error encountered", err, keysAndValues...) globalFlush() os.Exit(1) diff --git a/internal/registry/clientsecretrequest/rest_test.go b/internal/registry/clientsecretrequest/rest_test.go index 4a1f7aab3..480268a7e 100644 --- a/internal/registry/clientsecretrequest/rest_test.go +++ b/internal/registry/clientsecretrequest/rest_test.go @@ -29,7 +29,7 @@ import ( "k8s.io/klog/v2" clientsecretapi "go.pinniped.dev/generated/latest/apis/supervisor/clientsecret" - "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" "go.pinniped.dev/internal/oidcclientsecretstorage" "go.pinniped.dev/internal/plog" @@ -113,7 +113,7 @@ func TestCreate(t *testing.T) { tests := []struct { name string args args - seedOIDCClients []*v1alpha1.OIDCClient + seedOIDCClients []*supervisorconfigv1alpha1.OIDCClient seedHashes func(storage *oidcclientsecretstorage.OIDCClientSecretStorage) addReactors func(*kubefake.Clientset, *supervisorfake.Clientset) fakeByteGenerator io.Reader @@ -548,7 +548,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-no-secret-for-oidcclient", Namespace: namespace, @@ -593,7 +593,7 @@ func TestCreate(t *testing.T) { }, }, fakeByteGenerator: readerAlwaysErrors{}, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-fail-to-generate-secret", Namespace: namespace, @@ -636,7 +636,7 @@ func TestCreate(t *testing.T) { fakeHasher: func(password []byte, cost int) ([]byte, error) { return nil, errors.New("can't hash stuff") }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-fail-to-hash-secret", Namespace: namespace, @@ -677,7 +677,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-happy-new-secret", Namespace: namespace, @@ -745,7 +745,7 @@ func TestCreate(t *testing.T) { ), ) }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-append-new-secret-hash", Namespace: namespace, @@ -813,7 +813,7 @@ func TestCreate(t *testing.T) { }, )) }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-append-new-secret-hash", Namespace: namespace, @@ -879,7 +879,7 @@ func TestCreate(t *testing.T) { }, )) }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -946,7 +946,7 @@ func TestCreate(t *testing.T) { }, )) }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1012,7 +1012,7 @@ func TestCreate(t *testing.T) { }, )) }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1061,7 +1061,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1111,7 +1111,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1165,7 +1165,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1213,7 +1213,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-happy-new-secret", Namespace: namespace, @@ -1257,7 +1257,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1301,7 +1301,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1365,7 +1365,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1430,7 +1430,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1499,7 +1499,7 @@ func TestCreate(t *testing.T) { }, }, }, - seedOIDCClients: []*v1alpha1.OIDCClient{{ + seedOIDCClients: []*supervisorconfigv1alpha1.OIDCClient{{ ObjectMeta: metav1.ObjectMeta{ Name: "client.oauth.pinniped.dev-some-client", Namespace: namespace, @@ -1664,7 +1664,7 @@ func requireLogLinesContain(t *testing.T, fullLog string, wantLines []string) { require.Empty(t, fullLog) return } - var jsonLog map[string]interface{} + var jsonLog map[string]any err := json.Unmarshal([]byte(fullLog), &jsonLog) require.NoError(t, err) require.Contains(t, jsonLog, "message") diff --git a/internal/secret/cache.go b/internal/secret/cache.go index 7e87fe72c..a3bca18e1 100644 --- a/internal/secret/cache.go +++ b/internal/secret/cache.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package secret @@ -63,7 +63,7 @@ func (c *Cache) getFederationDomainCache(oidcIssuer string) *federationDomainCac return value.(*federationDomainCache) } -func bytesOrNil(b interface{}) []byte { +func bytesOrNil(b any) []byte { if b == nil { return nil } diff --git a/internal/supervisor/server/server.go b/internal/supervisor/server/server.go index 1be051b6e..2ee1b5753 100644 --- a/internal/supervisor/server/server.go +++ b/internal/supervisor/server/server.go @@ -38,7 +38,7 @@ import ( aggregatorclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset" "k8s.io/utils/clock" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/typed/config/v1alpha1" supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" @@ -238,7 +238,7 @@ func prepareControllers( secretCache.SetTokenHMACKey(federationDomainIssuer, symmetricKey) }, ), - func(fd *configv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference { + func(fd *supervisorconfigv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference { return &fd.Secrets.TokenSigningKey }, kubeClient, @@ -261,7 +261,7 @@ func prepareControllers( secretCache.SetStateEncoderHashKey(federationDomainIssuer, symmetricKey) }, ), - func(fd *configv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference { + func(fd *supervisorconfigv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference { return &fd.Secrets.StateSigningKey }, kubeClient, @@ -284,7 +284,7 @@ func prepareControllers( secretCache.SetStateEncoderBlockKey(federationDomainIssuer, symmetricKey) }, ), - func(fd *configv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference { + func(fd *supervisorconfigv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference { return &fd.Secrets.StateEncryptionKey }, kubeClient, diff --git a/internal/testutil/assertions.go b/internal/testutil/assertions.go index e104f7a7b..eb90860ce 100644 --- a/internal/testutil/assertions.go +++ b/internal/testutil/assertions.go @@ -163,7 +163,7 @@ func WantExactErrorString(wantErrStr string) RequireErrorStringFunc { // WantSprintfErrorString can be used to set up an expected value for an error string in a test table. // Use when you want to express that an expected string built using fmt.Sprintf semantics must be an exact match. -func WantSprintfErrorString(wantErrSprintfSpecifier string, a ...interface{}) RequireErrorStringFunc { +func WantSprintfErrorString(wantErrSprintfSpecifier string, a ...any) RequireErrorStringFunc { wantErrStr := fmt.Sprintf(wantErrSprintfSpecifier, a...) return func(t *testing.T, actualErrorStr string) { require.Equal(t, wantErrStr, actualErrorStr) diff --git a/internal/testutil/oidcclient.go b/internal/testutil/oidcclient.go index 936ec57ac..98c11c5f9 100644 --- a/internal/testutil/oidcclient.go +++ b/internal/testutil/oidcclient.go @@ -13,7 +13,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" ) const ( @@ -35,10 +35,10 @@ const ( ) // allDynamicClientScopes returns a slice of all scopes that are supported by the Supervisor for dynamic clients. -func allDynamicClientScopes() []configv1alpha1.Scope { - scopes := []configv1alpha1.Scope{} +func allDynamicClientScopes() []supervisorconfigv1alpha1.Scope { + scopes := []supervisorconfigv1alpha1.Scope{} for _, s := range strings.Split(AllDynamicClientScopesSpaceSep, " ") { - scopes = append(scopes, configv1alpha1.Scope(s)) + scopes = append(scopes, supervisorconfigv1alpha1.Scope(s)) } return scopes } @@ -48,24 +48,24 @@ func newOIDCClient( clientID string, clientUID string, redirectURI string, - allowedGrantTypes []configv1alpha1.GrantType, - allowedScopes []configv1alpha1.Scope, + allowedGrantTypes []supervisorconfigv1alpha1.GrantType, + allowedScopes []supervisorconfigv1alpha1.Scope, tokenLifetimesIDTokenSeconds *int32, -) *configv1alpha1.OIDCClient { - return &configv1alpha1.OIDCClient{ +) *supervisorconfigv1alpha1.OIDCClient { + return &supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: clientID, Generation: 1, UID: types.UID(clientUID)}, - Spec: configv1alpha1.OIDCClientSpec{ + Spec: supervisorconfigv1alpha1.OIDCClientSpec{ AllowedGrantTypes: allowedGrantTypes, AllowedScopes: allowedScopes, - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(redirectURI)}, - TokenLifetimes: configv1alpha1.OIDCClientTokenLifetimes{IDTokenSeconds: tokenLifetimesIDTokenSeconds}, + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(redirectURI)}, + TokenLifetimes: supervisorconfigv1alpha1.OIDCClientTokenLifetimes{IDTokenSeconds: tokenLifetimesIDTokenSeconds}, }, } } // OIDCClientValidatorFunc is an interface-like type that allows these test helpers to avoid having a direct dependency // on the production code, to avoid circular module dependencies. Implemented by oidcclientvalidator.Validate. -type OIDCClientValidatorFunc func(oidcClient *configv1alpha1.OIDCClient, secret *corev1.Secret, minBcryptCost int) (bool, []*metav1.Condition, []string) +type OIDCClientValidatorFunc func(oidcClient *supervisorconfigv1alpha1.OIDCClient, secret *corev1.Secret, minBcryptCost int) (bool, []*metav1.Condition, []string) // FullyCapableOIDCClientAndStorageSecret returns an OIDC client which is allowed to use all grant types and all scopes // that are supported by the Supervisor for dynamic clients, along with a corresponding client secret storage Secret. @@ -78,10 +78,10 @@ func FullyCapableOIDCClientAndStorageSecret( tokenLifetimesIDTokenSeconds *int32, hashes []string, validateFunc OIDCClientValidatorFunc, -) (*configv1alpha1.OIDCClient, *corev1.Secret) { +) (*supervisorconfigv1alpha1.OIDCClient, *corev1.Secret) { allScopes := allDynamicClientScopes() - allGrantTypes := []configv1alpha1.GrantType{ + allGrantTypes := []supervisorconfigv1alpha1.GrantType{ "authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token", } @@ -96,13 +96,13 @@ func OIDCClientAndStorageSecret( namespace string, clientID string, clientUID string, - allowedGrantTypes []configv1alpha1.GrantType, - allowedScopes []configv1alpha1.Scope, + allowedGrantTypes []supervisorconfigv1alpha1.GrantType, + allowedScopes []supervisorconfigv1alpha1.Scope, redirectURI string, tokenLifetimesIDTokenSeconds *int32, hashes []string, validateFunc OIDCClientValidatorFunc, -) (*configv1alpha1.OIDCClient, *corev1.Secret) { +) (*supervisorconfigv1alpha1.OIDCClient, *corev1.Secret) { oidcClient := newOIDCClient(namespace, clientID, clientUID, redirectURI, allowedGrantTypes, allowedScopes, tokenLifetimesIDTokenSeconds) secret := OIDCClientSecretStorageSecretForUID(t, namespace, clientUID, hashes) diff --git a/internal/testutil/oidctestutil/session_storage_assertions.go b/internal/testutil/oidctestutil/session_storage_assertions.go index 79260d597..94d2f5535 100644 --- a/internal/testutil/oidctestutil/session_storage_assertions.go +++ b/internal/testutil/oidctestutil/session_storage_assertions.go @@ -46,7 +46,7 @@ func RequireAuthCodeRegexpMatch( wantDownstreamClientID string, wantDownstreamRedirectURI string, wantCustomSessionData *psession.CustomSessionData, - wantDownstreamAdditionalClaims map[string]interface{}, + wantDownstreamAdditionalClaims map[string]any, ) { t.Helper() @@ -138,7 +138,7 @@ func validateAuthcodeStorage( wantDownstreamClientID string, wantDownstreamRedirectURI string, wantCustomSessionData *psession.CustomSessionData, - wantDownstreamAdditionalClaims map[string]interface{}, + wantDownstreamAdditionalClaims map[string]any, ) (*fosite.Request, *psession.PinnipedSession) { t.Helper() @@ -221,8 +221,8 @@ func validateAuthcodeStorage( require.Nil(t, actualDownstreamIDTokenGroups) } if len(wantDownstreamAdditionalClaims) > 0 { - actualAdditionalClaims, ok := actualClaims.Get("additionalClaims").(map[string]interface{}) - require.True(t, ok, "expected additionalClaims to be a map[string]interface{}") + actualAdditionalClaims, ok := actualClaims.Get("additionalClaims").(map[string]any) + require.True(t, ok, "expected additionalClaims to be a map[string]any") require.Equal(t, wantDownstreamAdditionalClaims, actualAdditionalClaims) } else { require.NotContains(t, actualClaims.Extra, "additionalClaims", "additionalClaims must not be present when there are no wanted additional claims") diff --git a/internal/testutil/oidctestutil/testoidcprovider.go b/internal/testutil/oidctestutil/testoidcprovider.go index 489f6304c..92a1d05ea 100644 --- a/internal/testutil/oidctestutil/testoidcprovider.go +++ b/internal/testutil/oidctestutil/testoidcprovider.go @@ -293,7 +293,7 @@ type TestUpstreamOIDCIdentityProviderBuilder struct { resourceUID types.UID clientID string scopes []string - idToken map[string]interface{} + idToken map[string]any refreshToken *oidctypes.RefreshToken accessToken *oidctypes.AccessToken usernameClaim string @@ -374,9 +374,9 @@ func (u *TestUpstreamOIDCIdentityProviderBuilder) WithoutGroupsClaim() *TestUpst return u } -func (u *TestUpstreamOIDCIdentityProviderBuilder) WithIDTokenClaim(name string, value interface{}) *TestUpstreamOIDCIdentityProviderBuilder { +func (u *TestUpstreamOIDCIdentityProviderBuilder) WithIDTokenClaim(name string, value any) *TestUpstreamOIDCIdentityProviderBuilder { if u.idToken == nil { - u.idToken = map[string]interface{}{} + u.idToken = map[string]any{} } u.idToken[name] = value return u diff --git a/internal/testutil/testlogger/stdr_copied.go b/internal/testutil/testlogger/stdr_copied.go index e227f8917..eb96fac0f 100644 --- a/internal/testutil/testlogger/stdr_copied.go +++ b/internal/testutil/testlogger/stdr_copied.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testlogger @@ -28,7 +28,7 @@ func newStdLogger(std stdr.StdLogger) logr.Logger { type logger struct { std stdr.StdLogger prefix string - values []interface{} + values []any } func (l logger) clone() logger { @@ -37,8 +37,8 @@ func (l logger) clone() logger { return out } -func copySlice(in []interface{}) []interface{} { - out := make([]interface{}, len(in)) +func copySlice(in []any) []any { + out := make([]any, len(in)) copy(out, in) return out } @@ -60,15 +60,15 @@ func framesToCaller() int { return 1 // something went wrong, this is safe } -func flatten(kvList ...interface{}) string { +func flatten(kvList ...any) string { keys := make([]string, 0, len(kvList)) - vals := make(map[string]interface{}, len(kvList)) + vals := make(map[string]any, len(kvList)) for i := 0; i < len(kvList); i += 2 { k, ok := kvList[i].(string) if !ok { panic(fmt.Sprintf("key is not a string: %s", pretty(kvList[i]))) } - var v interface{} + var v any if i+1 < len(kvList) { v = kvList[i+1] } @@ -89,14 +89,14 @@ func flatten(kvList ...interface{}) string { return buf.String() } -func pretty(value interface{}) string { +func pretty(value any) string { jb, _ := json.Marshal(value) return string(jb) } -func (l logger) Info(level int, msg string, kvList ...interface{}) { +func (l logger) Info(level int, msg string, kvList ...any) { if l.Enabled(level) { - builtin := make([]interface{}, 0, 4) + builtin := make([]any, 0, 4) builtin = append(builtin, "level", level, "msg", msg) builtinStr := flatten(builtin...) fixedStr := flatten(l.values...) @@ -109,11 +109,11 @@ func (l logger) Enabled(_level int) bool { return true } -func (l logger) Error(err error, msg string, kvList ...interface{}) { - builtin := make([]interface{}, 0, 4) +func (l logger) Error(err error, msg string, kvList ...any) { + builtin := make([]any, 0, 4) builtin = append(builtin, "msg", msg) builtinStr := flatten(builtin...) - var loggableErr interface{} + var loggableErr any if err != nil { loggableErr = err.Error() } @@ -152,7 +152,7 @@ func (l logger) WithName(name string) logr.LogSink { // WithValues returns a new logr.Logger with the specified key-and-values // saved. -func (l logger) WithValues(kvList ...interface{}) logr.LogSink { +func (l logger) WithValues(kvList ...any) logr.LogSink { lgr := l.clone() lgr.values = append(lgr.values, kvList...) return lgr diff --git a/internal/testutil/transcript_logger.go b/internal/testutil/transcript_logger.go index d485bdfb5..bc81c9a00 100644 --- a/internal/testutil/transcript_logger.go +++ b/internal/testutil/transcript_logger.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testutil @@ -37,7 +37,7 @@ func (log *TranscriptLogger) Transcript() []TranscriptLogMessage { return result } -func (log *TranscriptLogger) Info(_level int, msg string, keysAndValues ...interface{}) { +func (log *TranscriptLogger) Info(_level int, msg string, keysAndValues ...any) { log.lock.Lock() defer log.lock.Unlock() log.transcript = append(log.transcript, TranscriptLogMessage{ @@ -46,7 +46,7 @@ func (log *TranscriptLogger) Info(_level int, msg string, keysAndValues ...inter }) } -func (log *TranscriptLogger) Error(_ error, msg string, _ ...interface{}) { +func (log *TranscriptLogger) Error(_ error, msg string, _ ...any) { log.lock.Lock() defer log.lock.Unlock() log.transcript = append(log.transcript, TranscriptLogMessage{ @@ -67,7 +67,7 @@ func (log *TranscriptLogger) WithName(_ string) logr.LogSink { return log } -func (log *TranscriptLogger) WithValues(_ ...interface{}) logr.LogSink { +func (log *TranscriptLogger) WithValues(_ ...any) logr.LogSink { return log } diff --git a/internal/upstreamoidc/upstreamoidc.go b/internal/upstreamoidc/upstreamoidc.go index 8cd569a18..03ab5b498 100644 --- a/internal/upstreamoidc/upstreamoidc.go +++ b/internal/upstreamoidc/upstreamoidc.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package upstreamoidc implements an abstraction of upstream OIDC provider interactions. @@ -48,7 +48,7 @@ type ProviderConfig struct { RevocationURL *url.URL // will commonly be nil: many providers do not offer this Provider interface { Verifier(*coreosoidc.Config) *coreosoidc.IDTokenVerifier - Claims(v interface{}) error + Claims(v any) error UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*coreosoidc.UserInfo, error) } } @@ -282,7 +282,7 @@ func (p *ProviderConfig) tryRevokeToken( // ValidateTokenAndMergeWithUserInfo will validate the ID token. It will also merge the claims from the userinfo endpoint response, // if the provider offers the userinfo endpoint. func (p *ProviderConfig) ValidateTokenAndMergeWithUserInfo(ctx context.Context, tok *oauth2.Token, expectedIDTokenNonce nonce.Nonce, requireIDToken bool, requireUserInfo bool) (*oidctypes.Token, error) { - var validatedClaims = make(map[string]interface{}) + var validatedClaims = make(map[string]any) var idTokenExpiry time.Time // if we require the id token, make sure we have it. @@ -319,7 +319,7 @@ func (p *ProviderConfig) ValidateTokenAndMergeWithUserInfo(ctx context.Context, }, nil } -func (p *ProviderConfig) validateIDToken(ctx context.Context, tok *oauth2.Token, expectedIDTokenNonce nonce.Nonce, validatedClaims map[string]interface{}, requireIDToken bool) (time.Time, string, error) { +func (p *ProviderConfig) validateIDToken(ctx context.Context, tok *oauth2.Token, expectedIDTokenNonce nonce.Nonce, validatedClaims map[string]any, requireIDToken bool) (time.Time, string, error) { idTok, hasIDTok := tok.Extra("id_token").(string) if !hasIDTok && !requireIDToken { return time.Time{}, "", nil // exit early @@ -351,7 +351,7 @@ func (p *ProviderConfig) validateIDToken(ctx context.Context, tok *oauth2.Token, return idTokenExpiry, idTok, nil } -func (p *ProviderConfig) maybeFetchUserInfoAndMergeClaims(ctx context.Context, tok *oauth2.Token, claims map[string]interface{}, requireIDToken bool, requireUserInfo bool) error { +func (p *ProviderConfig) maybeFetchUserInfoAndMergeClaims(ctx context.Context, tok *oauth2.Token, claims map[string]any, requireIDToken bool, requireUserInfo bool) error { idTokenSubject, _ := claims[oidcapi.IDTokenClaimSubject].(string) userInfo, err := p.maybeFetchUserInfo(ctx, tok, requireUserInfo) @@ -414,7 +414,7 @@ func (p *ProviderConfig) maybeFetchUserInfo(ctx context.Context, tok *oauth2.Tok return userInfo, nil } -func maybeLogClaims(msg, name string, claims map[string]interface{}) { +func maybeLogClaims(msg, name string, claims map[string]any) { if plog.Enabled(plog.LevelAll) { // log keys and values at all level data, _ := json.Marshal(claims) // nothing we can do if it fails, but it really never should plog.All(msg, "providerName", name, "claims", string(data)) diff --git a/internal/upstreamoidc/upstreamoidc_test.go b/internal/upstreamoidc/upstreamoidc_test.go index 58f228fa8..2521d3016 100644 --- a/internal/upstreamoidc/upstreamoidc_test.go +++ b/internal/upstreamoidc/upstreamoidc_test.go @@ -126,7 +126,7 @@ func TestProviderConfig(t *testing.T) { IDToken: &oidctypes.IDToken{ Token: validIDToken, Expiry: metav1.Time{}, - Claims: map[string]interface{}{ + Claims: map[string]any{ "foo": "bar", "bat": "baz", "aud": "test-client-id", @@ -154,7 +154,7 @@ func TestProviderConfig(t *testing.T) { IDToken: &oidctypes.IDToken{ Token: validIDToken, Expiry: metav1.Time{}, - Claims: map[string]interface{}{ + Claims: map[string]any{ "foo": "awesomeness", // overwrite existing claim "bat": "baz", "aud": "test-client-id", @@ -227,7 +227,7 @@ func TestProviderConfig(t *testing.T) { IDToken: &oidctypes.IDToken{ Token: invalidSubClaim, Expiry: metav1.Time{}, - Claims: map[string]interface{}{ + Claims: map[string]any{ "foo": "bar", "bat": "baz", "aud": "test-client-id", @@ -328,7 +328,7 @@ func TestProviderConfig(t *testing.T) { wantErr string wantToken *oauth2.Token - wantTokenExtras map[string]interface{} + wantTokenExtras map[string]any }{ { name: "success when the server returns all tokens in the refresh result", @@ -344,7 +344,7 @@ func TestProviderConfig(t *testing.T) { TokenType: "test-token-type", Expiry: time.Now().Add(42 * time.Second), }, - wantTokenExtras: map[string]interface{}{ + wantTokenExtras: map[string]any{ // the ID token only appears in the extras map "id_token": "test-id-token", // the library also repeats all the other keys/values returned by the server in the raw extras map @@ -371,7 +371,7 @@ func TestProviderConfig(t *testing.T) { TokenType: "test-token-type", Expiry: time.Now().Add(42 * time.Second), }, - wantTokenExtras: map[string]interface{}{ + wantTokenExtras: map[string]any{ // the ID token only appears in the extras map "id_token": "test-id-token", // the library also repeats all the other keys/values returned by the server in the raw extras map @@ -396,7 +396,7 @@ func TestProviderConfig(t *testing.T) { TokenType: "test-token-type", Expiry: time.Now().Add(42 * time.Second), }, - wantTokenExtras: map[string]interface{}{ + wantTokenExtras: map[string]any{ // the library also repeats all the other keys/values returned by the server in the raw extras map "access_token": "test-access-token", "refresh_token": "test-refresh-token", @@ -754,7 +754,7 @@ func TestProviderConfig(t *testing.T) { }{ { name: "token with id, access and refresh tokens, valid nonce, and no userinfo", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-nonce", requireIDToken: true, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -769,7 +769,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: goodIDToken, - Claims: map[string]interface{}{ + Claims: map[string]any{ "iss": "some-issuer", "nonce": "some-nonce", "sub": "some-subject", @@ -779,7 +779,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "id token not required but is provided", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-nonce", requireIDToken: false, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -795,7 +795,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: goodIDToken, - Claims: map[string]interface{}{ + Claims: map[string]any{ "iss": "some-issuer", "nonce": "some-nonce", "sub": "some-subject", @@ -806,7 +806,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "token with id, access and refresh tokens, valid nonce, and userinfo with a value that doesn't exist in the id token", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-nonce", requireIDToken: true, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -822,7 +822,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: goodIDToken, - Claims: map[string]interface{}{ + Claims: map[string]any{ "iss": "some-issuer", "nonce": "some-nonce", "sub": "some-subject", @@ -833,7 +833,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "userinfo is required, token with id, access and refresh tokens, valid nonce, and userinfo with a value that doesn't exist in the id token", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-nonce", requireIDToken: true, requireUserInfo: true, @@ -850,7 +850,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: goodIDToken, - Claims: map[string]interface{}{ + Claims: map[string]any{ "iss": "some-issuer", "nonce": "some-nonce", "sub": "some-subject", @@ -861,7 +861,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "claims from userinfo override id token claims", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzb21lLXN1YmplY3QiLCJuYW1lIjoiSm9obiBEb2UiLCJpc3MiOiJzb21lLWlzc3VlciIsIm5vbmNlIjoic29tZS1ub25jZSJ9.sBWi3_4cfGwrmMFZWkCghw4uvCnHN35h9xNX1gkwOtj6Oz_yKqpj7wfO4AqeWsRyrDGnkmIZbVuhAAJqPSi4GlNzN4NU8zh53PGDUpFlpDI1dvqDjIRb9iIEJpRIj34--Sz41H0ooxviIzvUdZFvQlaSzLOqgjR3ddHe2urhbtUuz_DsabP84AWo2DSg0y3ull6DRvk_DvzC6HNN8JwVi08fFvvV9BVq8kjdVeob7gajJkuGSTjsxNZGs5rbBuxBx0MZTQ8boR1fDNdG70GoIb4SsCoBSs7pZxtmGZPHInteY1SilHDDDmpQuE-LvSmvvPN_Cyk1d3eS-IR7hBbCAA"}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzb21lLXN1YmplY3QiLCJuYW1lIjoiSm9obiBEb2UiLCJpc3MiOiJzb21lLWlzc3VlciIsIm5vbmNlIjoic29tZS1ub25jZSJ9.sBWi3_4cfGwrmMFZWkCghw4uvCnHN35h9xNX1gkwOtj6Oz_yKqpj7wfO4AqeWsRyrDGnkmIZbVuhAAJqPSi4GlNzN4NU8zh53PGDUpFlpDI1dvqDjIRb9iIEJpRIj34--Sz41H0ooxviIzvUdZFvQlaSzLOqgjR3ddHe2urhbtUuz_DsabP84AWo2DSg0y3ull6DRvk_DvzC6HNN8JwVi08fFvvV9BVq8kjdVeob7gajJkuGSTjsxNZGs5rbBuxBx0MZTQ8boR1fDNdG70GoIb4SsCoBSs7pZxtmGZPHInteY1SilHDDDmpQuE-LvSmvvPN_Cyk1d3eS-IR7hBbCAA"}), nonce: "some-nonce", requireIDToken: true, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -877,7 +877,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzb21lLXN1YmplY3QiLCJuYW1lIjoiSm9obiBEb2UiLCJpc3MiOiJzb21lLWlzc3VlciIsIm5vbmNlIjoic29tZS1ub25jZSJ9.sBWi3_4cfGwrmMFZWkCghw4uvCnHN35h9xNX1gkwOtj6Oz_yKqpj7wfO4AqeWsRyrDGnkmIZbVuhAAJqPSi4GlNzN4NU8zh53PGDUpFlpDI1dvqDjIRb9iIEJpRIj34--Sz41H0ooxviIzvUdZFvQlaSzLOqgjR3ddHe2urhbtUuz_DsabP84AWo2DSg0y3ull6DRvk_DvzC6HNN8JwVi08fFvvV9BVq8kjdVeob7gajJkuGSTjsxNZGs5rbBuxBx0MZTQ8boR1fDNdG70GoIb4SsCoBSs7pZxtmGZPHInteY1SilHDDDmpQuE-LvSmvvPN_Cyk1d3eS-IR7hBbCAA", - Claims: map[string]interface{}{ + Claims: map[string]any{ "iss": "some-issuer", // takes the issuer from the ID token, since the userinfo one is unreliable. "nonce": "some-nonce", "sub": "some-subject", @@ -888,7 +888,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "token with id, access and refresh tokens and valid nonce, but userinfo has a different issuer", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-nonce", requireIDToken: true, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -904,7 +904,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: goodIDToken, - Claims: map[string]interface{}{ + Claims: map[string]any{ "iss": "some-issuer", // takes the issuer from the ID token, since the userinfo one is unreliable. "nonce": "some-nonce", "sub": "some-subject", @@ -915,7 +915,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "token with id, access and refresh tokens and valid nonce, but no userinfo endpoint from discovery and it's not required", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-nonce", requireIDToken: true, requireUserInfo: false, @@ -931,7 +931,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: goodIDToken, - Claims: map[string]interface{}{ + Claims: map[string]any{ "iss": "some-issuer", "nonce": "some-nonce", "sub": "some-subject", @@ -957,7 +957,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: "", - Claims: map[string]interface{}{ + Claims: map[string]any{ "sub": "some-subject", "name": "Pinny TheSeal", }, @@ -980,13 +980,13 @@ func TestProviderConfig(t *testing.T) { Token: "test-initial-refresh-token", }, IDToken: &oidctypes.IDToken{ - Claims: map[string]interface{}{}, + Claims: map[string]any{}, }, }, }, { name: "token with id, access and refresh tokens, valid nonce, and userinfo subject that doesn't match", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-nonce", requireIDToken: true, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -995,7 +995,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "id token not required but is provided, and subjects don't match", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-nonce", requireIDToken: false, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -1004,7 +1004,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "invalid id token", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": "not-an-id-token"}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": "not-an-id-token"}), nonce: "some-nonce", requireIDToken: true, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -1013,7 +1013,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "invalid nonce", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": goodIDToken}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": goodIDToken}), nonce: "some-other-nonce", requireIDToken: true, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -1057,7 +1057,7 @@ func TestProviderConfig(t *testing.T) { }, { name: "id token missing subject, skip userinfo check", - tok: testTokenWithoutIDToken.WithExtra(map[string]interface{}{"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UiLCJpc3MiOiJzb21lLWlzc3VlciIsIm5vbmNlIjoic29tZS1ub25jZSJ9.aIhrhikAnQ4Mb1g6RAT08qqflT2LLLi2yj4F2S4zud8nYad4tfEd2ITVJ4Njdjf70ubqyzZ6XxojtC4OqaWbDaQOcd95sd3PW58SYrf4NMvEStFkcMG0HMhJEZLVGnuJQstuq3G9h5Z5bFCkx4mFNo5ho_isBWyHpk-uF14duXXlIDB10SnyZ9dRbcmu-3mMOq0g4oCUPEDiHWkv-Rf70Mk0harL2xvcpxlSMLK4glDfiiki5gl6IReIo4rTVosXAqv3JmjLDeVLtJQRG6F8YcIlDCIfUEUfk0GeYacBVjoDIO570ywVJy1LGvyUuvgXNQUjq2JgzCfb8HWGp7iJdQ"}), + tok: testTokenWithoutIDToken.WithExtra(map[string]any{"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UiLCJpc3MiOiJzb21lLWlzc3VlciIsIm5vbmNlIjoic29tZS1ub25jZSJ9.aIhrhikAnQ4Mb1g6RAT08qqflT2LLLi2yj4F2S4zud8nYad4tfEd2ITVJ4Njdjf70ubqyzZ6XxojtC4OqaWbDaQOcd95sd3PW58SYrf4NMvEStFkcMG0HMhJEZLVGnuJQstuq3G9h5Z5bFCkx4mFNo5ho_isBWyHpk-uF14duXXlIDB10SnyZ9dRbcmu-3mMOq0g4oCUPEDiHWkv-Rf70Mk0harL2xvcpxlSMLK4glDfiiki5gl6IReIo4rTVosXAqv3JmjLDeVLtJQRG6F8YcIlDCIfUEUfk0GeYacBVjoDIO570ywVJy1LGvyUuvgXNQUjq2JgzCfb8HWGp7iJdQ"}), nonce: "some-nonce", requireIDToken: true, rawClaims: []byte(`{"userinfo_endpoint": "not-empty"}`), @@ -1073,7 +1073,7 @@ func TestProviderConfig(t *testing.T) { }, IDToken: &oidctypes.IDToken{ Token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UiLCJpc3MiOiJzb21lLWlzc3VlciIsIm5vbmNlIjoic29tZS1ub25jZSJ9.aIhrhikAnQ4Mb1g6RAT08qqflT2LLLi2yj4F2S4zud8nYad4tfEd2ITVJ4Njdjf70ubqyzZ6XxojtC4OqaWbDaQOcd95sd3PW58SYrf4NMvEStFkcMG0HMhJEZLVGnuJQstuq3G9h5Z5bFCkx4mFNo5ho_isBWyHpk-uF14duXXlIDB10SnyZ9dRbcmu-3mMOq0g4oCUPEDiHWkv-Rf70Mk0harL2xvcpxlSMLK4glDfiiki5gl6IReIo4rTVosXAqv3JmjLDeVLtJQRG6F8YcIlDCIfUEUfk0GeYacBVjoDIO570ywVJy1LGvyUuvgXNQUjq2JgzCfb8HWGp7iJdQ", - Claims: map[string]interface{}{ + Claims: map[string]any{ "iss": "some-issuer", "name": "John Doe", "nonce": "some-nonce", @@ -1176,7 +1176,7 @@ func TestProviderConfig(t *testing.T) { IDToken: &oidctypes.IDToken{ Token: invalidNonceIDToken, Expiry: metav1.Time{}, - Claims: map[string]interface{}{ + Claims: map[string]any{ "aud": "test-client-id", "iat": 1.602283741e+09, "jti": "test-jti", @@ -1204,7 +1204,7 @@ func TestProviderConfig(t *testing.T) { IDToken: &oidctypes.IDToken{ Token: validIDToken, Expiry: metav1.Time{}, - Claims: map[string]interface{}{ + Claims: map[string]any{ "foo": "bar", "bat": "baz", "aud": "test-client-id", @@ -1234,7 +1234,7 @@ func TestProviderConfig(t *testing.T) { IDToken: &oidctypes.IDToken{ Token: validIDToken, Expiry: metav1.Time{}, - Claims: map[string]interface{}{ + Claims: map[string]any{ "foo": "bar", "bat": "baz", "aud": "test-client-id", @@ -1285,7 +1285,7 @@ func TestProviderConfig(t *testing.T) { IDToken: &oidctypes.IDToken{ Token: validIDToken, Expiry: metav1.Time{}, - Claims: map[string]interface{}{ + Claims: map[string]any{ "foo": "awesomeness", // overwrite existing claim "bat": "baz", "aud": "test-client-id", @@ -1316,7 +1316,7 @@ func TestProviderConfig(t *testing.T) { IDToken: &oidctypes.IDToken{ Token: invalidSubClaim, Expiry: metav1.Time{}, - Claims: map[string]interface{}{ + Claims: map[string]any{ "foo": "bar", "bat": "baz", "aud": "test-client-id", @@ -1438,7 +1438,7 @@ func (m *mockProvider) Verifier(_ *coreosoidc.Config) *coreosoidc.IDTokenVerifie return mockVerifier() } -func (m *mockProvider) Claims(v interface{}) error { +func (m *mockProvider) Claims(v any) error { return json.Unmarshal(m.rawClaims, v) } diff --git a/internal/valuelesscontext/valuelesscontext.go b/internal/valuelesscontext/valuelesscontext.go index 93c90a5ed..7c8ac48ed 100644 --- a/internal/valuelesscontext/valuelesscontext.go +++ b/internal/valuelesscontext/valuelesscontext.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package valuelesscontext @@ -11,4 +11,4 @@ func New(ctx context.Context) context.Context { type valuelessContext struct{ context.Context } -func (valuelessContext) Value(interface{}) interface{} { return nil } +func (valuelessContext) Value(any) any { return nil } diff --git a/pkg/oidcclient/filesession/cachefile_test.go b/pkg/oidcclient/filesession/cachefile_test.go index cf1cf7640..913364061 100644 --- a/pkg/oidcclient/filesession/cachefile_test.go +++ b/pkg/oidcclient/filesession/cachefile_test.go @@ -37,9 +37,9 @@ var validSession = sessionCache{ IDToken: &oidctypes.IDToken{ Token: "test-id-token", Expiry: metav1.NewTime(time.Date(2020, 10, 20, 19, 42, 07, 0, time.UTC).Local()), - Claims: map[string]interface{}{ + Claims: map[string]any{ "foo": "bar", - "nested": map[string]interface{}{ + "nested": map[string]any{ "key1": "value1", "key2": "value2", }, diff --git a/pkg/oidcclient/login_test.go b/pkg/oidcclient/login_test.go index 5243c3520..89352a110 100644 --- a/pkg/oidcclient/login_test.go +++ b/pkg/oidcclient/login_test.go @@ -2629,7 +2629,7 @@ func TestLogin(t *testing.T) { //nolint:gocyclo IDToken: &oidctypes.IDToken{ Token: testToken.IDToken.Token, Expiry: testToken.IDToken.Expiry, - Claims: map[string]interface{}{"aud": "request-this-test-audience"}, + Claims: map[string]any{"aud": "request-this-test-audience"}, }, RefreshToken: testToken.RefreshToken, }} @@ -2659,7 +2659,7 @@ func TestLogin(t *testing.T) { //nolint:gocyclo IDToken: &oidctypes.IDToken{ Token: testToken.IDToken.Token, Expiry: testToken.IDToken.Expiry, - Claims: map[string]interface{}{"aud": "request-this-test-audience"}, + Claims: map[string]any{"aud": "request-this-test-audience"}, }, RefreshToken: testToken.RefreshToken, }, @@ -2675,7 +2675,7 @@ func TestLogin(t *testing.T) { //nolint:gocyclo IDToken: &oidctypes.IDToken{ Token: testToken.IDToken.Token, Expiry: metav1.NewTime(time.Now().Add(9 * time.Minute)), // less than Now() + minIDTokenValidity - Claims: map[string]interface{}{"aud": "test-custom-request-audience"}, + Claims: map[string]any{"aud": "test-custom-request-audience"}, }, RefreshToken: testToken.RefreshToken, }} @@ -2691,7 +2691,7 @@ func TestLogin(t *testing.T) { //nolint:gocyclo require.Equal(t, &oidctypes.IDToken{ Token: testToken.IDToken.Token, Expiry: metav1.NewTime(fakeUniqueTime), - Claims: map[string]interface{}{"aud": "test-custom-request-audience"}, + Claims: map[string]any{"aud": "test-custom-request-audience"}, }, cache.sawPutTokens[0].IDToken) }) require.NoError(t, WithClient(buildHTTPClientForPEM(successServerCA))(h)) @@ -2707,7 +2707,7 @@ func TestLogin(t *testing.T) { //nolint:gocyclo IDToken: &oidctypes.IDToken{ Token: testToken.IDToken.Token, Expiry: metav1.NewTime(fakeUniqueTime), // less than Now() + minIDTokenValidity but does not matter because this is a freshly refreshed ID token - Claims: map[string]interface{}{"aud": "test-custom-request-audience"}, + Claims: map[string]any{"aud": "test-custom-request-audience"}, }, RefreshToken: testToken.RefreshToken, }, nil) @@ -2732,7 +2732,7 @@ func TestLogin(t *testing.T) { //nolint:gocyclo IDToken: &oidctypes.IDToken{ Token: testToken.IDToken.Token, Expiry: metav1.NewTime(fakeUniqueTime), - Claims: map[string]interface{}{"aud": "test-custom-request-audience"}, + Claims: map[string]any{"aud": "test-custom-request-audience"}, }, RefreshToken: testToken.RefreshToken, }, @@ -3452,11 +3452,11 @@ func mockUpstream(t *testing.T) *mockupstreamoidcidentityprovider.MockUpstreamOI // hasAccessTokenMatcher is a gomock.Matcher that expects an *oauth2.Token with a particular access token. type hasAccessTokenMatcher struct{ expected string } -func (m hasAccessTokenMatcher) Matches(arg interface{}) bool { +func (m hasAccessTokenMatcher) Matches(arg any) bool { return arg.(*oauth2.Token).AccessToken == m.expected } -func (m hasAccessTokenMatcher) Got(got interface{}) string { +func (m hasAccessTokenMatcher) Got(got any) string { return got.(*oauth2.Token).AccessToken } diff --git a/pkg/oidcclient/oidctypes/oidctypes.go b/pkg/oidcclient/oidctypes/oidctypes.go index a55e3ccb2..4cf9388b9 100644 --- a/pkg/oidcclient/oidctypes/oidctypes.go +++ b/pkg/oidcclient/oidctypes/oidctypes.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package oidctypes provides core data types for OIDC token structures. @@ -33,7 +33,7 @@ type IDToken struct { Expiry metav1.Time `json:"expiryTimestamp,omitempty"` // Claims are the claims expressed by the Token. - Claims map[string]interface{} `json:"claims,omitempty"` + Claims map[string]any `json:"claims,omitempty"` } // Token contains the elements of an OIDC session. diff --git a/test/integration/cli_test.go b/test/integration/cli_test.go index ff32f5bea..c8bac8eef 100644 --- a/test/integration/cli_test.go +++ b/test/integration/cli_test.go @@ -106,9 +106,9 @@ func TestCLIGetKubeconfigStaticToken_Parallel(t *testing.T) { type testingT interface { Helper() - Errorf(format string, args ...interface{}) + Errorf(format string, args ...any) FailNow() - Logf(format string, args ...interface{}) + Logf(format string, args ...any) } func runPinnipedCLI(t testingT, envVars []string, pinnipedExe string, args ...string) (string, string) { @@ -194,7 +194,7 @@ func TestCLILoginOIDC_Browser(t *testing.T) { require.NotEmpty(t, credOutput.Status.Token) jws, err := jose.ParseSigned(credOutput.Status.Token) require.NoError(t, err) - claims := map[string]interface{}{} + claims := map[string]any{} require.NoError(t, json.Unmarshal(jws.UnsafePayloadWithoutVerification(), &claims)) require.Equal(t, env.CLIUpstreamOIDC.Issuer, claims["iss"]) require.Equal(t, env.CLIUpstreamOIDC.ClientID, claims["aud"]) diff --git a/test/integration/e2e_test.go b/test/integration/e2e_test.go index f81206ede..7500b0b1e 100644 --- a/test/integration/e2e_test.go +++ b/test/integration/e2e_test.go @@ -35,7 +35,7 @@ import ( "k8s.io/utils/ptr" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" supervisorclient "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/typed/config/v1alpha1" "go.pinniped.dev/internal/certauthority" @@ -105,11 +105,11 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Create the downstream FederationDomain and expect it to go into the success status condition. federationDomain := testlib.CreateTestFederationDomain(topSetupCtx, t, - configv1alpha1.FederationDomainSpec{ + supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: issuerURL.String(), - TLS: &configv1alpha1.FederationDomainTLSSpec{SecretName: certSecret.Name}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: certSecret.Name}, }, - configv1alpha1.FederationDomainPhaseError, // in phase error until there is an IDP created + supervisorconfigv1alpha1.FederationDomainPhaseError, // in phase error until there is an IDP created ) // Create a JWTAuthenticator that will validate the tokens from the downstream issuer. @@ -163,7 +163,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { SecretName: testlib.CreateClientCredsSecret(t, env.SupervisorUpstreamOIDC.ClientID, env.SupervisorUpstreamOIDC.ClientSecret).Name, }, }, idpv1alpha1.PhaseReady) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -249,7 +249,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { SecretName: testlib.CreateClientCredsSecret(t, env.SupervisorUpstreamOIDC.ClientID, env.SupervisorUpstreamOIDC.ClientSecret).Name, }, }, idpv1alpha1.PhaseReady) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -337,7 +337,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { SecretName: testlib.CreateClientCredsSecret(t, env.SupervisorUpstreamOIDC.ClientID, env.SupervisorUpstreamOIDC.ClientSecret).Name, }, }, idpv1alpha1.PhaseReady) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -461,7 +461,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { SecretName: testlib.CreateClientCredsSecret(t, env.SupervisorUpstreamOIDC.ClientID, env.SupervisorUpstreamOIDC.ClientSecret).Name, }, }, idpv1alpha1.PhaseReady) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -592,7 +592,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { SecretName: testlib.CreateClientCredsSecret(t, env.SupervisorUpstreamOIDC.ClientID, env.SupervisorUpstreamOIDC.ClientSecret).Name, }, }, idpv1alpha1.PhaseReady) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -665,7 +665,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { SecretName: testlib.CreateClientCredsSecret(t, env.SupervisorUpstreamOIDC.ClientID, env.SupervisorUpstreamOIDC.ClientSecret).Name, }, }, idpv1alpha1.PhaseReady) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -729,7 +729,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { expectedGroups := env.SupervisorUpstreamLDAP.TestUserDirectGroupsDNs createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -788,7 +788,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { expectedGroups := env.SupervisorUpstreamLDAP.TestUserDirectGroupsDNs createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -851,7 +851,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { expectedGroups := env.SupervisorUpstreamLDAP.TestUserDirectGroupsDNs createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -922,7 +922,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { expectedGroups := env.SupervisorUpstreamActiveDirectory.TestUserIndirectGroupsSAMAccountPlusDomainNames createdProvider := setupClusterForEndToEndActiveDirectoryTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -981,7 +981,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { expectedGroups := env.SupervisorUpstreamActiveDirectory.TestUserIndirectGroupsSAMAccountPlusDomainNames createdProvider := setupClusterForEndToEndActiveDirectoryTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -1054,7 +1054,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { expectedGroups := env.SupervisorUpstreamLDAP.TestUserDirectGroupsDNs createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -1109,7 +1109,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { expectedGroups := env.SupervisorUpstreamActiveDirectory.TestUserIndirectGroupsSAMAccountPlusDomainNames createdProvider := setupClusterForEndToEndActiveDirectoryTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -1164,7 +1164,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { expectedGroups := env.SupervisorUpstreamLDAP.TestUserDirectGroupsDNs createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -1241,7 +1241,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdLDAPProvider := setupClusterForEndToEndLDAPTest(t, expectedDownstreamLDAPUsername, env) // Having one IDP should put the FederationDomain into a ready state. - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Create a ClusterRoleBinding to give our test user from the upstream read-only access to the cluster. @@ -1275,7 +1275,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, idpv1alpha1.PhaseReady) // Having a second IDP should put the FederationDomain back into an error state until we tell it which one to use. - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseError) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseError) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Update the FederationDomain to use the two IDPs. @@ -1290,7 +1290,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { ldapIDPDisplayName := "My LDAP IDP 💾" oidcIDPDisplayName := "My OIDC IDP 🚀" - gotFederationDomain.Spec.IdentityProviders = []configv1alpha1.FederationDomainIdentityProvider{ + gotFederationDomain.Spec.IdentityProviders = []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: ldapIDPDisplayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -1298,21 +1298,21 @@ func TestE2EFullIntegration_Browser(t *testing.T) { Kind: "LDAPIdentityProvider", Name: createdLDAPProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Constants: []configv1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "allowedUser", Type: "string", StringValue: expectedUpstreamLDAPUsername}, {Name: "allowedUsers", Type: "stringList", StringListValue: []string{"someone else", expectedUpstreamLDAPUsername, "someone else"}}, }, - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "policy/v1", Expression: `username == strConst.allowedUser && username in strListConst.allowedUsers`, Message: "only special users allowed"}, {Type: "username/v1", Expression: fmt.Sprintf(`"%s" + username`, downstreamPrefix)}, {Type: "groups/v1", Expression: fmt.Sprintf(`groups.map(g, "%s" + g)`, downstreamPrefix)}, }, - Examples: []configv1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { Username: expectedUpstreamLDAPUsername, Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: expectedDownstreamLDAPUsername, Groups: []string{downstreamPrefix + "a", downstreamPrefix + "b"}, }, @@ -1320,7 +1320,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { { Username: "someone other user", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "only special users allowed", }, @@ -1335,21 +1335,21 @@ func TestE2EFullIntegration_Browser(t *testing.T) { Kind: "OIDCIdentityProvider", Name: createdOIDCProvider.Name, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Constants: []configv1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "allowedUser", Type: "string", StringValue: expectedUpstreamOIDCUsername}, {Name: "allowedUsers", Type: "stringList", StringListValue: []string{"someone else", expectedUpstreamOIDCUsername, "someone else"}}, }, - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "policy/v1", Expression: `username == strConst.allowedUser && username in strListConst.allowedUsers`, Message: "only special users allowed"}, {Type: "username/v1", Expression: fmt.Sprintf(`"%s" + username`, downstreamPrefix)}, {Type: "groups/v1", Expression: fmt.Sprintf(`groups.map(g, "%s" + g)`, downstreamPrefix)}, }, - Examples: []configv1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { Username: expectedUpstreamOIDCUsername, Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: expectedDownstreamOIDCUsername, Groups: []string{downstreamPrefix + "a", downstreamPrefix + "b"}, }, @@ -1357,7 +1357,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { { Username: "someone other user", Groups: []string{"a", "b"}, - Expects: configv1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "only special users allowed", }, @@ -1370,7 +1370,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { require.NoError(t, err) // The FederationDomain should be valid after the above update. - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -1504,7 +1504,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { requireEventually.Equal(fd.Generation, fd.Status.Conditions[0].ObservedGeneration) }, 20*time.Second, 250*time.Millisecond) // The FederationDomain should be valid after the above update. - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Log out so we can try fresh logins again. @@ -1968,7 +1968,7 @@ func requireUserCanUseKubectlWithoutAuthenticatingAgain( ctx context.Context, t *testing.T, env *testlib.TestEnv, - downstream *configv1alpha1.FederationDomain, + downstream *supervisorconfigv1alpha1.FederationDomain, upstreamProviderName string, kubeconfigPath string, sessionCachePath string, @@ -2009,8 +2009,8 @@ func requireUserCanUseKubectlWithoutAuthenticatingAgain( if expectedGroups == nil { require.Nil(t, idTokenClaims["groups"]) } else { - // The groups claim in the file ends up as an []interface{}, so adjust our expectation to match. - expectedGroupsAsEmptyInterfaces := make([]interface{}, 0, len(expectedGroups)) + // The groups claim in the file ends up as an []any, so adjust our expectation to match. + expectedGroupsAsEmptyInterfaces := make([]any, 0, len(expectedGroups)) for _, g := range expectedGroups { expectedGroupsAsEmptyInterfaces = append(expectedGroupsAsEmptyInterfaces, g) } diff --git a/test/integration/securetls_test.go b/test/integration/securetls_test.go index ab48394a5..a6bc9c499 100644 --- a/test/integration/securetls_test.go +++ b/test/integration/securetls_test.go @@ -147,7 +147,7 @@ func (t *fakeT) FailNow() { t.Errorf("fakeT ignored FailNow") } -func (t *fakeT) Errorf(format string, args ...interface{}) { +func (t *fakeT) Errorf(format string, args ...any) { t.Cleanup(func() { if !t.Failed() { return diff --git a/test/integration/supervisor_discovery_test.go b/test/integration/supervisor_discovery_test.go index 2d3d9ff5d..11aa0a0d6 100644 --- a/test/integration/supervisor_discovery_test.go +++ b/test/integration/supervisor_discovery_test.go @@ -25,7 +25,7 @@ import ( "k8s.io/client-go/util/retry" "k8s.io/utils/strings/slices" - "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" "go.pinniped.dev/internal/certauthority" @@ -131,15 +131,15 @@ func TestSupervisorOIDCDiscovery_Disruptive(t *testing.T) { // When the same issuer is added twice, both issuers are marked as duplicates, and neither provider is serving. config6Duplicate1, _ := requireCreatingFederationDomainCausesDiscoveryEndpointsToAppear(ctx, t, scheme, addr, caBundle, issuer6, client) - config6Duplicate2 := testlib.CreateTestFederationDomain(ctx, t, v1alpha1.FederationDomainSpec{Issuer: issuer6}, v1alpha1.FederationDomainPhaseError) - requireStatus(t, client, ns, config6Duplicate1.Name, v1alpha1.FederationDomainPhaseError, withFalseConditions([]string{"Ready", "IssuerIsUnique"})) - requireStatus(t, client, ns, config6Duplicate2.Name, v1alpha1.FederationDomainPhaseError, withFalseConditions([]string{"Ready", "IssuerIsUnique"})) + config6Duplicate2 := testlib.CreateTestFederationDomain(ctx, t, supervisorconfigv1alpha1.FederationDomainSpec{Issuer: issuer6}, supervisorconfigv1alpha1.FederationDomainPhaseError) + requireStatus(t, client, ns, config6Duplicate1.Name, supervisorconfigv1alpha1.FederationDomainPhaseError, withFalseConditions([]string{"Ready", "IssuerIsUnique"})) + requireStatus(t, client, ns, config6Duplicate2.Name, supervisorconfigv1alpha1.FederationDomainPhaseError, withFalseConditions([]string{"Ready", "IssuerIsUnique"})) requireDiscoveryEndpointsAreNotFound(t, scheme, addr, caBundle, issuer6) // If we delete the first duplicate issuer, the second duplicate issuer starts serving. requireDelete(t, client, ns, config6Duplicate1.Name) requireWellKnownEndpointIsWorking(t, scheme, addr, caBundle, issuer6, nil) - requireStatus(t, client, ns, config6Duplicate2.Name, v1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) + requireStatus(t, client, ns, config6Duplicate2.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) // When we finally delete all issuers, the endpoint should be down. requireDeletingFederationDomainCausesDiscoveryEndpointsToDisappear(t, config6Duplicate2, client, ns, scheme, addr, caBundle, issuer6) @@ -150,8 +150,8 @@ func TestSupervisorOIDCDiscovery_Disruptive(t *testing.T) { requireDeletingFederationDomainCausesDiscoveryEndpointsToDisappear(t, config7, client, ns, scheme, addr, caBundle, issuer7) // When we create a provider with an invalid issuer, the status is set to invalid. - badConfig := testlib.CreateTestFederationDomain(ctx, t, v1alpha1.FederationDomainSpec{Issuer: badIssuer}, v1alpha1.FederationDomainPhaseError) - requireStatus(t, client, ns, badConfig.Name, v1alpha1.FederationDomainPhaseError, withFalseConditions([]string{"Ready", "IssuerURLValid"})) + badConfig := testlib.CreateTestFederationDomain(ctx, t, supervisorconfigv1alpha1.FederationDomainSpec{Issuer: badIssuer}, supervisorconfigv1alpha1.FederationDomainPhaseError) + requireStatus(t, client, ns, badConfig.Name, supervisorconfigv1alpha1.FederationDomainPhaseError, withFalseConditions([]string{"Ready", "IssuerURLValid"})) requireDiscoveryEndpointsAreNotFound(t, scheme, addr, caBundle, badIssuer) requireDeletingFederationDomainCausesDiscoveryEndpointsToDisappear(t, badConfig, client, ns, scheme, addr, caBundle, badIssuer) }) @@ -185,11 +185,11 @@ func TestSupervisorTLSTerminationWithSNI_Disruptive(t *testing.T) { // Create an FederationDomain with a spec.tls.secretName. federationDomain1 := testlib.CreateTestFederationDomain(ctx, t, - v1alpha1.FederationDomainSpec{ + supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: issuer1, - TLS: &v1alpha1.FederationDomainTLSSpec{SecretName: certSecretName1}, - }, v1alpha1.FederationDomainPhaseReady) - requireStatus(t, pinnipedClient, federationDomain1.Namespace, federationDomain1.Name, v1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: certSecretName1}, + }, supervisorconfigv1alpha1.FederationDomainPhaseReady) + requireStatus(t, pinnipedClient, federationDomain1.Namespace, federationDomain1.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) // The spec.tls.secretName Secret does not exist, so the endpoints should fail with TLS errors. requireEndpointHasBootstrapTLSErrorBecauseCertificatesAreNotReady(t, issuer1) @@ -207,7 +207,7 @@ func TestSupervisorTLSTerminationWithSNI_Disruptive(t *testing.T) { if err != nil { return err } - federationDomain1LatestVersion.Spec.TLS = &v1alpha1.FederationDomainTLSSpec{SecretName: certSecretName1update} + federationDomain1LatestVersion.Spec.TLS = &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: certSecretName1update} _, err = pinnipedClient.ConfigV1alpha1().FederationDomains(ns).Update(ctx, federationDomain1LatestVersion, metav1.UpdateOptions{}) return err })) @@ -229,11 +229,11 @@ func TestSupervisorTLSTerminationWithSNI_Disruptive(t *testing.T) { // Create an FederationDomain with a spec.tls.secretName. federationDomain2 := testlib.CreateTestFederationDomain(ctx, t, - v1alpha1.FederationDomainSpec{ + supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: issuer2, - TLS: &v1alpha1.FederationDomainTLSSpec{SecretName: certSecretName2}, - }, v1alpha1.FederationDomainPhaseReady) - requireStatus(t, pinnipedClient, federationDomain2.Namespace, federationDomain2.Name, v1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: certSecretName2}, + }, supervisorconfigv1alpha1.FederationDomainPhaseReady) + requireStatus(t, pinnipedClient, federationDomain2.Namespace, federationDomain2.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) // Create the Secret. ca2 := createTLSCertificateSecret(ctx, t, ns, hostname2, nil, certSecretName2, kubeClient) @@ -282,8 +282,8 @@ func TestSupervisorTLSTerminationWithDefaultCerts_Disruptive(t *testing.T) { issuerUsingHostname := fmt.Sprintf("%s://%s/issuer1", scheme, address) // Create an FederationDomain without a spec.tls.secretName. - federationDomain1 := testlib.CreateTestFederationDomain(ctx, t, v1alpha1.FederationDomainSpec{Issuer: issuerUsingIPAddress}, v1alpha1.FederationDomainPhaseReady) - requireStatus(t, pinnipedClient, federationDomain1.Namespace, federationDomain1.Name, v1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) + federationDomain1 := testlib.CreateTestFederationDomain(ctx, t, supervisorconfigv1alpha1.FederationDomainSpec{Issuer: issuerUsingIPAddress}, supervisorconfigv1alpha1.FederationDomainPhaseReady) + requireStatus(t, pinnipedClient, federationDomain1.Namespace, federationDomain1.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) // There is no default TLS cert and the spec.tls.secretName was not set, so the endpoints should fail with TLS errors. requireEndpointHasBootstrapTLSErrorBecauseCertificatesAreNotReady(t, issuerUsingIPAddress) @@ -297,11 +297,11 @@ func TestSupervisorTLSTerminationWithDefaultCerts_Disruptive(t *testing.T) { // Create an FederationDomain with a spec.tls.secretName. certSecretName := "integration-test-cert-1" federationDomain2 := testlib.CreateTestFederationDomain(ctx, t, - v1alpha1.FederationDomainSpec{ + supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: issuerUsingHostname, - TLS: &v1alpha1.FederationDomainTLSSpec{SecretName: certSecretName}, - }, v1alpha1.FederationDomainPhaseReady) - requireStatus(t, pinnipedClient, federationDomain2.Namespace, federationDomain2.Name, v1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: certSecretName}, + }, supervisorconfigv1alpha1.FederationDomainPhaseReady) + requireStatus(t, pinnipedClient, federationDomain2.Namespace, federationDomain2.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) // Create the Secret. certCA := createTLSCertificateSecret(ctx, t, ns, hostname, nil, certSecretName, kubeClient) @@ -485,11 +485,11 @@ func requireCreatingFederationDomainCausesDiscoveryEndpointsToAppear( supervisorScheme, supervisorAddress, supervisorCABundle string, issuerName string, client supervisorclientset.Interface, -) (*v1alpha1.FederationDomain, *ExpectedJWKSResponseFormat) { +) (*supervisorconfigv1alpha1.FederationDomain, *ExpectedJWKSResponseFormat) { t.Helper() - newFederationDomain := testlib.CreateTestFederationDomain(ctx, t, v1alpha1.FederationDomainSpec{Issuer: issuerName}, v1alpha1.FederationDomainPhaseReady) + newFederationDomain := testlib.CreateTestFederationDomain(ctx, t, supervisorconfigv1alpha1.FederationDomainSpec{Issuer: issuerName}, supervisorconfigv1alpha1.FederationDomainPhaseReady) jwksResult := requireDiscoveryEndpointsAreWorking(t, supervisorScheme, supervisorAddress, supervisorCABundle, issuerName, nil) - requireStatus(t, client, newFederationDomain.Namespace, newFederationDomain.Name, v1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) + requireStatus(t, client, newFederationDomain.Namespace, newFederationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady, withAllSuccessfulConditions()) return newFederationDomain, jwksResult } @@ -501,7 +501,7 @@ func requireDiscoveryEndpointsAreWorking(t *testing.T, supervisorScheme, supervi func requireDeletingFederationDomainCausesDiscoveryEndpointsToDisappear( t *testing.T, - existingFederationDomain *v1alpha1.FederationDomain, + existingFederationDomain *supervisorconfigv1alpha1.FederationDomain, client supervisorclientset.Interface, ns string, supervisorScheme, supervisorAddress, supervisorCABundle string, @@ -626,16 +626,16 @@ func requireSuccessEndpointResponse(t *testing.T, endpointURL, issuer, caBundle func editFederationDomainIssuerName( t *testing.T, - existingFederationDomain *v1alpha1.FederationDomain, + existingFederationDomain *supervisorconfigv1alpha1.FederationDomain, client supervisorclientset.Interface, ns string, newIssuerName string, -) *v1alpha1.FederationDomain { +) *supervisorconfigv1alpha1.FederationDomain { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() - var updated *v1alpha1.FederationDomain + var updated *supervisorconfigv1alpha1.FederationDomain require.NoError(t, retry.RetryOnConflict(retry.DefaultRetry, func() error { mostRecentVersion, err := client.ConfigV1alpha1().FederationDomains(ns).Get(ctx, existingFederationDomain.Name, metav1.GetOptions{}) if err != nil { @@ -684,7 +684,7 @@ func withFalseConditions(falseConditionTypes []string) map[string]metav1.Conditi return c } -func requireStatus(t *testing.T, client supervisorclientset.Interface, ns, name string, wantPhase v1alpha1.FederationDomainPhase, wantConditionTypeToStatus map[string]metav1.ConditionStatus) { +func requireStatus(t *testing.T, client supervisorclientset.Interface, ns, name string, wantPhase supervisorconfigv1alpha1.FederationDomainPhase, wantConditionTypeToStatus map[string]metav1.ConditionStatus) { t.Helper() testlib.RequireEventually(t, func(requireEventually *require.Assertions) { diff --git a/test/integration/supervisor_federationdomain_status_test.go b/test/integration/supervisor_federationdomain_status_test.go index 79bf8eae8..2cf158bc7 100644 --- a/test/integration/supervisor_federationdomain_status_test.go +++ b/test/integration/supervisor_federationdomain_status_test.go @@ -17,7 +17,7 @@ import ( "k8s.io/client-go/util/retry" "k8s.io/utils/ptr" - "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/here" "go.pinniped.dev/internal/testutil" @@ -43,9 +43,9 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { name: "valid spec in without explicit identity providers makes status error unless there is exactly one identity provider", run: func(t *testing.T) { // Creating FederationDomain without any explicit IDPs should put the FederationDomain into an error status. - fd := testlib.CreateTestFederationDomain(ctx, t, v1alpha1.FederationDomainSpec{ + fd := testlib.CreateTestFederationDomain(ctx, t, supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com/fake", - }, v1alpha1.FederationDomainPhaseError) + }, supervisorconfigv1alpha1.FederationDomainPhaseError) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, replaceSomeConditions( allSuccessfulLegacyFederationDomainConditions("", fd.Spec), []metav1.Condition{ @@ -65,7 +65,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Issuer: "https://example.cluster.local/fake-issuer-url-does-not-matter", Client: idpv1alpha1.OIDCClient{SecretName: "this-will-not-exist-but-does-not-matter"}, }, idpv1alpha1.PhaseError) - testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, v1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, allSuccessfulLegacyFederationDomainConditions(oidcIdentityProvider1.Name, fd.Spec)) @@ -74,7 +74,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Issuer: "https://example.cluster.local/fake-issuer-url-does-not-matter", Client: idpv1alpha1.OIDCClient{SecretName: "this-will-not-exist-but-does-not-matter"}, }, idpv1alpha1.PhaseError) - testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, v1alpha1.FederationDomainPhaseError) + testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, supervisorconfigv1alpha1.FederationDomainPhaseError) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, replaceSomeConditions( allSuccessfulLegacyFederationDomainConditions(oidcIdentityProvider2.Name, fd.Spec), []metav1.Condition{ @@ -98,9 +98,9 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { oidcIDP1Meta := testlib.ObjectMetaWithRandomName(t, "upstream-oidc-idp") oidcIDP2Meta := testlib.ObjectMetaWithRandomName(t, "upstream-oidc-idp") // Creating FederationDomain with explicit IDPs that don't exist should put the FederationDomain into an error status. - fd := testlib.CreateTestFederationDomain(ctx, t, v1alpha1.FederationDomainSpec{ + fd := testlib.CreateTestFederationDomain(ctx, t, supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com/fake", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "idp1", ObjectRef: corev1.TypedLocalObjectReference{ @@ -108,7 +108,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIDP1Meta.Name, }, - Transforms: v1alpha1.FederationDomainTransforms{}, + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{}, }, { DisplayName: "idp2", @@ -117,10 +117,10 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIDP2Meta.Name, }, - Transforms: v1alpha1.FederationDomainTransforms{}, + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{}, }, }, - }, v1alpha1.FederationDomainPhaseError) + }, supervisorconfigv1alpha1.FederationDomainPhaseError) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, replaceSomeConditions( allSuccessfulFederationDomainConditions(fd.Spec), []metav1.Condition{ @@ -144,7 +144,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Issuer: "https://example.cluster.local/fake-issuer-url-does-not-matter", Client: idpv1alpha1.OIDCClient{SecretName: "this-will-not-exist-but-does-not-matter"}, }, oidcIDP1Meta, idpv1alpha1.PhaseError) - testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, v1alpha1.FederationDomainPhaseError) + testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, supervisorconfigv1alpha1.FederationDomainPhaseError) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, replaceSomeConditions( allSuccessfulFederationDomainConditions(fd.Spec), []metav1.Condition{ @@ -164,7 +164,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Issuer: "https://example.cluster.local/fake-issuer-url-does-not-matter", Client: idpv1alpha1.OIDCClient{SecretName: "this-will-not-exist-but-does-not-matter"}, }, oidcIDP2Meta, idpv1alpha1.PhaseError) - testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, v1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, allSuccessfulFederationDomainConditions(fd.Spec)) @@ -172,7 +172,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { oidcIDPClient := supervisorClient.IDPV1alpha1().OIDCIdentityProviders(env.SupervisorNamespace) err := oidcIDPClient.Delete(ctx, oidcIdentityProvider1.Name, metav1.DeleteOptions{}) require.NoError(t, err) - testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, v1alpha1.FederationDomainPhaseError) + testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, supervisorconfigv1alpha1.FederationDomainPhaseError) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, replaceSomeConditions( allSuccessfulFederationDomainConditions(fd.Spec), []metav1.Condition{ @@ -198,9 +198,9 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Client: idpv1alpha1.OIDCClient{SecretName: "this-will-not-exist-but-does-not-matter"}, }, idpv1alpha1.PhaseError) - fd := testlib.CreateTestFederationDomain(ctx, t, v1alpha1.FederationDomainSpec{ + fd := testlib.CreateTestFederationDomain(ctx, t, supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com/fake", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "not unique", ObjectRef: corev1.TypedLocalObjectReference{ @@ -208,17 +208,17 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Kind: "OIDCIdentityProvider", Name: "will not be found", }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "foo", Type: "string", StringValue: "bar"}, }, - Expressions: []v1alpha1.FederationDomainTransformsExpression{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: "this is not a valid cel expression"}, {Type: "groups/v1", Expression: "this is also not a valid cel expression"}, {Type: "username/v1", Expression: "username"}, // valid {Type: "policy/v1", Expression: "still not a valid cel expression"}, }, - Examples: []v1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { Username: "does not matter because expressions did not compile", }, @@ -240,23 +240,23 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Kind: "this is the wrong kind", Name: "also will not be found", }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "ryan", Type: "string", StringValue: "ryan"}, {Name: "unused", Type: "stringList", StringListValue: []string{"foo", "bar"}}, {Name: "rejectMe", Type: "string", StringValue: "rejectMeWithDefaultMessage"}, }, - Expressions: []v1alpha1.FederationDomainTransformsExpression{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "policy/v1", Expression: `username == strConst.ryan || username == strConst.rejectMe`, Message: "only special users allowed"}, {Type: "policy/v1", Expression: `username != "rejectMeWithDefaultMessage"`}, // no message specified {Type: "username/v1", Expression: `"pre:" + username`}, {Type: "groups/v1", Expression: `groups.map(g, "pre:" + g)`}, }, - Examples: []v1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { // this example should pass Username: "ryan", Groups: []string{"a", "b"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:ryan", Groups: []string{"pre:b", "pre:a", "pre:b", "pre:a"}, // order and repeats don't matter, treated like a set Rejected: false, @@ -264,7 +264,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { }, { // this example should pass Username: "other", - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "only special users allowed", }, @@ -272,7 +272,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { { // this example should fail because it expects the user to be rejected but the user was actually not rejected Username: "ryan", Groups: []string{"a", "b"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "this input is ignored in this case", }, @@ -280,7 +280,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { { // this example should fail because it expects the user not to be rejected but they were actually rejected Username: "other", Groups: []string{"a", "b"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:other", Groups: []string{"pre:a", "pre:b"}, Rejected: false, @@ -289,7 +289,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { { // this example should fail because it expects the wrong rejection message Username: "other", Groups: []string{"a", "b"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "wrong message", }, @@ -298,14 +298,14 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { // because the message assertions defaults to asserting the default rejection message Username: "rejectMeWithDefaultMessage", Groups: []string{"a", "b"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, }, }, { // this example should fail because it expects both the wrong username and groups Username: "ryan", Groups: []string{"b", "a"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "wrong", Groups: []string{}, Rejected: false, @@ -314,7 +314,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { { // this example should fail because it expects the wrong username only Username: "ryan", Groups: []string{"a", "b"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "wrong", Groups: []string{"pre:b", "pre:a"}, Rejected: false, @@ -323,7 +323,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { { // this example should fail because it expects the wrong groups only Username: "ryan", Groups: []string{"b", "a"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:ryan", Groups: []string{"wrong2", "wrong1"}, Rejected: false, @@ -332,13 +332,13 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { { // this example should fail because it does not expect anything but the auth actually was successful Username: "ryan", Groups: []string{"b", "a"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{}, + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{}, }, }, }, }, }, - }, v1alpha1.FederationDomainPhaseError) + }, supervisorconfigv1alpha1.FederationDomainPhaseError) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, replaceSomeConditions( allSuccessfulFederationDomainConditions(fd.Spec), @@ -437,7 +437,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { gotFD, err := federationDomainsClient.Get(ctx, fd.Name, metav1.GetOptions{}) require.NoError(t, err) - gotFD.Spec.IdentityProviders[0] = v1alpha1.FederationDomainIdentityProvider{ + gotFD.Spec.IdentityProviders[0] = supervisorconfigv1alpha1.FederationDomainIdentityProvider{ // Fix the display name. DisplayName: "now made unique", // Fix the objectRef. @@ -446,19 +446,19 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Kind: "OIDCIdentityProvider", Name: oidcIdentityProvider.Name, }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "foo", Type: "string", StringValue: "bar"}, }, - Expressions: []v1alpha1.FederationDomainTransformsExpression{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ // Fix the compile errors. {Type: "username/v1", Expression: `"pre:" + username`}, }, - Examples: []v1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { // this example should fail because it expects both the wrong username and groups Username: "ryan", Groups: []string{"b", "a"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "wrong", Groups: []string{}, Rejected: false, @@ -468,10 +468,10 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { }, } - gotFD.Spec.IdentityProviders[2].Transforms.Examples = []v1alpha1.FederationDomainTransformsExample{ + gotFD.Spec.IdentityProviders[2].Transforms.Examples = []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { // this example should pass Username: "other", - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Rejected: true, Message: "only special users allowed", }, @@ -525,11 +525,11 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { Name: oidcIdentityProvider.Name, } - gotFD.Spec.IdentityProviders[0].Transforms.Examples = []v1alpha1.FederationDomainTransformsExample{ + gotFD.Spec.IdentityProviders[0].Transforms.Examples = []supervisorconfigv1alpha1.FederationDomainTransformsExample{ { // this example should pass Username: "ryan", Groups: []string{"b", "a"}, - Expects: v1alpha1.FederationDomainTransformsExampleExpects{ + Expects: supervisorconfigv1alpha1.FederationDomainTransformsExampleExpects{ Username: "pre:ryan", Groups: []string{"a", "b"}, }, @@ -541,7 +541,7 @@ func TestSupervisorFederationDomainStatus_Disruptive(t *testing.T) { }) require.NoError(t, err) - testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, v1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(ctx, t, fd.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForFederationDomainStatusConditions(ctx, t, fd.Name, allSuccessfulFederationDomainConditions(fd.Spec)) }, }, @@ -570,16 +570,16 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { tests := []struct { name string - fd *v1alpha1.FederationDomain + fd *supervisorconfigv1alpha1.FederationDomain wantErr string wantOldKubeErr string wantReallyOldKubeErr string }{ { name: "issuer cannot be empty", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "", }, }, @@ -589,11 +589,11 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP display names cannot be empty", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "", ObjectRef: corev1.TypedLocalObjectReference{ @@ -610,18 +610,18 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP transform constants must have unique names", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "notUnique", Type: "string", StringValue: "foo"}, {Name: "notUnique", Type: "string", StringValue: "bar"}, }, @@ -639,18 +639,18 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP transform constant names cannot be empty", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "", Type: "string"}, }, }, @@ -665,18 +665,18 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP transform constant names cannot be more than 64 characters", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "12345678901234567890123456789012345678901234567890123456789012345", Type: "string"}, }, }, @@ -698,18 +698,18 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP transform constant names must be a legal CEL variable name", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "cannot have spaces", Type: "string"}, {Name: "1mustStartWithLetter", Type: "string"}, {Name: "_mustStartWithLetter", Type: "string"}, @@ -740,18 +740,18 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP transform constant types must be one of the allowed enum strings", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "a", Type: "this is invalid"}, {Name: "b", Type: "string"}, {Name: "c", Type: "stringList"}, @@ -768,18 +768,18 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP transform expression types must be one of the allowed enum strings", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Expressions: []v1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "this is invalid", Expression: "foo"}, {Type: "policy/v1", Expression: "foo"}, {Type: "username/v1", Expression: "foo"}, @@ -797,18 +797,18 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP transform expressions cannot be empty", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Expressions: []v1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: ""}, }, }, @@ -823,18 +823,18 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "IDP transform example usernames cannot be empty", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: objectMeta, - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Examples: []v1alpha1.FederationDomainTransformsExample{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ {Username: ""}, {Username: "non-empty"}, }, @@ -850,20 +850,20 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "minimum valid", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "fd"), - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", }, }, }, { name: "minimum valid when IDPs are included", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "fd"), - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ @@ -876,24 +876,24 @@ func TestSupervisorFederationDomainCRDValidations_Parallel(t *testing.T) { }, { name: "minimum valid when IDP has transform constants, expressions, and examples", - fd: &v1alpha1.FederationDomain{ + fd: &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: testlib.ObjectMetaWithRandomName(t, "fd"), - Spec: v1alpha1.FederationDomainSpec{ + Spec: supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: "https://example.com", - IdentityProviders: []v1alpha1.FederationDomainIdentityProvider{ + IdentityProviders: []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: "foo", ObjectRef: corev1.TypedLocalObjectReference{ APIGroup: ptr.To("required in older versions of Kubernetes for each item in the identityProviders slice"), }, - Transforms: v1alpha1.FederationDomainTransforms{ - Constants: []v1alpha1.FederationDomainTransformsConstant{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Constants: []supervisorconfigv1alpha1.FederationDomainTransformsConstant{ {Name: "foo", Type: "string"}, }, - Expressions: []v1alpha1.FederationDomainTransformsExpression{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ {Type: "username/v1", Expression: "foo"}, }, - Examples: []v1alpha1.FederationDomainTransformsExample{ + Examples: []supervisorconfigv1alpha1.FederationDomainTransformsExample{ {Username: "foo"}, }, }, @@ -964,7 +964,7 @@ func replaceSomeConditions(conditions []metav1.Condition, replaceWithTheseCondit return cp } -func allSuccessfulLegacyFederationDomainConditions(idpName string, federationDomainSpec v1alpha1.FederationDomainSpec) []metav1.Condition { +func allSuccessfulLegacyFederationDomainConditions(idpName string, federationDomainSpec supervisorconfigv1alpha1.FederationDomainSpec) []metav1.Condition { return replaceSomeConditions( allSuccessfulFederationDomainConditions(federationDomainSpec), []metav1.Condition{ @@ -979,7 +979,7 @@ func allSuccessfulLegacyFederationDomainConditions(idpName string, federationDom ) } -func allSuccessfulFederationDomainConditions(federationDomainSpec v1alpha1.FederationDomainSpec) []metav1.Condition { +func allSuccessfulFederationDomainConditions(federationDomainSpec supervisorconfigv1alpha1.FederationDomainSpec) []metav1.Condition { return []metav1.Condition{ { Type: "IdentityProvidersDisplayNamesUnique", Status: "True", Reason: "Success", diff --git a/test/integration/supervisor_login_test.go b/test/integration/supervisor_login_test.go index ee5802a25..a2ae4da5b 100644 --- a/test/integration/supervisor_login_test.go +++ b/test/integration/supervisor_login_test.go @@ -29,7 +29,7 @@ import ( "k8s.io/utils/ptr" "k8s.io/utils/strings/slices" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/federationdomain/oidc" @@ -237,7 +237,7 @@ func TestSupervisorLogin_Browser(t *testing.T) { // Optionally specify the identityProviders part of the FederationDomain's spec by returning it from this function. // Also return the displayName of the IDP that should be used during authentication (or empty string for no IDP name in the auth request). // This function takes the name of the IDP CR which was returned by createIDP() as as argument. - federationDomainIDPs func(t *testing.T, idpName string) (idps []configv1alpha1.FederationDomainIdentityProvider, useIDPDisplayName string) + federationDomainIDPs func(t *testing.T, idpName string) (idps []supervisorconfigv1alpha1.FederationDomainIdentityProvider, useIDPDisplayName string) // Optionally create an OIDCClient CR for the test to use. Return the client ID and client secret for the // test to use. When not set, the test will default to using the "pinniped-cli" static client with no secret. @@ -280,7 +280,7 @@ func TestSupervisorLogin_Browser(t *testing.T) { wantDownstreamIDTokenGroups []string // The expected ID token additional claims, which will be nested under claim "additionalClaims", // for the original ID token and the refreshed ID token. - wantDownstreamIDTokenAdditionalClaims map[string]interface{} + wantDownstreamIDTokenAdditionalClaims map[string]any // The expected ID token lifetime, as calculated by token claim 'exp' subtracting token claim 'iat'. // ID tokens issued through authcode exchange or token refresh should have the configured lifetime (or default if not configured). // ID tokens issued through a token exchange should have the default lifetime. @@ -454,7 +454,7 @@ func TestSupervisorLogin_Browser(t *testing.T) { wantDownstreamIDTokenSubjectToMatch: expectedIDTokenSubjectRegexForUpstreamOIDC, // the ID token Username should include the upstream user ID after the upstream issuer name wantDownstreamIDTokenUsernameToMatch: func(_ string) string { return "^" + regexp.QuoteMeta(env.SupervisorUpstreamOIDC.Issuer+"?sub=") + ".+" }, - wantDownstreamIDTokenAdditionalClaims: wantGroupsInAdditionalClaimsIfGroupsExist(map[string]interface{}{ + wantDownstreamIDTokenAdditionalClaims: wantGroupsInAdditionalClaimsIfGroupsExist(map[string]any{ "upstream_issuer✅": env.SupervisorUpstreamOIDC.Issuer, "upstream_username": env.SupervisorUpstreamOIDC.Username, }, "upstream_groups", env.SupervisorUpstreamOIDC.ExpectedGroups), @@ -479,7 +479,7 @@ func TestSupervisorLogin_Browser(t *testing.T) { wantDownstreamIDTokenSubjectToMatch: expectedIDTokenSubjectRegexForUpstreamOIDC, // the ID token Username should include the upstream user ID after the upstream issuer name wantDownstreamIDTokenUsernameToMatch: func(_ string) string { return "^" + regexp.QuoteMeta(env.SupervisorUpstreamOIDC.Issuer+"?sub=") + ".+" }, - wantDownstreamIDTokenAdditionalClaims: wantGroupsInAdditionalClaimsIfGroupsExist(map[string]interface{}{ + wantDownstreamIDTokenAdditionalClaims: wantGroupsInAdditionalClaimsIfGroupsExist(map[string]any{ "upstream_issuer✅": env.SupervisorUpstreamOIDC.Issuer, "upstream_username": env.SupervisorUpstreamOIDC.Username, }, "upstream_groups", env.SupervisorUpstreamOIDC.ExpectedGroups), @@ -1423,11 +1423,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return testlib.CreateTestOIDCIdentityProvider(t, spec, idpv1alpha1.PhaseReady).Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, requestAuthorization: requestAuthorizationUsingBrowserAuthcodeFlowOIDC, wantDownstreamIDTokenSubjectToMatch: expectedIDTokenSubjectRegexForUpstreamOIDC, @@ -1449,14 +1449,14 @@ func TestSupervisorLogin_Browser(t *testing.T) { return testlib.CreateTestOIDCIdentityProvider(t, spec, idpv1alpha1.PhaseReady).Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - TokenLifetimes: configv1alpha1.OIDCClientTokenLifetimes{ + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + TokenLifetimes: supervisorconfigv1alpha1.OIDCClientTokenLifetimes{ IDTokenSeconds: ptr.To[int32](1234), }, - }, configv1alpha1.OIDCClientPhaseReady) + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, requestAuthorization: requestAuthorizationUsingBrowserAuthcodeFlowOIDC, wantDownstreamIDTokenSubjectToMatch: expectedIDTokenSubjectRegexForUpstreamOIDC, @@ -1478,9 +1478,9 @@ func TestSupervisorLogin_Browser(t *testing.T) { } return testlib.CreateTestOIDCIdentityProvider(t, spec, idpv1alpha1.PhaseReady).Name }, - federationDomainIDPs: func(t *testing.T, idpName string) ([]configv1alpha1.FederationDomainIdentityProvider, string) { + federationDomainIDPs: func(t *testing.T, idpName string) ([]supervisorconfigv1alpha1.FederationDomainIdentityProvider, string) { displayName := "my oidc idp" - return []configv1alpha1.FederationDomainIdentityProvider{ + return []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: displayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -1494,11 +1494,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { // which should cause the authorize endpoint to show the IDP chooser page }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, requestAuthorization: requestAuthorizationUsingBrowserAuthcodeFlowOIDCWithIDPChooserPage, wantDownstreamIDTokenSubjectToMatch: "^" + @@ -1530,17 +1530,17 @@ func TestSupervisorLogin_Browser(t *testing.T) { return testlib.CreateTestOIDCIdentityProvider(t, spec, idpv1alpha1.PhaseReady).Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, requestAuthorization: requestAuthorizationUsingBrowserAuthcodeFlowOIDC, wantDownstreamIDTokenSubjectToMatch: expectedIDTokenSubjectRegexForUpstreamOIDC, wantDownstreamIDTokenUsernameToMatch: func(_ string) string { return "^" + regexp.QuoteMeta(env.SupervisorUpstreamOIDC.Username) + "$" }, wantDownstreamIDTokenGroups: env.SupervisorUpstreamOIDC.ExpectedGroups, - wantDownstreamIDTokenAdditionalClaims: wantGroupsInAdditionalClaimsIfGroupsExist(map[string]interface{}{ + wantDownstreamIDTokenAdditionalClaims: wantGroupsInAdditionalClaimsIfGroupsExist(map[string]any{ "upstream_issuer✅": env.SupervisorUpstreamOIDC.Issuer, "upstream_username": env.SupervisorUpstreamOIDC.Username, }, "upstream_groups", env.SupervisorUpstreamOIDC.ExpectedGroups), @@ -1553,11 +1553,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1580,11 +1580,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange grant type not allowed - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "username", "groups"}, // a validation requires that we also disallow the pinniped:request-audience scope - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange grant type not allowed + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username", "groups"}, // a validation requires that we also disallow the pinniped:request-audience scope + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1614,11 +1614,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1648,11 +1648,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "groups"}, // username not allowed + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1674,11 +1674,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, // token exchange not allowed (required to exclude groups scope) + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "username"}, // groups not allowed + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1700,11 +1700,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1728,11 +1728,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1762,11 +1762,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access"}, // validations require that when username/groups are excluded, then token exchange must also not be allowed - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access"}, // validations require that when username/groups are excluded, then token exchange must also not be allowed + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1796,11 +1796,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - return testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + return testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) }, testUser: func(t *testing.T) (string, string) { // return the username and password of the existing user that we want to use for this test @@ -1823,11 +1823,11 @@ func TestSupervisorLogin_Browser(t *testing.T) { return idp.Name }, createOIDCClient: func(t *testing.T, callbackURL string) (string, string) { - clientID, _ := testlib.CreateOIDCClient(t, configv1alpha1.OIDCClientSpec{ - AllowedRedirectURIs: []configv1alpha1.RedirectURI{configv1alpha1.RedirectURI(callbackURL)}, - AllowedGrantTypes: []configv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, - AllowedScopes: []configv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, - }, configv1alpha1.OIDCClientPhaseReady) + clientID, _ := testlib.CreateOIDCClient(t, supervisorconfigv1alpha1.OIDCClientSpec{ + AllowedRedirectURIs: []supervisorconfigv1alpha1.RedirectURI{supervisorconfigv1alpha1.RedirectURI(callbackURL)}, + AllowedGrantTypes: []supervisorconfigv1alpha1.GrantType{"authorization_code", "urn:ietf:params:oauth:grant-type:token-exchange", "refresh_token"}, + AllowedScopes: []supervisorconfigv1alpha1.Scope{"openid", "offline_access", "pinniped:request-audience", "username", "groups"}, + }, supervisorconfigv1alpha1.OIDCClientPhaseReady) return clientID, "wrong-client-secret" }, testUser: func(t *testing.T) (string, string) { @@ -1852,9 +1852,9 @@ func TestSupervisorLogin_Browser(t *testing.T) { } return testlib.CreateTestOIDCIdentityProvider(t, spec, idpv1alpha1.PhaseReady).Name }, - federationDomainIDPs: func(t *testing.T, idpName string) ([]configv1alpha1.FederationDomainIdentityProvider, string) { + federationDomainIDPs: func(t *testing.T, idpName string) ([]supervisorconfigv1alpha1.FederationDomainIdentityProvider, string) { displayName := "my oidc idp" - return []configv1alpha1.FederationDomainIdentityProvider{ + return []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: displayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -1862,8 +1862,8 @@ func TestSupervisorLogin_Browser(t *testing.T) { Kind: "OIDCIdentityProvider", Name: idpName, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ { Type: "username/v1", Expression: fmt.Sprintf(`username == "%s" ? "username-prefix:" + username : username`, @@ -1913,9 +1913,9 @@ func TestSupervisorLogin_Browser(t *testing.T) { idp, _ := createLDAPIdentityProvider(t, nil) return idp.Name }, - federationDomainIDPs: func(t *testing.T, idpName string) ([]configv1alpha1.FederationDomainIdentityProvider, string) { + federationDomainIDPs: func(t *testing.T, idpName string) ([]supervisorconfigv1alpha1.FederationDomainIdentityProvider, string) { displayName := "my ldap idp" - return []configv1alpha1.FederationDomainIdentityProvider{ + return []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: displayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -1923,8 +1923,8 @@ func TestSupervisorLogin_Browser(t *testing.T) { Kind: "LDAPIdentityProvider", Name: idpName, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ { Type: "username/v1", Expression: fmt.Sprintf(`username == "%s" ? "username-prefix:" + username : username`, @@ -1980,9 +1980,9 @@ func TestSupervisorLogin_Browser(t *testing.T) { idp, _ := createLDAPIdentityProvider(t, nil) return idp.Name }, - federationDomainIDPs: func(t *testing.T, idpName string) ([]configv1alpha1.FederationDomainIdentityProvider, string) { + federationDomainIDPs: func(t *testing.T, idpName string) ([]supervisorconfigv1alpha1.FederationDomainIdentityProvider, string) { displayName := "my ldap idp" - return []configv1alpha1.FederationDomainIdentityProvider{ + return []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: displayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -1990,8 +1990,8 @@ func TestSupervisorLogin_Browser(t *testing.T) { Kind: "LDAPIdentityProvider", Name: idpName, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ { Type: "username/v1", Expression: fmt.Sprintf(`username == "%s" ? "username-prefix:" + username : username`, @@ -2044,9 +2044,9 @@ func TestSupervisorLogin_Browser(t *testing.T) { idp, _ := createActiveDirectoryIdentityProvider(t, nil) return idp.Name }, - federationDomainIDPs: func(t *testing.T, idpName string) ([]configv1alpha1.FederationDomainIdentityProvider, string) { + federationDomainIDPs: func(t *testing.T, idpName string) ([]supervisorconfigv1alpha1.FederationDomainIdentityProvider, string) { displayName := "my ad idp" - return []configv1alpha1.FederationDomainIdentityProvider{ + return []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: displayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -2054,8 +2054,8 @@ func TestSupervisorLogin_Browser(t *testing.T) { Kind: "ActiveDirectoryIdentityProvider", Name: idpName, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ { Type: "username/v1", Expression: fmt.Sprintf(`username == "%s" ? "username-prefix:" + username : username`, @@ -2113,9 +2113,9 @@ func TestSupervisorLogin_Browser(t *testing.T) { idp, _ := createActiveDirectoryIdentityProvider(t, nil) return idp.Name }, - federationDomainIDPs: func(t *testing.T, idpName string) ([]configv1alpha1.FederationDomainIdentityProvider, string) { + federationDomainIDPs: func(t *testing.T, idpName string) ([]supervisorconfigv1alpha1.FederationDomainIdentityProvider, string) { displayName := "my ad idp" - return []configv1alpha1.FederationDomainIdentityProvider{ + return []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: displayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -2123,8 +2123,8 @@ func TestSupervisorLogin_Browser(t *testing.T) { Kind: "ActiveDirectoryIdentityProvider", Name: idpName, }, - Transforms: configv1alpha1.FederationDomainTransforms{ - Expressions: []configv1alpha1.FederationDomainTransformsExpression{ + Transforms: supervisorconfigv1alpha1.FederationDomainTransforms{ + Expressions: []supervisorconfigv1alpha1.FederationDomainTransformsExpression{ { Type: "username/v1", Expression: fmt.Sprintf(`username == "%s" ? "username-prefix:" + username : username`, @@ -2206,9 +2206,9 @@ func TestSupervisorLogin_Browser(t *testing.T) { } } -func wantGroupsInAdditionalClaimsIfGroupsExist(additionalClaims map[string]interface{}, wantGroupsAdditionalClaimName string, wantGroups []string) map[string]interface{} { +func wantGroupsInAdditionalClaimsIfGroupsExist(additionalClaims map[string]any, wantGroupsAdditionalClaimName string, wantGroups []string) map[string]any { if len(wantGroups) > 0 { - var wantGroupsAnyType []interface{} + var wantGroupsAnyType []any for _, group := range wantGroups { wantGroupsAnyType = append(wantGroupsAnyType, group) } @@ -2338,7 +2338,7 @@ func requireEventuallySuccessfulActiveDirectoryIdentityProviderConditions(t *tes func testSupervisorLogin( t *testing.T, createIDP func(t *testing.T) string, - federationDomainIDPs func(t *testing.T, idpName string) ([]configv1alpha1.FederationDomainIdentityProvider, string), + federationDomainIDPs func(t *testing.T, idpName string) ([]supervisorconfigv1alpha1.FederationDomainIdentityProvider, string), requestAuthorization func(t *testing.T, downstreamIssuer string, downstreamAuthorizeURL string, downstreamCallbackURL string, username string, password string, httpClient *http.Client), editRefreshSessionDataWithoutBreaking func(t *testing.T, pinnipedSession *psession.PinnipedSession, idpName string, username string) []string, breakRefreshSessionData func(t *testing.T, pinnipedSession *psession.PinnipedSession, idpName string, username string), @@ -2351,7 +2351,7 @@ func testSupervisorLogin( wantDownstreamIDTokenSubjectToMatch string, wantDownstreamIDTokenUsernameToMatch func(username string) string, wantDownstreamIDTokenGroups []string, - wantDownstreamIDTokenAdditionalClaims map[string]interface{}, + wantDownstreamIDTokenAdditionalClaims map[string]any, wantDownstreamIDTokenLifetime *time.Duration, wantAuthorizationErrorType string, wantAuthorizationErrorDescription string, @@ -2420,7 +2420,7 @@ func testSupervisorLogin( idpName := createIDP(t) // Determine if and how we should set spec.identityProviders for the FederationDomain. - var fdIDPSpec []configv1alpha1.FederationDomainIdentityProvider + var fdIDPSpec []supervisorconfigv1alpha1.FederationDomainIdentityProvider useIDPDisplayName := "" if federationDomainIDPs != nil { fdIDPSpec, useIDPDisplayName = federationDomainIDPs(t, idpName) @@ -2428,14 +2428,14 @@ func testSupervisorLogin( // Create the downstream FederationDomain and expect it to go into the appropriate status condition. downstream := testlib.CreateTestFederationDomain(ctx, t, - configv1alpha1.FederationDomainSpec{ + supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: issuerURL.String(), - TLS: &configv1alpha1.FederationDomainTLSSpec{SecretName: certSecret.Name}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: certSecret.Name}, IdentityProviders: fdIDPSpec, }, // The IDP CR already exists, so even for legacy FederationDomains which do not explicitly list // the IDPs in the spec, the FederationDomain should be ready. - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, ) // Ensure that the JWKS data is created and ready for the new FederationDomain by waiting for @@ -2739,9 +2739,9 @@ func verifyTokenResponse( expectedIDTokenClaims []string, wantDownstreamIDTokenSubjectToMatch, wantDownstreamIDTokenUsernameToMatch string, wantDownstreamIDTokenGroups []string, - wantDownstreamIDTokenAdditionalClaims map[string]interface{}, + wantDownstreamIDTokenAdditionalClaims map[string]any, wantDownstreamIDTokenLifetime time.Duration, -) map[string]interface{} { +) map[string]any { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() @@ -2762,7 +2762,7 @@ func verifyTokenResponse( testutil.RequireTimeInDelta(t, time.Now().UTC().Add(wantDownstreamIDTokenLifetime), idToken.Expiry, time.Second*30) // Check the full list of claim names of the ID token. - idTokenClaims := map[string]interface{}{} + idTokenClaims := map[string]any{} err = idToken.Claims(&idTokenClaims) require.NoError(t, err) idTokenClaimNames := []string{} @@ -2819,7 +2819,7 @@ func verifyTokenResponse( return idTokenClaims } -func getFloat64Claim(t *testing.T, claims map[string]interface{}, claim string) float64 { +func getFloat64Claim(t *testing.T, claims map[string]any, claim string) float64 { t.Helper() v, ok := claims[claim] @@ -3104,7 +3104,7 @@ func doTokenExchange( httpClient *http.Client, provider *coreosoidc.Provider, wantTokenExchangeResponse func(t *testing.T, status int, body string), - previousIDTokenClaims map[string]interface{}, + previousIDTokenClaims map[string]any, wantIDTokenLifetime time.Duration, ) { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) @@ -3154,7 +3154,7 @@ func doTokenExchange( exchangedToken, err := clusterVerifier.Verify(ctx, respBody.AccessToken) require.NoError(t, err) - var claims map[string]interface{} + var claims map[string]any require.NoError(t, exchangedToken.Claims(&claims)) indentedClaims, err := json.MarshalIndent(claims, " ", " ") require.NoError(t, err) diff --git a/test/integration/supervisor_oidcclientsecret_test.go b/test/integration/supervisor_oidcclientsecret_test.go index 85ce75762..84faf8618 100644 --- a/test/integration/supervisor_oidcclientsecret_test.go +++ b/test/integration/supervisor_oidcclientsecret_test.go @@ -104,7 +104,7 @@ func TestKubectlOIDCClientSecretRequest_Parallel(t *testing.T) { return []string{"create", "-f", filePath, "-o", "yaml"} }, assertOnStdOut: func(t *testing.T, oidcClientName string, stdOutString string) { - var yamlObj map[string]interface{} + var yamlObj map[string]any err := yaml.Unmarshal([]byte(stdOutString), &yamlObj) require.NoError(t, err) @@ -112,7 +112,7 @@ func TestKubectlOIDCClientSecretRequest_Parallel(t *testing.T) { require.Equal(t, yamlObj["apiVersion"], fmt.Sprintf("clientsecret.supervisor.%s/v1alpha1", env.APIGroupSuffix)) require.Equal(t, yamlObj["kind"], "OIDCClientSecretRequest") - metadataMap, ok := yamlObj["metadata"].(map[string]interface{}) + metadataMap, ok := yamlObj["metadata"].(map[string]any) require.True(t, ok, "metadata should be a map") require.Len(t, metadataMap, 3, "metadata should contain only 3 keys (creationTimestamp, name, namespace): %v", metadataMap) require.Equal(t, metadataMap["name"], oidcClientName) @@ -124,13 +124,13 @@ func TestKubectlOIDCClientSecretRequest_Parallel(t *testing.T) { require.NoError(t, err) testutil.RequireTimeInDelta(t, parsedTime, time.Now(), 1*time.Minute) - specMap, ok := yamlObj["spec"].(map[string]interface{}) + specMap, ok := yamlObj["spec"].(map[string]any) require.True(t, ok, "spec should be a map") require.Len(t, specMap, 2, "spec should contain only 2 keys (generateNewSecret, revokeOldSecrets): %v", specMap) require.Equal(t, specMap["generateNewSecret"], true) require.Equal(t, specMap["revokeOldSecrets"], false) - statusMap, ok := yamlObj["status"].(map[string]interface{}) + statusMap, ok := yamlObj["status"].(map[string]any) require.True(t, ok, "status should be a map") require.Len(t, specMap, 2, "status should contain only 2 keys (generatedSecret, totalClientSecrets): %v", statusMap) require.Regexp(t, "^[0-9a-z]{64}$", statusMap["generatedSecret"], "generated secret must be precisely 40 hex encoded characters") diff --git a/test/integration/supervisor_secrets_test.go b/test/integration/supervisor_secrets_test.go index 4c4d0376a..65c782f13 100644 --- a/test/integration/supervisor_secrets_test.go +++ b/test/integration/supervisor_secrets_test.go @@ -15,7 +15,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" "go.pinniped.dev/test/testlib" ) @@ -30,48 +30,48 @@ func TestSupervisorSecrets_Parallel(t *testing.T) { // Create our FederationDomain under test. federationDomain := testlib.CreateTestFederationDomain(ctx, t, - configv1alpha1.FederationDomainSpec{ + supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: fmt.Sprintf("http://test-issuer-%s.pinniped.dev", testlib.RandHex(t, 8)), }, - configv1alpha1.FederationDomainPhaseError, // in phase error until there is an IDP created, but this test does not care + supervisorconfigv1alpha1.FederationDomainPhaseError, // in phase error until there is an IDP created, but this test does not care ) tests := []struct { name string - secretName func(federationDomain *configv1alpha1.FederationDomain) string + secretName func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string ensureValid func(t *testing.T, secret *corev1.Secret) }{ { name: "csrf cookie signing key", - secretName: func(federationDomain *configv1alpha1.FederationDomain) string { + secretName: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string { return env.SupervisorAppName + "-key" }, ensureValid: ensureValidSymmetricSecretOfTypeFunc("secrets.pinniped.dev/supervisor-csrf-signing-key"), }, { name: "jwks", - secretName: func(federationDomain *configv1alpha1.FederationDomain) string { + secretName: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string { return federationDomain.Status.Secrets.JWKS.Name }, ensureValid: ensureValidJWKS, }, { name: "hmac signing secret", - secretName: func(federationDomain *configv1alpha1.FederationDomain) string { + secretName: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string { return federationDomain.Status.Secrets.TokenSigningKey.Name }, ensureValid: ensureValidSymmetricSecretOfTypeFunc("secrets.pinniped.dev/federation-domain-token-signing-key"), }, { name: "state signature secret", - secretName: func(federationDomain *configv1alpha1.FederationDomain) string { + secretName: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string { return federationDomain.Status.Secrets.StateSigningKey.Name }, ensureValid: ensureValidSymmetricSecretOfTypeFunc("secrets.pinniped.dev/federation-domain-state-signing-key"), }, { name: "state encryption secret", - secretName: func(federationDomain *configv1alpha1.FederationDomain) string { + secretName: func(federationDomain *supervisorconfigv1alpha1.FederationDomain) string { return federationDomain.Status.Secrets.StateEncryptionKey.Name }, ensureValid: ensureValidSymmetricSecretOfTypeFunc("secrets.pinniped.dev/federation-domain-state-encryption-key"), @@ -80,7 +80,7 @@ func TestSupervisorSecrets_Parallel(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { // Ensure a secret is created with the FederationDomain's JWKS. - var updatedFederationDomain *configv1alpha1.FederationDomain + var updatedFederationDomain *supervisorconfigv1alpha1.FederationDomain testlib.RequireEventually(t, func(requireEventually *require.Assertions) { resp, err := supervisorClient. ConfigV1alpha1(). diff --git a/test/integration/supervisor_upstream_test.go b/test/integration/supervisor_upstream_test.go index fdd21269d..7cb21ce84 100644 --- a/test/integration/supervisor_upstream_test.go +++ b/test/integration/supervisor_upstream_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package integration @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/test/testlib" ) @@ -19,13 +19,13 @@ func TestSupervisorUpstreamOIDCDiscovery(t *testing.T) { t.Run("invalid missing secret and bad issuer", func(t *testing.T) { t.Parallel() - spec := v1alpha1.OIDCIdentityProviderSpec{ + spec := idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: "https://127.0.0.1:444444/invalid-url-that-is-really-really-long-nanananananananannanananan-batman-nanananananananananananananana-batman-lalalalalalalalalal-batman-weeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", - Client: v1alpha1.OIDCClient{ + Client: idpv1alpha1.OIDCClient{ SecretName: "does-not-exist", }, } - upstream := testlib.CreateTestOIDCIdentityProvider(t, spec, v1alpha1.PhaseError) + upstream := testlib.CreateTestOIDCIdentityProvider(t, spec, idpv1alpha1.PhaseError) expectUpstreamConditions(t, upstream, []metav1.Condition{ { Type: "ClientCredentialsValid", @@ -51,19 +51,19 @@ Get "https://127.0.0.1:444444/invalid-url-that-is-really-really-long-nananananan t.Run("invalid issuer with trailing slash", func(t *testing.T) { t.Parallel() - spec := v1alpha1.OIDCIdentityProviderSpec{ + spec := idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: env.SupervisorUpstreamOIDC.Issuer + "/", - TLS: &v1alpha1.TLSSpec{ + TLS: &idpv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte(env.SupervisorUpstreamOIDC.CABundle)), }, - AuthorizationConfig: v1alpha1.OIDCAuthorizationConfig{ + AuthorizationConfig: idpv1alpha1.OIDCAuthorizationConfig{ AdditionalScopes: []string{"email", "profile"}, }, - Client: v1alpha1.OIDCClient{ + Client: idpv1alpha1.OIDCClient{ SecretName: testlib.CreateClientCredsSecret(t, "test-client-id", "test-client-secret").Name, }, } - upstream := testlib.CreateTestOIDCIdentityProvider(t, spec, v1alpha1.PhaseError) + upstream := testlib.CreateTestOIDCIdentityProvider(t, spec, idpv1alpha1.PhaseError) expectUpstreamConditions(t, upstream, []metav1.Condition{ { Type: "ClientCredentialsValid", @@ -89,19 +89,19 @@ oidc: issuer did not match the issuer returned by provider, expected "` + env.Su t.Run("valid", func(t *testing.T) { t.Parallel() - spec := v1alpha1.OIDCIdentityProviderSpec{ + spec := idpv1alpha1.OIDCIdentityProviderSpec{ Issuer: env.SupervisorUpstreamOIDC.Issuer, - TLS: &v1alpha1.TLSSpec{ + TLS: &idpv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte(env.SupervisorUpstreamOIDC.CABundle)), }, - AuthorizationConfig: v1alpha1.OIDCAuthorizationConfig{ + AuthorizationConfig: idpv1alpha1.OIDCAuthorizationConfig{ AdditionalScopes: []string{"email", "profile"}, }, - Client: v1alpha1.OIDCClient{ + Client: idpv1alpha1.OIDCClient{ SecretName: testlib.CreateClientCredsSecret(t, "test-client-id", "test-client-secret").Name, }, } - upstream := testlib.CreateTestOIDCIdentityProvider(t, spec, v1alpha1.PhaseReady) + upstream := testlib.CreateTestOIDCIdentityProvider(t, spec, idpv1alpha1.PhaseReady) expectUpstreamConditions(t, upstream, []metav1.Condition{ { Type: "ClientCredentialsValid", @@ -125,7 +125,7 @@ oidc: issuer did not match the issuer returned by provider, expected "` + env.Su }) } -func expectUpstreamConditions(t *testing.T, upstream *v1alpha1.OIDCIdentityProvider, expected []metav1.Condition) { +func expectUpstreamConditions(t *testing.T, upstream *idpv1alpha1.OIDCIdentityProvider, expected []metav1.Condition) { t.Helper() normalized := make([]metav1.Condition, 0, len(upstream.Status.Conditions)) for _, c := range upstream.Status.Conditions { diff --git a/test/integration/supervisor_warnings_test.go b/test/integration/supervisor_warnings_test.go index 246bad365..574a34964 100644 --- a/test/integration/supervisor_warnings_test.go +++ b/test/integration/supervisor_warnings_test.go @@ -25,7 +25,7 @@ import ( rbacv1 "k8s.io/api/rbac/v1" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/federationdomain/oidc" @@ -83,11 +83,11 @@ func TestSupervisorWarnings_Browser(t *testing.T) { // Create the downstream FederationDomain and expect it to go into the success status condition. downstream := testlib.CreateTestFederationDomain(ctx, t, - configv1alpha1.FederationDomainSpec{ + supervisorconfigv1alpha1.FederationDomainSpec{ Issuer: issuerURL.String(), - TLS: &configv1alpha1.FederationDomainTLSSpec{SecretName: certSecret.Name}, + TLS: &supervisorconfigv1alpha1.FederationDomainTLSSpec{SecretName: certSecret.Name}, }, - configv1alpha1.FederationDomainPhaseError, // in phase error until there is an IDP created + supervisorconfigv1alpha1.FederationDomainPhaseError, // in phase error until there is an IDP created ) // Create a JWTAuthenticator that will validate the tokens from the downstream issuer. @@ -110,7 +110,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { expectedUsername := env.SupervisorUpstreamLDAP.TestUserMailAttributeValue createdProvider := setupClusterForEndToEndLDAPTest(t, expectedUsername, env) - testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -258,7 +258,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { sAMAccountName := expectedUsername + "@" + env.SupervisorUpstreamActiveDirectory.Domain createdProvider := setupClusterForEndToEndActiveDirectoryTest(t, sAMAccountName, env) - testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. @@ -420,7 +420,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { SecretName: testlib.CreateClientCredsSecret(t, env.SupervisorUpstreamOIDC.ClientID, env.SupervisorUpstreamOIDC.ClientSecret).Name, }, }, idpv1alpha1.PhaseReady) - testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, configv1alpha1.FederationDomainPhaseReady) + testlib.WaitForFederationDomainStatusPhase(ctx, t, downstream.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) testlib.WaitForJWTAuthenticatorStatusPhase(ctx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. diff --git a/test/testlib/assertions.go b/test/testlib/assertions.go index 21acf56b7..f6bae9bff 100644 --- a/test/testlib/assertions.go +++ b/test/testlib/assertions.go @@ -25,7 +25,7 @@ type ( // assertionFailure is a single error observed during an iteration of the RequireEventually() loop. assertionFailure struct { format string - args []interface{} + args []any } ) @@ -33,7 +33,7 @@ type ( var _ require.TestingT = (*loopTestingT)(nil) // Errorf is called by the assert.Assertions methods to record an error. -func (e *loopTestingT) Errorf(format string, args ...interface{}) { +func (e *loopTestingT) Errorf(format string, args ...any) { *e = append(*e, assertionFailure{format, args}) } @@ -62,7 +62,7 @@ func RequireEventuallyf( waitFor time.Duration, tick time.Duration, msg string, - args ...interface{}, + args ...any, ) { t.Helper() RequireEventually(t, f, waitFor, tick, fmt.Sprintf(msg, args...)) @@ -75,7 +75,7 @@ func RequireEventually( f func(requireEventually *require.Assertions), waitFor time.Duration, tick time.Duration, - msgAndArgs ...interface{}, + msgAndArgs ...any, ) { t.Helper() @@ -129,7 +129,7 @@ func RequireEventuallyWithoutError( f func() (bool, error), waitFor time.Duration, tick time.Duration, - msgAndArgs ...interface{}, + msgAndArgs ...any, ) { t.Helper() // This previously used wait.PollImmediate (now deprecated), which did not take a ctx arg in the func. @@ -146,7 +146,7 @@ func RequireNeverWithoutError( f func() (bool, error), waitFor time.Duration, tick time.Duration, - msgAndArgs ...interface{}, + msgAndArgs ...any, ) { t.Helper() // This previously used wait.PollImmediate (now deprecated), which did not take a ctx arg in the func. diff --git a/test/testlib/browsertest/browsertest.go b/test/testlib/browsertest/browsertest.go index b9ddfa2e7..5c2a93a95 100644 --- a/test/testlib/browsertest/browsertest.go +++ b/test/testlib/browsertest/browsertest.go @@ -104,7 +104,7 @@ func OpenBrowser(t *testing.T) *Browser { b := &Browser{chromeCtx: chromeCtx} // Subscribe to console events and exceptions to make them available later. - chromedp.ListenTarget(chromeCtx, func(ev interface{}) { + chromedp.ListenTarget(chromeCtx, func(ev any) { switch ev := ev.(type) { case *chromedpruntime.EventConsoleAPICalled: args := make([]string, len(ev.Args)) diff --git a/test/testlib/client.go b/test/testlib/client.go index 35f4c6d72..cf5cac9a9 100644 --- a/test/testlib/client.go +++ b/test/testlib/client.go @@ -30,7 +30,7 @@ import ( authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" clientsecretv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/clientsecret/v1alpha1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" + supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" @@ -357,9 +357,9 @@ func WaitForJWTAuthenticatorStatusConditions(ctx context.Context, t *testing.T, func CreateTestFederationDomain( ctx context.Context, t *testing.T, - spec configv1alpha1.FederationDomainSpec, - expectStatus configv1alpha1.FederationDomainPhase, -) *configv1alpha1.FederationDomain { + spec supervisorconfigv1alpha1.FederationDomainSpec, + expectStatus supervisorconfigv1alpha1.FederationDomainPhase, +) *supervisorconfigv1alpha1.FederationDomain { t.Helper() testEnv := IntegrationEnv(t) @@ -367,7 +367,7 @@ func CreateTestFederationDomain( defer cancel() federationDomainsClient := NewSupervisorClientset(t).ConfigV1alpha1().FederationDomains(testEnv.SupervisorNamespace) - federationDomain, err := federationDomainsClient.Create(createContext, &configv1alpha1.FederationDomain{ + federationDomain, err := federationDomainsClient.Create(createContext, &supervisorconfigv1alpha1.FederationDomain{ ObjectMeta: testObjectMeta(t, "oidc-provider"), Spec: spec, }, metav1.CreateOptions{}) @@ -393,7 +393,7 @@ func CreateTestFederationDomain( return federationDomain } -func WaitForFederationDomainStatusPhase(ctx context.Context, t *testing.T, federationDomainName string, expectPhase configv1alpha1.FederationDomainPhase) { +func WaitForFederationDomainStatusPhase(ctx context.Context, t *testing.T, federationDomainName string, expectPhase supervisorconfigv1alpha1.FederationDomainPhase) { t.Helper() testEnv := IntegrationEnv(t) federationDomainsClient := NewSupervisorClientset(t).ConfigV1alpha1().FederationDomains(testEnv.SupervisorNamespace) @@ -404,7 +404,7 @@ func WaitForFederationDomainStatusPhase(ctx context.Context, t *testing.T, feder requireEventually.Equalf(expectPhase, fd.Status.Phase, "actual status conditions were: %#v", fd.Status.Conditions) // If the FederationDomain was successfully created, ensure all secrets are present before continuing - if expectPhase == configv1alpha1.FederationDomainPhaseReady { + if expectPhase == supervisorconfigv1alpha1.FederationDomainPhaseReady { requireEventually.NotEmpty(fd.Status.Secrets.JWKS.Name, "expected status.secrets.jwks.name not to be empty") requireEventually.NotEmpty(fd.Status.Secrets.TokenSigningKey.Name, "expected status.secrets.tokenSigningKey.name not to be empty") requireEventually.NotEmpty(fd.Status.Secrets.StateSigningKey.Name, "expected status.secrets.stateSigningKey.name not to be empty") @@ -510,7 +510,7 @@ func CreateClientCredsSecret(t *testing.T, clientID string, clientSecret string) ) } -func CreateOIDCClient(t *testing.T, spec configv1alpha1.OIDCClientSpec, expectedPhase configv1alpha1.OIDCClientPhase) (string, string) { +func CreateOIDCClient(t *testing.T, spec supervisorconfigv1alpha1.OIDCClientSpec, expectedPhase supervisorconfigv1alpha1.OIDCClientPhase) (string, string) { t.Helper() env := IntegrationEnv(t) client := NewSupervisorClientset(t) @@ -520,7 +520,7 @@ func CreateOIDCClient(t *testing.T, spec configv1alpha1.OIDCClientSpec, expected oidcClientClient := client.ConfigV1alpha1().OIDCClients(env.SupervisorNamespace) // Create the OIDCClient using GenerateName to get a random name. - created, err := oidcClientClient.Create(ctx, &configv1alpha1.OIDCClient{ + created, err := oidcClientClient.Create(ctx, &supervisorconfigv1alpha1.OIDCClient{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "client.oauth.pinniped.dev-test-", // use the required name prefix Labels: map[string]string{"pinniped.dev/test": ""}, @@ -542,7 +542,7 @@ func CreateOIDCClient(t *testing.T, spec configv1alpha1.OIDCClientSpec, expected clientSecret := createOIDCClientSecret(t, created) // Wait for the OIDCClient to enter the expected phase (or time out). - var result *configv1alpha1.OIDCClient + var result *supervisorconfigv1alpha1.OIDCClient RequireEventuallyf(t, func(requireEventually *require.Assertions) { var err error result, err = oidcClientClient.Get(ctx, created.Name, metav1.GetOptions{}) @@ -553,7 +553,7 @@ func CreateOIDCClient(t *testing.T, spec configv1alpha1.OIDCClientSpec, expected return created.Name, clientSecret } -func createOIDCClientSecret(t *testing.T, forOIDCClient *configv1alpha1.OIDCClient) string { +func createOIDCClientSecret(t *testing.T, forOIDCClient *supervisorconfigv1alpha1.OIDCClient) string { t.Helper() env := IntegrationEnv(t) supervisorClient := NewSupervisorClientset(t) diff --git a/test/testlib/spew.go b/test/testlib/spew.go index d03b27fba..70e1e3294 100644 --- a/test/testlib/spew.go +++ b/test/testlib/spew.go @@ -1,11 +1,11 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testlib import "github.com/davecgh/go-spew/spew" -func Sdump(a ...interface{}) string { +func Sdump(a ...any) string { config := spew.ConfigState{ Indent: "\t", MaxDepth: 10, // prevent log explosion From 513f43f4651af5e0d7f814577fe82ea85bbc1ea5 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Sun, 12 May 2024 17:03:48 -0500 Subject: [PATCH 05/10] Enforce more imports - go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1 - go.pinniped.dev/generated/latest/client/concierge/clientset/versioned - go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme - go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned - go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme --- .golangci.yaml | 14 + cmd/pinniped/cmd/flag_types.go | 10 +- cmd/pinniped/cmd/flag_types_test.go | 16 +- cmd/pinniped/cmd/kubeconfig.go | 40 +- cmd/pinniped/cmd/kubeconfig_test.go | 122 +-- .../impersonatorconfig/impersonator_config.go | 114 +-- .../impersonator_config_test.go | 852 +++++++++--------- .../controller/issuerconfig/issuerconfig.go | 26 +- .../issuerconfig/issuerconfig_test.go | 104 +-- .../controller/kubecertagent/kubecertagent.go | 42 +- .../kubecertagent/kubecertagent_test.go | 208 ++--- .../active_directory_upstream_watcher.go | 8 +- .../federation_domain_watcher.go | 6 +- .../generator/federation_domain_secrets.go | 6 +- .../supervisorconfig/jwks_writer.go | 6 +- internal/kubeclient/kubeclient.go | 16 +- internal/kubeclient/scheme_test.go | 14 +- internal/supervisor/server/server.go | 4 +- internal/testutil/fakekubeapi/fakekubeapi.go | 8 +- .../concierge_credentialissuer_test.go | 20 +- .../concierge_impersonation_proxy_test.go | 118 +-- .../concierge_kubecertagent_test.go | 10 +- test/testlib/client.go | 6 +- 23 files changed, 892 insertions(+), 878 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index e067158c2..3219728ad 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -121,6 +121,20 @@ linters-settings: alias: clientsecretv1alpha1 - pkg: go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1 alias: supervisorconfigv1alpha1 + - pkg: go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1 + alias: conciergeconfigv1alpha1 + - pkg: go.pinniped.dev/generated/latest/client/concierge/clientset/versioned + alias: conciergeclientset + - pkg: go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme + alias: conciergeclientsetscheme +# - pkg: go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake +# alias: conciergefake + - pkg: go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned + alias: supervisorclientset + - pkg: go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme + alias: supervisorclientsetscheme +# - pkg: go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake +# alias: supervisorfake - pkg: go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1 alias: idpv1alpha1 # Pinniped internal diff --git a/cmd/pinniped/cmd/flag_types.go b/cmd/pinniped/cmd/flag_types.go index 18dacb632..61c731d58 100644 --- a/cmd/pinniped/cmd/flag_types.go +++ b/cmd/pinniped/cmd/flag_types.go @@ -1,4 +1,4 @@ -// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -13,7 +13,7 @@ import ( "github.com/spf13/pflag" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" ) // conciergeModeFlag represents the method by which we should connect to the Concierge on a cluster during login. @@ -62,12 +62,12 @@ func (f *conciergeModeFlag) Type() string { } // MatchesFrontend returns true iff the flag matches the type of the provided frontend. -func (f *conciergeModeFlag) MatchesFrontend(frontend *configv1alpha1.CredentialIssuerFrontend) bool { +func (f *conciergeModeFlag) MatchesFrontend(frontend *conciergeconfigv1alpha1.CredentialIssuerFrontend) bool { switch *f { case modeImpersonationProxy: - return frontend.Type == configv1alpha1.ImpersonationProxyFrontendType + return frontend.Type == conciergeconfigv1alpha1.ImpersonationProxyFrontendType case modeTokenCredentialRequestAPI: - return frontend.Type == configv1alpha1.TokenCredentialRequestAPIFrontendType + return frontend.Type == conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType case modeUnknown: fallthrough default: diff --git a/cmd/pinniped/cmd/flag_types_test.go b/cmd/pinniped/cmd/flag_types_test.go index 255ad2a8d..d962eb812 100644 --- a/cmd/pinniped/cmd/flag_types_test.go +++ b/cmd/pinniped/cmd/flag_types_test.go @@ -1,4 +1,4 @@ -// Copyright 2021-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/require" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" "go.pinniped.dev/internal/certauthority" ) @@ -24,14 +24,14 @@ func TestConciergeModeFlag(t *testing.T) { require.NoError(t, f.Set("")) require.Equal(t, modeUnknown, f) require.EqualError(t, f.Set("foo"), `invalid mode "foo", valid modes are TokenCredentialRequestAPI and ImpersonationProxy`) - require.True(t, f.MatchesFrontend(&configv1alpha1.CredentialIssuerFrontend{Type: configv1alpha1.TokenCredentialRequestAPIFrontendType})) - require.True(t, f.MatchesFrontend(&configv1alpha1.CredentialIssuerFrontend{Type: configv1alpha1.ImpersonationProxyFrontendType})) + require.True(t, f.MatchesFrontend(&conciergeconfigv1alpha1.CredentialIssuerFrontend{Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType})) + require.True(t, f.MatchesFrontend(&conciergeconfigv1alpha1.CredentialIssuerFrontend{Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType})) require.NoError(t, f.Set("TokenCredentialRequestAPI")) require.Equal(t, modeTokenCredentialRequestAPI, f) require.Equal(t, "TokenCredentialRequestAPI", f.String()) - require.True(t, f.MatchesFrontend(&configv1alpha1.CredentialIssuerFrontend{Type: configv1alpha1.TokenCredentialRequestAPIFrontendType})) - require.False(t, f.MatchesFrontend(&configv1alpha1.CredentialIssuerFrontend{Type: configv1alpha1.ImpersonationProxyFrontendType})) + require.True(t, f.MatchesFrontend(&conciergeconfigv1alpha1.CredentialIssuerFrontend{Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType})) + require.False(t, f.MatchesFrontend(&conciergeconfigv1alpha1.CredentialIssuerFrontend{Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType})) require.NoError(t, f.Set("tokencredentialrequestapi")) require.Equal(t, modeTokenCredentialRequestAPI, f) @@ -40,8 +40,8 @@ func TestConciergeModeFlag(t *testing.T) { require.NoError(t, f.Set("ImpersonationProxy")) require.Equal(t, modeImpersonationProxy, f) require.Equal(t, "ImpersonationProxy", f.String()) - require.False(t, f.MatchesFrontend(&configv1alpha1.CredentialIssuerFrontend{Type: configv1alpha1.TokenCredentialRequestAPIFrontendType})) - require.True(t, f.MatchesFrontend(&configv1alpha1.CredentialIssuerFrontend{Type: configv1alpha1.ImpersonationProxyFrontendType})) + require.False(t, f.MatchesFrontend(&conciergeconfigv1alpha1.CredentialIssuerFrontend{Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType})) + require.True(t, f.MatchesFrontend(&conciergeconfigv1alpha1.CredentialIssuerFrontend{Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType})) require.NoError(t, f.Set("impersonationproxy")) require.Equal(t, modeImpersonationProxy, f) diff --git a/cmd/pinniped/cmd/kubeconfig.go b/cmd/pinniped/cmd/kubeconfig.go index 85c04bbbc..f3651bc1d 100644 --- a/cmd/pinniped/cmd/kubeconfig.go +++ b/cmd/pinniped/cmd/kubeconfig.go @@ -26,7 +26,7 @@ import ( "k8s.io/utils/strings/slices" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" idpdiscoveryv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idpdiscovery/v1alpha1" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" @@ -380,7 +380,7 @@ func getCurrentContext(currentKubeConfig clientcmdapi.Config, flags getKubeconfi return &kubeconfigNames{ContextName: contextName, UserName: ctx.AuthInfo, ClusterName: ctx.Cluster}, nil } -func waitForCredentialIssuer(ctx context.Context, clientset conciergeclientset.Interface, flags getKubeconfigParams, deps kubeconfigDeps) (*configv1alpha1.CredentialIssuer, error) { +func waitForCredentialIssuer(ctx context.Context, clientset conciergeclientset.Interface, flags getKubeconfigParams, deps kubeconfigDeps) (*conciergeconfigv1alpha1.CredentialIssuer, error) { credentialIssuer, err := lookupCredentialIssuer(clientset, flags.concierge.credentialIssuer, deps.log) if err != nil { return nil, err @@ -416,7 +416,7 @@ func waitForCredentialIssuer(ctx context.Context, clientset conciergeclientset.I return credentialIssuer, nil } -func discoverConciergeParams(credentialIssuer *configv1alpha1.CredentialIssuer, flags *getKubeconfigParams, v1Cluster *clientcmdapi.Cluster, log plog.MinLogger) error { +func discoverConciergeParams(credentialIssuer *conciergeconfigv1alpha1.CredentialIssuer, flags *getKubeconfigParams, v1Cluster *clientcmdapi.Cluster, log plog.MinLogger) error { // Autodiscover the --concierge-mode. frontend, err := getConciergeFrontend(credentialIssuer, flags.concierge.mode) if err != nil { @@ -427,10 +427,10 @@ func discoverConciergeParams(credentialIssuer *configv1alpha1.CredentialIssuer, // Auto-set --concierge-mode if it wasn't explicitly set. if flags.concierge.mode == modeUnknown { switch frontend.Type { - case configv1alpha1.TokenCredentialRequestAPIFrontendType: + case conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType: log.Info("discovered Concierge operating in TokenCredentialRequest API mode") flags.concierge.mode = modeTokenCredentialRequestAPI - case configv1alpha1.ImpersonationProxyFrontendType: + case conciergeconfigv1alpha1.ImpersonationProxyFrontendType: log.Info("discovered Concierge operating in impersonation proxy mode") flags.concierge.mode = modeImpersonationProxy } @@ -439,9 +439,9 @@ func discoverConciergeParams(credentialIssuer *configv1alpha1.CredentialIssuer, // Auto-set --concierge-endpoint if it wasn't explicitly set. if flags.concierge.endpoint == "" { switch frontend.Type { - case configv1alpha1.TokenCredentialRequestAPIFrontendType: + case conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType: flags.concierge.endpoint = v1Cluster.Server - case configv1alpha1.ImpersonationProxyFrontendType: + case conciergeconfigv1alpha1.ImpersonationProxyFrontendType: flags.concierge.endpoint = frontend.ImpersonationProxyInfo.Endpoint } log.Info("discovered Concierge endpoint", "endpoint", flags.concierge.endpoint) @@ -450,9 +450,9 @@ func discoverConciergeParams(credentialIssuer *configv1alpha1.CredentialIssuer, // Auto-set --concierge-ca-bundle if it wasn't explicitly set.. if len(flags.concierge.caBundle) == 0 { switch frontend.Type { - case configv1alpha1.TokenCredentialRequestAPIFrontendType: + case conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType: flags.concierge.caBundle = v1Cluster.CertificateAuthorityData - case configv1alpha1.ImpersonationProxyFrontendType: + case conciergeconfigv1alpha1.ImpersonationProxyFrontendType: data, err := base64.StdEncoding.DecodeString(frontend.ImpersonationProxyInfo.CertificateAuthorityData) if err != nil { return fmt.Errorf("autodiscovered Concierge CA bundle is invalid: %w", err) @@ -464,7 +464,7 @@ func discoverConciergeParams(credentialIssuer *configv1alpha1.CredentialIssuer, return nil } -func logStrategies(credentialIssuer *configv1alpha1.CredentialIssuer, log plog.MinLogger) { +func logStrategies(credentialIssuer *conciergeconfigv1alpha1.CredentialIssuer, log plog.MinLogger) { for _, strategy := range credentialIssuer.Status.Strategies { log.Info("found CredentialIssuer strategy", "type", strategy.Type, @@ -520,19 +520,19 @@ func discoverAuthenticatorParams(authenticator metav1.Object, flags *getKubeconf return nil } -func getConciergeFrontend(credentialIssuer *configv1alpha1.CredentialIssuer, mode conciergeModeFlag) (*configv1alpha1.CredentialIssuerFrontend, error) { +func getConciergeFrontend(credentialIssuer *conciergeconfigv1alpha1.CredentialIssuer, mode conciergeModeFlag) (*conciergeconfigv1alpha1.CredentialIssuerFrontend, error) { for _, strategy := range credentialIssuer.Status.Strategies { // Skip unhealthy strategies. - if strategy.Status != configv1alpha1.SuccessStrategyStatus { + if strategy.Status != conciergeconfigv1alpha1.SuccessStrategyStatus { continue } // Backfill the .status.strategies[].frontend field from .status.kubeConfigInfo for backwards compatibility. - if strategy.Type == configv1alpha1.KubeClusterSigningCertificateStrategyType && strategy.Frontend == nil && credentialIssuer.Status.KubeConfigInfo != nil { + if strategy.Type == conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType && strategy.Frontend == nil && credentialIssuer.Status.KubeConfigInfo != nil { strategy = *strategy.DeepCopy() - strategy.Frontend = &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.TokenCredentialRequestAPIFrontendType, - TokenCredentialRequestAPIInfo: &configv1alpha1.TokenCredentialRequestAPIInfo{ + strategy.Frontend = &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, + TokenCredentialRequestAPIInfo: &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: credentialIssuer.Status.KubeConfigInfo.Server, CertificateAuthorityData: credentialIssuer.Status.KubeConfigInfo.CertificateAuthorityData, }, @@ -546,7 +546,7 @@ func getConciergeFrontend(credentialIssuer *configv1alpha1.CredentialIssuer, mod // Skip any unknown frontend types. switch strategy.Frontend.Type { - case configv1alpha1.TokenCredentialRequestAPIFrontendType, configv1alpha1.ImpersonationProxyFrontendType: + case conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, conciergeconfigv1alpha1.ImpersonationProxyFrontendType: default: continue } @@ -574,7 +574,7 @@ func newExecKubeconfig(cluster *clientcmdapi.Cluster, execConfig *clientcmdapi.E } } -func lookupCredentialIssuer(clientset conciergeclientset.Interface, name string, log plog.MinLogger) (*configv1alpha1.CredentialIssuer, error) { +func lookupCredentialIssuer(clientset conciergeclientset.Interface, name string, log plog.MinLogger) (*conciergeconfigv1alpha1.CredentialIssuer, error) { ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*20) defer cancelFunc() @@ -736,9 +736,9 @@ func countCACerts(pemData []byte) int { return len(pool.Subjects()) } -func hasPendingStrategy(credentialIssuer *configv1alpha1.CredentialIssuer) bool { +func hasPendingStrategy(credentialIssuer *conciergeconfigv1alpha1.CredentialIssuer) bool { for _, strategy := range credentialIssuer.Status.Strategies { - if strategy.Reason == configv1alpha1.PendingStrategyReason { + if strategy.Reason == conciergeconfigv1alpha1.PendingStrategyReason { return true } } diff --git a/cmd/pinniped/cmd/kubeconfig_test.go b/cmd/pinniped/cmd/kubeconfig_test.go index 7a791c44f..035060472 100644 --- a/cmd/pinniped/cmd/kubeconfig_test.go +++ b/cmd/pinniped/cmd/kubeconfig_test.go @@ -21,7 +21,7 @@ import ( "k8s.io/utils/ptr" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" fakeconciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" "go.pinniped.dev/internal/certauthority" @@ -44,16 +44,16 @@ func TestGetKubeconfig(t *testing.T) { require.NoError(t, os.WriteFile(testConciergeCABundlePath, testConciergeCA.Bundle(), 0600)) credentialIssuer := func() runtime.Object { - return &configv1alpha1.CredentialIssuer{ + return &conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}, - Status: configv1alpha1.CredentialIssuerStatus{ - Strategies: []configv1alpha1.CredentialIssuerStrategy{{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.SuccessStrategyStatus, - Reason: configv1alpha1.FetchedKeyStrategyReason, - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.TokenCredentialRequestAPIFrontendType, - TokenCredentialRequestAPIInfo: &configv1alpha1.TokenCredentialRequestAPIInfo{ + Status: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.FetchedKeyStrategyReason, + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, + TokenCredentialRequestAPIInfo: &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: "https://concierge-endpoint.example.com", CertificateAuthorityData: base64.StdEncoding.EncodeToString(testConciergeCA.Bundle()), }, @@ -271,7 +271,7 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, + &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, } }, wantError: true, @@ -290,7 +290,7 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, + &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -314,7 +314,7 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, + &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -338,7 +338,7 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, + &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -360,7 +360,7 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, + &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -391,7 +391,7 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, + &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, } }, conciergeReactions: []kubetesting.Reactor{ @@ -422,7 +422,7 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, + &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, } }, wantLogs: func(issuerCABundle string, issuerURL string) []string { @@ -444,7 +444,7 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, + &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}}, &authenticationv1alpha1.JWTAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-1"}}, &authenticationv1alpha1.JWTAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-2"}}, &authenticationv1alpha1.WebhookAuthenticator{ObjectMeta: metav1.ObjectMeta{Name: "test-authenticator-3"}}, @@ -474,12 +474,12 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ + &conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}, - Status: configv1alpha1.CredentialIssuerStatus{ - Strategies: []configv1alpha1.CredentialIssuerStrategy{{ + Status: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{{ Type: "SomeType", - Status: configv1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "SomeReason", Message: "Some message", }}, @@ -508,36 +508,36 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ + &conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}, - Status: configv1alpha1.CredentialIssuerStatus{ - Strategies: []configv1alpha1.CredentialIssuerStrategy{ + Status: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "SomeBrokenType", - Status: configv1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "SomeFailureReason", Message: "Some error message", LastUpdateTime: metav1.Now(), }, { Type: "SomeUnknownType", - Status: configv1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "SomeReason", Message: "Some error message", LastUpdateTime: metav1.Now(), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ Type: "SomeUnknownFrontendType", }, }, { Type: "SomeType", - Status: configv1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "SomeReason", Message: "Some message", LastUpdateTime: metav1.Now(), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.ImpersonationProxyFrontendType, - ImpersonationProxyInfo: &configv1alpha1.ImpersonationProxyInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType, + ImpersonationProxyInfo: &conciergeconfigv1alpha1.ImpersonationProxyInfo{ Endpoint: "https://impersonation-endpoint", CertificateAuthorityData: "invalid-base-64", }, @@ -597,17 +597,17 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ + &conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}, - Status: configv1alpha1.CredentialIssuerStatus{ - KubeConfigInfo: &configv1alpha1.CredentialIssuerKubeConfigInfo{ + Status: conciergeconfigv1alpha1.CredentialIssuerStatus{ + KubeConfigInfo: &conciergeconfigv1alpha1.CredentialIssuerKubeConfigInfo{ Server: "https://concierge-endpoint", CertificateAuthorityData: "ZmFrZS1jZXJ0aWZpY2F0ZS1hdXRob3JpdHktZGF0YS12YWx1ZQ==", }, - Strategies: []configv1alpha1.CredentialIssuerStrategy{{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.SuccessStrategyStatus, - Reason: configv1alpha1.FetchedKeyStrategyReason, + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.FetchedKeyStrategyReason, Message: "Successfully fetched key", LastUpdateTime: metav1.Now(), // Simulate a previous version of CredentialIssuer that's missing this Frontend field. @@ -1686,21 +1686,21 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ + &conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}, - Status: configv1alpha1.CredentialIssuerStatus{ - Strategies: []configv1alpha1.CredentialIssuerStrategy{ + Status: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ // This TokenCredentialRequestAPI strategy would normally be chosen, but // --concierge-mode=ImpersonationProxy should force it to be skipped. { Type: "SomeType", - Status: configv1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "SomeReason", Message: "Some message", LastUpdateTime: metav1.Now(), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.TokenCredentialRequestAPIFrontendType, - TokenCredentialRequestAPIInfo: &configv1alpha1.TokenCredentialRequestAPIInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, + TokenCredentialRequestAPIInfo: &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: "https://token-credential-request-api-endpoint.test", CertificateAuthorityData: "dGVzdC10Y3ItYXBpLWNh", }, @@ -1709,13 +1709,13 @@ func TestGetKubeconfig(t *testing.T) { // The endpoint and CA from this impersonation proxy strategy should be autodiscovered. { Type: "SomeOtherType", - Status: configv1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "SomeOtherReason", Message: "Some other message", LastUpdateTime: metav1.Now(), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.ImpersonationProxyFrontendType, - ImpersonationProxyInfo: &configv1alpha1.ImpersonationProxyInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType, + ImpersonationProxyInfo: &conciergeconfigv1alpha1.ImpersonationProxyInfo{ Endpoint: "https://impersonation-proxy-endpoint.test", CertificateAuthorityData: base64.StdEncoding.EncodeToString(testConciergeCA.Bundle()), }, @@ -1797,19 +1797,19 @@ func TestGetKubeconfig(t *testing.T) { }, conciergeObjects: func(issuerCABundle string, issuerURL string) []runtime.Object { return []runtime.Object{ - &configv1alpha1.CredentialIssuer{ + &conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: "test-credential-issuer"}, - Status: configv1alpha1.CredentialIssuerStatus{ - Strategies: []configv1alpha1.CredentialIssuerStrategy{ + Status: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "SomeType", - Status: configv1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "SomeReason", Message: "Some message", LastUpdateTime: metav1.Now(), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.ImpersonationProxyFrontendType, - ImpersonationProxyInfo: &configv1alpha1.ImpersonationProxyInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType, + ImpersonationProxyInfo: &conciergeconfigv1alpha1.ImpersonationProxyInfo{ Endpoint: "https://impersonation-proxy-endpoint.test", CertificateAuthorityData: "dGVzdC1jb25jaWVyZ2UtY2E=", }, @@ -1817,13 +1817,13 @@ func TestGetKubeconfig(t *testing.T) { }, { Type: "SomeOtherType", - Status: configv1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "SomeOtherReason", Message: "Some other message", LastUpdateTime: metav1.Now(), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.ImpersonationProxyFrontendType, - ImpersonationProxyInfo: &configv1alpha1.ImpersonationProxyInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType, + ImpersonationProxyInfo: &conciergeconfigv1alpha1.ImpersonationProxyInfo{ Endpoint: "https://some-other-impersonation-endpoint", CertificateAuthorityData: "dGVzdC1jb25jaWVyZ2UtY2E=", }, diff --git a/internal/controller/impersonatorconfig/impersonator_config.go b/internal/controller/impersonatorconfig/impersonator_config.go index 6edbfa82c..12e63768f 100644 --- a/internal/controller/impersonatorconfig/impersonator_config.go +++ b/internal/controller/impersonatorconfig/impersonator_config.go @@ -32,7 +32,7 @@ import ( "k8s.io/klog/v2" "k8s.io/utils/clock" - "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" conciergeconfiginformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions/config/v1alpha1" "go.pinniped.dev/internal/certauthority" @@ -193,9 +193,9 @@ func (c *impersonatorConfigController) Sync(syncCtx controllerlib.Context) error strategy, err := c.doSync(syncCtx, credIssuer) if err != nil { - strategy = &v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.ErrorStrategyStatus, + strategy = &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: strategyReasonForError(err), Message: err.Error(), LastUpdateTime: metav1.NewTime(c.clock.Now()), @@ -218,12 +218,12 @@ func (c *impersonatorConfigController) Sync(syncCtx controllerlib.Context) error // strategyReasonForError returns the proper v1alpha1.StrategyReason for a sync error. Some errors are occasionally // expected because there are multiple pods running, in these cases we should report a Pending reason and we'll // recover on a following sync. -func strategyReasonForError(err error) v1alpha1.StrategyReason { +func strategyReasonForError(err error) conciergeconfigv1alpha1.StrategyReason { switch { case apierrors.IsConflict(err), apierrors.IsAlreadyExists(err): - return v1alpha1.PendingStrategyReason + return conciergeconfigv1alpha1.PendingStrategyReason default: - return v1alpha1.ErrorDuringSetupStrategyReason + return conciergeconfigv1alpha1.ErrorDuringSetupStrategyReason } } @@ -243,7 +243,7 @@ type certNameInfo struct { clientEndpoint string } -func (c *impersonatorConfigController) doSync(syncCtx controllerlib.Context, credIssuer *v1alpha1.CredentialIssuer) (*v1alpha1.CredentialIssuerStrategy, error) { +func (c *impersonatorConfigController) doSync(syncCtx controllerlib.Context, credIssuer *conciergeconfigv1alpha1.CredentialIssuer) (*conciergeconfigv1alpha1.CredentialIssuerStrategy, error) { ctx := syncCtx.Context impersonationSpec, err := c.loadImpersonationProxyConfiguration(credIssuer) @@ -354,7 +354,7 @@ func (c *impersonatorConfigController) ensureCAAndTLSSecrets( func (c *impersonatorConfigController) evaluateExternallyProvidedTLSSecret( ctx context.Context, - tlsSpec *v1alpha1.ImpersonationProxyTLSSpec, + tlsSpec *conciergeconfigv1alpha1.ImpersonationProxyTLSSpec, ) ([]byte, error) { if tlsSpec.SecretName == "" { return nil, fmt.Errorf("must provide impersonationSpec.TLS.secretName if impersonationSpec.TLS is provided") @@ -396,7 +396,7 @@ func (c *impersonatorConfigController) evaluateExternallyProvidedTLSSecret( return caBundle, nil } -func (c *impersonatorConfigController) loadImpersonationProxyConfiguration(credIssuer *v1alpha1.CredentialIssuer) (*v1alpha1.ImpersonationProxySpec, error) { +func (c *impersonatorConfigController) loadImpersonationProxyConfiguration(credIssuer *conciergeconfigv1alpha1.CredentialIssuer) (*conciergeconfigv1alpha1.ImpersonationProxySpec, error) { // Make a copy of the spec since we got this object from informer cache. spec := credIssuer.Spec.DeepCopy().ImpersonationProxy if spec == nil { @@ -405,7 +405,7 @@ func (c *impersonatorConfigController) loadImpersonationProxyConfiguration(credI // Default service type to LoadBalancer (this is normally already done via CRD defaulting). if spec.Service.Type == "" { - spec.Service.Type = v1alpha1.ImpersonationProxyServiceTypeLoadBalancer + spec.Service.Type = conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer } if err := validateCredentialIssuerSpec(spec); err != nil { @@ -415,28 +415,28 @@ func (c *impersonatorConfigController) loadImpersonationProxyConfiguration(credI return spec, nil } -func (c *impersonatorConfigController) shouldHaveImpersonator(config *v1alpha1.ImpersonationProxySpec) bool { - return c.enabledByAutoMode(config) || config.Mode == v1alpha1.ImpersonationProxyModeEnabled +func (c *impersonatorConfigController) shouldHaveImpersonator(config *conciergeconfigv1alpha1.ImpersonationProxySpec) bool { + return c.enabledByAutoMode(config) || config.Mode == conciergeconfigv1alpha1.ImpersonationProxyModeEnabled } -func (c *impersonatorConfigController) enabledByAutoMode(config *v1alpha1.ImpersonationProxySpec) bool { - return config.Mode == v1alpha1.ImpersonationProxyModeAuto && !*c.hasControlPlaneNodes +func (c *impersonatorConfigController) enabledByAutoMode(config *conciergeconfigv1alpha1.ImpersonationProxySpec) bool { + return config.Mode == conciergeconfigv1alpha1.ImpersonationProxyModeAuto && !*c.hasControlPlaneNodes } -func (c *impersonatorConfigController) disabledByAutoMode(config *v1alpha1.ImpersonationProxySpec) bool { - return config.Mode == v1alpha1.ImpersonationProxyModeAuto && *c.hasControlPlaneNodes +func (c *impersonatorConfigController) disabledByAutoMode(config *conciergeconfigv1alpha1.ImpersonationProxySpec) bool { + return config.Mode == conciergeconfigv1alpha1.ImpersonationProxyModeAuto && *c.hasControlPlaneNodes } -func (c *impersonatorConfigController) disabledExplicitly(config *v1alpha1.ImpersonationProxySpec) bool { - return config.Mode == v1alpha1.ImpersonationProxyModeDisabled +func (c *impersonatorConfigController) disabledExplicitly(config *conciergeconfigv1alpha1.ImpersonationProxySpec) bool { + return config.Mode == conciergeconfigv1alpha1.ImpersonationProxyModeDisabled } -func (c *impersonatorConfigController) shouldHaveLoadBalancer(config *v1alpha1.ImpersonationProxySpec) bool { - return c.shouldHaveImpersonator(config) && config.Service.Type == v1alpha1.ImpersonationProxyServiceTypeLoadBalancer +func (c *impersonatorConfigController) shouldHaveLoadBalancer(config *conciergeconfigv1alpha1.ImpersonationProxySpec) bool { + return c.shouldHaveImpersonator(config) && config.Service.Type == conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer } -func (c *impersonatorConfigController) shouldHaveClusterIPService(config *v1alpha1.ImpersonationProxySpec) bool { - return c.shouldHaveImpersonator(config) && config.Service.Type == v1alpha1.ImpersonationProxyServiceTypeClusterIP +func (c *impersonatorConfigController) shouldHaveClusterIPService(config *conciergeconfigv1alpha1.ImpersonationProxySpec) bool { + return c.shouldHaveImpersonator(config) && config.Service.Type == conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP } func (c *impersonatorConfigController) serviceExists(serviceName string) (bool, *corev1.Service, error) { @@ -537,7 +537,7 @@ func (c *impersonatorConfigController) ensureImpersonatorIsStopped(shouldCloseEr return stopErr } -func (c *impersonatorConfigController) ensureLoadBalancerIsStarted(ctx context.Context, config *v1alpha1.ImpersonationProxySpec) error { +func (c *impersonatorConfigController) ensureLoadBalancerIsStarted(ctx context.Context, config *conciergeconfigv1alpha1.ImpersonationProxySpec) error { appNameLabel := c.labels[appLabelKey] loadBalancer := corev1.Service{ Spec: corev1.ServiceSpec{ @@ -583,7 +583,7 @@ func (c *impersonatorConfigController) ensureLoadBalancerIsStopped(ctx context.C return utilerrors.FilterOut(err, apierrors.IsNotFound) } -func (c *impersonatorConfigController) ensureClusterIPServiceIsStarted(ctx context.Context, config *v1alpha1.ImpersonationProxySpec) error { +func (c *impersonatorConfigController) ensureClusterIPServiceIsStarted(ctx context.Context, config *conciergeconfigv1alpha1.ImpersonationProxySpec) error { appNameLabel := c.labels[appLabelKey] clusterIP := corev1.Service{ Spec: corev1.ServiceSpec{ @@ -950,16 +950,16 @@ func (c *impersonatorConfigController) createCASecret(ctx context.Context) (*cer return impersonationCA, nil } -func (c *impersonatorConfigController) findDesiredTLSCertificateName(config *v1alpha1.ImpersonationProxySpec) (*certNameInfo, error) { +func (c *impersonatorConfigController) findDesiredTLSCertificateName(config *conciergeconfigv1alpha1.ImpersonationProxySpec) (*certNameInfo, error) { if config.ExternalEndpoint != "" { return c.findTLSCertificateNameFromEndpointConfig(config), nil - } else if config.Service.Type == v1alpha1.ImpersonationProxyServiceTypeClusterIP { + } else if config.Service.Type == conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP { return c.findTLSCertificateNameFromClusterIPService() } return c.findTLSCertificateNameFromLoadBalancer() } -func (c *impersonatorConfigController) findTLSCertificateNameFromEndpointConfig(config *v1alpha1.ImpersonationProxySpec) *certNameInfo { +func (c *impersonatorConfigController) findTLSCertificateNameFromEndpointConfig(config *conciergeconfigv1alpha1.ImpersonationProxySpec) *certNameInfo { addr, _ := endpointaddr.Parse(config.ExternalEndpoint, 443) endpoint := strings.TrimSuffix(addr.Endpoint(), ":443") @@ -1136,42 +1136,42 @@ func (c *impersonatorConfigController) clearSignerCA() { c.impersonationSigningCertProvider.UnsetCertKeyContent() } -func (c *impersonatorConfigController) doSyncResult(nameInfo *certNameInfo, config *v1alpha1.ImpersonationProxySpec, caBundle []byte) *v1alpha1.CredentialIssuerStrategy { +func (c *impersonatorConfigController) doSyncResult(nameInfo *certNameInfo, config *conciergeconfigv1alpha1.ImpersonationProxySpec, caBundle []byte) *conciergeconfigv1alpha1.CredentialIssuerStrategy { switch { case c.disabledExplicitly(config): - return &v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.ErrorStrategyStatus, - Reason: v1alpha1.DisabledStrategyReason, + return &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.DisabledStrategyReason, Message: "impersonation proxy was explicitly disabled by configuration", LastUpdateTime: metav1.NewTime(c.clock.Now()), } case c.disabledByAutoMode(config): - return &v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.ErrorStrategyStatus, - Reason: v1alpha1.DisabledStrategyReason, + return &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.DisabledStrategyReason, Message: "automatically determined that impersonation proxy should be disabled", LastUpdateTime: metav1.NewTime(c.clock.Now()), } case !nameInfo.ready: - return &v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.ErrorStrategyStatus, - Reason: v1alpha1.PendingStrategyReason, + return &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.PendingStrategyReason, Message: "waiting for load balancer Service to be assigned IP or hostname", LastUpdateTime: metav1.NewTime(c.clock.Now()), } default: - return &v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.SuccessStrategyStatus, - Reason: v1alpha1.ListeningStrategyReason, + return &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.ListeningStrategyReason, Message: "impersonation proxy is ready to accept client connections", LastUpdateTime: metav1.NewTime(c.clock.Now()), - Frontend: &v1alpha1.CredentialIssuerFrontend{ - Type: v1alpha1.ImpersonationProxyFrontendType, - ImpersonationProxyInfo: &v1alpha1.ImpersonationProxyInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType, + ImpersonationProxyInfo: &conciergeconfigv1alpha1.ImpersonationProxyInfo{ Endpoint: "https://" + nameInfo.clientEndpoint, CertificateAuthorityData: base64.StdEncoding.EncodeToString(caBundle), }, @@ -1180,26 +1180,26 @@ func (c *impersonatorConfigController) doSyncResult(nameInfo *certNameInfo, conf } } -func validateCredentialIssuerSpec(spec *v1alpha1.ImpersonationProxySpec) error { +func validateCredentialIssuerSpec(spec *conciergeconfigv1alpha1.ImpersonationProxySpec) error { // Validate that the mode is one of our known values. switch spec.Mode { - case v1alpha1.ImpersonationProxyModeDisabled: - case v1alpha1.ImpersonationProxyModeAuto: - case v1alpha1.ImpersonationProxyModeEnabled: + case conciergeconfigv1alpha1.ImpersonationProxyModeDisabled: + case conciergeconfigv1alpha1.ImpersonationProxyModeAuto: + case conciergeconfigv1alpha1.ImpersonationProxyModeEnabled: default: return fmt.Errorf("invalid proxy mode %q (expected auto, disabled, or enabled)", spec.Mode) } // If disabled, ignore all other fields and consider the configuration valid. - if spec.Mode == v1alpha1.ImpersonationProxyModeDisabled { + if spec.Mode == conciergeconfigv1alpha1.ImpersonationProxyModeDisabled { return nil } // Validate that the service type is one of our known values. switch spec.Service.Type { - case v1alpha1.ImpersonationProxyServiceTypeNone: - case v1alpha1.ImpersonationProxyServiceTypeLoadBalancer: - case v1alpha1.ImpersonationProxyServiceTypeClusterIP: + case conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone: + case conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer: + case conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP: default: return fmt.Errorf("invalid service type %q (expected None, LoadBalancer, or ClusterIP)", spec.Service.Type) } @@ -1210,7 +1210,7 @@ func validateCredentialIssuerSpec(spec *v1alpha1.ImpersonationProxySpec) error { } // If service is type "None", a non-empty external endpoint must be specified. - if spec.ExternalEndpoint == "" && spec.Service.Type == v1alpha1.ImpersonationProxyServiceTypeNone { + if spec.ExternalEndpoint == "" && spec.Service.Type == conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone { return fmt.Errorf("externalEndpoint must be set when service.type is None") } diff --git a/internal/controller/impersonatorconfig/impersonator_config_test.go b/internal/controller/impersonatorconfig/impersonator_config_test.go index f012ff9b2..ae40ee11e 100644 --- a/internal/controller/impersonatorconfig/impersonator_config_test.go +++ b/internal/controller/impersonatorconfig/impersonator_config_test.go @@ -35,7 +35,7 @@ import ( coretesting "k8s.io/client-go/testing" clocktesting "k8s.io/utils/clock/testing" - "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" pinnipedfake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" pinnipedinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" "go.pinniped.dev/internal/certauthority" @@ -103,13 +103,13 @@ func TestImpersonatorConfigControllerOptions(t *testing.T) { when("watching CredentialIssuer objects", func() { var subject controllerlib.Filter - var target, wrongName, otherWrongName *v1alpha1.CredentialIssuer + var target, wrongName, otherWrongName *conciergeconfigv1alpha1.CredentialIssuer it.Before(func() { subject = credIssuerInformerFilter - target = &v1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}} - wrongName = &v1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "wrong-name"}} - otherWrongName = &v1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "other-wrong-name"}} + target = &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}} + wrongName = &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "wrong-name"}} + otherWrongName = &conciergeconfigv1alpha1.CredentialIssuer{ObjectMeta: metav1.ObjectMeta{Name: "other-wrong-name"}} }) when("the target CredentialIssuer changes", func() { @@ -609,7 +609,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { controllerlib.TestRunSynchronously(t, subject) } - var addCredentialIssuerToTrackers = func(credIssuer v1alpha1.CredentialIssuer, informerClient *pinnipedfake.Clientset, mainClient *pinnipedfake.Clientset) { + var addCredentialIssuerToTrackers = func(credIssuer conciergeconfigv1alpha1.CredentialIssuer, informerClient *pinnipedfake.Clientset, mainClient *pinnipedfake.Clientset) { t.Logf("adding CredentialIssuer %s to informer and main clientsets", credIssuer.Name) r.NoError(informerClient.Tracker().Add(&credIssuer)) r.NoError(mainClient.Tracker().Add(&credIssuer)) @@ -772,12 +772,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addObjectToKubeInformerAndWait(createdObject, informer) } - var updateCredentialIssuerInInformerAndWait = func(resourceName string, credIssuerSpec v1alpha1.CredentialIssuerSpec, informer controllerlib.InformerGetter) { - credIssuersGVR := v1alpha1.Resource("credentialissuers").WithVersion("v1alpha1") + var updateCredentialIssuerInInformerAndWait = func(resourceName string, credIssuerSpec conciergeconfigv1alpha1.CredentialIssuerSpec, informer controllerlib.InformerGetter) { + credIssuersGVR := conciergeconfigv1alpha1.Resource("credentialissuers").WithVersion("v1alpha1") credIssuerObj, err := pinnipedInformerClient.Tracker().Get(credIssuersGVR, "", resourceName) r.NoError(err, "could not find CredentialIssuer to update for test") - credIssuer := credIssuerObj.(*v1alpha1.CredentialIssuer) + credIssuer := credIssuerObj.(*conciergeconfigv1alpha1.CredentialIssuer) credIssuer = credIssuer.DeepCopy() // don't edit the original from the tracker credIssuer.Spec = credIssuerSpec r.NoError(pinnipedInformerClient.Tracker().Update(credIssuersGVR, credIssuer, "")) @@ -899,16 +899,16 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { ) } - var newSuccessStrategy = func(endpoint string, ca []byte) v1alpha1.CredentialIssuerStrategy { - return v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.SuccessStrategyStatus, - Reason: v1alpha1.ListeningStrategyReason, + var newSuccessStrategy = func(endpoint string, ca []byte) conciergeconfigv1alpha1.CredentialIssuerStrategy { + return conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.ListeningStrategyReason, Message: "impersonation proxy is ready to accept client connections", LastUpdateTime: metav1.NewTime(frozenNow), - Frontend: &v1alpha1.CredentialIssuerFrontend{ - Type: v1alpha1.ImpersonationProxyFrontendType, - ImpersonationProxyInfo: &v1alpha1.ImpersonationProxyInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.ImpersonationProxyFrontendType, + ImpersonationProxyInfo: &conciergeconfigv1alpha1.ImpersonationProxyInfo{ Endpoint: "https://" + endpoint, CertificateAuthorityData: base64.StdEncoding.EncodeToString(ca), }, @@ -916,64 +916,64 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { } } - var newAutoDisabledStrategy = func() v1alpha1.CredentialIssuerStrategy { - return v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.ErrorStrategyStatus, - Reason: v1alpha1.DisabledStrategyReason, + var newAutoDisabledStrategy = func() conciergeconfigv1alpha1.CredentialIssuerStrategy { + return conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.DisabledStrategyReason, Message: "automatically determined that impersonation proxy should be disabled", LastUpdateTime: metav1.NewTime(frozenNow), Frontend: nil, } } - var newManuallyDisabledStrategy = func() v1alpha1.CredentialIssuerStrategy { + var newManuallyDisabledStrategy = func() conciergeconfigv1alpha1.CredentialIssuerStrategy { s := newAutoDisabledStrategy() s.Message = "impersonation proxy was explicitly disabled by configuration" return s } - var newPendingStrategy = func(msg string) v1alpha1.CredentialIssuerStrategy { - return v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.ErrorStrategyStatus, - Reason: v1alpha1.PendingStrategyReason, + var newPendingStrategy = func(msg string) conciergeconfigv1alpha1.CredentialIssuerStrategy { + return conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.PendingStrategyReason, Message: msg, LastUpdateTime: metav1.NewTime(frozenNow), Frontend: nil, } } - var newPendingStrategyWaitingForLB = func() v1alpha1.CredentialIssuerStrategy { + var newPendingStrategyWaitingForLB = func() conciergeconfigv1alpha1.CredentialIssuerStrategy { return newPendingStrategy("waiting for load balancer Service to be assigned IP or hostname") } - var newErrorStrategy = func(msg string) v1alpha1.CredentialIssuerStrategy { - return v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.ImpersonationProxyStrategyType, - Status: v1alpha1.ErrorStrategyStatus, - Reason: v1alpha1.ErrorDuringSetupStrategyReason, + var newErrorStrategy = func(msg string) conciergeconfigv1alpha1.CredentialIssuerStrategy { + return conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.ErrorDuringSetupStrategyReason, Message: msg, LastUpdateTime: metav1.NewTime(frozenNow), Frontend: nil, } } - var getCredentialIssuer = func() *v1alpha1.CredentialIssuer { + var getCredentialIssuer = func() *conciergeconfigv1alpha1.CredentialIssuer { credentialIssuerObj, err := pinnipedAPIClient.Tracker().Get( schema.GroupVersionResource{ - Group: v1alpha1.SchemeGroupVersion.Group, - Version: v1alpha1.SchemeGroupVersion.Version, + Group: conciergeconfigv1alpha1.SchemeGroupVersion.Group, + Version: conciergeconfigv1alpha1.SchemeGroupVersion.Version, Resource: "credentialissuers", }, "", credentialIssuerResourceName, ) r.NoError(err) - credentialIssuer, ok := credentialIssuerObj.(*v1alpha1.CredentialIssuer) + credentialIssuer, ok := credentialIssuerObj.(*conciergeconfigv1alpha1.CredentialIssuer) r.True(ok, "should have been able to cast this obj to CredentialIssuer: %v", credentialIssuerObj) return credentialIssuer } - var requireCredentialIssuer = func(expectedStrategy v1alpha1.CredentialIssuerStrategy) { + var requireCredentialIssuer = func(expectedStrategy conciergeconfigv1alpha1.CredentialIssuerStrategy) { // Rather than looking at the specific API actions on pinnipedAPIClient, we just look // at the final result here. // This is because the implementation is using a helper from another package to create @@ -982,7 +982,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { // As long as we get the final result that we wanted then we are happy for the purposes // of this test. credentialIssuer := getCredentialIssuer() - r.Equal([]v1alpha1.CredentialIssuerStrategy{expectedStrategy}, credentialIssuer.Status.Strategies) + r.Equal([]conciergeconfigv1alpha1.CredentialIssuerStrategy{expectedStrategy}, credentialIssuer.Status.Strategies) } var requireServiceWasDeleted = func(action coretesting.Action, serviceName string) { @@ -1178,14 +1178,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the configuration is auto mode with an endpoint and service type none", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -1232,16 +1232,16 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) addSecretToTrackers(externalTLSSecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, - TLS: &v1alpha1.ImpersonationProxyTLSSpec{ + TLS: &conciergeconfigv1alpha1.ImpersonationProxyTLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(externalCA.Bundle()), SecretName: externallyProvidedTLSSecretName, }, @@ -1293,16 +1293,16 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) addSecretToTrackers(externalTLSSecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, - TLS: &v1alpha1.ImpersonationProxyTLSSpec{ + TLS: &conciergeconfigv1alpha1.ImpersonationProxyTLSSpec{ CertificateAuthorityData: string(externalCA.Bundle()), SecretName: externallyProvidedTLSSecretName, }, @@ -1325,16 +1325,16 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) addSecretToTrackers(externalTLSSecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, - TLS: &v1alpha1.ImpersonationProxyTLSSpec{ + TLS: &conciergeconfigv1alpha1.ImpersonationProxyTLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte("hello")), SecretName: externallyProvidedTLSSecretName, }, @@ -1364,16 +1364,16 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) externalTLSSecret.Data["ca.crt"] = externalCA.Bundle() addSecretToTrackers(externalTLSSecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, - TLS: &v1alpha1.ImpersonationProxyTLSSpec{ + TLS: &conciergeconfigv1alpha1.ImpersonationProxyTLSSpec{ SecretName: externallyProvidedTLSSecretName, }, }, @@ -1397,16 +1397,16 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) externalTLSSecret.Data["ca.crt"] = []byte("hello") addSecretToTrackers(externalTLSSecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, - TLS: &v1alpha1.ImpersonationProxyTLSSpec{ + TLS: &conciergeconfigv1alpha1.ImpersonationProxyTLSSpec{ SecretName: externallyProvidedTLSSecretName, }, }, @@ -1428,16 +1428,16 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) addSecretToTrackers(externalTLSSecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, - TLS: &v1alpha1.ImpersonationProxyTLSSpec{ + TLS: &conciergeconfigv1alpha1.ImpersonationProxyTLSSpec{ SecretName: externallyProvidedTLSSecretName, }, }, @@ -1461,11 +1461,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the configuration is auto mode", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -1762,11 +1762,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the configuration is disabled mode", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeDisabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeDisabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -1790,11 +1790,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { }) when("no load balancer", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -1824,11 +1824,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("a loadbalancer already exists", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -1860,13 +1860,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("a clusterip already exists with ingress", func() { const fakeIP = "127.0.0.123" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }, @@ -1893,13 +1893,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { const fakeIP1 = "127.0.0.123" const fakeIP2 = "fd00::5118" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }, @@ -1925,11 +1925,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("a load balancer and a secret already exists", func() { var caCrt []byte it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -1957,13 +1957,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("credentialissuer has service type loadbalancer and custom annotations", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, Annotations: map[string]string{"some-annotation-key": "some-annotation-value"}, }, }, @@ -1992,14 +1992,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has a hostname specified and service type none", func() { const fakeHostname = "fake.example.com" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -2024,14 +2024,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has a hostname specified and service type loadbalancer", func() { const fakeHostname = "fake.example.com" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, }, }, }, @@ -2056,13 +2056,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has a hostname specified and service type clusterip", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }, @@ -2087,14 +2087,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has a endpoint which is an IP address with a port", func() { const fakeIPWithPort = "127.0.0.1:3000" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeIPWithPort, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -2119,14 +2119,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has a endpoint which is a hostname with a port, service type none", func() { const fakeHostnameWithPort = "fake.example.com:3000" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostnameWithPort, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -2151,14 +2151,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has a endpoint which is a hostname with a port, service type loadbalancer with loadbalancerip", func() { const fakeHostnameWithPort = "fake.example.com:3000" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostnameWithPort, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, LoadBalancerIP: localhostIP, }, }, @@ -2187,27 +2187,27 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { const fakeHostname = "fake.example.com" const fakeIP = "127.0.0.42" - var hostnameConfig = v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + var hostnameConfig = conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, } - var ipAddressConfig = v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + var ipAddressConfig = conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, } it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, Spec: ipAddressConfig, }, pinnipedInformerClient, pinnipedAPIClient) @@ -2264,14 +2264,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the TLS cert goes missing and needs to be recreated, e.g. when a user manually deleted it", func() { const fakeHostname = "fake.example.com" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -2312,14 +2312,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CA cert goes missing and needs to be recreated, e.g. when a user manually deleted it", func() { const fakeHostname = "fake.example.com" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -2363,14 +2363,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { const fakeHostname = "fake.example.com" var caCrt []byte it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -2439,11 +2439,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("service type loadbalancer", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -2467,9 +2467,9 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addObjectFromCreateActionToInformerAndWait(kubeAPIClient.Actions()[2], kubeInformers.Core().V1().Secrets()) // Update the CredentialIssuer. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeDisabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeDisabled, }, }, pinnipedInformers.Config().V1alpha1().CredentialIssuers()) @@ -2484,9 +2484,9 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { waitForObjectToBeDeletedFromInformer(loadBalancerServiceName, kubeInformers.Core().V1().Services()) // Update the CredentialIssuer again. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, }, }, pinnipedInformers.Config().V1alpha1().CredentialIssuers()) @@ -2502,13 +2502,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("service type clusterip", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }, @@ -2533,9 +2533,9 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addObjectFromCreateActionToInformerAndWait(kubeAPIClient.Actions()[2], kubeInformers.Core().V1().Secrets()) // Update the CredentialIssuer. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeDisabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeDisabled, }, }, pinnipedInformers.Config().V1alpha1().CredentialIssuers()) @@ -2550,11 +2550,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { waitForObjectToBeDeletedFromInformer(clusterIPServiceName, kubeInformers.Core().V1().Services()) // Update the CredentialIssuer again. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }, pinnipedInformers.Config().V1alpha1().CredentialIssuers()) @@ -2572,14 +2572,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { const fakeHostname = "hello.com" it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -2607,9 +2607,9 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addObjectFromCreateActionToInformerAndWait(kubeAPIClient.Actions()[2], kubeInformers.Core().V1().Secrets()) // Update the CredentialIssuer. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeDisabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeDisabled, }, }, pinnipedInformers.Config().V1alpha1().CredentialIssuers()) @@ -2627,12 +2627,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { waitForObjectToBeDeletedFromInformer(internallyGeneratedTLSServingCertSecretName, kubeInformers.Core().V1().Secrets()) // Update the CredentialIssuer again. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, pinnipedInformers.Config().V1alpha1().CredentialIssuers()) @@ -2653,14 +2653,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the endpoint and mode switch from specified with no service, to not specified, to specified again", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -2686,9 +2686,9 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addObjectFromCreateActionToInformerAndWait(kubeAPIClient.Actions()[2], kubeInformers.Core().V1().Secrets()) // Switch to "enabled" mode without an "endpoint", so a load balancer is needed now. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, }, }, pinnipedInformers.Config().V1alpha1().CredentialIssuers()) @@ -2727,12 +2727,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addObjectFromCreateActionToInformerAndWait(kubeAPIClient.Actions()[5], kubeInformers.Core().V1().Secrets()) // Now switch back to having the "endpoint" specified and explicitly saying that we don't want the load balancer service. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, pinnipedInformers.Config().V1alpha1().CredentialIssuers()) @@ -2751,14 +2751,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("requesting a load balancer via CredentialIssuer, then updating the annotations", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, }, }, }, @@ -2798,12 +2798,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { // Add annotations to the CredentialIssuer spec. credentialIssuerAnnotations := map[string]string{"my-annotation-key": "my-annotation-val"} - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, Annotations: credentialIssuerAnnotations, }, }, @@ -2829,14 +2829,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("requesting a cluster ip via CredentialIssuer, then updating the annotations", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }, @@ -2876,12 +2876,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { // Add annotations to the CredentialIssuer spec. credentialIssuerAnnotations := map[string]string{"my-annotation-key": "my-annotation-val"} - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, Annotations: credentialIssuerAnnotations, }, }, @@ -2907,14 +2907,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("requesting a load balancer via CredentialIssuer with annotations, then updating the CredentialIssuer annotations to remove one", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, Annotations: map[string]string{ "my-initial-annotation1-key": "my-initial-annotation1-val", "my-initial-annotation2-key": "my-initial-annotation2-val", @@ -2960,12 +2960,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { r.Len(kubeAPIClient.Actions(), 4) // no new actions because the controller decides there is nothing to update on the Service // Remove one of the annotations from the CredentialIssuer spec. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, Annotations: map[string]string{ "my-initial-annotation1-key": "my-initial-annotation1-val", "my-initial-annotation3-key": "my-initial-annotation3-val", @@ -2992,12 +2992,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { requireMTLSClientCertProviderHasLoadedCerts(mTLSClientCertCACertPEM, mTLSClientCertCAPrivateKeyPEM) // Remove all the rest of the annotations from the CredentialIssuer spec so there are none remaining. - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, Annotations: map[string]string{}, }, }, @@ -3021,14 +3021,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("requesting a load balancer via CredentialIssuer, but there is already a load balancer with an invalid bookkeeping annotation value", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, Annotations: map[string]string{"some-annotation": "annotation-value"}, }, }, @@ -3066,14 +3066,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("requesting a load balancer via CredentialIssuer, then adding a static loadBalancerIP to the spec", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, }, }, }, @@ -3104,12 +3104,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { // Add annotations to the spec. loadBalancerIP := "1.2.3.4" - updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + updateCredentialIssuerInInformerAndWait(credentialIssuerResourceName, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeLoadBalancer, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, LoadBalancerIP: loadBalancerIP, }, }, @@ -3129,11 +3129,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) addNodeWithRoleToTracker("worker", kubeAPIClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3237,28 +3237,28 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { }) when("there is already a CredentialIssuer", func() { - preExistingStrategy := v1alpha1.CredentialIssuerStrategy{ - Type: v1alpha1.KubeClusterSigningCertificateStrategyType, - Status: v1alpha1.SuccessStrategyStatus, - Reason: v1alpha1.FetchedKeyStrategyReason, + preExistingStrategy := conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.FetchedKeyStrategyReason, Message: "happy other unrelated strategy", LastUpdateTime: metav1.NewTime(frozenNow), - Frontend: &v1alpha1.CredentialIssuerFrontend{ - Type: v1alpha1.TokenCredentialRequestAPIFrontendType, + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, }, } it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, - Status: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + Status: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ preExistingStrategy, }, }, @@ -3275,17 +3275,17 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { requireLoadBalancerWasCreated(kubeAPIClient.Actions()[1]) requireCASecretWasCreated(kubeAPIClient.Actions()[2]) credentialIssuer := getCredentialIssuer() - r.Equal([]v1alpha1.CredentialIssuerStrategy{preExistingStrategy, newPendingStrategyWaitingForLB()}, credentialIssuer.Status.Strategies) + r.Equal([]conciergeconfigv1alpha1.CredentialIssuerStrategy{preExistingStrategy, newPendingStrategyWaitingForLB()}, credentialIssuer.Status.Strategies) }) }) when("getting the control plane nodes returns an error, e.g. when there are no nodes", func() { it("returns an error", func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3302,11 +3302,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) addNodeWithRoleToTracker("worker", kubeAPIClient) impersonatorFuncReturnedFuncError = errors.New("some immediate impersonator startup error") - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3366,11 +3366,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) addNodeWithRoleToTracker("worker", kubeAPIClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3425,9 +3425,9 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has nil impersonation spec", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ ImpersonationProxy: nil, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3445,10 +3445,10 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has invalid mode", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ Mode: "not-valid", }, }, @@ -3467,12 +3467,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has invalid service type", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, - Service: v1alpha1.ImpersonationProxyServiceSpec{ + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ Type: "not-valid", }, }, @@ -3492,12 +3492,12 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has invalid LoadBalancerIP", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, - Service: v1alpha1.ImpersonationProxyServiceSpec{ + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ LoadBalancerIP: "invalid-ip-address", }, }, @@ -3517,11 +3517,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CredentialIssuer has invalid ExternalEndpoint", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: "[invalid", }, }, @@ -3547,11 +3547,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { action.(coretesting.CreateAction).GetObject().(*corev1.Service).Name, ) }) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3572,11 +3572,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { kubeAPIClient.PrependReactor("delete", "services", func(action coretesting.Action) (handled bool, ret runtime.Object, err error) { return true, nil, fmt.Errorf("error on delete") }) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeDisabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeDisabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3598,13 +3598,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { kubeAPIClient.PrependReactor("create", "services", func(action coretesting.Action) (handled bool, ret runtime.Object, err error) { return true, nil, fmt.Errorf("error on create") }) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }, @@ -3626,13 +3626,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { kubeAPIClient.PrependReactor("update", "services", func(action coretesting.Action) (handled bool, ret runtime.Object, err error) { return true, nil, fmt.Errorf("error on update") }) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeClusterIP, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, Annotations: map[string]string{"key": "val"}, }, }, @@ -3657,11 +3657,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { kubeAPIClient.PrependReactor("delete", "services", func(action coretesting.Action) (handled bool, ret runtime.Object, err error) { return true, nil, fmt.Errorf("error on delete") }) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeDisabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeDisabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3679,14 +3679,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("there is an error creating the tls secret", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: "example.com", - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -3716,14 +3716,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("there is an error creating the CA secret", func() { it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: "example.com", - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -3753,14 +3753,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the CA secret exists but is invalid while the TLS secret needs to be created", func() { it.Before(func() { addNodeWithRoleToTracker("control-plane", kubeAPIClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: "example.com", - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -3786,11 +3786,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addLoadBalancerServiceToTracker(loadBalancerServiceName, kubeInformerClient) addLoadBalancerServiceToTracker(loadBalancerServiceName, kubeAPIClient) addSecretToTrackers(newEmptySecret(internallyGeneratedTLSServingCertSecretName), kubeAPIClient, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3816,11 +3816,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addNodeWithRoleToTracker("control-plane", kubeAPIClient) addSecretToTrackers(newEmptySecret(internallyGeneratedTLSServingCertSecretName), kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeDisabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeDisabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3841,14 +3841,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the PEM formatted data in the TLS Secret is not a valid cert", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: localhostIP, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -3901,11 +3901,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { var caCrt []byte it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -3967,11 +3967,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { addSecretToTrackers(tlsSecret, kubeAPIClient, kubeInformerClient) addLoadBalancerServiceWithIngressToTracker(loadBalancerServiceName, []corev1.LoadBalancerIngress{{IP: localhostIP}}, kubeInformerClient) addLoadBalancerServiceWithIngressToTracker(loadBalancerServiceName, []corev1.LoadBalancerIngress{{IP: localhostIP}}, kubeAPIClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -4015,11 +4015,11 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) addNodeWithRoleToTracker("worker", kubeAPIClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeAuto, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, }, }, }, pinnipedInformerClient, pinnipedAPIClient) @@ -4050,14 +4050,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the impersonator is ready but there is a problem with the signing secret, which should be created by another controller", func() { const fakeHostname = "foo.example.com" it.Before(func() { - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: fakeHostname, - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, @@ -4145,14 +4145,14 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { when("the impersonator is enabled but the service type is none and the external endpoint is empty", func() { it.Before(func() { addSecretToTrackers(mTLSClientCertCASecret, kubeInformerClient) - addCredentialIssuerToTrackers(v1alpha1.CredentialIssuer{ + addCredentialIssuerToTrackers(conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: credentialIssuerResourceName}, - Spec: v1alpha1.CredentialIssuerSpec{ - ImpersonationProxy: &v1alpha1.ImpersonationProxySpec{ - Mode: v1alpha1.ImpersonationProxyModeEnabled, + Spec: conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: "", - Service: v1alpha1.ImpersonationProxyServiceSpec{ - Type: v1alpha1.ImpersonationProxyServiceTypeNone, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeNone, }, }, }, diff --git a/internal/controller/issuerconfig/issuerconfig.go b/internal/controller/issuerconfig/issuerconfig.go index 136734bc4..faea9ad30 100644 --- a/internal/controller/issuerconfig/issuerconfig.go +++ b/internal/controller/issuerconfig/issuerconfig.go @@ -1,4 +1,4 @@ -// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package issuerconfig contains helpers for updating CredentialIssuer status entries. @@ -12,12 +12,12 @@ import ( apiequality "k8s.io/apimachinery/pkg/api/equality" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" - "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" ) // Update a strategy on an existing CredentialIssuer, merging into any existing strategy entries. -func Update(ctx context.Context, client versioned.Interface, issuer *v1alpha1.CredentialIssuer, strategy v1alpha1.CredentialIssuerStrategy) error { +func Update(ctx context.Context, client conciergeclientset.Interface, issuer *conciergeconfigv1alpha1.CredentialIssuer, strategy conciergeconfigv1alpha1.CredentialIssuerStrategy) error { // Update the existing object to merge in the new strategy. updated := issuer.DeepCopy() mergeStrategy(&updated.Status, strategy) @@ -33,8 +33,8 @@ func Update(ctx context.Context, client versioned.Interface, issuer *v1alpha1.Cr return nil } -func mergeStrategy(configToUpdate *v1alpha1.CredentialIssuerStatus, strategy v1alpha1.CredentialIssuerStrategy) { - var existing *v1alpha1.CredentialIssuerStrategy +func mergeStrategy(configToUpdate *conciergeconfigv1alpha1.CredentialIssuerStatus, strategy conciergeconfigv1alpha1.CredentialIssuerStrategy) { + var existing *conciergeconfigv1alpha1.CredentialIssuerStrategy for i := range configToUpdate.Strategies { if configToUpdate.Strategies[i].Type == strategy.Type { existing = &configToUpdate.Strategies[i] @@ -51,8 +51,8 @@ func mergeStrategy(configToUpdate *v1alpha1.CredentialIssuerStatus, strategy v1a sort.Stable(sortableStrategies(configToUpdate.Strategies)) // Special case: the "TokenCredentialRequestAPI" data is mirrored into the deprecated status.kubeConfigInfo field. - if strategy.Frontend != nil && strategy.Frontend.Type == v1alpha1.TokenCredentialRequestAPIFrontendType { - configToUpdate.KubeConfigInfo = &v1alpha1.CredentialIssuerKubeConfigInfo{ + if strategy.Frontend != nil && strategy.Frontend.Type == conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType { + configToUpdate.KubeConfigInfo = &conciergeconfigv1alpha1.CredentialIssuerKubeConfigInfo{ Server: strategy.Frontend.TokenCredentialRequestAPIInfo.Server, CertificateAuthorityData: strategy.Frontend.TokenCredentialRequestAPIInfo.CertificateAuthorityData, } @@ -60,13 +60,13 @@ func mergeStrategy(configToUpdate *v1alpha1.CredentialIssuerStatus, strategy v1a } // weights are a set of priorities for each strategy type. -var weights = map[v1alpha1.StrategyType]int{ //nolint:gochecknoglobals - v1alpha1.KubeClusterSigningCertificateStrategyType: 2, // most preferred strategy - v1alpha1.ImpersonationProxyStrategyType: 1, +var weights = map[conciergeconfigv1alpha1.StrategyType]int{ //nolint:gochecknoglobals + conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType: 2, // most preferred strategy + conciergeconfigv1alpha1.ImpersonationProxyStrategyType: 1, // unknown strategy types will have weight 0 by default } -type sortableStrategies []v1alpha1.CredentialIssuerStrategy +type sortableStrategies []conciergeconfigv1alpha1.CredentialIssuerStrategy func (s sortableStrategies) Len() int { return len(s) } func (s sortableStrategies) Less(i, j int) bool { @@ -77,7 +77,7 @@ func (s sortableStrategies) Less(i, j int) bool { } func (s sortableStrategies) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func equalExceptLastUpdated(s1, s2 *v1alpha1.CredentialIssuerStrategy) bool { +func equalExceptLastUpdated(s1, s2 *conciergeconfigv1alpha1.CredentialIssuerStrategy) bool { s1 = s1.DeepCopy() s2 = s2.DeepCopy() s1.LastUpdateTime = metav1.Time{} diff --git a/internal/controller/issuerconfig/issuerconfig_test.go b/internal/controller/issuerconfig/issuerconfig_test.go index 7b4fef97f..f671c03ea 100644 --- a/internal/controller/issuerconfig/issuerconfig_test.go +++ b/internal/controller/issuerconfig/issuerconfig_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" ) func TestMergeStrategy(t *testing.T) { @@ -23,27 +23,27 @@ func TestMergeStrategy(t *testing.T) { tests := []struct { name string - configToUpdate v1alpha1.CredentialIssuerStatus - strategy v1alpha1.CredentialIssuerStrategy - expected v1alpha1.CredentialIssuerStatus + configToUpdate conciergeconfigv1alpha1.CredentialIssuerStatus + strategy conciergeconfigv1alpha1.CredentialIssuerStrategy + expected conciergeconfigv1alpha1.CredentialIssuerStatus }{ { name: "new entry", - configToUpdate: v1alpha1.CredentialIssuerStatus{ + configToUpdate: conciergeconfigv1alpha1.CredentialIssuerStatus{ Strategies: nil, }, - strategy: v1alpha1.CredentialIssuerStrategy{ + strategy: conciergeconfigv1alpha1.CredentialIssuerStrategy{ Type: "Type1", - Status: v1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "some reason", Message: "some message", LastUpdateTime: t1, }, - expected: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + expected: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "Type1", - Status: v1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "some reason", Message: "some message", LastUpdateTime: t1, @@ -53,41 +53,41 @@ func TestMergeStrategy(t *testing.T) { }, { name: "new entry updating deprecated kubeConfigInfo", - configToUpdate: v1alpha1.CredentialIssuerStatus{ + configToUpdate: conciergeconfigv1alpha1.CredentialIssuerStatus{ Strategies: nil, }, - strategy: v1alpha1.CredentialIssuerStrategy{ + strategy: conciergeconfigv1alpha1.CredentialIssuerStrategy{ Type: "Type1", - Status: v1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "some reason", Message: "some message", LastUpdateTime: t1, - Frontend: &v1alpha1.CredentialIssuerFrontend{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ Type: "TokenCredentialRequestAPI", - TokenCredentialRequestAPIInfo: &v1alpha1.TokenCredentialRequestAPIInfo{ + TokenCredentialRequestAPIInfo: &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: "https://test-server", CertificateAuthorityData: "test-ca-bundle", }, }, }, - expected: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + expected: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "Type1", - Status: v1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "some reason", Message: "some message", LastUpdateTime: t1, - Frontend: &v1alpha1.CredentialIssuerFrontend{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ Type: "TokenCredentialRequestAPI", - TokenCredentialRequestAPIInfo: &v1alpha1.TokenCredentialRequestAPIInfo{ + TokenCredentialRequestAPIInfo: &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: "https://test-server", CertificateAuthorityData: "test-ca-bundle", }, }, }, }, - KubeConfigInfo: &v1alpha1.CredentialIssuerKubeConfigInfo{ + KubeConfigInfo: &conciergeconfigv1alpha1.CredentialIssuerKubeConfigInfo{ Server: "https://test-server", CertificateAuthorityData: "test-ca-bundle", }, @@ -95,29 +95,29 @@ func TestMergeStrategy(t *testing.T) { }, { name: "existing entry to update", - configToUpdate: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + configToUpdate: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "Type1", - Status: v1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "some starting reason", Message: "some starting message", LastUpdateTime: t2, }, }, }, - strategy: v1alpha1.CredentialIssuerStrategy{ + strategy: conciergeconfigv1alpha1.CredentialIssuerStrategy{ Type: "Type1", - Status: v1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "some reason", Message: "some message", LastUpdateTime: t1, }, - expected: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + expected: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "Type1", - Status: v1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "some reason", Message: "some message", LastUpdateTime: t1, @@ -127,29 +127,29 @@ func TestMergeStrategy(t *testing.T) { }, { name: "existing entry matches except for LastUpdated time", - configToUpdate: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + configToUpdate: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "Type1", - Status: v1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "some starting reason", Message: "some starting message", LastUpdateTime: t1, }, }, }, - strategy: v1alpha1.CredentialIssuerStrategy{ + strategy: conciergeconfigv1alpha1.CredentialIssuerStrategy{ Type: "Type1", - Status: v1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "some starting reason", Message: "some starting message", LastUpdateTime: t2, }, - expected: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + expected: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "Type1", - Status: v1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "some starting reason", Message: "some starting message", LastUpdateTime: t1, @@ -159,36 +159,36 @@ func TestMergeStrategy(t *testing.T) { }, { name: "new entry among others", - configToUpdate: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + configToUpdate: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "Type0", - Status: v1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "some starting reason 0", Message: "some starting message 0", LastUpdateTime: t2, }, { Type: "Type2", - Status: v1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "some starting reason 0", Message: "some starting message 0", LastUpdateTime: t2, }, }, }, - strategy: v1alpha1.CredentialIssuerStrategy{ + strategy: conciergeconfigv1alpha1.CredentialIssuerStrategy{ Type: "Type1", - Status: v1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "some reason", Message: "some message", LastUpdateTime: t1, }, - expected: v1alpha1.CredentialIssuerStatus{ - Strategies: []v1alpha1.CredentialIssuerStrategy{ + expected: conciergeconfigv1alpha1.CredentialIssuerStatus{ + Strategies: []conciergeconfigv1alpha1.CredentialIssuerStrategy{ { Type: "Type0", - Status: v1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "some starting reason 0", Message: "some starting message 0", LastUpdateTime: t2, @@ -196,14 +196,14 @@ func TestMergeStrategy(t *testing.T) { // Expect the Type1 entry to be sorted alphanumerically between the existing entries. { Type: "Type1", - Status: v1alpha1.SuccessStrategyStatus, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, Reason: "some reason", Message: "some message", LastUpdateTime: t1, }, { Type: "Type2", - Status: v1alpha1.ErrorStrategyStatus, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: "some starting reason 0", Message: "some starting message 0", LastUpdateTime: t2, @@ -222,9 +222,9 @@ func TestMergeStrategy(t *testing.T) { } func TestStrategySorting(t *testing.T) { - expected := []v1alpha1.CredentialIssuerStrategy{ - {Type: v1alpha1.KubeClusterSigningCertificateStrategyType}, - {Type: v1alpha1.ImpersonationProxyStrategyType}, + expected := []conciergeconfigv1alpha1.CredentialIssuerStrategy{ + {Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType}, + {Type: conciergeconfigv1alpha1.ImpersonationProxyStrategyType}, {Type: "Type1"}, {Type: "Type2"}, {Type: "Type3"}, @@ -233,7 +233,7 @@ func TestStrategySorting(t *testing.T) { // Create a randomly shuffled copy of the expected output. //nolint:gosec // this is not meant to be a secure random, just a seeded RNG for shuffling deterministically rng := rand.New(rand.NewSource(seed)) - output := make([]v1alpha1.CredentialIssuerStrategy, len(expected)) + output := make([]conciergeconfigv1alpha1.CredentialIssuerStrategy, len(expected)) copy(output, expected) rng.Shuffle( len(output), diff --git a/internal/controller/kubecertagent/kubecertagent.go b/internal/controller/kubecertagent/kubecertagent.go index 2a441fc90..6a02f782a 100644 --- a/internal/controller/kubecertagent/kubecertagent.go +++ b/internal/controller/kubecertagent/kubecertagent.go @@ -32,7 +32,7 @@ import ( "k8s.io/utils/clock" "k8s.io/utils/ptr" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" configv1alpha1informers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions/config/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controller/issuerconfig" @@ -272,7 +272,7 @@ func (c *agentController) Sync(ctx controllerlib.Context) error { controllerManagerPods, err := c.kubeSystemPods.Lister().Pods(ControllerManagerNamespace).List(controllerManagerLabels) if err != nil { err := fmt.Errorf("could not list controller manager pods: %w", err) - return c.failStrategyAndErr(ctx.Context, credIssuer, err, configv1alpha1.CouldNotFetchKeyStrategyReason) + return c.failStrategyAndErr(ctx.Context, credIssuer, err, conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason) } newestControllerManager := newestRunningPod(controllerManagerPods) @@ -286,7 +286,7 @@ func (c *agentController) Sync(ctx controllerlib.Context) error { } else { err = errors.New(msg) } - return c.failStrategyAndErr(ctx.Context, credIssuer, err, configv1alpha1.CouldNotFetchKeyStrategyReason) + return c.failStrategyAndErr(ctx.Context, credIssuer, err, conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason) } depErr := c.createOrUpdateDeployment(ctx, newestControllerManager) @@ -301,7 +301,7 @@ func (c *agentController) Sync(ctx controllerlib.Context) error { agentPods, err := c.agentPods.Lister().Pods(c.cfg.Namespace).List(agentLabels) if err != nil { err := fmt.Errorf("could not list agent pods: %w", err) - return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), configv1alpha1.CouldNotFetchKeyStrategyReason) + return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason) } newestAgentPod := newestRunningPod(agentPods) @@ -309,42 +309,42 @@ func (c *agentController) Sync(ctx controllerlib.Context) error { // the CredentialIssuer. if newestAgentPod == nil { err := fmt.Errorf("could not find a healthy agent pod (%s)", pluralize(agentPods)) - return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), configv1alpha1.CouldNotFetchKeyStrategyReason) + return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason) } // Load the Kubernetes API info from the kube-public/cluster-info ConfigMap. configMap, err := c.kubePublicConfigMaps.Lister().ConfigMaps(ClusterInfoNamespace).Get(clusterInfoName) if err != nil { err := fmt.Errorf("failed to get %s/%s configmap: %w", ClusterInfoNamespace, clusterInfoName, err) - return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), configv1alpha1.CouldNotGetClusterInfoStrategyReason) + return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), conciergeconfigv1alpha1.CouldNotGetClusterInfoStrategyReason) } apiInfo, err := c.extractAPIInfo(configMap) if err != nil { err := fmt.Errorf("could not extract Kubernetes API endpoint info from %s/%s configmap: %w", ClusterInfoNamespace, clusterInfoName, err) - return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), configv1alpha1.CouldNotGetClusterInfoStrategyReason) + return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), conciergeconfigv1alpha1.CouldNotGetClusterInfoStrategyReason) } // Load the certificate and key from the agent pod into our in-memory signer. if err := c.loadSigningKey(ctx.Context, newestAgentPod); err != nil { - return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), configv1alpha1.CouldNotFetchKeyStrategyReason) + return c.failStrategyAndErr(ctx.Context, credIssuer, firstErr(depErr, err), conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason) } if depErr != nil { // if we get here, it means that we have successfully loaded a signing key but failed to reconcile the deployment. // mark the status as failed and re-kick the sync loop until we are happy with the state of the deployment. - return c.failStrategyAndErr(ctx.Context, credIssuer, depErr, configv1alpha1.CouldNotFetchKeyStrategyReason) + return c.failStrategyAndErr(ctx.Context, credIssuer, depErr, conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason) } // Set the CredentialIssuer strategy to successful. - return issuerconfig.Update(ctx.Context, c.client.PinnipedConcierge, credIssuer, configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.SuccessStrategyStatus, - Reason: configv1alpha1.FetchedKeyStrategyReason, + return issuerconfig.Update(ctx.Context, c.client.PinnipedConcierge, credIssuer, conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.FetchedKeyStrategyReason, Message: "key was fetched successfully", LastUpdateTime: metav1.NewTime(c.clock.Now()), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.TokenCredentialRequestAPIFrontendType, + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, TokenCredentialRequestAPIInfo: apiInfo, }, }) @@ -454,10 +454,10 @@ func (c *agentController) createOrUpdateDeployment(ctx controllerlib.Context, ne return err } -func (c *agentController) failStrategyAndErr(ctx context.Context, credIssuer *configv1alpha1.CredentialIssuer, err error, reason configv1alpha1.StrategyReason) error { - updateErr := issuerconfig.Update(ctx, c.client.PinnipedConcierge, credIssuer, configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, +func (c *agentController) failStrategyAndErr(ctx context.Context, credIssuer *conciergeconfigv1alpha1.CredentialIssuer, err error, reason conciergeconfigv1alpha1.StrategyReason) error { + updateErr := issuerconfig.Update(ctx, c.client.PinnipedConcierge, credIssuer, conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, Reason: reason, Message: err.Error(), LastUpdateTime: metav1.NewTime(c.clock.Now()), @@ -465,7 +465,7 @@ func (c *agentController) failStrategyAndErr(ctx context.Context, credIssuer *co return utilerrors.NewAggregate([]error{err, updateErr}) } -func (c *agentController) extractAPIInfo(configMap *corev1.ConfigMap) (*configv1alpha1.TokenCredentialRequestAPIInfo, error) { +func (c *agentController) extractAPIInfo(configMap *corev1.ConfigMap) (*conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo, error) { kubeConfigYAML, kubeConfigPresent := configMap.Data[clusterInfoConfigMapKey] if !kubeConfigPresent { return nil, fmt.Errorf("missing %q key", clusterInfoConfigMapKey) @@ -478,7 +478,7 @@ func (c *agentController) extractAPIInfo(configMap *corev1.ConfigMap) (*configv1 } for _, v := range kubeconfig.Clusters { - result := &configv1alpha1.TokenCredentialRequestAPIInfo{ + result := &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: v.Server, CertificateAuthorityData: base64.StdEncoding.EncodeToString(v.CertificateAuthorityData), } diff --git a/internal/controller/kubecertagent/kubecertagent_test.go b/internal/controller/kubecertagent/kubecertagent_test.go index 3f7e38010..5a9d9160f 100644 --- a/internal/controller/kubecertagent/kubecertagent_test.go +++ b/internal/controller/kubecertagent/kubecertagent_test.go @@ -28,7 +28,7 @@ import ( clocktesting "k8s.io/utils/clock/testing" "k8s.io/utils/ptr" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" conciergefake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" conciergeinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" "go.pinniped.dev/internal/controller/kubecertagent/mocks" @@ -45,7 +45,7 @@ func TestAgentController(t *testing.T) { t.Parallel() now := time.Date(2021, 4, 13, 9, 57, 0, 0, time.UTC) - initialCredentialIssuer := &configv1alpha1.CredentialIssuer{ + initialCredentialIssuer := &conciergeconfigv1alpha1.CredentialIssuer{ ObjectMeta: metav1.ObjectMeta{Name: "pinniped-concierge-config"}, } @@ -247,7 +247,7 @@ func TestAgentController(t *testing.T) { wantAgentDeployment *appsv1.Deployment wantDeploymentActionVerbs []string wantDeploymentDeleteActionOpts []metav1.DeleteOptions - wantStrategy *configv1alpha1.CredentialIssuerStrategy + wantStrategy *conciergeconfigv1alpha1.CredentialIssuerStrategy }{ { name: "no CredentialIssuer found", @@ -273,10 +273,10 @@ func TestAgentController(t *testing.T) { "could not find a healthy kube-controller-manager pod (0 candidates): " + "note that this error is the expected behavior for some cluster types, including most cloud provider clusters (e.g. GKE, AKS, EKS)", }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not find a healthy kube-controller-manager pod (0 candidates): " + "note that this error is the expected behavior for some cluster types, including most cloud provider clusters (e.g. GKE, AKS, EKS)", LastUpdateTime: metav1.NewTime(now), @@ -317,10 +317,10 @@ func TestAgentController(t *testing.T) { wantDistinctErrors: []string{ "could not find a healthy kube-controller-manager pod (2 candidates)", }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not find a healthy kube-controller-manager pod (2 candidates)", LastUpdateTime: metav1.NewTime(now), }, @@ -344,10 +344,10 @@ func TestAgentController(t *testing.T) { wantDistinctLogs: []string{ `{"level":"info","timestamp":"2099-08-08T13:57:36.123456Z","logger":"kube-cert-agent-controller","caller":"kubecertagent/kubecertagent.go:$kubecertagent.(*agentController).createOrUpdateDeployment","message":"creating new deployment","deployment":{"name":"pinniped-concierge-kube-cert-agent","namespace":"concierge"},"templatePod":{"name":"kube-controller-manager-1","namespace":"kube-system"}}`, }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not ensure agent deployment: some creation error", LastUpdateTime: metav1.NewTime(now), }, @@ -393,10 +393,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch", "create"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not find a healthy agent pod (1 candidate)", LastUpdateTime: metav1.NewTime(now), }, @@ -442,10 +442,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeploymentWithDefaultedPaths, wantDeploymentActionVerbs: []string{"list", "watch", "create"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not find a healthy agent pod (1 candidate)", LastUpdateTime: metav1.NewTime(now), }, @@ -472,10 +472,10 @@ func TestAgentController(t *testing.T) { wantDeploymentDeleteActionOpts: []metav1.DeleteOptions{ testutil.NewPreconditions(healthyAgentDeploymentWithOldStyleSelector.UID, healthyAgentDeploymentWithOldStyleSelector.ResourceVersion), }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not find a healthy agent pod (1 candidate)", LastUpdateTime: metav1.NewTime(now), }, @@ -508,10 +508,10 @@ func TestAgentController(t *testing.T) { testutil.NewPreconditions(healthyAgentDeploymentWithOldStyleSelector.UID, healthyAgentDeploymentWithOldStyleSelector.ResourceVersion), testutil.NewPreconditions(healthyAgentDeploymentWithOldStyleSelector.UID, healthyAgentDeploymentWithOldStyleSelector.ResourceVersion), }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not ensure agent deployment: some delete error", LastUpdateTime: metav1.NewTime(now), }, @@ -545,10 +545,10 @@ func TestAgentController(t *testing.T) { wantDeploymentDeleteActionOpts: []metav1.DeleteOptions{ testutil.NewPreconditions(healthyAgentDeploymentWithOldStyleSelector.UID, healthyAgentDeploymentWithOldStyleSelector.ResourceVersion), }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not ensure agent deployment: some create error", LastUpdateTime: metav1.NewTime(now), }, @@ -591,10 +591,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeploymentWithExtraLabels, wantDeploymentActionVerbs: []string{"list", "watch", "update"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not find a healthy agent pod (1 candidate)", LastUpdateTime: metav1.NewTime(now), }, @@ -614,10 +614,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeploymentWithHostNetwork, wantDeploymentActionVerbs: []string{"list", "watch", "update"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotGetClusterInfoStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotGetClusterInfoStrategyReason, Message: "failed to get kube-public/cluster-info configmap: configmap \"cluster-info\" not found", LastUpdateTime: metav1.NewTime(now), }, @@ -640,10 +640,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotGetClusterInfoStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotGetClusterInfoStrategyReason, Message: "failed to get kube-public/cluster-info configmap: configmap \"cluster-info\" not found", LastUpdateTime: metav1.NewTime(now), }, @@ -667,10 +667,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotGetClusterInfoStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotGetClusterInfoStrategyReason, Message: "could not extract Kubernetes API endpoint info from kube-public/cluster-info configmap: missing \"kubeconfig\" key", LastUpdateTime: metav1.NewTime(now), }, @@ -694,10 +694,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotGetClusterInfoStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotGetClusterInfoStrategyReason, Message: "could not extract Kubernetes API endpoint info from kube-public/cluster-info configmap: key \"kubeconfig\" does not contain a valid kubeconfig", LastUpdateTime: metav1.NewTime(now), }, @@ -721,10 +721,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotGetClusterInfoStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotGetClusterInfoStrategyReason, Message: "could not extract Kubernetes API endpoint info from kube-public/cluster-info configmap: kubeconfig in key \"kubeconfig\" does not contain any clusters", LastUpdateTime: metav1.NewTime(now), }, @@ -750,10 +750,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not exec into agent pod concierge/pinniped-concierge-kube-cert-agent-xyz-1234: some exec error", LastUpdateTime: metav1.NewTime(now), }, @@ -779,10 +779,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: `failed to decode signing cert/key JSON from agent pod concierge/pinniped-concierge-kube-cert-agent-xyz-1234: invalid character 'b' looking for beginning of value`, LastUpdateTime: metav1.NewTime(now), }, @@ -808,10 +808,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: `failed to decode signing cert base64 from agent pod concierge/pinniped-concierge-kube-cert-agent-xyz-1234: illegal base64 data at input byte 4`, LastUpdateTime: metav1.NewTime(now), }, @@ -837,10 +837,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: `failed to decode signing key base64 from agent pod concierge/pinniped-concierge-kube-cert-agent-xyz-1234: illegal base64 data at input byte 4`, LastUpdateTime: metav1.NewTime(now), }, @@ -869,10 +869,10 @@ func TestAgentController(t *testing.T) { }, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "failed to set signing cert/key content from agent pod concierge/pinniped-concierge-kube-cert-agent-xyz-1234: some dynamic cert error", LastUpdateTime: metav1.NewTime(now), }, @@ -895,15 +895,15 @@ func TestAgentController(t *testing.T) { wantDistinctErrors: []string{""}, wantAgentDeployment: healthyAgentDeployment, wantDeploymentActionVerbs: []string{"list", "watch"}, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.SuccessStrategyStatus, - Reason: configv1alpha1.FetchedKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.FetchedKeyStrategyReason, Message: "key was fetched successfully", LastUpdateTime: metav1.NewTime(now), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.TokenCredentialRequestAPIFrontendType, - TokenCredentialRequestAPIInfo: &configv1alpha1.TokenCredentialRequestAPIInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, + TokenCredentialRequestAPIInfo: &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: "https://test-kubernetes-endpoint.example.com", CertificateAuthorityData: "dGVzdC1rdWJlcm5ldGVzLWNh", }, @@ -941,10 +941,10 @@ func TestAgentController(t *testing.T) { testutil.NewPreconditions(healthyAgentDeploymentWithOldStyleSelector.UID, healthyAgentDeploymentWithOldStyleSelector.ResourceVersion), testutil.NewPreconditions(healthyAgentDeploymentWithOldStyleSelector.UID, healthyAgentDeploymentWithOldStyleSelector.ResourceVersion), }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.ErrorStrategyStatus, - Reason: configv1alpha1.CouldNotFetchKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.ErrorStrategyStatus, + Reason: conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, Message: "could not ensure agent deployment: some delete error", LastUpdateTime: metav1.NewTime(now), }, @@ -967,15 +967,15 @@ func TestAgentController(t *testing.T) { wantDistinctLogs: []string{ `{"level":"info","timestamp":"2099-08-08T13:57:36.123456Z","logger":"kube-cert-agent-controller","caller":"kubecertagent/kubecertagent.go:$kubecertagent.(*agentController).loadSigningKey","message":"successfully loaded signing key from agent pod into cache"}`, }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.SuccessStrategyStatus, - Reason: configv1alpha1.FetchedKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.FetchedKeyStrategyReason, Message: "key was fetched successfully", LastUpdateTime: metav1.NewTime(now), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.TokenCredentialRequestAPIFrontendType, - TokenCredentialRequestAPIInfo: &configv1alpha1.TokenCredentialRequestAPIInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, + TokenCredentialRequestAPIInfo: &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: "https://test-kubernetes-endpoint.example.com", CertificateAuthorityData: "dGVzdC1rdWJlcm5ldGVzLWNh", }, @@ -1001,15 +1001,15 @@ func TestAgentController(t *testing.T) { wantDistinctLogs: []string{ `{"level":"info","timestamp":"2099-08-08T13:57:36.123456Z","logger":"kube-cert-agent-controller","caller":"kubecertagent/kubecertagent.go:$kubecertagent.(*agentController).loadSigningKey","message":"successfully loaded signing key from agent pod into cache"}`, }, - wantStrategy: &configv1alpha1.CredentialIssuerStrategy{ - Type: configv1alpha1.KubeClusterSigningCertificateStrategyType, - Status: configv1alpha1.SuccessStrategyStatus, - Reason: configv1alpha1.FetchedKeyStrategyReason, + wantStrategy: &conciergeconfigv1alpha1.CredentialIssuerStrategy{ + Type: conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType, + Status: conciergeconfigv1alpha1.SuccessStrategyStatus, + Reason: conciergeconfigv1alpha1.FetchedKeyStrategyReason, Message: "key was fetched successfully", LastUpdateTime: metav1.NewTime(now), - Frontend: &configv1alpha1.CredentialIssuerFrontend{ - Type: configv1alpha1.TokenCredentialRequestAPIFrontendType, - TokenCredentialRequestAPIInfo: &configv1alpha1.TokenCredentialRequestAPIInfo{ + Frontend: &conciergeconfigv1alpha1.CredentialIssuerFrontend{ + Type: conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, + TokenCredentialRequestAPIInfo: &conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: "https://overridden-server.example.com/some/path", CertificateAuthorityData: "dGVzdC1rdWJlcm5ldGVzLWNh", }, diff --git a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go index 6b64a7add..0a29c06c8 100644 --- a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go +++ b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher.go @@ -20,7 +20,7 @@ import ( corev1informers "k8s.io/client-go/informers/core/v1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" - pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controller/conditionsutil" @@ -232,7 +232,7 @@ type activeDirectoryWatcherController struct { cache UpstreamActiveDirectoryIdentityProviderICache validatedSettingsCache upstreamwatchers.ValidatedSettingsCacheI ldapDialer upstreamldap.LDAPDialer - client pinnipedsupervisorclientset.Interface + client supervisorclientset.Interface activeDirectoryIdentityProviderInformer idpinformers.ActiveDirectoryIdentityProviderInformer secretInformer corev1informers.SecretInformer } @@ -240,7 +240,7 @@ type activeDirectoryWatcherController struct { // New instantiates a new controllerlib.Controller which will populate the provided UpstreamActiveDirectoryIdentityProviderICache. func New( idpCache UpstreamActiveDirectoryIdentityProviderICache, - client pinnipedsupervisorclientset.Interface, + client supervisorclientset.Interface, activeDirectoryIdentityProviderInformer idpinformers.ActiveDirectoryIdentityProviderInformer, secretInformer corev1informers.SecretInformer, withInformer pinnipedcontroller.WithInformerOptionFunc, @@ -263,7 +263,7 @@ func newInternal( idpCache UpstreamActiveDirectoryIdentityProviderICache, validatedSettingsCache upstreamwatchers.ValidatedSettingsCacheI, ldapDialer upstreamldap.LDAPDialer, - client pinnipedsupervisorclientset.Interface, + client supervisorclientset.Interface, activeDirectoryIdentityProviderInformer idpinformers.ActiveDirectoryIdentityProviderInformer, secretInformer corev1informers.SecretInformer, withInformer pinnipedcontroller.WithInformerOptionFunc, diff --git a/internal/controller/supervisorconfig/federation_domain_watcher.go b/internal/controller/supervisorconfig/federation_domain_watcher.go index 664f29e6f..99eb66a02 100644 --- a/internal/controller/supervisorconfig/federation_domain_watcher.go +++ b/internal/controller/supervisorconfig/federation_domain_watcher.go @@ -22,7 +22,7 @@ import ( "k8s.io/utils/clock" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" "go.pinniped.dev/internal/celtransformer" @@ -82,7 +82,7 @@ type federationDomainWatcherController struct { federationDomainsSetter FederationDomainsSetter apiGroup string clock clock.Clock - client pinnipedsupervisorclientset.Interface + client supervisorclientset.Interface federationDomainInformer configinformers.FederationDomainInformer oidcIdentityProviderInformer idpinformers.OIDCIdentityProviderInformer @@ -99,7 +99,7 @@ func NewFederationDomainWatcherController( federationDomainsSetter FederationDomainsSetter, apiGroupSuffix string, clock clock.Clock, - client pinnipedsupervisorclientset.Interface, + client supervisorclientset.Interface, federationDomainInformer configinformers.FederationDomainInformer, oidcIdentityProviderInformer idpinformers.OIDCIdentityProviderInformer, ldapIdentityProviderInformer idpinformers.LDAPIdentityProviderInformer, diff --git a/internal/controller/supervisorconfig/generator/federation_domain_secrets.go b/internal/controller/supervisorconfig/generator/federation_domain_secrets.go index b4dae4fe2..ac9db77ca 100644 --- a/internal/controller/supervisorconfig/generator/federation_domain_secrets.go +++ b/internal/controller/supervisorconfig/generator/federation_domain_secrets.go @@ -17,7 +17,7 @@ import ( "k8s.io/klog/v2" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controllerlib" @@ -28,7 +28,7 @@ type federationDomainSecretsController struct { secretHelper SecretHelper secretRefFunc func(domain *supervisorconfigv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference kubeClient kubernetes.Interface - pinnipedClient pinnipedsupervisorclientset.Interface + pinnipedClient supervisorclientset.Interface federationDomainInformer configinformers.FederationDomainInformer secretInformer corev1informers.SecretInformer } @@ -40,7 +40,7 @@ func NewFederationDomainSecretsController( secretHelper SecretHelper, secretRefFunc func(domain *supervisorconfigv1alpha1.FederationDomainStatus) *corev1.LocalObjectReference, kubeClient kubernetes.Interface, - pinnipedClient pinnipedsupervisorclientset.Interface, + pinnipedClient supervisorclientset.Interface, secretInformer corev1informers.SecretInformer, federationDomainInformer configinformers.FederationDomainInformer, withInformer pinnipedcontroller.WithInformerOptionFunc, diff --git a/internal/controller/supervisorconfig/jwks_writer.go b/internal/controller/supervisorconfig/jwks_writer.go index 8379796e5..c15a7fb9b 100644 --- a/internal/controller/supervisorconfig/jwks_writer.go +++ b/internal/controller/supervisorconfig/jwks_writer.go @@ -23,7 +23,7 @@ import ( "k8s.io/klog/v2" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" configinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/config/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controller/supervisorconfig/generator" @@ -60,7 +60,7 @@ func generateECKey(r io.Reader) (any, error) { // secrets, both via a cache and via the API. type jwksWriterController struct { jwksSecretLabels map[string]string - pinnipedClient pinnipedsupervisorclientset.Interface + pinnipedClient supervisorclientset.Interface kubeClient kubernetes.Interface federationDomainInformer configinformers.FederationDomainInformer secretInformer corev1informers.SecretInformer @@ -71,7 +71,7 @@ type jwksWriterController struct { func NewJWKSWriterController( jwksSecretLabels map[string]string, kubeClient kubernetes.Interface, - pinnipedClient pinnipedsupervisorclientset.Interface, + pinnipedClient supervisorclientset.Interface, secretInformer corev1informers.SecretInformer, federationDomainInformer configinformers.FederationDomainInformer, withInformer pinnipedcontroller.WithInformerOptionFunc, diff --git a/internal/kubeclient/kubeclient.go b/internal/kubeclient/kubeclient.go index e1ba1681f..6c70eea9f 100644 --- a/internal/kubeclient/kubeclient.go +++ b/internal/kubeclient/kubeclient.go @@ -19,18 +19,18 @@ import ( aggregatorclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset" aggregatorclientscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" - pinnipedconciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" - pinnipedconciergeclientsetscheme "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme" - pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" - pinnipedsupervisorclientsetscheme "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme" + conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" + conciergeclientsetscheme "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme" + supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + supervisorclientsetscheme "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme" "go.pinniped.dev/internal/crypto/ptls" ) type Client struct { Kubernetes kubernetes.Interface Aggregation aggregatorclient.Interface - PinnipedConcierge pinnipedconciergeclientset.Interface - PinnipedSupervisor pinnipedsupervisorclientset.Interface + PinnipedConcierge conciergeclientset.Interface + PinnipedSupervisor supervisorclientset.Interface JSONConfig, ProtoConfig *restclient.Config } @@ -79,7 +79,7 @@ func New(opts ...Option) (*Client, error) { // Connect to the pinniped concierge API. // We cannot use protobuf encoding here because we are using CRDs // (for which protobuf encoding is not yet supported). - pinnipedConciergeClient, err := pinnipedconciergeclientset.NewForConfig(configWithWrapper(jsonKubeConfig, pinnipedconciergeclientsetscheme.Scheme, pinnipedconciergeclientsetscheme.Codecs, c.middlewares, c.transportWrapper)) + pinnipedConciergeClient, err := conciergeclientset.NewForConfig(configWithWrapper(jsonKubeConfig, conciergeclientsetscheme.Scheme, conciergeclientsetscheme.Codecs, c.middlewares, c.transportWrapper)) if err != nil { return nil, fmt.Errorf("could not initialize pinniped client: %w", err) } @@ -87,7 +87,7 @@ func New(opts ...Option) (*Client, error) { // Connect to the pinniped supervisor API. // We cannot use protobuf encoding here because we are using CRDs // (for which protobuf encoding is not yet supported). - pinnipedSupervisorClient, err := pinnipedsupervisorclientset.NewForConfig(configWithWrapper(jsonKubeConfig, pinnipedsupervisorclientsetscheme.Scheme, pinnipedsupervisorclientsetscheme.Codecs, c.middlewares, c.transportWrapper)) + pinnipedSupervisorClient, err := supervisorclientset.NewForConfig(configWithWrapper(jsonKubeConfig, supervisorclientsetscheme.Scheme, supervisorclientsetscheme.Codecs, c.middlewares, c.transportWrapper)) if err != nil { return nil, fmt.Errorf("could not initialize pinniped client: %w", err) } diff --git a/internal/kubeclient/scheme_test.go b/internal/kubeclient/scheme_test.go index 314f352d6..9d641b4b0 100644 --- a/internal/kubeclient/scheme_test.go +++ b/internal/kubeclient/scheme_test.go @@ -16,8 +16,8 @@ import ( loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" - pinnipedconciergeclientsetscheme "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme" - pinnipedsupervisorclientsetscheme "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme" + conciergeclientsetscheme "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme" + supervisorclientsetscheme "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme" ) func Test_schemeRestMapper(t *testing.T) { @@ -96,7 +96,7 @@ func Test_schemeRestMapper(t *testing.T) { { name: "token credential delete", args: args{ - scheme: pinnipedconciergeclientsetscheme.Scheme, + scheme: conciergeclientsetscheme.Scheme, gvr: loginv1alpha1.SchemeGroupVersion.WithResource("tokencredentialrequests"), v: VerbDelete, }, @@ -105,7 +105,7 @@ func Test_schemeRestMapper(t *testing.T) { { name: "token credential list", args: args{ - scheme: pinnipedconciergeclientsetscheme.Scheme, + scheme: conciergeclientsetscheme.Scheme, gvr: loginv1alpha1.SchemeGroupVersion.WithResource("tokencredentialrequests"), v: VerbList, }, @@ -114,7 +114,7 @@ func Test_schemeRestMapper(t *testing.T) { { name: "oidc idp update", args: args{ - scheme: pinnipedsupervisorclientsetscheme.Scheme, + scheme: supervisorclientsetscheme.Scheme, gvr: idpv1alpha1.SchemeGroupVersion.WithResource("oidcidentityproviders"), v: VerbUpdate, }, @@ -123,7 +123,7 @@ func Test_schemeRestMapper(t *testing.T) { { name: "oidc idp list", args: args{ - scheme: pinnipedsupervisorclientsetscheme.Scheme, + scheme: supervisorclientsetscheme.Scheme, gvr: idpv1alpha1.SchemeGroupVersion.WithResource("oidcidentityproviders"), v: VerbList, }, @@ -132,7 +132,7 @@ func Test_schemeRestMapper(t *testing.T) { { name: "oidc idp list - wrong scheme", args: args{ - scheme: pinnipedconciergeclientsetscheme.Scheme, + scheme: conciergeclientsetscheme.Scheme, gvr: idpv1alpha1.SchemeGroupVersion.WithResource("oidcidentityproviders"), v: VerbList, }, diff --git a/internal/supervisor/server/server.go b/internal/supervisor/server/server.go index 2ee1b5753..3dd56bafd 100644 --- a/internal/supervisor/server/server.go +++ b/internal/supervisor/server/server.go @@ -39,7 +39,7 @@ import ( "k8s.io/utils/clock" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/typed/config/v1alpha1" supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" supervisoropenapi "go.pinniped.dev/generated/latest/client/supervisor/openapi" @@ -141,7 +141,7 @@ func prepareControllers( secretCache *secret.Cache, supervisorDeployment *appsv1.Deployment, kubeClient kubernetes.Interface, - pinnipedClient pinnipedsupervisorclientset.Interface, + pinnipedClient supervisorclientset.Interface, aggregatorClient aggregatorclient.Interface, kubeInformers k8sinformers.SharedInformerFactory, pinnipedInformers supervisorinformers.SharedInformerFactory, diff --git a/internal/testutil/fakekubeapi/fakekubeapi.go b/internal/testutil/fakekubeapi/fakekubeapi.go index fc6b6d4c1..3c8b5a0cf 100644 --- a/internal/testutil/fakekubeapi/fakekubeapi.go +++ b/internal/testutil/fakekubeapi/fakekubeapi.go @@ -37,8 +37,8 @@ import ( restclient "k8s.io/client-go/rest" aggregatorclientscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" - pinnipedconciergeclientsetscheme "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme" - pinnipedsupervisorclientsetscheme "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme" + conciergeclientsetscheme "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme" + supervisorclientsetscheme "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme" "go.pinniped.dev/internal/crypto/ptls" "go.pinniped.dev/internal/httputil/httperr" "go.pinniped.dev/internal/testutil/tlsserver" @@ -117,8 +117,8 @@ func decodeObj(r *http.Request) (runtime.Object, error) { codecsThatWeUseInOurCode := []runtime.NegotiatedSerializer{ kubescheme.Codecs, aggregatorclientscheme.Codecs, - pinnipedconciergeclientsetscheme.Codecs, - pinnipedsupervisorclientsetscheme.Codecs, + conciergeclientsetscheme.Codecs, + supervisorclientsetscheme.Codecs, } for _, codec := range codecsThatWeUseInOurCode { obj, err = tryDecodeObj(mediaType, body, codec) diff --git a/test/integration/concierge_credentialissuer_test.go b/test/integration/concierge_credentialissuer_test.go index c7edd1388..3ebb5de06 100644 --- a/test/integration/concierge_credentialissuer_test.go +++ b/test/integration/concierge_credentialissuer_test.go @@ -13,7 +13,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" - configv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" "go.pinniped.dev/test/testlib" ) @@ -57,9 +57,9 @@ func TestCredentialIssuer(t *testing.T) { // The details of the ImpersonationProxy type is tested by a different integration test for the impersonator. // Grab the KubeClusterSigningCertificate result so we can check it in detail below. - var actualStatusStrategy configv1alpha1.CredentialIssuerStrategy + var actualStatusStrategy conciergeconfigv1alpha1.CredentialIssuerStrategy for _, s := range actualStatusStrategies { - if s.Type == configv1alpha1.KubeClusterSigningCertificateStrategyType { + if s.Type == conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType { actualStatusStrategy = s break } @@ -67,12 +67,12 @@ func TestCredentialIssuer(t *testing.T) { require.NotNil(t, actualStatusStrategy) if env.HasCapability(testlib.ClusterSigningKeyIsAvailable) { - require.Equal(t, configv1alpha1.SuccessStrategyStatus, actualStatusStrategy.Status) - require.Equal(t, configv1alpha1.FetchedKeyStrategyReason, actualStatusStrategy.Reason) + require.Equal(t, conciergeconfigv1alpha1.SuccessStrategyStatus, actualStatusStrategy.Status) + require.Equal(t, conciergeconfigv1alpha1.FetchedKeyStrategyReason, actualStatusStrategy.Reason) require.Equal(t, "key was fetched successfully", actualStatusStrategy.Message) require.NotNil(t, actualStatusStrategy.Frontend) - require.Equal(t, configv1alpha1.TokenCredentialRequestAPIFrontendType, actualStatusStrategy.Frontend.Type) - expectedTokenRequestAPIInfo := configv1alpha1.TokenCredentialRequestAPIInfo{ + require.Equal(t, conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType, actualStatusStrategy.Frontend.Type) + expectedTokenRequestAPIInfo := conciergeconfigv1alpha1.TokenCredentialRequestAPIInfo{ Server: config.Host, CertificateAuthorityData: base64.StdEncoding.EncodeToString(config.TLSClientConfig.CAData), } @@ -81,15 +81,15 @@ func TestCredentialIssuer(t *testing.T) { // Verify the published kube config info. require.Equal( t, - &configv1alpha1.CredentialIssuerKubeConfigInfo{ + &conciergeconfigv1alpha1.CredentialIssuerKubeConfigInfo{ Server: expectedTokenRequestAPIInfo.Server, CertificateAuthorityData: expectedTokenRequestAPIInfo.CertificateAuthorityData, }, actualStatusKubeConfigInfo, ) } else { - require.Equal(t, configv1alpha1.ErrorStrategyStatus, actualStatusStrategy.Status) - require.Equal(t, configv1alpha1.CouldNotFetchKeyStrategyReason, actualStatusStrategy.Reason) + require.Equal(t, conciergeconfigv1alpha1.ErrorStrategyStatus, actualStatusStrategy.Status) + require.Equal(t, conciergeconfigv1alpha1.CouldNotFetchKeyStrategyReason, actualStatusStrategy.Reason) require.Contains(t, actualStatusStrategy.Message, "could not find a healthy kube-controller-manager pod (0 candidates): "+ "note that this error is the expected behavior for some cluster types, including most cloud provider clusters (e.g. GKE, AKS, EKS)") require.Nil(t, actualStatusKubeConfigInfo) diff --git a/test/integration/concierge_impersonation_proxy_test.go b/test/integration/concierge_impersonation_proxy_test.go index 98f6cd2f0..a3edddc25 100644 --- a/test/integration/concierge_impersonation_proxy_test.go +++ b/test/integration/concierge_impersonation_proxy_test.go @@ -62,10 +62,10 @@ import ( "k8s.io/utils/ptr" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" - conciergev1alpha "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" identityv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/identity/v1alpha1" loginv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/login/v1alpha1" - pinnipedconciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" + conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/crypto/ptls" "go.pinniped.dev/internal/httputil/roundtripper" @@ -132,7 +132,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl mostRecentTokenCredentialRequestResponseLock sync.Mutex ) - refreshCredentialHelper := func(t *testing.T, client pinnipedconciergeclientset.Interface) *loginv1alpha1.ClusterCredential { + refreshCredentialHelper := func(t *testing.T, client conciergeclientset.Interface) *loginv1alpha1.ClusterCredential { t.Helper() mostRecentTokenCredentialRequestResponseLock.Lock() @@ -209,11 +209,11 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl switch { case impersonatorShouldHaveStartedAutomaticallyByDefault && clusterSupportsLoadBalancers: // configure the credential issuer spec to have the impersonation proxy in auto mode - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeAuto, - Service: conciergev1alpha.ImpersonationProxyServiceSpec{ - Type: conciergev1alpha.ImpersonationProxyServiceTypeLoadBalancer, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeAuto, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeLoadBalancer, Annotations: map[string]string{ "service.beta.kubernetes.io/aws-load-balancer-connection-idle-timeout": "4000", }, @@ -241,9 +241,9 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl requireDisabledStrategy(ctx, t, env, adminConciergeClient) // Create configuration to make the impersonation proxy turn on with no endpoint (i.e. automatically create a load balancer). - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeEnabled, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, }, }) @@ -267,12 +267,12 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl require.Truef(t, isErr, "wanted error %q to be service unavailable via squid error, but: %s", err, message) // Create configuration to make the impersonation proxy turn on with a hard coded endpoint (without a load balancer). - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeEnabled, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: proxyServiceEndpoint, - Service: conciergev1alpha.ImpersonationProxyServiceSpec{ - Type: conciergev1alpha.ImpersonationProxyServiceTypeClusterIP, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }) @@ -1759,12 +1759,12 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl t.Skip("Skipping ClusterIP test because squid proxy is not present") } clusterIPServiceURL := fmt.Sprintf("%s.%s.svc.cluster.local", impersonationProxyClusterIPName(env), env.ConciergeNamespace) - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeEnabled, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: clusterIPServiceURL, - Service: conciergev1alpha.ImpersonationProxyServiceSpec{ - Type: conciergev1alpha.ImpersonationProxyServiceTypeClusterIP, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }) @@ -1815,12 +1815,12 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl t.Cleanup(func() { // Remove the TLS block from the CredentialIssuer, which should revert the ImpersonationProxy to using an // internally generated TLS serving cert derived from the original CA. - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeEnabled, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: proxyServiceEndpoint, - Service: conciergev1alpha.ImpersonationProxyServiceSpec{ - Type: conciergev1alpha.ImpersonationProxyServiceTypeClusterIP, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }) @@ -1833,14 +1833,14 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl }, 2*time.Minute, 500*time.Millisecond) }) - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeEnabled, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: proxyServiceEndpoint, - Service: conciergev1alpha.ImpersonationProxyServiceSpec{ - Type: conciergev1alpha.ImpersonationProxyServiceTypeClusterIP, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, - TLS: &conciergev1alpha.ImpersonationProxyTLSSpec{ + TLS: &conciergeconfigv1alpha1.ImpersonationProxyTLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(externallyProvidedCA.Bundle()), SecretName: externallyProvidedTLSServingCertSecret.Name, }, @@ -1887,12 +1887,12 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl t.Cleanup(func() { // Remove the TLS block from the CredentialIssuer, which should revert the ImpersonationProxy to using an // internally generated TLS serving cert derived from the original CA. - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeEnabled, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: proxyServiceEndpoint, - Service: conciergev1alpha.ImpersonationProxyServiceSpec{ - Type: conciergev1alpha.ImpersonationProxyServiceTypeClusterIP, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, }, }) @@ -1905,14 +1905,14 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl }, 2*time.Minute, 500*time.Millisecond) }) - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeEnabled, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeEnabled, ExternalEndpoint: proxyServiceEndpoint, - Service: conciergev1alpha.ImpersonationProxyServiceSpec{ - Type: conciergev1alpha.ImpersonationProxyServiceTypeClusterIP, + Service: conciergeconfigv1alpha1.ImpersonationProxyServiceSpec{ + Type: conciergeconfigv1alpha1.ImpersonationProxyServiceTypeClusterIP, }, - TLS: &conciergev1alpha.ImpersonationProxyTLSSpec{ + TLS: &conciergeconfigv1alpha1.ImpersonationProxyTLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(externallyProvidedCA.Bundle()), SecretName: externallyProvidedTLSServingCertSecret.Name, }, @@ -1934,9 +1934,9 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl t.Run("manually disabling the impersonation proxy feature", func(t *testing.T) { // Update configuration to force the proxy to disabled mode - updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergev1alpha.CredentialIssuerSpec{ - ImpersonationProxy: &conciergev1alpha.ImpersonationProxySpec{ - Mode: conciergev1alpha.ImpersonationProxyModeDisabled, + updateCredentialIssuer(ctx, t, env, adminConciergeClient, conciergeconfigv1alpha1.CredentialIssuerSpec{ + ImpersonationProxy: &conciergeconfigv1alpha1.ImpersonationProxySpec{ + Mode: conciergeconfigv1alpha1.ImpersonationProxyModeDisabled, }, }) @@ -2101,7 +2101,7 @@ func expectedWhoAmIRequestResponse(username string, groups []string, extra map[s } func performImpersonatorDiscovery(ctx context.Context, t *testing.T, env *testlib.TestEnv, - adminClient kubernetes.Interface, adminConciergeClient pinnipedconciergeclientset.Interface, + adminClient kubernetes.Interface, adminConciergeClient conciergeclientset.Interface, refreshCredential func(t *testing.T, impersonationProxyURL string, impersonationProxyCACertPEM []byte) *loginv1alpha1.ClusterCredential) (string, []byte) { t.Helper() @@ -2157,7 +2157,7 @@ func performImpersonatorDiscovery(ctx context.Context, t *testing.T, env *testli return impersonationProxyURL, impersonationProxyCACertPEM } -func performImpersonatorDiscoveryURL(ctx context.Context, t *testing.T, env *testlib.TestEnv, adminConciergeClient pinnipedconciergeclientset.Interface) (string, []byte) { +func performImpersonatorDiscoveryURL(ctx context.Context, t *testing.T, env *testlib.TestEnv, adminConciergeClient conciergeclientset.Interface) (string, []byte) { t.Helper() var impersonationProxyURL string @@ -2173,7 +2173,7 @@ func performImpersonatorDiscoveryURL(ctx context.Context, t *testing.T, env *tes } for _, strategy := range credentialIssuer.Status.Strategies { // There will be other strategy types in the list, so ignore those. - if strategy.Type == conciergev1alpha.ImpersonationProxyStrategyType && strategy.Status == conciergev1alpha.SuccessStrategyStatus { //nolint:nestif + if strategy.Type == conciergeconfigv1alpha1.ImpersonationProxyStrategyType && strategy.Status == conciergeconfigv1alpha1.SuccessStrategyStatus { //nolint:nestif if strategy.Frontend == nil { return false, fmt.Errorf("did not find a Frontend") // unexpected, fail the test } @@ -2187,10 +2187,10 @@ func performImpersonatorDiscoveryURL(ctx context.Context, t *testing.T, env *tes return false, err // unexpected, fail the test } return true, nil // found it, continue the test! - } else if strategy.Type == conciergev1alpha.ImpersonationProxyStrategyType { + } else if strategy.Type == conciergeconfigv1alpha1.ImpersonationProxyStrategyType { t.Logf("Waiting for successful impersonation proxy strategy on %s: found status %s with reason %s and message: %s", credentialIssuerName(env), strategy.Status, strategy.Reason, strategy.Message) - if strategy.Reason == conciergev1alpha.ErrorDuringSetupStrategyReason { + if strategy.Reason == conciergeconfigv1alpha1.ErrorDuringSetupStrategyReason { // The server encountered an unexpected error while starting the impersonator, so fail the test fast. return false, fmt.Errorf("found impersonation strategy in %s state with message: %s", strategy.Reason, strategy.Message) } @@ -2204,7 +2204,7 @@ func performImpersonatorDiscoveryURL(ctx context.Context, t *testing.T, env *tes return impersonationProxyURL, impersonationProxyCACertPEM } -func requireDisabledStrategy(ctx context.Context, t *testing.T, env *testlib.TestEnv, adminConciergeClient pinnipedconciergeclientset.Interface) { +func requireDisabledStrategy(ctx context.Context, t *testing.T, env *testlib.TestEnv, adminConciergeClient conciergeclientset.Interface) { t.Helper() testlib.RequireEventuallyWithoutError(t, func() (bool, error) { @@ -2215,14 +2215,14 @@ func requireDisabledStrategy(ctx context.Context, t *testing.T, env *testlib.Tes } for _, strategy := range credentialIssuer.Status.Strategies { // There will be other strategy types in the list, so ignore those. - if strategy.Type == conciergev1alpha.ImpersonationProxyStrategyType && - strategy.Status == conciergev1alpha.ErrorStrategyStatus && - strategy.Reason == conciergev1alpha.DisabledStrategyReason { + if strategy.Type == conciergeconfigv1alpha1.ImpersonationProxyStrategyType && + strategy.Status == conciergeconfigv1alpha1.ErrorStrategyStatus && + strategy.Reason == conciergeconfigv1alpha1.DisabledStrategyReason { return true, nil // found it, continue the test! - } else if strategy.Type == conciergev1alpha.ImpersonationProxyStrategyType { + } else if strategy.Type == conciergeconfigv1alpha1.ImpersonationProxyStrategyType { t.Logf("Waiting for disabled impersonation proxy strategy on %s: found status %s with reason %s and message: %s", credentialIssuerName(env), strategy.Status, strategy.Reason, strategy.Message) - if strategy.Reason == conciergev1alpha.ErrorDuringSetupStrategyReason { + if strategy.Reason == conciergeconfigv1alpha1.ErrorDuringSetupStrategyReason { // The server encountered an unexpected error while stopping the impersonator, so fail the test fast. return false, fmt.Errorf("found impersonation strategy in %s state with message: %s", strategy.Reason, strategy.Message) } @@ -2283,7 +2283,7 @@ func kubeconfigProxyFunc(t *testing.T, squidProxyURL string) func(req *http.Requ } } -func updateCredentialIssuer(ctx context.Context, t *testing.T, env *testlib.TestEnv, adminConciergeClient pinnipedconciergeclientset.Interface, spec conciergev1alpha.CredentialIssuerSpec) { +func updateCredentialIssuer(ctx context.Context, t *testing.T, env *testlib.TestEnv, adminConciergeClient conciergeclientset.Interface, spec conciergeconfigv1alpha1.CredentialIssuerSpec) { t.Helper() err := retry.RetryOnConflict(retry.DefaultRetry, func() error { @@ -2445,7 +2445,7 @@ func requireClose(t *testing.T, c chan struct{}, timeout time.Duration) { func createTokenCredentialRequest( spec loginv1alpha1.TokenCredentialRequestSpec, - client pinnipedconciergeclientset.Interface, + client conciergeclientset.Interface, ) (*loginv1alpha1.TokenCredentialRequest, error) { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() diff --git a/test/integration/concierge_kubecertagent_test.go b/test/integration/concierge_kubecertagent_test.go index b306da99f..12c778a77 100644 --- a/test/integration/concierge_kubecertagent_test.go +++ b/test/integration/concierge_kubecertagent_test.go @@ -16,7 +16,7 @@ import ( "k8s.io/apimachinery/pkg/labels" "k8s.io/utils/ptr" - conciergev1alpha "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" + conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" "go.pinniped.dev/test/testlib" ) @@ -60,7 +60,7 @@ func TestKubeCertAgent(t *testing.T) { } // If there's no successful strategy yet, wait until there is. - strategy := findSuccessfulStrategy(credentialIssuer, conciergev1alpha.KubeClusterSigningCertificateStrategyType) + strategy := findSuccessfulStrategy(credentialIssuer, conciergeconfigv1alpha1.KubeClusterSigningCertificateStrategyType) if strategy == nil { t.Log("could not find a successful TokenCredentialRequestAPI strategy in the CredentialIssuer:") for _, s := range credentialIssuer.Status.Strategies { @@ -73,19 +73,19 @@ func TestKubeCertAgent(t *testing.T) { if strategy.Frontend == nil { return false, fmt.Errorf("strategy did not find a Frontend") } - if strategy.Frontend.Type != conciergev1alpha.TokenCredentialRequestAPIFrontendType { + if strategy.Frontend.Type != conciergeconfigv1alpha1.TokenCredentialRequestAPIFrontendType { return false, fmt.Errorf("strategy had unexpected frontend type %q", strategy.Frontend.Type) } return true, nil }, 3*time.Minute, 2*time.Second) } -func findSuccessfulStrategy(credentialIssuer *conciergev1alpha.CredentialIssuer, strategyType conciergev1alpha.StrategyType) *conciergev1alpha.CredentialIssuerStrategy { +func findSuccessfulStrategy(credentialIssuer *conciergeconfigv1alpha1.CredentialIssuer, strategyType conciergeconfigv1alpha1.StrategyType) *conciergeconfigv1alpha1.CredentialIssuerStrategy { for _, strategy := range credentialIssuer.Status.Strategies { if strategy.Type != strategyType { continue } - if strategy.Status != conciergev1alpha.SuccessStrategyStatus { + if strategy.Status != conciergeconfigv1alpha1.SuccessStrategyStatus { continue } return &strategy diff --git a/test/testlib/client.go b/test/testlib/client.go index cf5cac9a9..13f642f13 100644 --- a/test/testlib/client.go +++ b/test/testlib/client.go @@ -33,7 +33,7 @@ import ( supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" - pinnipedsupervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" + supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" "go.pinniped.dev/internal/groupsuffix" "go.pinniped.dev/internal/kubeclient" @@ -80,13 +80,13 @@ func NewKubernetesClientset(t *testing.T) kubernetes.Interface { return NewKubeclient(t, NewClientConfig(t)).Kubernetes } -func NewSupervisorClientset(t *testing.T) pinnipedsupervisorclientset.Interface { +func NewSupervisorClientset(t *testing.T) supervisorclientset.Interface { t.Helper() return NewKubeclient(t, NewClientConfig(t)).PinnipedSupervisor } -func NewAnonymousSupervisorClientset(t *testing.T) pinnipedsupervisorclientset.Interface { +func NewAnonymousSupervisorClientset(t *testing.T) supervisorclientset.Interface { t.Helper() return NewKubeclient(t, NewAnonymousClientRestConfig(t)).PinnipedSupervisor From bdd79a998439ad2b88a973f0a692b633cdcf5279 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Sun, 12 May 2024 18:30:52 -0500 Subject: [PATCH 06/10] Enforce more imports - go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake - go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake - go.pinniped.dev/generated/latest/client/concierge/informers/externalversions - go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions --- .golangci.yaml | 12 ++++--- cmd/pinniped/cmd/kubeconfig_test.go | 6 ++-- cmd/pinniped/cmd/whoami_test.go | 4 +-- .../cachecleaner/cachecleaner_test.go | 8 ++--- .../jwtcachefiller/jwtcachefiller_test.go | 12 +++---- .../webhookcachefiller_test.go | 12 +++---- .../impersonator_config_test.go | 20 +++++------ .../active_directory_upstream_watcher_test.go | 16 ++++----- .../federation_domain_watcher_test.go | 24 ++++++------- .../federation_domain_secrets_test.go | 36 +++++++++---------- .../supervisorconfig/jwks_observer_test.go | 14 ++++---- .../supervisorconfig/jwks_writer_test.go | 24 ++++++------- .../ldap_upstream_watcher_test.go | 16 ++++----- .../oidc_client_watcher_test.go | 18 +++++----- .../oidc_upstream_watcher_test.go | 12 +++---- .../tls_cert_observer_test.go | 14 ++++---- 16 files changed, 126 insertions(+), 122 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 3219728ad..a9a4923a3 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -127,16 +127,20 @@ linters-settings: alias: conciergeclientset - pkg: go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme alias: conciergeclientsetscheme -# - pkg: go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake -# alias: conciergefake + - pkg: go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake + alias: conciergefake - pkg: go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned alias: supervisorclientset - pkg: go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme alias: supervisorclientsetscheme -# - pkg: go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake -# alias: supervisorfake + - pkg: go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake + alias: supervisorfake - pkg: go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1 alias: idpv1alpha1 + - pkg: go.pinniped.dev/generated/latest/client/concierge/informers/externalversions + alias: conciergeinformers + - pkg: go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions + alias: supervisorinformers # Pinniped internal - pkg: go.pinniped.dev/internal/concierge/scheme alias: conciergescheme diff --git a/cmd/pinniped/cmd/kubeconfig_test.go b/cmd/pinniped/cmd/kubeconfig_test.go index 035060472..3e0ae2687 100644 --- a/cmd/pinniped/cmd/kubeconfig_test.go +++ b/cmd/pinniped/cmd/kubeconfig_test.go @@ -23,7 +23,7 @@ import ( authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" - fakeconciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" + conciergefake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/here" "go.pinniped.dev/internal/testutil" @@ -3247,9 +3247,9 @@ func TestGetKubeconfig(t *testing.T) { if tt.getClientsetErr != nil { return nil, tt.getClientsetErr } - fake := fakeconciergeclientset.NewSimpleClientset() + fake := conciergefake.NewSimpleClientset() if tt.conciergeObjects != nil { - fake = fakeconciergeclientset.NewSimpleClientset(tt.conciergeObjects(string(testServerCA), testServer.URL)...) + fake = conciergefake.NewSimpleClientset(tt.conciergeObjects(string(testServerCA), testServer.URL)...) } if len(tt.conciergeReactions) > 0 { fake.ReactionChain = append(tt.conciergeReactions, fake.ReactionChain...) diff --git a/cmd/pinniped/cmd/whoami_test.go b/cmd/pinniped/cmd/whoami_test.go index e40bd15ca..408f34879 100644 --- a/cmd/pinniped/cmd/whoami_test.go +++ b/cmd/pinniped/cmd/whoami_test.go @@ -15,7 +15,7 @@ import ( identityv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/identity/v1alpha1" conciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned" - fakeconciergeclientset "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" + conciergefake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" "go.pinniped.dev/internal/constable" "go.pinniped.dev/internal/here" ) @@ -284,7 +284,7 @@ func TestWhoami(t *testing.T) { if test.gettingClientsetErr != nil { return nil, test.gettingClientsetErr } - clientset := fakeconciergeclientset.NewSimpleClientset() + clientset := conciergefake.NewSimpleClientset() clientset.PrependReactor("create", "whoamirequests", func(_ kubetesting.Action) (bool, runtime.Object, error) { if test.callingAPIErr != nil { return true, nil, test.callingAPIErr diff --git a/internal/controller/authenticator/cachecleaner/cachecleaner_test.go b/internal/controller/authenticator/cachecleaner/cachecleaner_test.go index c72068829..8837d9483 100644 --- a/internal/controller/authenticator/cachecleaner/cachecleaner_test.go +++ b/internal/controller/authenticator/cachecleaner/cachecleaner_test.go @@ -13,8 +13,8 @@ import ( "k8s.io/apiserver/pkg/authentication/authenticator" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" + conciergefake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" + conciergeinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" controllerAuthenticator "go.pinniped.dev/internal/controller/authenticator" "go.pinniped.dev/internal/controller/authenticator/authncache" "go.pinniped.dev/internal/controllerlib" @@ -136,8 +136,8 @@ func TestController(t *testing.T) { t.Run(tt.name, func(t *testing.T) { // When we have t.Parallel() here, this test blocks pretty consistently...y tho? - fakeClient := pinnipedfake.NewSimpleClientset(tt.objects...) - informers := pinnipedinformers.NewSharedInformerFactory(fakeClient, 0) + fakeClient := conciergefake.NewSimpleClientset(tt.objects...) + informers := conciergeinformers.NewSharedInformerFactory(fakeClient, 0) cache := authncache.New() if tt.initialCache != nil { tt.initialCache(t, cache) diff --git a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go index 6126716b1..deff9907b 100644 --- a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go +++ b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go @@ -34,8 +34,8 @@ import ( clocktesting "k8s.io/utils/clock/testing" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" + conciergefake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" + conciergeinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" "go.pinniped.dev/internal/controller/authenticator/authncache" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/crypto/ptls" @@ -581,7 +581,7 @@ func TestController(t *testing.T) { syncKey controllerlib.Key jwtAuthenticators []runtime.Object // for modifying the clients to hack in arbitrary api responses - configClient func(*pinnipedfake.Clientset) + configClient func(*conciergefake.Clientset) wantClose bool // Only errors that are non-config related errors are returned from the sync loop. // Errors such as url.Parse of the issuer are not returned as they imply a user error. @@ -1612,7 +1612,7 @@ func TestController(t *testing.T) { }, }, syncKey: controllerlib.Key{Name: "test-name"}, - configClient: func(client *pinnipedfake.Clientset) { + configClient: func(client *conciergefake.Clientset) { client.PrependReactor( "update", "jwtauthenticators", @@ -1666,11 +1666,11 @@ func TestController(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - pinnipedAPIClient := pinnipedfake.NewSimpleClientset(tt.jwtAuthenticators...) + pinnipedAPIClient := conciergefake.NewSimpleClientset(tt.jwtAuthenticators...) if tt.configClient != nil { tt.configClient(pinnipedAPIClient) } - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(pinnipedAPIClient, 0) + pinnipedInformers := conciergeinformers.NewSharedInformerFactory(pinnipedAPIClient, 0) cache := authncache.New() var log bytes.Buffer diff --git a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go index 53da3ce83..e923f0ebb 100644 --- a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go +++ b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go @@ -29,8 +29,8 @@ import ( "k8s.io/utils/ptr" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" + conciergefake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" + conciergeinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/controller/authenticator/authncache" "go.pinniped.dev/internal/controllerlib" @@ -363,7 +363,7 @@ func TestController(t *testing.T) { syncKey controllerlib.Key webhooks []runtime.Object // for modifying the clients to hack in arbitrary api responses - configClient func(*pinnipedfake.Clientset) + configClient func(*conciergefake.Clientset) wantSyncLoopErr testutil.RequireErrorStringFunc wantLogs []map[string]any wantActions func() []coretesting.Action @@ -1245,7 +1245,7 @@ func TestController(t *testing.T) { { name: "updateStatus: when update request fails: error will enqueue a resync", syncKey: controllerlib.Key{Name: "test-name"}, - configClient: func(client *pinnipedfake.Clientset) { + configClient: func(client *conciergefake.Clientset) { client.PrependReactor( "update", "webhookauthenticators", @@ -1309,11 +1309,11 @@ func TestController(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - pinnipedAPIClient := pinnipedfake.NewSimpleClientset(tt.webhooks...) + pinnipedAPIClient := conciergefake.NewSimpleClientset(tt.webhooks...) if tt.configClient != nil { tt.configClient(pinnipedAPIClient) } - informers := pinnipedinformers.NewSharedInformerFactory(pinnipedAPIClient, 0) + informers := conciergeinformers.NewSharedInformerFactory(pinnipedAPIClient, 0) cache := authncache.New() var log bytes.Buffer diff --git a/internal/controller/impersonatorconfig/impersonator_config_test.go b/internal/controller/impersonatorconfig/impersonator_config_test.go index ae40ee11e..19956387c 100644 --- a/internal/controller/impersonatorconfig/impersonator_config_test.go +++ b/internal/controller/impersonatorconfig/impersonator_config_test.go @@ -36,8 +36,8 @@ import ( clocktesting "k8s.io/utils/clock/testing" conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" + conciergefake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" + conciergeinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/controller/apicerts" "go.pinniped.dev/internal/controllerlib" @@ -68,7 +68,7 @@ func TestImpersonatorConfigControllerOptions(t *testing.T) { it.Before(func() { r = require.New(t) observableWithInformerOption = testutil.NewObservableWithInformerOption() - pinnipedInformerFactory := pinnipedinformers.NewSharedInformerFactory(nil, 0) + pinnipedInformerFactory := conciergeinformers.NewSharedInformerFactory(nil, 0) sharedInformerFactory := k8sinformers.NewSharedInformerFactory(nil, 0) credIssuerInformer := pinnipedInformerFactory.Config().V1alpha1().CredentialIssuers() servicesInformer := sharedInformerFactory.Core().V1().Services() @@ -281,9 +281,9 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { var subject controllerlib.Controller var kubeAPIClient *kubernetesfake.Clientset - var pinnipedAPIClient *pinnipedfake.Clientset - var pinnipedInformerClient *pinnipedfake.Clientset - var pinnipedInformers pinnipedinformers.SharedInformerFactory + var pinnipedAPIClient *conciergefake.Clientset + var pinnipedInformerClient *conciergefake.Clientset + var pinnipedInformers conciergeinformers.SharedInformerFactory var kubeInformerClient *kubernetesfake.Clientset var kubeInformers k8sinformers.SharedInformerFactory var cancelContext context.Context @@ -609,7 +609,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { controllerlib.TestRunSynchronously(t, subject) } - var addCredentialIssuerToTrackers = func(credIssuer conciergeconfigv1alpha1.CredentialIssuer, informerClient *pinnipedfake.Clientset, mainClient *pinnipedfake.Clientset) { + var addCredentialIssuerToTrackers = func(credIssuer conciergeconfigv1alpha1.CredentialIssuer, informerClient *conciergefake.Clientset, mainClient *conciergefake.Clientset) { t.Logf("adding CredentialIssuer %s to informer and main clientsets", credIssuer.Name) r.NoError(informerClient.Tracker().Add(&credIssuer)) r.NoError(mainClient.Tracker().Add(&credIssuer)) @@ -1123,15 +1123,15 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { queue = &testQueue{} cancelContext, cancelContextCancelFunc = context.WithCancel(context.Background()) - pinnipedInformerClient = pinnipedfake.NewSimpleClientset() - pinnipedInformers = pinnipedinformers.NewSharedInformerFactoryWithOptions(pinnipedInformerClient, 0) + pinnipedInformerClient = conciergefake.NewSimpleClientset() + pinnipedInformers = conciergeinformers.NewSharedInformerFactoryWithOptions(pinnipedInformerClient, 0) kubeInformerClient = kubernetesfake.NewSimpleClientset() kubeInformers = k8sinformers.NewSharedInformerFactoryWithOptions(kubeInformerClient, 0, k8sinformers.WithNamespace(installedInNamespace), ) kubeAPIClient = kubernetesfake.NewSimpleClientset() - pinnipedAPIClient = pinnipedfake.NewSimpleClientset() + pinnipedAPIClient = conciergefake.NewSimpleClientset() frozenNow = time.Date(2021, time.March, 2, 7, 42, 0, 0, time.Local) mTLSClientCertProvider = dynamiccert.NewCA(name) diff --git a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher_test.go b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher_test.go index 3b8aa9b2b..c8bded274 100644 --- a/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher_test.go +++ b/internal/controller/supervisorconfig/activedirectoryupstreamwatcher/active_directory_upstream_watcher_test.go @@ -23,8 +23,8 @@ import ( "k8s.io/client-go/kubernetes/fake" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/controller/supervisorconfig/upstreamwatchers" "go.pinniped.dev/internal/controllerlib" @@ -74,8 +74,8 @@ func TestActiveDirectoryUpstreamWatcherControllerFilterSecrets(t *testing.T) { t.Run(test.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset() - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset() + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClient, 0) activeDirectoryIDPInformer := pinnipedInformers.IDP().V1alpha1().ActiveDirectoryIdentityProviders() fakeKubeClient := fake.NewSimpleClientset() kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) @@ -118,8 +118,8 @@ func TestActiveDirectoryUpstreamWatcherControllerFilterActiveDirectoryIdentityPr t.Run(test.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset() - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset() + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClient, 0) activeDirectoryIDPInformer := pinnipedInformers.IDP().V1alpha1().ActiveDirectoryIdentityProviders() fakeKubeClient := fake.NewSimpleClientset() kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) @@ -2003,8 +2003,8 @@ func TestActiveDirectoryUpstreamWatcherControllerSync(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset(tt.inputUpstreams...) - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset(tt.inputUpstreams...) + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClient, 0) fakeKubeClient := fake.NewSimpleClientset(tt.inputSecrets...) kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) cache := dynamicupstreamprovider.NewDynamicUpstreamIDPProvider() diff --git a/internal/controller/supervisorconfig/federation_domain_watcher_test.go b/internal/controller/supervisorconfig/federation_domain_watcher_test.go index 2190d533f..d51c4f61b 100644 --- a/internal/controller/supervisorconfig/federation_domain_watcher_test.go +++ b/internal/controller/supervisorconfig/federation_domain_watcher_test.go @@ -24,8 +24,8 @@ import ( supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/celtransformer" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/federationdomain/federationdomainproviders" @@ -38,10 +38,10 @@ import ( func TestFederationDomainWatcherControllerInformerFilters(t *testing.T) { t.Parallel() - federationDomainInformer := pinnipedinformers.NewSharedInformerFactoryWithOptions(nil, 0).Config().V1alpha1().FederationDomains() - oidcIdentityProviderInformer := pinnipedinformers.NewSharedInformerFactoryWithOptions(nil, 0).IDP().V1alpha1().OIDCIdentityProviders() - ldapIdentityProviderInformer := pinnipedinformers.NewSharedInformerFactoryWithOptions(nil, 0).IDP().V1alpha1().LDAPIdentityProviders() - adIdentityProviderInformer := pinnipedinformers.NewSharedInformerFactoryWithOptions(nil, 0).IDP().V1alpha1().ActiveDirectoryIdentityProviders() + federationDomainInformer := supervisorinformers.NewSharedInformerFactoryWithOptions(nil, 0).Config().V1alpha1().FederationDomains() + oidcIdentityProviderInformer := supervisorinformers.NewSharedInformerFactoryWithOptions(nil, 0).IDP().V1alpha1().OIDCIdentityProviders() + ldapIdentityProviderInformer := supervisorinformers.NewSharedInformerFactoryWithOptions(nil, 0).IDP().V1alpha1().LDAPIdentityProviders() + adIdentityProviderInformer := supervisorinformers.NewSharedInformerFactoryWithOptions(nil, 0).IDP().V1alpha1().ActiveDirectoryIdentityProviders() tests := []struct { name string @@ -521,7 +521,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { tests := []struct { name string inputObjects []runtime.Object - configClient func(*pinnipedfake.Clientset) + configClient func(*supervisorfake.Clientset) wantErr string wantStatusUpdates []*supervisorconfigv1alpha1.FederationDomain wantFDIssuers []*federationdomainproviders.FederationDomainIssuer @@ -671,7 +671,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomain2, oidcIdentityProvider, }, - configClient: func(client *pinnipedfake.Clientset) { + configClient: func(client *supervisorfake.Clientset) { client.PrependReactor( "update", "federationdomains", @@ -736,7 +736,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomain2, oidcIdentityProvider, }, - configClient: func(client *pinnipedfake.Clientset) { + configClient: func(client *supervisorfake.Clientset) { client.PrependReactor( "update", "federationdomains", @@ -2002,8 +2002,8 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { t.Parallel() federationDomainsSetter := &fakeFederationDomainsSetter{} - pinnipedAPIClient := pinnipedfake.NewSimpleClientset() - pinnipedInformerClient := pinnipedfake.NewSimpleClientset() + pinnipedAPIClient := supervisorfake.NewSimpleClientset() + pinnipedInformerClient := supervisorfake.NewSimpleClientset() for _, o := range tt.inputObjects { require.NoError(t, pinnipedAPIClient.Tracker().Add(o)) require.NoError(t, pinnipedInformerClient.Tracker().Add(o)) @@ -2011,7 +2011,7 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { if tt.configClient != nil { tt.configClient(pinnipedAPIClient) } - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(pinnipedInformerClient, 0) + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(pinnipedInformerClient, 0) controller := NewFederationDomainWatcherController( federationDomainsSetter, diff --git a/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go b/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go index 8abd82f58..9d58a5809 100644 --- a/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go +++ b/internal/controller/supervisorconfig/generator/federation_domain_secrets_test.go @@ -23,8 +23,8 @@ import ( kubetesting "k8s.io/client-go/testing" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/mocks/mocksecrethelper" "go.pinniped.dev/internal/testutil" @@ -183,8 +183,8 @@ func TestFederationDomainControllerFilterSecret(t *testing.T) { kubernetesfake.NewSimpleClientset(), 0, ).Core().V1().Secrets() - federationDomainInformer := pinnipedinformers.NewSharedInformerFactory( - pinnipedfake.NewSimpleClientset(), + federationDomainInformer := supervisorinformers.NewSharedInformerFactory( + supervisorfake.NewSimpleClientset(), 0, ).Config().V1alpha1().FederationDomains() withInformer := testutil.NewObservableWithInformerOption() @@ -245,8 +245,8 @@ func TestNewFederationDomainSecretsControllerFilterFederationDomain(t *testing.T kubernetesfake.NewSimpleClientset(), 0, ).Core().V1().Secrets() - federationDomainInformer := pinnipedinformers.NewSharedInformerFactory( - pinnipedfake.NewSimpleClientset(), + federationDomainInformer := supervisorinformers.NewSharedInformerFactory( + supervisorfake.NewSimpleClientset(), 0, ).Config().V1alpha1().FederationDomains() withInformer := testutil.NewObservableWithInformerOption() @@ -360,7 +360,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { tests := []struct { name string storage func(**supervisorconfigv1alpha1.FederationDomain, **corev1.Secret) - client func(*pinnipedfake.Clientset, *kubernetesfake.Clientset) + client func(*supervisorfake.Clientset, *kubernetesfake.Clientset) secretHelper func(*mocksecrethelper.MockSecretHelper) wantFederationDomainActions []kubetesting.Action wantSecretActions []kubetesting.Action @@ -406,7 +406,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { secretHelper.EXPECT().Generate(goodFederationDomain).Times(1).Return(goodSecret, nil) secretHelper.EXPECT().ObserveActiveSecretAndUpdateParentFederationDomain(goodFederationDomain, goodSecret).Times(1).Return(goodFederationDomainWithTokenSigningKey) }, - client: func(c *pinnipedfake.Clientset, _ *kubernetesfake.Clientset) { + client: func(c *supervisorfake.Clientset, _ *kubernetesfake.Clientset) { c.PrependReactor("get", "federationdomains", func(_ kubetesting.Action) (bool, runtime.Object, error) { return true, goodFederationDomainWithJWKS, nil }) @@ -429,7 +429,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { secretHelper.EXPECT().Generate(goodFederationDomain).Times(1).Return(goodSecret, nil) secretHelper.EXPECT().ObserveActiveSecretAndUpdateParentFederationDomain(goodFederationDomain, goodSecret).Times(1).Return(goodFederationDomainWithTokenSigningKey) }, - client: func(c *pinnipedfake.Clientset, _ *kubernetesfake.Clientset) { + client: func(c *supervisorfake.Clientset, _ *kubernetesfake.Clientset) { c.PrependReactor("get", "federationdomains", func(_ kubetesting.Action) (bool, runtime.Object, error) { return true, goodFederationDomainWithJWKSAndTokenSigningKey, nil }) @@ -493,7 +493,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { secretHelper.EXPECT().Generate(goodFederationDomain).Times(1).Return(goodSecret, nil) secretHelper.EXPECT().IsValid(goodFederationDomain, goodSecret).Times(1).Return(false) }, - client: func(_ *pinnipedfake.Clientset, c *kubernetesfake.Clientset) { + client: func(_ *supervisorfake.Clientset, c *kubernetesfake.Clientset) { c.PrependReactor("get", "secrets", func(_ kubetesting.Action) (bool, runtime.Object, error) { return true, nil, errors.New("some get error") }) @@ -511,7 +511,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { secretHelper: func(secretHelper *mocksecrethelper.MockSecretHelper) { secretHelper.EXPECT().Generate(goodFederationDomain).Times(1).Return(goodSecret, nil) }, - client: func(_ *pinnipedfake.Clientset, c *kubernetesfake.Clientset) { + client: func(_ *supervisorfake.Clientset, c *kubernetesfake.Clientset) { c.PrependReactor("create", "secrets", func(_ kubetesting.Action) (bool, runtime.Object, error) { return true, nil, errors.New("some create error") }) @@ -528,7 +528,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { secretHelper.EXPECT().Generate(goodFederationDomain).Times(1).Return(goodSecret, nil) secretHelper.EXPECT().IsValid(goodFederationDomain, goodSecret).Times(2).Return(false) }, - client: func(_ *pinnipedfake.Clientset, c *kubernetesfake.Clientset) { + client: func(_ *supervisorfake.Clientset, c *kubernetesfake.Clientset) { c.PrependReactor("update", "secrets", func(_ kubetesting.Action) (bool, runtime.Object, error) { return true, nil, errors.New("some update error") }) @@ -549,7 +549,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { secretHelper.EXPECT().IsValid(goodFederationDomain, invalidSecret).Times(3).Return(false) secretHelper.EXPECT().ObserveActiveSecretAndUpdateParentFederationDomain(goodFederationDomain, goodSecret).Times(1).Return(goodFederationDomainWithTokenSigningKey) }, - client: func(_ *pinnipedfake.Clientset, c *kubernetesfake.Clientset) { + client: func(_ *supervisorfake.Clientset, c *kubernetesfake.Clientset) { once := sync.Once{} c.PrependReactor("update", "secrets", func(_ kubetesting.Action) (bool, runtime.Object, error) { var err error @@ -578,7 +578,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { secretHelper.EXPECT().IsValid(goodFederationDomain, invalidSecret).Times(2).Return(false) secretHelper.EXPECT().ObserveActiveSecretAndUpdateParentFederationDomain(goodFederationDomain, goodSecret).Times(1).Return(goodFederationDomainWithTokenSigningKey) }, - client: func(c *pinnipedfake.Clientset, _ *kubernetesfake.Clientset) { + client: func(c *supervisorfake.Clientset, _ *kubernetesfake.Clientset) { c.PrependReactor("get", "federationdomains", func(_ kubetesting.Action) (bool, runtime.Object, error) { return true, nil, errors.New("some get error") }) @@ -602,7 +602,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { secretHelper.EXPECT().IsValid(goodFederationDomain, invalidSecret).Times(2).Return(false) secretHelper.EXPECT().ObserveActiveSecretAndUpdateParentFederationDomain(goodFederationDomain, goodSecret).Times(1).Return(goodFederationDomainWithTokenSigningKey) }, - client: func(c *pinnipedfake.Clientset, _ *kubernetesfake.Clientset) { + client: func(c *supervisorfake.Clientset, _ *kubernetesfake.Clientset) { once := sync.Once{} c.PrependReactor("update", "federationdomains", func(_ kubetesting.Action) (bool, runtime.Object, error) { var err error @@ -629,8 +629,8 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - pinnipedAPIClient := pinnipedfake.NewSimpleClientset() - pinnipedInformerClient := pinnipedfake.NewSimpleClientset() + pinnipedAPIClient := supervisorfake.NewSimpleClientset() + pinnipedInformerClient := supervisorfake.NewSimpleClientset() kubeAPIClient := kubernetesfake.NewSimpleClientset() kubeInformerClient := kubernetesfake.NewSimpleClientset() @@ -657,7 +657,7 @@ func TestFederationDomainSecretsControllerSync(t *testing.T) { kubeInformerClient, 0, ) - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory( + pinnipedInformers := supervisorinformers.NewSharedInformerFactory( pinnipedInformerClient, 0, ) diff --git a/internal/controller/supervisorconfig/jwks_observer_test.go b/internal/controller/supervisorconfig/jwks_observer_test.go index 60d8cbb91..7cfb04a72 100644 --- a/internal/controller/supervisorconfig/jwks_observer_test.go +++ b/internal/controller/supervisorconfig/jwks_observer_test.go @@ -18,8 +18,8 @@ import ( kubernetesfake "k8s.io/client-go/kubernetes/fake" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/testutil" ) @@ -37,7 +37,7 @@ func TestJWKSObserverControllerInformerFilters(t *testing.T) { r = require.New(t) observableWithInformerOption = testutil.NewObservableWithInformerOption() secretsInformer := k8sinformers.NewSharedInformerFactory(nil, 0).Core().V1().Secrets() - federationDomainInformer := pinnipedinformers.NewSharedInformerFactory(nil, 0).Config().V1alpha1().FederationDomains() + federationDomainInformer := supervisorinformers.NewSharedInformerFactory(nil, 0).Config().V1alpha1().FederationDomains() _ = NewJWKSObserverController( nil, secretsInformer, @@ -125,9 +125,9 @@ func TestJWKSObserverControllerSync(t *testing.T) { var ( r *require.Assertions subject controllerlib.Controller - pinnipedInformerClient *pinnipedfake.Clientset + pinnipedInformerClient *supervisorfake.Clientset kubeInformerClient *kubernetesfake.Clientset - pinnipedInformers pinnipedinformers.SharedInformerFactory + pinnipedInformers supervisorinformers.SharedInformerFactory kubeInformers k8sinformers.SharedInformerFactory cancelContext context.Context cancelContextCancelFunc context.CancelFunc @@ -169,8 +169,8 @@ func TestJWKSObserverControllerSync(t *testing.T) { kubeInformerClient = kubernetesfake.NewSimpleClientset() kubeInformers = k8sinformers.NewSharedInformerFactory(kubeInformerClient, 0) - pinnipedInformerClient = pinnipedfake.NewSimpleClientset() - pinnipedInformers = pinnipedinformers.NewSharedInformerFactory(pinnipedInformerClient, 0) + pinnipedInformerClient = supervisorfake.NewSimpleClientset() + pinnipedInformers = supervisorinformers.NewSharedInformerFactory(pinnipedInformerClient, 0) issuerToJWKSSetter = &fakeIssuerToJWKSMapSetter{} unrelatedSecret := &corev1.Secret{ diff --git a/internal/controller/supervisorconfig/jwks_writer_test.go b/internal/controller/supervisorconfig/jwks_writer_test.go index 247f6df56..e28bc5951 100644 --- a/internal/controller/supervisorconfig/jwks_writer_test.go +++ b/internal/controller/supervisorconfig/jwks_writer_test.go @@ -23,8 +23,8 @@ import ( kubetesting "k8s.io/client-go/testing" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/testutil" ) @@ -174,8 +174,8 @@ func TestJWKSWriterControllerFilterSecret(t *testing.T) { kubernetesfake.NewSimpleClientset(), 0, ).Core().V1().Secrets() - federationDomainInformer := pinnipedinformers.NewSharedInformerFactory( - pinnipedfake.NewSimpleClientset(), + federationDomainInformer := supervisorinformers.NewSharedInformerFactory( + supervisorfake.NewSimpleClientset(), 0, ).Config().V1alpha1().FederationDomains() withInformer := testutil.NewObservableWithInformerOption() @@ -227,8 +227,8 @@ func TestJWKSWriterControllerFilterFederationDomain(t *testing.T) { kubernetesfake.NewSimpleClientset(), 0, ).Core().V1().Secrets() - federationDomainInformer := pinnipedinformers.NewSharedInformerFactory( - pinnipedfake.NewSimpleClientset(), + federationDomainInformer := supervisorinformers.NewSharedInformerFactory( + supervisorfake.NewSimpleClientset(), 0, ).Config().V1alpha1().FederationDomains() withInformer := testutil.NewObservableWithInformerOption() @@ -331,7 +331,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { key controllerlib.Key secrets []*corev1.Secret configKubeClient func(*kubernetesfake.Clientset) - configPinnipedClient func(*pinnipedfake.Clientset) + configPinnipedClient func(*supervisorfake.Clientset) federationDomains []*supervisorconfigv1alpha1.FederationDomain generateKeyErr error wantGenerateKeyCount int @@ -640,7 +640,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, - configPinnipedClient: func(client *pinnipedfake.Clientset) { + configPinnipedClient: func(client *supervisorfake.Clientset) { client.PrependReactor("get", "federationdomains", func(_ kubetesting.Action) (bool, runtime.Object, error) { return true, nil, errors.New("some get error") }) @@ -653,7 +653,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { federationDomains: []*supervisorconfigv1alpha1.FederationDomain{ goodFederationDomain, }, - configPinnipedClient: func(client *pinnipedfake.Clientset) { + configPinnipedClient: func(client *supervisorfake.Clientset) { client.PrependReactor("update", "federationdomains", func(_ kubetesting.Action) (bool, runtime.Object, error) { return true, nil, errors.New("some update error") }) @@ -683,8 +683,8 @@ func TestJWKSWriterControllerSync(t *testing.T) { test.configKubeClient(kubeAPIClient) } - pinnipedAPIClient := pinnipedfake.NewSimpleClientset() - pinnipedInformerClient := pinnipedfake.NewSimpleClientset() + pinnipedAPIClient := supervisorfake.NewSimpleClientset() + pinnipedInformerClient := supervisorfake.NewSimpleClientset() for _, federationDomain := range test.federationDomains { require.NoError(t, pinnipedAPIClient.Tracker().Add(federationDomain)) require.NoError(t, pinnipedInformerClient.Tracker().Add(federationDomain)) @@ -697,7 +697,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { kubeInformerClient, 0, ) - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory( + pinnipedInformers := supervisorinformers.NewSharedInformerFactory( pinnipedInformerClient, 0, ) diff --git a/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher_test.go b/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher_test.go index b42068912..c5f313d4a 100644 --- a/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher_test.go +++ b/internal/controller/supervisorconfig/ldapupstreamwatcher/ldap_upstream_watcher_test.go @@ -22,8 +22,8 @@ import ( "k8s.io/client-go/kubernetes/fake" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/controller/supervisorconfig/upstreamwatchers" "go.pinniped.dev/internal/controllerlib" @@ -73,8 +73,8 @@ func TestLDAPUpstreamWatcherControllerFilterSecrets(t *testing.T) { t.Run(test.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset() - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset() + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClient, 0) ldapIDPInformer := pinnipedInformers.IDP().V1alpha1().LDAPIdentityProviders() fakeKubeClient := fake.NewSimpleClientset() kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) @@ -117,8 +117,8 @@ func TestLDAPUpstreamWatcherControllerFilterLDAPIdentityProviders(t *testing.T) t.Run(test.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset() - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset() + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClient, 0) ldapIDPInformer := pinnipedInformers.IDP().V1alpha1().LDAPIdentityProviders() fakeKubeClient := fake.NewSimpleClientset() kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) @@ -1132,8 +1132,8 @@ func TestLDAPUpstreamWatcherControllerSync(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset(tt.inputUpstreams...) - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset(tt.inputUpstreams...) + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClient, 0) fakeKubeClient := fake.NewSimpleClientset(tt.inputSecrets...) kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) cache := dynamicupstreamprovider.NewDynamicUpstreamIDPProvider() diff --git a/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher_test.go b/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher_test.go index 7e4aadf9a..ba64c71d8 100644 --- a/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher_test.go +++ b/internal/controller/supervisorconfig/oidcclientwatcher/oidc_client_watcher_test.go @@ -17,8 +17,8 @@ import ( kubernetesfake "k8s.io/client-go/kubernetes/fake" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/testutil" ) @@ -66,8 +66,8 @@ func TestOIDCClientWatcherControllerFilterSecret(t *testing.T) { kubernetesfake.NewSimpleClientset(), 0, ).Core().V1().Secrets() - oidcClientsInformer := pinnipedinformers.NewSharedInformerFactory( - pinnipedfake.NewSimpleClientset(), + oidcClientsInformer := supervisorinformers.NewSharedInformerFactory( + supervisorfake.NewSimpleClientset(), 0, ).Config().V1alpha1().OIDCClients() withInformer := testutil.NewObservableWithInformerOption() @@ -135,8 +135,8 @@ func TestOIDCClientWatcherControllerFilterOIDCClient(t *testing.T) { kubernetesfake.NewSimpleClientset(), 0, ).Core().V1().Secrets() - oidcClientsInformer := pinnipedinformers.NewSharedInformerFactory( - pinnipedfake.NewSimpleClientset(), + oidcClientsInformer := supervisorinformers.NewSharedInformerFactory( + supervisorfake.NewSimpleClientset(), 0, ).Config().V1alpha1().OIDCClients() withInformer := testutil.NewObservableWithInformerOption() @@ -956,9 +956,9 @@ func TestOIDCClientWatcherControllerSync(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset(tt.inputObjects...) - fakePinnipedClientForInformers := pinnipedfake.NewSimpleClientset(tt.inputObjects...) - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClientForInformers, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset(tt.inputObjects...) + fakePinnipedClientForInformers := supervisorfake.NewSimpleClientset(tt.inputObjects...) + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClientForInformers, 0) fakeKubeClient := kubernetesfake.NewSimpleClientset(tt.inputSecrets...) kubeInformers := k8sinformers.NewSharedInformerFactoryWithOptions(fakeKubeClient, 0) diff --git a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go index 4221eb968..ab813242d 100644 --- a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go +++ b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go @@ -24,8 +24,8 @@ import ( "k8s.io/client-go/kubernetes/fake" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/certauthority" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/federationdomain/dynamicupstreamprovider" @@ -76,8 +76,8 @@ func TestOIDCUpstreamWatcherControllerFilterSecret(t *testing.T) { t.Run(test.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset() - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset() + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClient, 0) fakeKubeClient := fake.NewSimpleClientset() kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) cache := dynamicupstreamprovider.NewDynamicUpstreamIDPProvider() @@ -1409,8 +1409,8 @@ oidc: issuer did not match the issuer returned by provider, expected "` + testIs for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - fakePinnipedClient := pinnipedfake.NewSimpleClientset(tt.inputUpstreams...) - pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) + fakePinnipedClient := supervisorfake.NewSimpleClientset(tt.inputUpstreams...) + pinnipedInformers := supervisorinformers.NewSharedInformerFactory(fakePinnipedClient, 0) fakeKubeClient := fake.NewSimpleClientset(tt.inputSecrets...) kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) testLog := testlogger.NewLegacy(t) //nolint:staticcheck // old test with lots of log statements diff --git a/internal/controller/supervisorconfig/tls_cert_observer_test.go b/internal/controller/supervisorconfig/tls_cert_observer_test.go index 01a33e865..4a019516a 100644 --- a/internal/controller/supervisorconfig/tls_cert_observer_test.go +++ b/internal/controller/supervisorconfig/tls_cert_observer_test.go @@ -19,8 +19,8 @@ import ( kubernetesfake "k8s.io/client-go/kubernetes/fake" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" - pinnipedfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/testutil" ) @@ -38,7 +38,7 @@ func TestTLSCertObserverControllerInformerFilters(t *testing.T) { r = require.New(t) observableWithInformerOption = testutil.NewObservableWithInformerOption() secretsInformer := k8sinformers.NewSharedInformerFactory(nil, 0).Core().V1().Secrets() - federationDomainInformer := pinnipedinformers.NewSharedInformerFactory(nil, 0).Config().V1alpha1().FederationDomains() + federationDomainInformer := supervisorinformers.NewSharedInformerFactory(nil, 0).Config().V1alpha1().FederationDomains() _ = NewTLSCertObserverController( nil, "", // don't care about the secret name for this test @@ -131,9 +131,9 @@ func TestTLSCertObserverControllerSync(t *testing.T) { var ( r *require.Assertions subject controllerlib.Controller - pinnipedInformerClient *pinnipedfake.Clientset + pinnipedInformerClient *supervisorfake.Clientset kubeInformerClient *kubernetesfake.Clientset - pinnipedInformers pinnipedinformers.SharedInformerFactory + pinnipedInformers supervisorinformers.SharedInformerFactory kubeInformers k8sinformers.SharedInformerFactory cancelContext context.Context cancelContextCancelFunc context.CancelFunc @@ -182,8 +182,8 @@ func TestTLSCertObserverControllerSync(t *testing.T) { kubeInformerClient = kubernetesfake.NewSimpleClientset() kubeInformers = k8sinformers.NewSharedInformerFactory(kubeInformerClient, 0) - pinnipedInformerClient = pinnipedfake.NewSimpleClientset() - pinnipedInformers = pinnipedinformers.NewSharedInformerFactory(pinnipedInformerClient, 0) + pinnipedInformerClient = supervisorfake.NewSimpleClientset() + pinnipedInformers = supervisorinformers.NewSharedInformerFactory(pinnipedInformerClient, 0) issuerTLSCertSetter = &fakeIssuerTLSCertSetter{} unrelatedSecret := &corev1.Secret{ From fe911a7b7a820d5fbd4993a5bed6e19a391b4812 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Mon, 20 May 2024 22:15:53 -0500 Subject: [PATCH 07/10] Prefer slices package and slices.Concat where possible --- cmd/pinniped/cmd/kubeconfig.go | 12 ++-- cmd/pinniped/cmd/kubeconfig_test.go | 3 +- .../controller/kubecertagent/kubecertagent.go | 3 +- .../kubecertagent/kubecertagent_test.go | 4 +- .../mocks/mockpodcommandexecutor.go | 3 +- .../downstreamsession/downstream_session.go | 2 +- .../endpoints/token/token_handler.go | 2 +- .../endpoints/token/token_handler_test.go | 2 +- internal/kubeclient/kubeclient_test.go | 3 +- internal/plog/plog.go | 13 +++-- internal/plog/zap.go | 7 ++- internal/registry/clientsecretrequest/rest.go | 5 +- .../session_storage_assertions.go | 2 +- .../testutil/testidplister/testidplister.go | 7 ++- internal/testutil/testlogger/stdr_copied.go | 3 +- internal/testutil/transcript_logger.go | 3 +- pkg/oidcclient/filesession/cachefile.go | 5 +- pkg/oidcclient/login.go | 2 +- test/integration/cli_test.go | 5 +- .../concierge_impersonation_proxy_test.go | 11 ++-- test/integration/e2e_test.go | 56 +++++++++---------- test/integration/pod_shutdown_test.go | 4 +- test/integration/supervisor_discovery_test.go | 2 +- test/integration/supervisor_login_test.go | 4 +- .../supervisor_oidcclientsecret_test.go | 6 +- test/integration/supervisor_warnings_test.go | 13 +++-- 26 files changed, 97 insertions(+), 85 deletions(-) diff --git a/cmd/pinniped/cmd/kubeconfig.go b/cmd/pinniped/cmd/kubeconfig.go index f3651bc1d..193dde6fe 100644 --- a/cmd/pinniped/cmd/kubeconfig.go +++ b/cmd/pinniped/cmd/kubeconfig.go @@ -12,6 +12,7 @@ import ( "io" "net/http" "os" + "slices" "strconv" "strings" "time" @@ -23,7 +24,6 @@ import ( _ "k8s.io/client-go/plugin/pkg/client/auth" // Adds handlers for various dynamic auth plugins in client-go "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "k8s.io/utils/strings/slices" authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" @@ -303,7 +303,7 @@ func newExecConfig(deps kubeconfigDeps, flags getKubeconfigParams) (*clientcmdap if flags.staticToken != "" && flags.staticTokenEnvName != "" { return nil, fmt.Errorf("only one of --static-token and --static-token-env can be specified") } - execConfig.Args = append([]string{"login", "static"}, execConfig.Args...) + execConfig.Args = slices.Concat([]string{"login", "static"}, execConfig.Args) if flags.staticToken != "" { execConfig.Args = append(execConfig.Args, "--token="+flags.staticToken) } @@ -314,7 +314,7 @@ func newExecConfig(deps kubeconfigDeps, flags getKubeconfigParams) (*clientcmdap } // Otherwise continue to parse the OIDC-related flags and output a config that runs `pinniped login oidc`. - execConfig.Args = append([]string{"login", "oidc"}, execConfig.Args...) + execConfig.Args = slices.Concat([]string{"login", "oidc"}, execConfig.Args) if flags.oidc.issuer == "" { return nil, fmt.Errorf("could not autodiscover --oidc-issuer and none was provided") } @@ -783,12 +783,12 @@ func pinnipedSupervisorDiscovery(ctx context.Context, flags *getKubeconfigParams return err } if !supervisorSupportsBothUsernameAndGroupsScopes { - flags.oidc.scopes = slices.Filter(nil, flags.oidc.scopes, func(scope string) bool { + flags.oidc.scopes = slices.DeleteFunc(flags.oidc.scopes, func(scope string) bool { if scope == oidcapi.ScopeUsername || scope == oidcapi.ScopeGroups { log.Info("removed scope from --oidc-scopes list because it is not supported by this Supervisor", "scope", scope) - return false // Remove username and groups scopes if there were present in the flags. + return true // Remove username and groups scopes if there were present in the flags. } - return true // Keep any other scopes in the flag list. + return false // Keep any other scopes in the flag list. }) } diff --git a/cmd/pinniped/cmd/kubeconfig_test.go b/cmd/pinniped/cmd/kubeconfig_test.go index 3e0ae2687..0e6d74f59 100644 --- a/cmd/pinniped/cmd/kubeconfig_test.go +++ b/cmd/pinniped/cmd/kubeconfig_test.go @@ -10,6 +10,7 @@ import ( "net/http" "os" "path/filepath" + "slices" "testing" "time" @@ -3252,7 +3253,7 @@ func TestGetKubeconfig(t *testing.T) { fake = conciergefake.NewSimpleClientset(tt.conciergeObjects(string(testServerCA), testServer.URL)...) } if len(tt.conciergeReactions) > 0 { - fake.ReactionChain = append(tt.conciergeReactions, fake.ReactionChain...) + fake.ReactionChain = slices.Concat(tt.conciergeReactions, fake.ReactionChain) } return fake, nil }, diff --git a/internal/controller/kubecertagent/kubecertagent.go b/internal/controller/kubecertagent/kubecertagent.go index 6a02f782a..9e02e6c3b 100644 --- a/internal/controller/kubecertagent/kubecertagent.go +++ b/internal/controller/kubecertagent/kubecertagent.go @@ -11,6 +11,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "strings" "time" @@ -609,7 +610,7 @@ func getContainerArgByName(pod *corev1.Pod, name, fallbackValue string) string { flagset.ParseErrorsWhitelist = pflag.ParseErrorsWhitelist{UnknownFlags: true} var val string flagset.StringVar(&val, name, "", "") - _ = flagset.Parse(append(container.Command, container.Args...)) + _ = flagset.Parse(slices.Concat(container.Command, container.Args)) if val != "" { return val } diff --git a/internal/controller/kubecertagent/kubecertagent_test.go b/internal/controller/kubecertagent/kubecertagent_test.go index 5a9d9160f..400a4694d 100644 --- a/internal/controller/kubecertagent/kubecertagent_test.go +++ b/internal/controller/kubecertagent/kubecertagent_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "fmt" + "slices" "testing" "time" @@ -1081,8 +1082,7 @@ func TestAgentController(t *testing.T) { actualErrors := deduplicate(errorMessages) assert.Subsetf(t, actualErrors, tt.wantDistinctErrors, "required error(s) were not found in the actual errors") - allAllowedErrors := append([]string{}, tt.wantDistinctErrors...) - allAllowedErrors = append(allAllowedErrors, tt.alsoAllowUndesiredDistinctErrors...) + allAllowedErrors := slices.Concat(tt.wantDistinctErrors, tt.alsoAllowUndesiredDistinctErrors) assert.Subsetf(t, allAllowedErrors, actualErrors, "actual errors contained additional error(s) which is not expected by the test") assert.Equal(t, tt.wantDistinctLogs, deduplicate(testutil.SplitByNewline(buf.String())), "unexpected logs") diff --git a/internal/controller/kubecertagent/mocks/mockpodcommandexecutor.go b/internal/controller/kubecertagent/mocks/mockpodcommandexecutor.go index 3bf7e753b..ef6379620 100644 --- a/internal/controller/kubecertagent/mocks/mockpodcommandexecutor.go +++ b/internal/controller/kubecertagent/mocks/mockpodcommandexecutor.go @@ -16,6 +16,7 @@ package mocks import ( context "context" reflect "reflect" + "slices" gomock "go.uber.org/mock/gomock" ) @@ -59,6 +60,6 @@ func (m *MockPodCommandExecutor) Exec(arg0 context.Context, arg1, arg2, arg3 str // Exec indicates an expected call of Exec. func (mr *MockPodCommandExecutorMockRecorder) Exec(arg0, arg1, arg2, arg3 any, arg4 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]any{arg0, arg1, arg2, arg3}, arg4...) + varargs := slices.Concat([]any{arg0, arg1, arg2, arg3}, arg4) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Exec", reflect.TypeOf((*MockPodCommandExecutor)(nil).Exec), varargs...) } diff --git a/internal/federationdomain/downstreamsession/downstream_session.go b/internal/federationdomain/downstreamsession/downstream_session.go index cf97cfdeb..bac780a75 100644 --- a/internal/federationdomain/downstreamsession/downstream_session.go +++ b/internal/federationdomain/downstreamsession/downstream_session.go @@ -7,12 +7,12 @@ package downstreamsession import ( "context" "fmt" + "slices" "time" "github.com/ory/fosite" "github.com/ory/fosite/handler/openid" "github.com/ory/fosite/token/jwt" - "k8s.io/utils/strings/slices" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" "go.pinniped.dev/internal/constable" diff --git a/internal/federationdomain/endpoints/token/token_handler.go b/internal/federationdomain/endpoints/token/token_handler.go index 1653a3cd0..50f127f14 100644 --- a/internal/federationdomain/endpoints/token/token_handler.go +++ b/internal/federationdomain/endpoints/token/token_handler.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "net/http" + "slices" "time" "github.com/ory/fosite" @@ -16,7 +17,6 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apiserver/pkg/warning" - "k8s.io/utils/strings/slices" oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc" "go.pinniped.dev/internal/federationdomain/federationdomainproviders" diff --git a/internal/federationdomain/endpoints/token/token_handler_test.go b/internal/federationdomain/endpoints/token/token_handler_test.go index 91362d651..65bb4db1f 100644 --- a/internal/federationdomain/endpoints/token/token_handler_test.go +++ b/internal/federationdomain/endpoints/token/token_handler_test.go @@ -17,6 +17,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "slices" "strings" "testing" "time" @@ -39,7 +40,6 @@ import ( "k8s.io/client-go/kubernetes/fake" v1 "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/utils/ptr" - "k8s.io/utils/strings/slices" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" diff --git a/internal/kubeclient/kubeclient_test.go b/internal/kubeclient/kubeclient_test.go index c16c9d8fb..c4b082d59 100644 --- a/internal/kubeclient/kubeclient_test.go +++ b/internal/kubeclient/kubeclient_test.go @@ -10,6 +10,7 @@ import ( "net/http" "net/url" "runtime" + "slices" "strings" "sync" "testing" @@ -1184,7 +1185,7 @@ func makeClient(t *testing.T, restConfig *rest.Config, f func(*rest.Config), opt f(restConfig) - client, err := New(append([]Option{WithConfig(restConfig)}, opts...)...) + client, err := New(slices.Concat([]Option{WithConfig(restConfig)}, opts)...) require.NoError(t, err) return client diff --git a/internal/plog/plog.go b/internal/plog/plog.go index 713887cf3..9a7d7371d 100644 --- a/internal/plog/plog.go +++ b/internal/plog/plog.go @@ -28,6 +28,7 @@ package plog import ( "os" + "slices" "github.com/go-logr/logr" ) @@ -87,7 +88,7 @@ func (p pLogger) warningDepth(msg string, depth int, keysAndValues ...any) { // Thus we use info at log level zero as a proxy // klog's info logs have an I prefix and its warning logs have a W prefix // Since we lose the W prefix by using InfoS, just add a key to make these easier to find - keysAndValues = append([]any{"warning", true}, keysAndValues...) + keysAndValues = slices.Concat([]any{"warning", true}, keysAndValues) p.logr().V(klogLevelWarning).WithCallDepth(depth+1).Info(msg, keysAndValues...) } } @@ -97,7 +98,7 @@ func (p pLogger) Warning(msg string, keysAndValues ...any) { } func (p pLogger) WarningErr(msg string, err error, keysAndValues ...any) { - p.warningDepth(msg, p.depth+1, append([]any{errorKey, err}, keysAndValues...)...) + p.warningDepth(msg, p.depth+1, slices.Concat([]any{errorKey, err}, keysAndValues)...) } func (p pLogger) infoDepth(msg string, depth int, keysAndValues ...any) { @@ -111,7 +112,7 @@ func (p pLogger) Info(msg string, keysAndValues ...any) { } func (p pLogger) InfoErr(msg string, err error, keysAndValues ...any) { - p.infoDepth(msg, p.depth+1, append([]any{errorKey, err}, keysAndValues...)...) + p.infoDepth(msg, p.depth+1, slices.Concat([]any{errorKey, err}, keysAndValues)...) } func (p pLogger) debugDepth(msg string, depth int, keysAndValues ...any) { @@ -125,7 +126,7 @@ func (p pLogger) Debug(msg string, keysAndValues ...any) { } func (p pLogger) DebugErr(msg string, err error, keysAndValues ...any) { - p.debugDepth(msg, p.depth+1, append([]any{errorKey, err}, keysAndValues...)...) + p.debugDepth(msg, p.depth+1, slices.Concat([]any{errorKey, err}, keysAndValues)...) } func (p pLogger) traceDepth(msg string, depth int, keysAndValues ...any) { @@ -139,7 +140,7 @@ func (p pLogger) Trace(msg string, keysAndValues ...any) { } func (p pLogger) TraceErr(msg string, err error, keysAndValues ...any) { - p.traceDepth(msg, p.depth+1, append([]any{errorKey, err}, keysAndValues...)...) + p.traceDepth(msg, p.depth+1, slices.Concat([]any{errorKey, err}, keysAndValues)...) } func (p pLogger) All(msg string, keysAndValues ...any) { @@ -181,7 +182,7 @@ func (p pLogger) withDepth(d int) Logger { func (p pLogger) withLogrMod(mod func(logr.Logger) logr.Logger) Logger { out := p // make a copy and carefully avoid mutating the mods slice mods := make([]func(logr.Logger) logr.Logger, 0, len(out.mods)+1) - mods = append(mods, out.mods...) + mods = slices.Concat(mods, out.mods) mods = append(mods, mod) out.mods = mods return out diff --git a/internal/plog/zap.go b/internal/plog/zap.go index 57dd16a36..2b9fa654c 100644 --- a/internal/plog/zap.go +++ b/internal/plog/zap.go @@ -1,4 +1,4 @@ -// Copyright 2020-2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package plog @@ -9,6 +9,7 @@ import ( "fmt" "io" "os" + "slices" "strings" "time" @@ -85,7 +86,7 @@ func newLogr(ctx context.Context, encoding string, klogLevel klog.Level) (logr.L if overrides.f != nil { f = overrides.f } - opts = append(opts, overrides.opts...) + opts = slices.Concat(opts, overrides.opts) } // when using the trace or all log levels, an error log will contain the full stack. @@ -96,7 +97,7 @@ func newLogr(ctx context.Context, encoding string, klogLevel klog.Level) (logr.L } func newZapr(level zap.AtomicLevel, addStack zapcore.LevelEnabler, encoding, path string, f func(config *zap.Config), opts ...zap.Option) (logr.Logger, func(), error) { - opts = append([]zap.Option{zap.AddStacktrace(addStack)}, opts...) + opts = slices.Concat([]zap.Option{zap.AddStacktrace(addStack)}, opts) config := zap.Config{ Level: level, diff --git a/internal/registry/clientsecretrequest/rest.go b/internal/registry/clientsecretrequest/rest.go index ffa66c973..27f7b5fb9 100644 --- a/internal/registry/clientsecretrequest/rest.go +++ b/internal/registry/clientsecretrequest/rest.go @@ -9,6 +9,7 @@ import ( "encoding/hex" "fmt" "io" + "slices" "strings" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -172,7 +173,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } t.Step("bcrypt.GenerateFromPassword") - hashes = append([]string{string(hash)}, hashes...) + hashes = slices.Concat([]string{string(hash)}, hashes) } // If requested, remove all client secrets except for the most recent one. @@ -267,7 +268,7 @@ func (r *REST) validateRequest( if !strings.HasPrefix(name, "client.oauth.pinniped.dev-") { errs = append(errs, `must start with 'client.oauth.pinniped.dev-'`) } - return append(errs, path.IsValidPathSegmentName(name)...) + return slices.Concat(errs, path.IsValidPathSegmentName(name)) }, field.NewPath("metadata"), ); len(errs) > 0 { diff --git a/internal/testutil/oidctestutil/session_storage_assertions.go b/internal/testutil/oidctestutil/session_storage_assertions.go index 94d2f5535..0d5f896b0 100644 --- a/internal/testutil/oidctestutil/session_storage_assertions.go +++ b/internal/testutil/oidctestutil/session_storage_assertions.go @@ -7,6 +7,7 @@ import ( "context" "net/url" "regexp" + "slices" "strings" "testing" "time" @@ -17,7 +18,6 @@ import ( "k8s.io/client-go/kubernetes/fake" v1 "k8s.io/client-go/kubernetes/typed/core/v1" kubetesting "k8s.io/client-go/testing" - "k8s.io/utils/strings/slices" "go.pinniped.dev/internal/crud" "go.pinniped.dev/internal/fositestorage/authorizationcode" diff --git a/internal/testutil/testidplister/testidplister.go b/internal/testutil/testidplister/testidplister.go index ee0f9ae82..6212ce3db 100644 --- a/internal/testutil/testidplister/testidplister.go +++ b/internal/testutil/testidplister/testidplister.go @@ -5,6 +5,7 @@ package testidplister import ( "fmt" + "slices" "testing" "github.com/stretchr/testify/require" @@ -135,17 +136,17 @@ type UpstreamIDPListerBuilder struct { } func (b *UpstreamIDPListerBuilder) WithOIDC(upstreamOIDCIdentityProviders ...*oidctestutil.TestUpstreamOIDCIdentityProvider) *UpstreamIDPListerBuilder { - b.upstreamOIDCIdentityProviders = append(b.upstreamOIDCIdentityProviders, upstreamOIDCIdentityProviders...) + b.upstreamOIDCIdentityProviders = slices.Concat(b.upstreamOIDCIdentityProviders, upstreamOIDCIdentityProviders) return b } func (b *UpstreamIDPListerBuilder) WithLDAP(upstreamLDAPIdentityProviders ...*oidctestutil.TestUpstreamLDAPIdentityProvider) *UpstreamIDPListerBuilder { - b.upstreamLDAPIdentityProviders = append(b.upstreamLDAPIdentityProviders, upstreamLDAPIdentityProviders...) + b.upstreamLDAPIdentityProviders = slices.Concat(b.upstreamLDAPIdentityProviders, upstreamLDAPIdentityProviders) return b } func (b *UpstreamIDPListerBuilder) WithActiveDirectory(upstreamActiveDirectoryIdentityProviders ...*oidctestutil.TestUpstreamLDAPIdentityProvider) *UpstreamIDPListerBuilder { - b.upstreamActiveDirectoryIdentityProviders = append(b.upstreamActiveDirectoryIdentityProviders, upstreamActiveDirectoryIdentityProviders...) + b.upstreamActiveDirectoryIdentityProviders = slices.Concat(b.upstreamActiveDirectoryIdentityProviders, upstreamActiveDirectoryIdentityProviders) return b } diff --git a/internal/testutil/testlogger/stdr_copied.go b/internal/testutil/testlogger/stdr_copied.go index eb96fac0f..b67e52efd 100644 --- a/internal/testutil/testlogger/stdr_copied.go +++ b/internal/testutil/testlogger/stdr_copied.go @@ -9,6 +9,7 @@ import ( "fmt" "log" "runtime" + "slices" "sort" "github.com/go-logr/logr" @@ -154,7 +155,7 @@ func (l logger) WithName(name string) logr.LogSink { // saved. func (l logger) WithValues(kvList ...any) logr.LogSink { lgr := l.clone() - lgr.values = append(lgr.values, kvList...) + lgr.values = slices.Concat(lgr.values, kvList) return lgr } diff --git a/internal/testutil/transcript_logger.go b/internal/testutil/transcript_logger.go index bc81c9a00..0f85c18d4 100644 --- a/internal/testutil/transcript_logger.go +++ b/internal/testutil/transcript_logger.go @@ -5,6 +5,7 @@ package testutil import ( "fmt" + "slices" "sync" "testing" @@ -33,7 +34,7 @@ func (log *TranscriptLogger) Transcript() []TranscriptLogMessage { log.lock.Lock() defer log.lock.Unlock() result := make([]TranscriptLogMessage, 0, len(log.transcript)) - result = append(result, log.transcript...) + result = slices.Concat(result, log.transcript) return result } diff --git a/pkg/oidcclient/filesession/cachefile.go b/pkg/oidcclient/filesession/cachefile.go index fb8578754..6c9bc7c6e 100644 --- a/pkg/oidcclient/filesession/cachefile.go +++ b/pkg/oidcclient/filesession/cachefile.go @@ -1,4 +1,4 @@ -// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package filesession implements the file format for session caches. @@ -9,6 +9,7 @@ import ( "fmt" "os" "reflect" + "slices" "sort" "time" @@ -153,5 +154,5 @@ func (c *sessionCache) lookup(key oidcclient.SessionCacheKey) *sessionEntry { // insert a cache entry. func (c *sessionCache) insert(entries ...sessionEntry) { - c.Sessions = append(c.Sessions, entries...) + c.Sessions = slices.Concat(c.Sessions, entries) } diff --git a/pkg/oidcclient/login.go b/pkg/oidcclient/login.go index bcaba7e50..fa1f214af 100644 --- a/pkg/oidcclient/login.go +++ b/pkg/oidcclient/login.go @@ -480,7 +480,7 @@ func (h *handlerState) baseLogin() (*oidctypes.Token, error) { return nil, err } h.loginFlow = loginFlow - authorizeOptions = append(authorizeOptions, pinnipedSupervisorOptions...) + authorizeOptions = slices.Concat(authorizeOptions, pinnipedSupervisorOptions) // Preserve the legacy behavior where browser-based auth is preferred authFunc := h.webBrowserBasedAuth diff --git a/test/integration/cli_test.go b/test/integration/cli_test.go index c8bac8eef..f5d8a239a 100644 --- a/test/integration/cli_test.go +++ b/test/integration/cli_test.go @@ -14,6 +14,7 @@ import ( "os/exec" "path/filepath" "regexp" + "slices" "strings" "testing" "time" @@ -142,7 +143,7 @@ func assertWhoami(ctx context.Context, t *testing.T, useProxy bool, pinnipedExe, apiGroupSuffix, ) if useProxy { - cmd.Env = append(os.Environ(), testlib.IntegrationEnv(t).ProxyEnv()...) + cmd.Env = slices.Concat(os.Environ(), testlib.IntegrationEnv(t).ProxyEnv()) } cmd.Stdout = &stdout cmd.Stderr = &stderr @@ -427,6 +428,6 @@ func oidcLoginCommand(ctx context.Context, t *testing.T, pinnipedExe string, ses } // If there is a custom proxy, set it using standard environment variables. - cmd.Env = append(os.Environ(), env.ProxyEnv()...) + cmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) return cmd } diff --git a/test/integration/concierge_impersonation_proxy_test.go b/test/integration/concierge_impersonation_proxy_test.go index a3edddc25..0fc6b718d 100644 --- a/test/integration/concierge_impersonation_proxy_test.go +++ b/test/integration/concierge_impersonation_proxy_test.go @@ -22,6 +22,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "sort" "strings" "sync" @@ -594,7 +595,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl require.NoError(t, err) expectedGroups := make([]string, 0, len(env.TestUser.ExpectedGroups)+1) // make sure we do not mutate env.TestUser.ExpectedGroups - expectedGroups = append(expectedGroups, env.TestUser.ExpectedGroups...) + expectedGroups = slices.Concat(expectedGroups, env.TestUser.ExpectedGroups) expectedGroups = append(expectedGroups, "system:authenticated") expectedOriginalUserInfo := authenticationv1.UserInfo{ Username: env.TestUser.ExpectedUsername, @@ -880,7 +881,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl Create(ctx, &identityv1alpha1.WhoAmIRequest{}, metav1.CreateOptions{}) require.NoError(t, err, testlib.Sdump(err)) expectedGroups := make([]string, 0, len(env.TestUser.ExpectedGroups)+1) // make sure we do not mutate env.TestUser.ExpectedGroups - expectedGroups = append(expectedGroups, env.TestUser.ExpectedGroups...) + expectedGroups = slices.Concat(expectedGroups, env.TestUser.ExpectedGroups) expectedGroups = append(expectedGroups, "system:authenticated") require.Equal(t, expectedWhoAmIRequestResponse( @@ -2116,7 +2117,7 @@ func performImpersonatorDiscovery(ctx context.Context, t *testing.T, env *testli require.NoError(t, err) expectedGroups := make([]string, 0, len(env.TestUser.ExpectedGroups)+1) // make sure we do not mutate env.TestUser.ExpectedGroups - expectedGroups = append(expectedGroups, env.TestUser.ExpectedGroups...) + expectedGroups = slices.Concat(expectedGroups, env.TestUser.ExpectedGroups) expectedGroups = append(expectedGroups, "system:authenticated") // probe each pod directly for readiness since the concierge status is a lie - it just means a single pod is ready @@ -2339,7 +2340,7 @@ func getImpersonationKubeconfig(t *testing.T, env *testlib.TestEnv, impersonatio var envVarsWithProxy []string if !env.HasCapability(testlib.HasExternalLoadBalancerProvider) { // Only if you don't have a load balancer, use the squid proxy when it's available. - envVarsWithProxy = append(os.Environ(), env.ProxyEnv()...) + envVarsWithProxy = slices.Concat(os.Environ(), env.ProxyEnv()) } // Get the kubeconfig. @@ -2380,7 +2381,7 @@ func getImpersonationKubeconfig(t *testing.T, env *testlib.TestEnv, impersonatio func kubectlCommand(timeout context.Context, t *testing.T, kubeconfigPath string, envVarsWithProxy []string, args ...string) (*exec.Cmd, *syncBuffer, *syncBuffer) { t.Helper() - allArgs := append([]string{"--kubeconfig", kubeconfigPath}, args...) + allArgs := slices.Concat([]string{"--kubeconfig", kubeconfigPath}, args) kubectlCmd := exec.CommandContext(timeout, "kubectl", allArgs...) var stdout, stderr syncBuffer kubectlCmd.Stdout = &stdout diff --git a/test/integration/e2e_test.go b/test/integration/e2e_test.go index 7500b0b1e..2f853f902 100644 --- a/test/integration/e2e_test.go +++ b/test/integration/e2e_test.go @@ -184,7 +184,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser login via the plugin. kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath, "-v", "6") - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) // Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser. kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser) @@ -270,7 +270,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser login via the plugin. kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath, "-v", "6") - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) // Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser. kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser) @@ -360,7 +360,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser login via the plugin. start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -484,7 +484,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser login via the plugin. start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) var kubectlStdoutPipe io.ReadCloser if runtime.GOOS != "darwin" { // For some unknown reason this breaks the pty library on some MacOS machines. @@ -616,7 +616,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser-less CLI prompt login via the plugin. start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -699,7 +699,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // would be stuck waiting for input on the second username prompt. "kubectl get --raw /healthz" doesn't need // to do API discovery, so we know it will only call the credential exec plugin once. kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "--raw", "/healthz", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -749,7 +749,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger an LDAP-style login CLI prompt via the plugin. start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -808,7 +808,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger an LDAP-style login CLI prompt via the plugin. start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -889,7 +889,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should run an LDAP-style login without interactive prompts for username and password. start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -942,7 +942,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger an LDAP-style login CLI prompt via the plugin. start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -1019,7 +1019,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should run an LDAP-style login without interactive prompts for username and password. start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -1076,7 +1076,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser login via the plugin. kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath, "-v", "6") - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) // Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser. kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser) @@ -1131,7 +1131,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser login via the plugin. kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath, "-v", "6") - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) // Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser. kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser) @@ -1192,7 +1192,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser login via the plugin. kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath, "-v", "6") - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) // Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser. kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser) @@ -1404,7 +1404,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { t.Log("starting LDAP auth via kubectl") start := time.Now() kubectlCmd := exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", ldapKubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err := pty.Start(kubectlCmd) require.NoError(t, err) @@ -1431,7 +1431,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a browser login via the plugin for the OIDC IDP. t.Log("starting OIDC auth via kubectl") kubectlCmd = exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", oidcKubeconfigPath, "-v", "6") - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) // Run the kubectl command, wait for the Pinniped CLI to print the authorization URL, and open it in the browser. kubectlOutputChan := startKubectlAndOpenAuthorizationURLInBrowser(testCtx, t, kubectlCmd, browser) @@ -1517,7 +1517,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger an LDAP-style login CLI prompt via the plugin for the LDAP IDP. t.Log("starting second LDAP auth via kubectl") kubectlCmd = exec.CommandContext(testCtx, "kubectl", "get", "namespace", "--kubeconfig", ldapKubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) ptyFile, err = pty.Start(kubectlCmd) require.NoError(t, err) @@ -1561,8 +1561,8 @@ func TestE2EFullIntegration_Browser(t *testing.T) { createdLDAPProvider := setupClusterForEndToEndLDAPTest(t, expectedDownstreamLDAPUsername, env) // Having one IDP should put the FederationDomain into a ready state. - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Create a ClusterRoleBinding to give our test user from the upstream read-only access to the cluster. testlib.CreateTestClusterRoleBinding(t, @@ -1596,8 +1596,8 @@ func TestE2EFullIntegration_Browser(t *testing.T) { }, idpv1alpha1.PhaseReady) // Having a second IDP should put the FederationDomain back into an error state until we tell it which one to use. - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseError) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseError) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Update the FederationDomain to use the two IDPs. federationDomainsClient := testlib.NewSupervisorClientset(t).ConfigV1alpha1().FederationDomains(env.SupervisorNamespace) @@ -1611,7 +1611,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { ldapIDPDisplayName := "My LDAP IDP 💾" oidcIDPDisplayName := "My OIDC IDP 🚀" - gotFederationDomain.Spec.IdentityProviders = []configv1alpha1.FederationDomainIdentityProvider{ + gotFederationDomain.Spec.IdentityProviders = []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: ldapIDPDisplayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -1633,8 +1633,8 @@ func TestE2EFullIntegration_Browser(t *testing.T) { require.NoError(t, err) // The FederationDomain should be valid after the above update. - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -1979,7 +1979,7 @@ func requireUserCanUseKubectlWithoutAuthenticatingAgain( ) { // Run kubectl, which should work without any prompting for authentication. kubectlCmd := exec.CommandContext(ctx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) startTime := time.Now() kubectlOutput2, err := kubectlCmd.CombinedOutput() require.NoError(t, err) @@ -2017,7 +2017,7 @@ func requireUserCanUseKubectlWithoutAuthenticatingAgain( require.ElementsMatch(t, expectedGroupsAsEmptyInterfaces, idTokenClaims["groups"]) } - expectedGroupsPlusAuthenticated := append([]string{}, expectedGroups...) + expectedGroupsPlusAuthenticated := expectedGroups expectedGroupsPlusAuthenticated = append(expectedGroupsPlusAuthenticated, "system:authenticated") // Confirm we are the right user according to Kube by calling the WhoAmIRequest API. @@ -2029,7 +2029,7 @@ func requireUserCanUseKubectlWithoutAuthenticatingAgain( // While it is true that the user cannot list CRDs, that fact seems unrelated to making a create call to the // aggregated API endpoint, so this is a strange error, but it can be easily reproduced. kubectlCmd3 := exec.CommandContext(ctx, "kubectl", "create", "-f", "-", "-o", "yaml", "--kubeconfig", kubeconfigPath, "--validate=false") - kubectlCmd3.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd3.Env = slices.Concat(os.Environ(), env.ProxyEnv()) kubectlCmd3.Stdin = strings.NewReader(here.Docf(` apiVersion: identity.concierge.%s/v1alpha1 kind: WhoAmIRequest @@ -2091,7 +2091,7 @@ func requireGCAnnotationsOnSessionStorage(ctx context.Context, t *testing.T, sup func runPinnipedGetKubeconfig(t *testing.T, env *testlib.TestEnv, pinnipedExe string, tempDir string, pinnipedCLICommand []string) string { // Run "pinniped get kubeconfig" to get a kubeconfig YAML. - envVarsWithProxy := append(os.Environ(), env.ProxyEnv()...) + envVarsWithProxy := slices.Concat(os.Environ(), env.ProxyEnv()) kubeconfigYAML, stderr := runPinnipedCLI(t, envVarsWithProxy, pinnipedExe, pinnipedCLICommand...) t.Logf("stderr output from 'pinniped get kubeconfig':\n%s\n\n", stderr) t.Logf("test kubeconfig:\n%s\n\n", kubeconfigYAML) diff --git a/test/integration/pod_shutdown_test.go b/test/integration/pod_shutdown_test.go index fc6cc80ec..77ad4d1e9 100644 --- a/test/integration/pod_shutdown_test.go +++ b/test/integration/pod_shutdown_test.go @@ -1,4 +1,4 @@ -// Copyright 2023 the Pinniped contributors. All Rights Reserved. +// Copyright 2023-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package integration @@ -7,6 +7,7 @@ import ( "bytes" "context" "io" + "slices" "strings" "testing" "time" @@ -14,7 +15,6 @@ import ( "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/utils/strings/slices" "go.pinniped.dev/test/testlib" ) diff --git a/test/integration/supervisor_discovery_test.go b/test/integration/supervisor_discovery_test.go index 11aa0a0d6..0e2c5e864 100644 --- a/test/integration/supervisor_discovery_test.go +++ b/test/integration/supervisor_discovery_test.go @@ -13,6 +13,7 @@ import ( "net" "net/http" "net/url" + "slices" "strings" "testing" "time" @@ -23,7 +24,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/util/retry" - "k8s.io/utils/strings/slices" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" diff --git a/test/integration/supervisor_login_test.go b/test/integration/supervisor_login_test.go index a2ae4da5b..21c53fa5b 100644 --- a/test/integration/supervisor_login_test.go +++ b/test/integration/supervisor_login_test.go @@ -16,6 +16,7 @@ import ( "net/http/httptest" "net/url" "regexp" + "slices" "strings" "testing" "time" @@ -27,7 +28,6 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" - "k8s.io/utils/strings/slices" supervisorconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/config/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" @@ -802,7 +802,7 @@ func TestSupervisorLogin_Browser(t *testing.T) { requestAuthorizationUsingCLIPasswordFlow(t, downstreamAuthorizeURL, env.SupervisorUpstreamLDAP.TestUserMailAttributeValue, // username to present to server during login - "incorrect", // password to present to server during login + "incorrect", // password to present to server during login httpClient, true, ) diff --git a/test/integration/supervisor_oidcclientsecret_test.go b/test/integration/supervisor_oidcclientsecret_test.go index 84faf8618..34ff16f5c 100644 --- a/test/integration/supervisor_oidcclientsecret_test.go +++ b/test/integration/supervisor_oidcclientsecret_test.go @@ -10,6 +10,7 @@ import ( "encoding/json" "fmt" "os/exec" + "slices" "testing" "time" @@ -1020,10 +1021,7 @@ func retainOnlyMostRecentSecret(list []string) []string { } func prependSecret(list []string, newItem string) []string { - newList := make([]string, 0, len(list)+1) - newList = append(newList, newItem) - newList = append(newList, list...) - return newList + return slices.Concat([]string{newItem}, list) } func TestOIDCClientSecretRequestUnauthenticated_Parallel(t *testing.T) { diff --git a/test/integration/supervisor_warnings_test.go b/test/integration/supervisor_warnings_test.go index 574a34964..cdf7fbb8a 100644 --- a/test/integration/supervisor_warnings_test.go +++ b/test/integration/supervisor_warnings_test.go @@ -13,6 +13,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "sort" "strings" "testing" @@ -129,7 +130,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a cli-based login. start := time.Now() kubectlCmd := exec.CommandContext(ctx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) var kubectlStdoutPipe io.ReadCloser if runtime.GOOS != "darwin" { // For some unknown reason this breaks the pty library on some MacOS machines. @@ -219,7 +220,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { // Run kubectl, which should work without any prompting for authentication. kubectlCmd2 := exec.CommandContext(ctx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd2.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd2.Env = slices.Concat(os.Environ(), env.ProxyEnv()) startTime2 := time.Now() var kubectlStdoutPipe2 io.ReadCloser if runtime.GOOS != "darwin" { @@ -277,7 +278,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a cli-based login. start := time.Now() kubectlCmd := exec.CommandContext(ctx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) var kubectlStdoutPipe io.ReadCloser if runtime.GOOS != "darwin" { // For some unknown reason this breaks the pty library on some MacOS machines. @@ -348,7 +349,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { // Run kubectl, which should work without any prompting for authentication. kubectlCmd2 := exec.CommandContext(ctx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd2.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd2.Env = slices.Concat(os.Environ(), env.ProxyEnv()) startTime2 := time.Now() var kubectlStdoutPipe2 io.ReadCloser if runtime.GOOS != "darwin" { @@ -442,7 +443,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { // Run "kubectl get namespaces" which should trigger a cli-based login. start := time.Now() kubectlCmd := exec.CommandContext(ctx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) var kubectlStdoutPipe io.ReadCloser if runtime.GOOS != "darwin" { // For some unknown reason this breaks the pty library on some MacOS machines. @@ -555,7 +556,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { // Run kubectl, which should work without any prompting for authentication. kubectlCmd2 := exec.CommandContext(ctx, "kubectl", "get", "namespace", "--kubeconfig", kubeconfigPath) - kubectlCmd2.Env = append(os.Environ(), env.ProxyEnv()...) + kubectlCmd2.Env = slices.Concat(os.Environ(), env.ProxyEnv()) startTime2 := time.Now() var kubectlStdoutPipe2 io.ReadCloser if runtime.GOOS != "darwin" { From 0076f1251cbb8d465b5a03894430b82dbbcaf4f1 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Tue, 21 May 2024 10:38:25 -0500 Subject: [PATCH 08/10] Move all mock files into internal/mocks and use mock prefix --- internal/clientcertissuer/issuer_test.go | 20 ++++++------- .../kubecertagent/kubecertagent_test.go | 2 +- .../generate.go | 0 .../mockcredentialrequest.go} | 0 .../{issuermocks => mockissuer}/generate.go | 0 .../mockissuer.go} | 0 .../mockkubecertagent}/generate.go | 0 .../mockkubecertagent}/mockdynamiccert.go | 0 .../mockpodcommandexecutor.go | 0 .../registry/credentialrequest/rest_test.go | 28 +++++++++---------- 10 files changed, 25 insertions(+), 25 deletions(-) rename internal/mocks/{credentialrequestmocks => mockcredentialrequest}/generate.go (100%) rename internal/mocks/{credentialrequestmocks/credentialrequestmocks.go => mockcredentialrequest/mockcredentialrequest.go} (100%) rename internal/mocks/{issuermocks => mockissuer}/generate.go (100%) rename internal/mocks/{issuermocks/issuermocks.go => mockissuer/mockissuer.go} (100%) rename internal/{controller/kubecertagent/mocks => mocks/mockkubecertagent}/generate.go (100%) rename internal/{controller/kubecertagent/mocks => mocks/mockkubecertagent}/mockdynamiccert.go (100%) rename internal/{controller/kubecertagent/mocks => mocks/mockkubecertagent}/mockpodcommandexecutor.go (100%) diff --git a/internal/clientcertissuer/issuer_test.go b/internal/clientcertissuer/issuer_test.go index 9063d8b6f..81a615971 100644 --- a/internal/clientcertissuer/issuer_test.go +++ b/internal/clientcertissuer/issuer_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" - "go.pinniped.dev/internal/mocks/issuermocks" + "go.pinniped.dev/internal/mocks/mockissuer" ) func TestName(t *testing.T) { @@ -30,7 +30,7 @@ func TestName(t *testing.T) { { name: "foo issuer", buildIssuerMocks: func() ClientCertIssuers { - fooClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + fooClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) fooClientCertIssuer.EXPECT().Name().Return("foo") return ClientCertIssuers{fooClientCertIssuer} @@ -40,10 +40,10 @@ func TestName(t *testing.T) { { name: "foo and bar issuers", buildIssuerMocks: func() ClientCertIssuers { - fooClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + fooClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) fooClientCertIssuer.EXPECT().Name().Return("foo") - barClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + barClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) barClientCertIssuer.EXPECT().Name().Return("bar") return ClientCertIssuers{fooClientCertIssuer, barClientCertIssuer} @@ -81,7 +81,7 @@ func TestIssueClientCertPEM(t *testing.T) { { name: "issuers with error", buildIssuerMocks: func() ClientCertIssuers { - errClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + errClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) errClientCertIssuer.EXPECT().Name().Return("error cert issuer") errClientCertIssuer.EXPECT(). IssueClientCertPEM("username", []string{"group1", "group2"}, 32*time.Second). @@ -93,7 +93,7 @@ func TestIssueClientCertPEM(t *testing.T) { { name: "valid issuer", buildIssuerMocks: func() ClientCertIssuers { - validClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + validClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) validClientCertIssuer.EXPECT(). IssueClientCertPEM("username", []string{"group1", "group2"}, 32*time.Second). Return([]byte("cert"), []byte("key"), nil) @@ -105,13 +105,13 @@ func TestIssueClientCertPEM(t *testing.T) { { name: "fallthrough issuer", buildIssuerMocks: func() ClientCertIssuers { - errClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + errClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) errClientCertIssuer.EXPECT().Name().Return("error cert issuer") errClientCertIssuer.EXPECT(). IssueClientCertPEM("username", []string{"group1", "group2"}, 32*time.Second). Return(nil, nil, errors.New("error from wrapped cert issuer")) - validClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + validClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) validClientCertIssuer.EXPECT(). IssueClientCertPEM("username", []string{"group1", "group2"}, 32*time.Second). Return([]byte("cert"), []byte("key"), nil) @@ -126,13 +126,13 @@ func TestIssueClientCertPEM(t *testing.T) { { name: "multiple error issuers", buildIssuerMocks: func() ClientCertIssuers { - err1ClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + err1ClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) err1ClientCertIssuer.EXPECT().Name().Return("error1 cert issuer") err1ClientCertIssuer.EXPECT(). IssueClientCertPEM("username", []string{"group1", "group2"}, 32*time.Second). Return(nil, nil, errors.New("error1 from wrapped cert issuer")) - err2ClientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + err2ClientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) err2ClientCertIssuer.EXPECT().Name().Return("error2 cert issuer") err2ClientCertIssuer.EXPECT(). IssueClientCertPEM("username", []string{"group1", "group2"}, 32*time.Second). diff --git a/internal/controller/kubecertagent/kubecertagent_test.go b/internal/controller/kubecertagent/kubecertagent_test.go index 400a4694d..d826ba750 100644 --- a/internal/controller/kubecertagent/kubecertagent_test.go +++ b/internal/controller/kubecertagent/kubecertagent_test.go @@ -32,11 +32,11 @@ import ( conciergeconfigv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/config/v1alpha1" conciergefake "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/fake" conciergeinformers "go.pinniped.dev/generated/latest/client/concierge/informers/externalversions" - "go.pinniped.dev/internal/controller/kubecertagent/mocks" "go.pinniped.dev/internal/controllerinit" "go.pinniped.dev/internal/controllerlib" "go.pinniped.dev/internal/here" "go.pinniped.dev/internal/kubeclient" + mocks "go.pinniped.dev/internal/mocks/mockkubecertagent" "go.pinniped.dev/internal/plog" "go.pinniped.dev/internal/testutil" "go.pinniped.dev/test/testlib" diff --git a/internal/mocks/credentialrequestmocks/generate.go b/internal/mocks/mockcredentialrequest/generate.go similarity index 100% rename from internal/mocks/credentialrequestmocks/generate.go rename to internal/mocks/mockcredentialrequest/generate.go diff --git a/internal/mocks/credentialrequestmocks/credentialrequestmocks.go b/internal/mocks/mockcredentialrequest/mockcredentialrequest.go similarity index 100% rename from internal/mocks/credentialrequestmocks/credentialrequestmocks.go rename to internal/mocks/mockcredentialrequest/mockcredentialrequest.go diff --git a/internal/mocks/issuermocks/generate.go b/internal/mocks/mockissuer/generate.go similarity index 100% rename from internal/mocks/issuermocks/generate.go rename to internal/mocks/mockissuer/generate.go diff --git a/internal/mocks/issuermocks/issuermocks.go b/internal/mocks/mockissuer/mockissuer.go similarity index 100% rename from internal/mocks/issuermocks/issuermocks.go rename to internal/mocks/mockissuer/mockissuer.go diff --git a/internal/controller/kubecertagent/mocks/generate.go b/internal/mocks/mockkubecertagent/generate.go similarity index 100% rename from internal/controller/kubecertagent/mocks/generate.go rename to internal/mocks/mockkubecertagent/generate.go diff --git a/internal/controller/kubecertagent/mocks/mockdynamiccert.go b/internal/mocks/mockkubecertagent/mockdynamiccert.go similarity index 100% rename from internal/controller/kubecertagent/mocks/mockdynamiccert.go rename to internal/mocks/mockkubecertagent/mockdynamiccert.go diff --git a/internal/controller/kubecertagent/mocks/mockpodcommandexecutor.go b/internal/mocks/mockkubecertagent/mockpodcommandexecutor.go similarity index 100% rename from internal/controller/kubecertagent/mocks/mockpodcommandexecutor.go rename to internal/mocks/mockkubecertagent/mockpodcommandexecutor.go diff --git a/internal/registry/credentialrequest/rest_test.go b/internal/registry/credentialrequest/rest_test.go index dffa0b69b..5054c5cc9 100644 --- a/internal/registry/credentialrequest/rest_test.go +++ b/internal/registry/credentialrequest/rest_test.go @@ -26,8 +26,8 @@ import ( loginapi "go.pinniped.dev/generated/latest/apis/concierge/login" "go.pinniped.dev/internal/clientcertissuer" - "go.pinniped.dev/internal/mocks/credentialrequestmocks" - "go.pinniped.dev/internal/mocks/issuermocks" + "go.pinniped.dev/internal/mocks/mockcredentialrequest" + "go.pinniped.dev/internal/mocks/mockissuer" "go.pinniped.dev/internal/testutil" ) @@ -89,14 +89,14 @@ func TestCreate(t *testing.T) { it("CreateSucceedsWhenGivenATokenAndTheWebhookAuthenticatesTheToken", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req). Return(&user.DefaultInfo{ Name: "test-user", Groups: []string{"test-group-1", "test-group-2"}, }, nil) - clientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + clientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) clientCertIssuer.EXPECT().IssueClientCertPEM( "test-user", []string{"test-group-1", "test-group-2"}, @@ -130,14 +130,14 @@ func TestCreate(t *testing.T) { it("CreateFailsWithValidTokenWhenCertIssuerFails", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req). Return(&user.DefaultInfo{ Name: "test-user", Groups: []string{"test-group-1", "test-group-2"}, }, nil) - clientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + clientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) clientCertIssuer.EXPECT(). IssueClientCertPEM(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, nil, fmt.Errorf("some certificate authority error")) @@ -152,7 +152,7 @@ func TestCreate(t *testing.T) { it("CreateSucceedsWithAnUnauthenticatedStatusWhenGivenATokenAndTheWebhookReturnsNilUser", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req).Return(nil, nil) storage := NewREST(requestAuthenticator, nil, schema.GroupResource{}) @@ -166,7 +166,7 @@ func TestCreate(t *testing.T) { it("CreateSucceedsWithAnUnauthenticatedStatusWhenWebhookFails", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req). Return(nil, errors.New("some webhook error")) @@ -181,7 +181,7 @@ func TestCreate(t *testing.T) { it("CreateSucceedsWithAnUnauthenticatedStatusWhenWebhookReturnsAnEmptyUsername", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req). Return(&user.DefaultInfo{Name: ""}, nil) @@ -196,7 +196,7 @@ func TestCreate(t *testing.T) { it("CreateSucceedsWithAnUnauthenticatedStatusWhenWebhookReturnsAUserWithUID", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req). Return(&user.DefaultInfo{ Name: "test-user", @@ -215,7 +215,7 @@ func TestCreate(t *testing.T) { it("CreateSucceedsWithAnUnauthenticatedStatusWhenWebhookReturnsAUserWithExtra", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req). Return(&user.DefaultInfo{ Name: "test-user", @@ -271,7 +271,7 @@ func TestCreate(t *testing.T) { it("CreateDoesNotAllowValidationFunctionToMutateRequest", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req.DeepCopy()). Return(&user.DefaultInfo{Name: "test-user"}, nil) @@ -292,7 +292,7 @@ func TestCreate(t *testing.T) { it("CreateDoesNotAllowValidationFunctionToSeeTheActualRequestToken", func() { req := validCredentialRequest() - requestAuthenticator := credentialrequestmocks.NewMockTokenCredentialRequestAuthenticator(ctrl) + requestAuthenticator := mockcredentialrequest.NewMockTokenCredentialRequestAuthenticator(ctrl) requestAuthenticator.EXPECT().AuthenticateTokenCredentialRequest(gomock.Any(), req.DeepCopy()). Return(&user.DefaultInfo{Name: "test-user"}, nil) @@ -398,7 +398,7 @@ func requireSuccessfulResponseWithAuthenticationFailureMessage(t *testing.T, err } func successfulIssuer(ctrl *gomock.Controller) clientcertissuer.ClientCertIssuer { - clientCertIssuer := issuermocks.NewMockClientCertIssuer(ctrl) + clientCertIssuer := mockissuer.NewMockClientCertIssuer(ctrl) clientCertIssuer.EXPECT(). IssueClientCertPEM(gomock.Any(), gomock.Any(), gomock.Any()). Return([]byte("test-cert"), []byte("test-key"), nil) From 2f9df8c8e2f29354e94ab39a485c1d57a64d19d0 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Tue, 21 May 2024 10:43:52 -0500 Subject: [PATCH 09/10] Add module generate command and update all generated files --- hack/module.sh | 3 +++ internal/mocks/mockcredentialrequest/generate.go | 4 ++-- .../mocks/mockcredentialrequest/mockcredentialrequest.go | 6 +++--- internal/mocks/mockissuer/generate.go | 4 ++-- internal/mocks/mockissuer/mockissuer.go | 6 +++--- internal/mocks/mockkubecertagent/generate.go | 4 ++-- internal/mocks/mockkubecertagent/mockdynamiccert.go | 2 +- internal/mocks/mockkubecertagent/mockpodcommandexecutor.go | 5 ++--- 8 files changed, 18 insertions(+), 16 deletions(-) diff --git a/hack/module.sh b/hack/module.sh index 17f83976b..647ccb1e1 100755 --- a/hack/module.sh +++ b/hack/module.sh @@ -50,6 +50,9 @@ function main() { KUBE_PANIC_WATCH_DECODE_ERROR=${kube_panic_watch_decode_error} \ go test -short -race ./... ;; + 'generate') + go generate ./internal/mocks/... + ;; *) usage ;; diff --git a/internal/mocks/mockcredentialrequest/generate.go b/internal/mocks/mockcredentialrequest/generate.go index ef425dfb1..9663ed8e9 100644 --- a/internal/mocks/mockcredentialrequest/generate.go +++ b/internal/mocks/mockcredentialrequest/generate.go @@ -1,6 +1,6 @@ // Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -package credentialrequestmocks +package mockcredentialrequest -//go:generate go run -v go.uber.org/mock/mockgen -destination=credentialrequestmocks.go -package=credentialrequestmocks -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/registry/credentialrequest TokenCredentialRequestAuthenticator +//go:generate go run -v go.uber.org/mock/mockgen -destination=mockcredentialrequest.go -package=mockcredentialrequest -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/registry/credentialrequest TokenCredentialRequestAuthenticator diff --git a/internal/mocks/mockcredentialrequest/mockcredentialrequest.go b/internal/mocks/mockcredentialrequest/mockcredentialrequest.go index 041a897fa..93c3cad48 100644 --- a/internal/mocks/mockcredentialrequest/mockcredentialrequest.go +++ b/internal/mocks/mockcredentialrequest/mockcredentialrequest.go @@ -7,11 +7,11 @@ // // Generated by this command: // -// mockgen -destination=credentialrequestmocks.go -package=credentialrequestmocks -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/registry/credentialrequest TokenCredentialRequestAuthenticator +// mockgen -destination=mockcredentialrequest.go -package=mockcredentialrequest -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/registry/credentialrequest TokenCredentialRequestAuthenticator // -// Package credentialrequestmocks is a generated GoMock package. -package credentialrequestmocks +// Package mockcredentialrequest is a generated GoMock package. +package mockcredentialrequest import ( context "context" diff --git a/internal/mocks/mockissuer/generate.go b/internal/mocks/mockissuer/generate.go index 7296a44d6..d1b8594a9 100644 --- a/internal/mocks/mockissuer/generate.go +++ b/internal/mocks/mockissuer/generate.go @@ -1,6 +1,6 @@ // Copyright 2020-2024 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -package issuermocks +package mockissuer -//go:generate go run -v go.uber.org/mock/mockgen -destination=issuermocks.go -package=issuermocks -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/clientcertissuer ClientCertIssuer +//go:generate go run -v go.uber.org/mock/mockgen -destination=mockissuer.go -package=mockissuer -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/clientcertissuer ClientCertIssuer diff --git a/internal/mocks/mockissuer/mockissuer.go b/internal/mocks/mockissuer/mockissuer.go index 35f979bc9..35a061778 100644 --- a/internal/mocks/mockissuer/mockissuer.go +++ b/internal/mocks/mockissuer/mockissuer.go @@ -7,11 +7,11 @@ // // Generated by this command: // -// mockgen -destination=issuermocks.go -package=issuermocks -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/clientcertissuer ClientCertIssuer +// mockgen -destination=mockissuer.go -package=mockissuer -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/clientcertissuer ClientCertIssuer // -// Package issuermocks is a generated GoMock package. -package issuermocks +// Package mockissuer is a generated GoMock package. +package mockissuer import ( reflect "reflect" diff --git a/internal/mocks/mockkubecertagent/generate.go b/internal/mocks/mockkubecertagent/generate.go index 488abb703..c48ccd5b4 100644 --- a/internal/mocks/mockkubecertagent/generate.go +++ b/internal/mocks/mockkubecertagent/generate.go @@ -3,5 +3,5 @@ package mocks -//go:generate go run -v go.uber.org/mock/mockgen -destination=mockpodcommandexecutor.go -package=mocks -copyright_file=../../../../hack/header.txt go.pinniped.dev/internal/controller/kubecertagent PodCommandExecutor -//go:generate go run -v go.uber.org/mock/mockgen -destination=mockdynamiccert.go -package=mocks -copyright_file=../../../../hack/header.txt -mock_names Private=MockDynamicCertPrivate go.pinniped.dev/internal/dynamiccert Private +//go:generate go run -v go.uber.org/mock/mockgen -destination=mockpodcommandexecutor.go -package=mocks -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/controller/kubecertagent PodCommandExecutor +//go:generate go run -v go.uber.org/mock/mockgen -destination=mockdynamiccert.go -package=mocks -copyright_file=../../../hack/header.txt -mock_names Private=MockDynamicCertPrivate go.pinniped.dev/internal/dynamiccert Private diff --git a/internal/mocks/mockkubecertagent/mockdynamiccert.go b/internal/mocks/mockkubecertagent/mockdynamiccert.go index 83429341f..08af407c4 100644 --- a/internal/mocks/mockkubecertagent/mockdynamiccert.go +++ b/internal/mocks/mockkubecertagent/mockdynamiccert.go @@ -7,7 +7,7 @@ // // Generated by this command: // -// mockgen -destination=mockdynamiccert.go -package=mocks -copyright_file=../../../../hack/header.txt -mock_names Private=MockDynamicCertPrivate go.pinniped.dev/internal/dynamiccert Private +// mockgen -destination=mockdynamiccert.go -package=mocks -copyright_file=../../../hack/header.txt -mock_names Private=MockDynamicCertPrivate go.pinniped.dev/internal/dynamiccert Private // // Package mocks is a generated GoMock package. diff --git a/internal/mocks/mockkubecertagent/mockpodcommandexecutor.go b/internal/mocks/mockkubecertagent/mockpodcommandexecutor.go index ef6379620..87746b0b3 100644 --- a/internal/mocks/mockkubecertagent/mockpodcommandexecutor.go +++ b/internal/mocks/mockkubecertagent/mockpodcommandexecutor.go @@ -7,7 +7,7 @@ // // Generated by this command: // -// mockgen -destination=mockpodcommandexecutor.go -package=mocks -copyright_file=../../../../hack/header.txt go.pinniped.dev/internal/controller/kubecertagent PodCommandExecutor +// mockgen -destination=mockpodcommandexecutor.go -package=mocks -copyright_file=../../../hack/header.txt go.pinniped.dev/internal/controller/kubecertagent PodCommandExecutor // // Package mocks is a generated GoMock package. @@ -16,7 +16,6 @@ package mocks import ( context "context" reflect "reflect" - "slices" gomock "go.uber.org/mock/gomock" ) @@ -60,6 +59,6 @@ func (m *MockPodCommandExecutor) Exec(arg0 context.Context, arg1, arg2, arg3 str // Exec indicates an expected call of Exec. func (mr *MockPodCommandExecutorMockRecorder) Exec(arg0, arg1, arg2, arg3 any, arg4 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := slices.Concat([]any{arg0, arg1, arg2, arg3}, arg4) + varargs := append([]any{arg0, arg1, arg2, arg3}, arg4...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Exec", reflect.TypeOf((*MockPodCommandExecutor)(nil).Exec), varargs...) } From 678be9902a52374abfe1b697fbd658f301ab7bc2 Mon Sep 17 00:00:00 2001 From: Joshua Casey Date: Tue, 11 Jun 2024 10:16:18 -0500 Subject: [PATCH 10/10] Lint new files from the GitHub branch --- .../federation_domain_watcher_test.go | 6 +- .../github_upstream_watcher.go | 57 ++- .../github_upstream_watcher_test.go | 388 +++++++++--------- internal/controller/utils.go | 4 +- .../callback/callback_handler_test.go | 6 +- .../endpoints/token/token_handler_test.go | 2 +- .../resolved_github_provider.go | 4 +- .../upstreamprovider/upstream_provider.go | 6 +- .../oidctestutil/testgithubprovider.go | 18 +- internal/upstreamgithub/upstreamgithub.go | 20 +- .../upstreamgithub/upstreamgithub_test.go | 30 +- test/integration/e2e_test.go | 16 +- test/integration/supervisor_login_test.go | 12 +- test/testlib/client.go | 2 +- 14 files changed, 285 insertions(+), 286 deletions(-) diff --git a/internal/controller/supervisorconfig/federation_domain_watcher_test.go b/internal/controller/supervisorconfig/federation_domain_watcher_test.go index b606f9c87..172dec76c 100644 --- a/internal/controller/supervisorconfig/federation_domain_watcher_test.go +++ b/internal/controller/supervisorconfig/federation_domain_watcher_test.go @@ -633,13 +633,13 @@ func TestTestFederationDomainWatcherControllerSync(t *testing.T) { federationDomainIssuerWithDefaultIDP(t, federationDomain1.Spec.Issuer, gitHubIdentityProvider.ObjectMeta), federationDomainIssuerWithDefaultIDP(t, federationDomain2.Spec.Issuer, gitHubIdentityProvider.ObjectMeta), }, - wantStatusUpdates: []*configv1alpha1.FederationDomain{ + wantStatusUpdates: []*supervisorconfigv1alpha1.FederationDomain{ expectedFederationDomainStatusUpdate(federationDomain1, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain1.Spec.Issuer, gitHubIdentityProvider.Name, frozenMetav1Now, 123), ), expectedFederationDomainStatusUpdate(federationDomain2, - configv1alpha1.FederationDomainPhaseReady, + supervisorconfigv1alpha1.FederationDomainPhaseReady, allHappyConditionsLegacyConfigurationSuccess(federationDomain2.Spec.Issuer, gitHubIdentityProvider.Name, frozenMetav1Now, 123), ), }, diff --git a/internal/controller/supervisorconfig/githubupstreamwatcher/github_upstream_watcher.go b/internal/controller/supervisorconfig/githubupstreamwatcher/github_upstream_watcher.go index b1de18d0c..c9580d98b 100644 --- a/internal/controller/supervisorconfig/githubupstreamwatcher/github_upstream_watcher.go +++ b/internal/controller/supervisorconfig/githubupstreamwatcher/github_upstream_watcher.go @@ -18,15 +18,14 @@ import ( "golang.org/x/oauth2" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" - k8sapierrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - errorsutil "k8s.io/apimachinery/pkg/util/errors" - k8sutilerrors "k8s.io/apimachinery/pkg/util/errors" + utilerrors "k8s.io/apimachinery/pkg/util/errors" corev1informers "k8s.io/client-go/informers/core/v1" "k8s.io/utils/clock" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" supervisorclientset "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned" idpinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions/idp/v1alpha1" pinnipedcontroller "go.pinniped.dev/internal/controller" @@ -106,7 +105,7 @@ func New( withInformer( gitHubIdentityProviderInformer, pinnipedcontroller.SimpleFilter(func(obj metav1.Object) bool { - gitHubIDP, ok := obj.(*v1alpha1.GitHubIdentityProvider) + gitHubIDP, ok := obj.(*idpv1alpha1.GitHubIdentityProvider) return ok && gitHubIDP.Namespace == namespace }, pinnipedcontroller.SingletonQueue()), controllerlib.InformerOption{}, @@ -127,7 +126,7 @@ func (c *gitHubWatcherController) Sync(ctx controllerlib.Context) error { } // Sort them by name just so that the logs output is consistent - slices.SortStableFunc(actualUpstreams, func(a, b *v1alpha1.GitHubIdentityProvider) int { + slices.SortStableFunc(actualUpstreams, func(a, b *idpv1alpha1.GitHubIdentityProvider) int { return strings.Compare(a.Name, b.Name) }) @@ -151,14 +150,14 @@ func (c *gitHubWatcherController) Sync(ctx controllerlib.Context) error { applicationErrors = append([]error{controllerlib.ErrSyntheticRequeue}, applicationErrors...) } - return errorsutil.NewAggregate(applicationErrors) + return utilerrors.NewAggregate(applicationErrors) } func (c *gitHubWatcherController) validateClientSecret(secretName string) (*metav1.Condition, string, string, error) { secret, unableToRetrieveSecretErr := c.secretInformer.Lister().Secrets(c.namespace).Get(secretName) // This error requires user interaction, so ignore it. - if k8sapierrors.IsNotFound(unableToRetrieveSecretErr) { + if apierrors.IsNotFound(unableToRetrieveSecretErr) { unableToRetrieveSecretErr = nil } @@ -207,16 +206,16 @@ func (c *gitHubWatcherController) validateClientSecret(secretName string) (*meta }, clientID, clientSecret, nil } -func validateOrganizationsPolicy(organizationsSpec *v1alpha1.GitHubOrganizationsSpec) *metav1.Condition { - var policy v1alpha1.GitHubAllowedAuthOrganizationsPolicy +func validateOrganizationsPolicy(organizationsSpec *idpv1alpha1.GitHubOrganizationsSpec) *metav1.Condition { + var policy idpv1alpha1.GitHubAllowedAuthOrganizationsPolicy if organizationsSpec.Policy != nil { policy = *organizationsSpec.Policy } // Should not happen due to CRD defaulting, enum validation, and CEL validation (for recent versions of K8s only!) // That is why the message here is very minimal - if (policy == v1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers && len(organizationsSpec.Allowed) == 0) || - (policy == v1alpha1.GitHubAllowedAuthOrganizationsPolicyOnlyUsersFromAllowedOrganizations && len(organizationsSpec.Allowed) > 0) { + if (policy == idpv1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers && len(organizationsSpec.Allowed) == 0) || + (policy == idpv1alpha1.GitHubAllowedAuthOrganizationsPolicyOnlyUsersFromAllowedOrganizations && len(organizationsSpec.Allowed) > 0) { return &metav1.Condition{ Type: OrganizationsPolicyValid, Status: metav1.ConditionTrue, @@ -242,7 +241,7 @@ func validateOrganizationsPolicy(organizationsSpec *v1alpha1.GitHubOrganizations } } -func (c *gitHubWatcherController) validateUpstreamAndUpdateConditions(ctx controllerlib.Context, upstream *v1alpha1.GitHubIdentityProvider) ( +func (c *gitHubWatcherController) validateUpstreamAndUpdateConditions(ctx controllerlib.Context, upstream *idpv1alpha1.GitHubIdentityProvider) ( *upstreamgithub.Provider, // If validated, returns the config error, // This error will only refer to programmatic errors such as inability to perform a Dial or dereference a pointer, not configuration errors ) { @@ -285,7 +284,7 @@ func (c *gitHubWatcherController) validateUpstreamAndUpdateConditions(ctx contro // Status: metav1.ConditionFalse, never be omitted. if len(conditions) != countExpectedConditions { // untested since all code paths return the same number of conditions applicationErrors = append(applicationErrors, fmt.Errorf("expected %d conditions but found %d conditions", countExpectedConditions, len(conditions))) - return nil, k8sutilerrors.NewAggregate(applicationErrors) + return nil, utilerrors.NewAggregate(applicationErrors) } hadErrorCondition, updateStatusErr := c.updateStatus(ctx.Context, upstream, conditions) if updateStatusErr != nil { @@ -293,7 +292,7 @@ func (c *gitHubWatcherController) validateUpstreamAndUpdateConditions(ctx contro } // Any error condition means we will not add the IDP to the cache, so just return nil here if hadErrorCondition { - return nil, k8sutilerrors.NewAggregate(applicationErrors) + return nil, utilerrors.NewAggregate(applicationErrors) } provider := upstreamgithub.New( @@ -320,7 +319,7 @@ func (c *gitHubWatcherController) validateUpstreamAndUpdateConditions(ctx contro HttpClient: httpClient, }, ) - return provider, k8sutilerrors.NewAggregate(applicationErrors) + return provider, utilerrors.NewAggregate(applicationErrors) } func apiBaseUrl(upstreamSpecHost string, hostURL string) string { @@ -330,7 +329,7 @@ func apiBaseUrl(upstreamSpecHost string, hostURL string) string { return defaultApiBaseURL } -func validateHost(gitHubAPIConfig v1alpha1.GitHubAPIConfig) (*metav1.Condition, *endpointaddr.HostPort) { +func validateHost(gitHubAPIConfig idpv1alpha1.GitHubAPIConfig) (*metav1.Condition, *endpointaddr.HostPort) { buildInvalidHost := func(host, reason string) *metav1.Condition { return &metav1.Condition{ Type: HostValid, @@ -360,7 +359,7 @@ func validateHost(gitHubAPIConfig v1alpha1.GitHubAPIConfig) (*metav1.Condition, }, &hostPort } -func (c *gitHubWatcherController) validateTLSConfiguration(tlsSpec *v1alpha1.TLSSpec) (*metav1.Condition, *x509.CertPool) { +func (c *gitHubWatcherController) validateTLSConfiguration(tlsSpec *idpv1alpha1.TLSSpec) (*metav1.Condition, *x509.CertPool) { certPool, _, buildCertPoolErr := pinnipedcontroller.BuildCertPoolIDP(tlsSpec) if buildCertPoolErr != nil { // buildCertPoolErr is not recoverable with a resync. @@ -428,7 +427,7 @@ func buildDialErrorMessage(tlsDialErr error) string { return reason } -func validateUserAndGroupAttributes(upstream *v1alpha1.GitHubIdentityProvider) (*metav1.Condition, v1alpha1.GitHubGroupNameAttribute, v1alpha1.GitHubUsernameAttribute) { +func validateUserAndGroupAttributes(upstream *idpv1alpha1.GitHubIdentityProvider) (*metav1.Condition, idpv1alpha1.GitHubGroupNameAttribute, idpv1alpha1.GitHubUsernameAttribute) { buildInvalidCondition := func(message string) *metav1.Condition { return &metav1.Condition{ Type: ClaimsValid, @@ -438,14 +437,14 @@ func validateUserAndGroupAttributes(upstream *v1alpha1.GitHubIdentityProvider) ( } } - var usernameAttribute v1alpha1.GitHubUsernameAttribute + var usernameAttribute idpv1alpha1.GitHubUsernameAttribute if upstream.Spec.Claims.Username == nil { return buildInvalidCondition("spec.claims.username is required"), "", "" } else { usernameAttribute = *upstream.Spec.Claims.Username } - var groupNameAttribute v1alpha1.GitHubGroupNameAttribute + var groupNameAttribute idpv1alpha1.GitHubGroupNameAttribute if upstream.Spec.Claims.Groups == nil { return buildInvalidCondition("spec.claims.groups is required"), "", "" } else { @@ -453,17 +452,17 @@ func validateUserAndGroupAttributes(upstream *v1alpha1.GitHubIdentityProvider) ( } switch usernameAttribute { - case v1alpha1.GitHubUsernameLoginAndID: - case v1alpha1.GitHubUsernameLogin: - case v1alpha1.GitHubUsernameID: + case idpv1alpha1.GitHubUsernameLoginAndID: + case idpv1alpha1.GitHubUsernameLogin: + case idpv1alpha1.GitHubUsernameID: default: // Should not happen due to CRD enum validation return buildInvalidCondition(fmt.Sprintf("spec.claims.username (%q) is not valid", usernameAttribute)), "", "" } switch groupNameAttribute { - case v1alpha1.GitHubUseTeamNameForGroupName: - case v1alpha1.GitHubUseTeamSlugForGroupName: + case idpv1alpha1.GitHubUseTeamNameForGroupName: + case idpv1alpha1.GitHubUseTeamSlugForGroupName: default: // Should not happen due to CRD enum validation return buildInvalidCondition(fmt.Sprintf("spec.claims.groups (%q) is not valid", groupNameAttribute)), "", "" @@ -479,7 +478,7 @@ func validateUserAndGroupAttributes(upstream *v1alpha1.GitHubIdentityProvider) ( func (c *gitHubWatcherController) updateStatus( ctx context.Context, - upstream *v1alpha1.GitHubIdentityProvider, + upstream *idpv1alpha1.GitHubIdentityProvider, conditions []*metav1.Condition) (bool, error) { log := c.log.WithValues("namespace", upstream.Namespace, "name", upstream.Name) updated := upstream.DeepCopy() @@ -492,9 +491,9 @@ func (c *gitHubWatcherController) updateStatus( metav1.NewTime(c.clock.Now()), ) - updated.Status.Phase = v1alpha1.GitHubPhaseReady + updated.Status.Phase = idpv1alpha1.GitHubPhaseReady if hadErrorCondition { - updated.Status.Phase = v1alpha1.GitHubPhaseError + updated.Status.Phase = idpv1alpha1.GitHubPhaseError } if equality.Semantic.DeepEqual(upstream, updated) { diff --git a/internal/controller/supervisorconfig/githubupstreamwatcher/github_upstream_watcher_test.go b/internal/controller/supervisorconfig/githubupstreamwatcher/github_upstream_watcher_test.go index 0da18dff8..5b9df963f 100644 --- a/internal/controller/supervisorconfig/githubupstreamwatcher/github_upstream_watcher_test.go +++ b/internal/controller/supervisorconfig/githubupstreamwatcher/github_upstream_watcher_test.go @@ -30,9 +30,9 @@ import ( clocktesting "k8s.io/utils/clock/testing" "k8s.io/utils/ptr" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" supervisorfake "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/fake" - pinnipedinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" + supervisorinformers "go.pinniped.dev/generated/latest/client/supervisor/informers/externalversions" "go.pinniped.dev/internal/certauthority" pinnipedcontroller "go.pinniped.dev/internal/controller" "go.pinniped.dev/internal/controller/supervisorconfig/upstreamwatchers" @@ -49,12 +49,12 @@ import ( var ( githubIDPGVR = schema.GroupVersionResource{ - Group: v1alpha1.SchemeGroupVersion.Group, - Version: v1alpha1.SchemeGroupVersion.Version, + Group: idpv1alpha1.SchemeGroupVersion.Group, + Version: idpv1alpha1.SchemeGroupVersion.Version, Resource: "githubidentityproviders", } - githubIDPKind = v1alpha1.SchemeGroupVersion.WithKind("GitHubIdentityProvider") + githubIDPKind = idpv1alpha1.SchemeGroupVersion.WithKind("GitHubIdentityProvider") ) func TestController(t *testing.T) { @@ -98,62 +98,62 @@ func TestController(t *testing.T) { }, } - validMinimalIDP := &v1alpha1.GitHubIdentityProvider{ + validMinimalIDP := &idpv1alpha1.GitHubIdentityProvider{ ObjectMeta: metav1.ObjectMeta{ Name: "minimal-idp-name", Namespace: namespace, UID: types.UID("minimal-uid"), Generation: wantObservedGeneration, }, - Spec: v1alpha1.GitHubIdentityProviderSpec{ - GitHubAPI: v1alpha1.GitHubAPIConfig{ + Spec: idpv1alpha1.GitHubIdentityProviderSpec{ + GitHubAPI: idpv1alpha1.GitHubAPIConfig{ Host: ptr.To(goodServerDomain), - TLS: &v1alpha1.TLSSpec{ + TLS: &idpv1alpha1.TLSSpec{ CertificateAuthorityData: goodServerCAB64, }, }, - Client: v1alpha1.GitHubClientSpec{ + Client: idpv1alpha1.GitHubClientSpec{ SecretName: goodSecret.Name, }, // These claims are optional when using the actual Kubernetes CRD. // However, they are required here because CRD defaulting/validation does not occur during testing. - Claims: v1alpha1.GitHubClaims{ - Username: ptr.To(v1alpha1.GitHubUsernameLogin), - Groups: ptr.To(v1alpha1.GitHubUseTeamSlugForGroupName), + Claims: idpv1alpha1.GitHubClaims{ + Username: ptr.To(idpv1alpha1.GitHubUsernameLogin), + Groups: ptr.To(idpv1alpha1.GitHubUseTeamSlugForGroupName), }, - AllowAuthentication: v1alpha1.GitHubAllowAuthenticationSpec{ - Organizations: v1alpha1.GitHubOrganizationsSpec{ - Policy: ptr.To(v1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers), + AllowAuthentication: idpv1alpha1.GitHubAllowAuthenticationSpec{ + Organizations: idpv1alpha1.GitHubOrganizationsSpec{ + Policy: ptr.To(idpv1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers), }, }, }, } - validFilledOutIDP := &v1alpha1.GitHubIdentityProvider{ + validFilledOutIDP := &idpv1alpha1.GitHubIdentityProvider{ ObjectMeta: metav1.ObjectMeta{ Name: "some-idp-name", Namespace: namespace, UID: types.UID("some-resource-uid"), Generation: wantObservedGeneration, }, - Spec: v1alpha1.GitHubIdentityProviderSpec{ - GitHubAPI: v1alpha1.GitHubAPIConfig{ + Spec: idpv1alpha1.GitHubIdentityProviderSpec{ + GitHubAPI: idpv1alpha1.GitHubAPIConfig{ Host: ptr.To(goodServerDomain), - TLS: &v1alpha1.TLSSpec{ + TLS: &idpv1alpha1.TLSSpec{ CertificateAuthorityData: goodServerCAB64, }, }, - Claims: v1alpha1.GitHubClaims{ - Username: ptr.To(v1alpha1.GitHubUsernameID), - Groups: ptr.To(v1alpha1.GitHubUseTeamNameForGroupName), + Claims: idpv1alpha1.GitHubClaims{ + Username: ptr.To(idpv1alpha1.GitHubUsernameID), + Groups: ptr.To(idpv1alpha1.GitHubUseTeamNameForGroupName), }, - AllowAuthentication: v1alpha1.GitHubAllowAuthenticationSpec{ - Organizations: v1alpha1.GitHubOrganizationsSpec{ - Policy: ptr.To(v1alpha1.GitHubAllowedAuthOrganizationsPolicyOnlyUsersFromAllowedOrganizations), + AllowAuthentication: idpv1alpha1.GitHubAllowAuthenticationSpec{ + Organizations: idpv1alpha1.GitHubOrganizationsSpec{ + Policy: ptr.To(idpv1alpha1.GitHubAllowedAuthOrganizationsPolicyOnlyUsersFromAllowedOrganizations), Allowed: []string{"organization1", "org2"}, }, }, - Client: v1alpha1.GitHubClientSpec{ + Client: idpv1alpha1.GitHubClientSpec{ SecretName: goodSecret.Name, }, }, @@ -211,7 +211,7 @@ func TestController(t *testing.T) { } } - buildOrganizationsPolicyValidTrue := func(t *testing.T, policy v1alpha1.GitHubAllowedAuthOrganizationsPolicy) metav1.Condition { + buildOrganizationsPolicyValidTrue := func(t *testing.T, policy idpv1alpha1.GitHubAllowedAuthOrganizationsPolicy) metav1.Condition { t.Helper() return metav1.Condition{ @@ -377,12 +377,12 @@ func TestController(t *testing.T) { wantErr string wantLogs []string wantResultingCache []*upstreamgithub.ProviderConfig - wantResultingUpstreams []v1alpha1.GitHubIdentityProvider + wantResultingUpstreams []idpv1alpha1.GitHubIdentityProvider }{ { name: "no GitHubIdentityProviders", wantResultingCache: []*upstreamgithub.ProviderConfig{}, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{}, + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{}, wantLogs: []string{}, }, { @@ -414,12 +414,12 @@ func TestController(t *testing.T) { HttpClient: nil, // let the test runner populate this for us }, }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, Spec: validFilledOutIDP.Spec, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseReady, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseReady, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -470,12 +470,12 @@ func TestController(t *testing.T) { HttpClient: nil, // let the test runner populate this for us }, }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, Spec: validMinimalIDP.Spec, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseReady, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseReady, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -540,17 +540,17 @@ func TestController(t *testing.T) { HttpClient: nil, // let the test runner populate this for us }, }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { githubIDP := validMinimalIDP.DeepCopy() githubIDP.Spec.GitHubAPI.Host = ptr.To("github.com") // don't change the CA because we are not really going to dial github.com in this test return githubIDP.Spec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseReady, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseReady, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -579,7 +579,7 @@ func TestController(t *testing.T) { func() runtime.Object { ipv6IDP := validMinimalIDP.DeepCopy() ipv6IDP.Spec.GitHubAPI.Host = ptr.To(goodServerIPv6Domain) - ipv6IDP.Spec.GitHubAPI.TLS = &v1alpha1.TLSSpec{ + ipv6IDP.Spec.GitHubAPI.TLS = &idpv1alpha1.TLSSpec{ CertificateAuthorityData: goodServerIPv6CAB64, } return ipv6IDP @@ -608,20 +608,20 @@ func TestController(t *testing.T) { HttpClient: nil, // let the test runner populate this for us }, }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { otherSpec := validMinimalIDP.Spec.DeepCopy() otherSpec.GitHubAPI.Host = ptr.To(goodServerIPv6Domain) - otherSpec.GitHubAPI.TLS = &v1alpha1.TLSSpec{ + otherSpec.GitHubAPI.TLS = &idpv1alpha1.TLSSpec{ CertificateAuthorityData: goodServerIPv6CAB64, } return *otherSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseReady, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseReady, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -663,7 +663,7 @@ func TestController(t *testing.T) { otherIDP.Spec.Client.SecretName = "other-secret-name" // No other test happens to that this particular value passes validation - otherIDP.Spec.Claims.Username = ptr.To(v1alpha1.GitHubUsernameLoginAndID) + otherIDP.Spec.Claims.Username = ptr.To(idpv1alpha1.GitHubUsernameLoginAndID) return otherIDP }(), func() runtime.Object { @@ -717,20 +717,20 @@ func TestController(t *testing.T) { HttpClient: nil, // let the test runner populate this for us }, }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: func() metav1.ObjectMeta { otherMeta := validFilledOutIDP.ObjectMeta.DeepCopy() otherMeta.Name = "invalid-idp-name" return *otherMeta }(), - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { otherSpec := validFilledOutIDP.Spec.DeepCopy() otherSpec.Client.SecretName = "no-secret-with-this-name" return *otherSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidFalse( @@ -753,14 +753,14 @@ func TestController(t *testing.T) { otherMeta.Name = "other-idp-name" return *otherMeta }(), - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { otherSpec := validFilledOutIDP.Spec.DeepCopy() otherSpec.Client.SecretName = "other-secret-name" - otherSpec.Claims.Username = ptr.To(v1alpha1.GitHubUsernameLoginAndID) + otherSpec.Claims.Username = ptr.To(idpv1alpha1.GitHubUsernameLoginAndID) return *otherSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseReady, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseReady, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, "other-secret-name"), @@ -774,8 +774,8 @@ func TestController(t *testing.T) { { ObjectMeta: validFilledOutIDP.ObjectMeta, Spec: validFilledOutIDP.Spec, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseReady, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseReady, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -823,16 +823,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() badSpec.GitHubAPI.Host = nil return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -864,16 +864,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validMinimalIDP.Spec.DeepCopy() badSpec.GitHubAPI.Host = ptr.To("https://example.com") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -905,16 +905,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validMinimalIDP.Spec.DeepCopy() badSpec.GitHubAPI.Host = ptr.To("example.com/foo") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -946,16 +946,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validMinimalIDP.Spec.DeepCopy() badSpec.GitHubAPI.Host = ptr.To("u:p@example.com") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -987,16 +987,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validMinimalIDP.Spec.DeepCopy() badSpec.GitHubAPI.Host = ptr.To("example.com?a=b") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -1028,16 +1028,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validMinimalIDP.Spec.DeepCopy() badSpec.GitHubAPI.Host = ptr.To("example.com#a") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -1065,24 +1065,24 @@ func TestController(t *testing.T) { githubIdentityProviders: []runtime.Object{ func() runtime.Object { badIDP := validFilledOutIDP.DeepCopy() - badIDP.Spec.GitHubAPI.TLS = &v1alpha1.TLSSpec{ + badIDP.Spec.GitHubAPI.TLS = &idpv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte("foo")), } return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() - badSpec.GitHubAPI.TLS = &v1alpha1.TLSSpec{ + badSpec.GitHubAPI.TLS = &idpv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte("foo")), } return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1115,16 +1115,16 @@ func TestController(t *testing.T) { }(), }, wantErr: "dial tcp: lookup nowhere.bad-tld: no such host", - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validMinimalIDP.Spec.DeepCopy() badSpec.GitHubAPI.Host = ptr.To("nowhere.bad-tld") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -1156,16 +1156,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validMinimalIDP.Spec.DeepCopy() badSpec.GitHubAPI.Host = ptr.To("0:0:0:0:0:0:0:1:9876") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validMinimalIDP.Spec.Client.SecretName), @@ -1198,16 +1198,16 @@ func TestController(t *testing.T) { }(), }, wantErr: "tls: failed to verify certificate: x509: certificate signed by unknown authority", - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() badSpec.GitHubAPI.TLS = nil return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1235,25 +1235,25 @@ func TestController(t *testing.T) { githubIdentityProviders: []runtime.Object{ func() runtime.Object { badIDP := validFilledOutIDP.DeepCopy() - badIDP.Spec.GitHubAPI.TLS = &v1alpha1.TLSSpec{ + badIDP.Spec.GitHubAPI.TLS = &idpv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(unknownServerCABytes), } return badIDP }(), }, wantErr: "tls: failed to verify certificate: x509: certificate signed by unknown authority", - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() - badSpec.GitHubAPI.TLS = &v1alpha1.TLSSpec{ + badSpec.GitHubAPI.TLS = &idpv1alpha1.TLSSpec{ CertificateAuthorityData: base64.StdEncoding.EncodeToString(unknownServerCABytes), } return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1285,16 +1285,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() badSpec.AllowAuthentication.Organizations.Policy = nil return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1322,20 +1322,20 @@ func TestController(t *testing.T) { githubIdentityProviders: []runtime.Object{ func() runtime.Object { badIDP := validFilledOutIDP.DeepCopy() - badIDP.Spec.AllowAuthentication.Organizations.Policy = ptr.To[v1alpha1.GitHubAllowedAuthOrganizationsPolicy]("a") + badIDP.Spec.AllowAuthentication.Organizations.Policy = ptr.To[idpv1alpha1.GitHubAllowedAuthOrganizationsPolicy]("a") return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() - badSpec.AllowAuthentication.Organizations.Policy = ptr.To[v1alpha1.GitHubAllowedAuthOrganizationsPolicy]("a") + badSpec.AllowAuthentication.Organizations.Policy = ptr.To[idpv1alpha1.GitHubAllowedAuthOrganizationsPolicy]("a") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1363,20 +1363,20 @@ func TestController(t *testing.T) { githubIdentityProviders: []runtime.Object{ func() runtime.Object { badIDP := validFilledOutIDP.DeepCopy() - badIDP.Spec.AllowAuthentication.Organizations.Policy = ptr.To(v1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers) + badIDP.Spec.AllowAuthentication.Organizations.Policy = ptr.To(idpv1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers) return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() - badSpec.AllowAuthentication.Organizations.Policy = ptr.To(v1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers) + badSpec.AllowAuthentication.Organizations.Policy = ptr.To(idpv1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers) return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1408,16 +1408,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() badSpec.AllowAuthentication.Organizations.Allowed = nil return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1449,16 +1449,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() badSpec.Claims.Username = nil return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedFalse(t, "spec.claims.username is required"), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1486,20 +1486,20 @@ func TestController(t *testing.T) { githubIdentityProviders: []runtime.Object{ func() runtime.Object { badIDP := validFilledOutIDP.DeepCopy() - badIDP.Spec.Claims.Username = ptr.To[v1alpha1.GitHubUsernameAttribute]("a") + badIDP.Spec.Claims.Username = ptr.To[idpv1alpha1.GitHubUsernameAttribute]("a") return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() - badSpec.Claims.Username = ptr.To[v1alpha1.GitHubUsernameAttribute]("a") + badSpec.Claims.Username = ptr.To[idpv1alpha1.GitHubUsernameAttribute]("a") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedFalse(t, `spec.claims.username ("a") is not valid`), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1531,16 +1531,16 @@ func TestController(t *testing.T) { return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() badSpec.Claims.Groups = nil return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedFalse(t, "spec.claims.groups is required"), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1568,20 +1568,20 @@ func TestController(t *testing.T) { githubIdentityProviders: []runtime.Object{ func() runtime.Object { badIDP := validFilledOutIDP.DeepCopy() - badIDP.Spec.Claims.Groups = ptr.To[v1alpha1.GitHubGroupNameAttribute]("b") + badIDP.Spec.Claims.Groups = ptr.To[idpv1alpha1.GitHubGroupNameAttribute]("b") return badIDP }(), }, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validFilledOutIDP.ObjectMeta, - Spec: func() v1alpha1.GitHubIdentityProviderSpec { + Spec: func() idpv1alpha1.GitHubIdentityProviderSpec { badSpec := validFilledOutIDP.Spec.DeepCopy() - badSpec.Claims.Groups = ptr.To[v1alpha1.GitHubGroupNameAttribute]("b") + badSpec.Claims.Groups = ptr.To[idpv1alpha1.GitHubGroupNameAttribute]("b") return *badSpec }(), - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedFalse(t, `spec.claims.groups ("b") is not valid`), buildClientCredentialsSecretValidTrue(t, validFilledOutIDP.Spec.Client.SecretName), @@ -1613,12 +1613,12 @@ func TestController(t *testing.T) { }(), }, githubIdentityProviders: []runtime.Object{validMinimalIDP}, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, Spec: validMinimalIDP.Spec, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidFalse( @@ -1656,12 +1656,12 @@ func TestController(t *testing.T) { }(), }, githubIdentityProviders: []runtime.Object{validMinimalIDP}, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, Spec: validMinimalIDP.Spec, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidFalse( @@ -1699,12 +1699,12 @@ func TestController(t *testing.T) { }(), }, githubIdentityProviders: []runtime.Object{validMinimalIDP}, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, Spec: validMinimalIDP.Spec, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidFalse( @@ -1742,12 +1742,12 @@ func TestController(t *testing.T) { }(), }, githubIdentityProviders: []runtime.Object{validMinimalIDP}, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, Spec: validMinimalIDP.Spec, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidFalse( @@ -1785,12 +1785,12 @@ func TestController(t *testing.T) { }(), }, githubIdentityProviders: []runtime.Object{validMinimalIDP}, - wantResultingUpstreams: []v1alpha1.GitHubIdentityProvider{ + wantResultingUpstreams: []idpv1alpha1.GitHubIdentityProvider{ { ObjectMeta: validMinimalIDP.ObjectMeta, Spec: validMinimalIDP.Spec, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ buildClaimsValidatedTrue(t), buildClientCredentialsSecretValidFalse( @@ -1825,7 +1825,7 @@ func TestController(t *testing.T) { t.Parallel() fakeSupervisorClient := supervisorfake.NewSimpleClientset(tt.githubIdentityProviders...) - supervisorInformers := pinnipedinformers.NewSharedInformerFactory(fakeSupervisorClient, 0) + supervisorInformers := supervisorinformers.NewSharedInformerFactory(fakeSupervisorClient, 0) fakeKubeClient := kubernetesfake.NewSimpleClientset(tt.secrets...) kubeInformers := k8sinformers.NewSharedInformerFactoryWithOptions(fakeKubeClient, 0) @@ -1898,7 +1898,7 @@ func TestController(t *testing.T) { require.Equal(t, tt.wantResultingCache[i].AllowedOrganizations, actualProvider.GetAllowedOrganizations()) require.GreaterOrEqual(t, len(tt.githubIdentityProviders), i+1, "there must be at least as many input identity providers as items in the cache") - githubIDP, ok := tt.githubIdentityProviders[i].(*v1alpha1.GitHubIdentityProvider) + githubIDP, ok := tt.githubIdentityProviders[i].(*idpv1alpha1.GitHubIdentityProvider) require.True(t, ok) certPool, _, err := pinnipedcontroller.BuildCertPoolIDP(githubIDP.Spec.GitHubAPI.TLS) require.NoError(t, err) @@ -1917,7 +1917,7 @@ func TestController(t *testing.T) { require.Len(t, tt.wantResultingUpstreams[i].Status.Conditions, countExpectedConditions) // Do not expect any particular order in the K8s objects - var actualIDP *v1alpha1.GitHubIdentityProvider + var actualIDP *idpv1alpha1.GitHubIdentityProvider for _, possibleMatch := range allGitHubIDPs.Items { if possibleMatch.GetName() == tt.wantResultingUpstreams[i].Name { actualIDP = ptr.To(possibleMatch) @@ -1977,65 +1977,65 @@ func TestController_OnlyWantActions(t *testing.T) { }, } - validMinimalIDP := &v1alpha1.GitHubIdentityProvider{ + validMinimalIDP := &idpv1alpha1.GitHubIdentityProvider{ ObjectMeta: metav1.ObjectMeta{ Name: "minimal-idp-name", Namespace: namespace, UID: types.UID("minimal-uid"), Generation: 1234, }, - Spec: v1alpha1.GitHubIdentityProviderSpec{ - GitHubAPI: v1alpha1.GitHubAPIConfig{ + Spec: idpv1alpha1.GitHubIdentityProviderSpec{ + GitHubAPI: idpv1alpha1.GitHubAPIConfig{ Host: ptr.To(goodServerDomain), - TLS: &v1alpha1.TLSSpec{ + TLS: &idpv1alpha1.TLSSpec{ CertificateAuthorityData: goodServerCAB64, }, }, // These claims are optional when using the actual Kubernetes CRD. // However, they are required here because CRD defaulting/validation does not occur during testing. - Claims: v1alpha1.GitHubClaims{ - Username: ptr.To(v1alpha1.GitHubUsernameLogin), - Groups: ptr.To(v1alpha1.GitHubUseTeamSlugForGroupName), + Claims: idpv1alpha1.GitHubClaims{ + Username: ptr.To(idpv1alpha1.GitHubUsernameLogin), + Groups: ptr.To(idpv1alpha1.GitHubUseTeamSlugForGroupName), }, - Client: v1alpha1.GitHubClientSpec{ + Client: idpv1alpha1.GitHubClientSpec{ SecretName: goodSecret.Name, }, - AllowAuthentication: v1alpha1.GitHubAllowAuthenticationSpec{ - Organizations: v1alpha1.GitHubOrganizationsSpec{ - Policy: ptr.To(v1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers), + AllowAuthentication: idpv1alpha1.GitHubAllowAuthenticationSpec{ + Organizations: idpv1alpha1.GitHubOrganizationsSpec{ + Policy: ptr.To(idpv1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers), }, }, }, } - alreadyInvalidExistingIDP := &v1alpha1.GitHubIdentityProvider{ + alreadyInvalidExistingIDP := &idpv1alpha1.GitHubIdentityProvider{ ObjectMeta: metav1.ObjectMeta{ Name: "already-existing-invalid-idp-name", Namespace: namespace, UID: types.UID("some-resource-uid"), Generation: 333, }, - Spec: v1alpha1.GitHubIdentityProviderSpec{ - GitHubAPI: v1alpha1.GitHubAPIConfig{ + Spec: idpv1alpha1.GitHubIdentityProviderSpec{ + GitHubAPI: idpv1alpha1.GitHubAPIConfig{ Host: ptr.To(goodServerDomain), - TLS: &v1alpha1.TLSSpec{ + TLS: &idpv1alpha1.TLSSpec{ CertificateAuthorityData: goodServerCAB64, }, }, - AllowAuthentication: v1alpha1.GitHubAllowAuthenticationSpec{ - Organizations: v1alpha1.GitHubOrganizationsSpec{ - Policy: ptr.To(v1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers), + AllowAuthentication: idpv1alpha1.GitHubAllowAuthenticationSpec{ + Organizations: idpv1alpha1.GitHubOrganizationsSpec{ + Policy: ptr.To(idpv1alpha1.GitHubAllowedAuthOrganizationsPolicyAllGitHubUsers), }, }, - Claims: v1alpha1.GitHubClaims{ - Groups: ptr.To(v1alpha1.GitHubUseTeamSlugForGroupName), + Claims: idpv1alpha1.GitHubClaims{ + Groups: ptr.To(idpv1alpha1.GitHubUseTeamSlugForGroupName), }, - Client: v1alpha1.GitHubClientSpec{ + Client: idpv1alpha1.GitHubClientSpec{ SecretName: "unknown-secret", }, }, - Status: v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseError, + Status: idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseError, Conditions: []metav1.Condition{ { Type: ClaimsValid, @@ -2114,7 +2114,7 @@ func TestController_OnlyWantActions(t *testing.T) { func() runtime.Object { otherIDP := alreadyInvalidExistingIDP.DeepCopy() otherIDP.Generation = 400 - otherIDP.Status.Phase = v1alpha1.GitHubPhaseReady + otherIDP.Status.Phase = idpv1alpha1.GitHubPhaseReady otherIDP.Status.Conditions[0].Status = metav1.ConditionTrue otherIDP.Status.Conditions[0].Message = "some other message indicating that things are good" return otherIDP @@ -2146,8 +2146,8 @@ func TestController_OnlyWantActions(t *testing.T) { wantActions: []coretesting.Action{ coretesting.NewUpdateSubresourceAction(githubIDPGVR, "status", namespace, func() runtime.Object { idpWithConditions := validMinimalIDP.DeepCopy() - idpWithConditions.Status = v1alpha1.GitHubIdentityProviderStatus{ - Phase: v1alpha1.GitHubPhaseReady, + idpWithConditions.Status = idpv1alpha1.GitHubIdentityProviderStatus{ + Phase: idpv1alpha1.GitHubPhaseReady, Conditions: []metav1.Condition{ { Type: ClaimsValid, @@ -2210,7 +2210,7 @@ func TestController_OnlyWantActions(t *testing.T) { t.Parallel() fakeSupervisorClient := supervisorfake.NewSimpleClientset(tt.githubIdentityProviders...) - supervisorInformers := pinnipedinformers.NewSharedInformerFactory(supervisorfake.NewSimpleClientset(tt.githubIdentityProviders...), 0) + supervisorInformers := supervisorinformers.NewSharedInformerFactory(supervisorfake.NewSimpleClientset(tt.githubIdentityProviders...), 0) if tt.addSupervisorReactors != nil { tt.addSupervisorReactors(fakeSupervisorClient) @@ -2335,7 +2335,7 @@ func TestGitHubUpstreamWatcherControllerFilterSecret(t *testing.T) { namespace, dynamicupstreamprovider.NewDynamicUpstreamIDPProvider(), supervisorfake.NewSimpleClientset(), - pinnipedinformers.NewSharedInformerFactory(supervisorfake.NewSimpleClientset(), 0).IDP().V1alpha1().GitHubIdentityProviders(), + supervisorinformers.NewSharedInformerFactory(supervisorfake.NewSimpleClientset(), 0).IDP().V1alpha1().GitHubIdentityProviders(), secretInformer, logger, observableInformers.WithInformer, @@ -2355,7 +2355,7 @@ func TestGitHubUpstreamWatcherControllerFilterSecret(t *testing.T) { func TestGitHubUpstreamWatcherControllerFilterGitHubIDP(t *testing.T) { namespace := "some-namespace" - goodIDP := &v1alpha1.GitHubIdentityProvider{ + goodIDP := &idpv1alpha1.GitHubIdentityProvider{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, }, @@ -2397,7 +2397,7 @@ func TestGitHubUpstreamWatcherControllerFilterGitHubIDP(t *testing.T) { var log bytes.Buffer logger := plog.TestLogger(t, &log) - gitHubIdentityProviderInformer := pinnipedinformers.NewSharedInformerFactory(supervisorfake.NewSimpleClientset(), 0).IDP().V1alpha1().GitHubIdentityProviders() + gitHubIdentityProviderInformer := supervisorinformers.NewSharedInformerFactory(supervisorfake.NewSimpleClientset(), 0).IDP().V1alpha1().GitHubIdentityProviders() observableInformers := testutil.NewObservableWithInformerOption() _ = New( @@ -2412,7 +2412,7 @@ func TestGitHubUpstreamWatcherControllerFilterGitHubIDP(t *testing.T) { tls.Dial, ) - unrelated := &v1alpha1.GitHubIdentityProvider{} + unrelated := &idpv1alpha1.GitHubIdentityProvider{} filter := observableInformers.GetFilterForInformer(gitHubIdentityProviderInformer) require.Equal(t, tt.wantAdd, filter.Add(tt.idp)) require.Equal(t, tt.wantUpdate, filter.Update(unrelated, tt.idp)) diff --git a/internal/controller/utils.go b/internal/controller/utils.go index 5b84ba109..e280cce68 100644 --- a/internal/controller/utils.go +++ b/internal/controller/utils.go @@ -13,7 +13,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/util/cert" - authv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" + authenticationv1alpha1 "go.pinniped.dev/generated/latest/apis/concierge/authentication/v1alpha1" idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/controllerlib" ) @@ -103,7 +103,7 @@ type WithInitialEventOptionFunc func(key controllerlib.Key) controllerlib.Option // BuildCertPoolAuth returns a PEM-encoded CA bundle from the provided spec. If the provided spec is nil, a // nil CA bundle will be returned. If the provided spec contains a CA bundle that is not properly // encoded, an error will be returned. -func BuildCertPoolAuth(spec *authv1alpha1.TLSSpec) (*x509.CertPool, []byte, error) { +func BuildCertPoolAuth(spec *authenticationv1alpha1.TLSSpec) (*x509.CertPool, []byte, error) { if spec == nil { return nil, nil, nil } diff --git a/internal/federationdomain/endpoints/callback/callback_handler_test.go b/internal/federationdomain/endpoints/callback/callback_handler_test.go index 8859d7ebe..2dd34d078 100644 --- a/internal/federationdomain/endpoints/callback/callback_handler_test.go +++ b/internal/federationdomain/endpoints/callback/callback_handler_test.go @@ -242,7 +242,7 @@ func TestCallbackEndpoint(t *testing.T) { wantDownstreamPKCEChallenge string wantDownstreamPKCEChallengeMethod string wantDownstreamCustomSessionData *psession.CustomSessionData - wantDownstreamAdditionalClaims map[string]interface{} + wantDownstreamAdditionalClaims map[string]any wantOIDCAuthcodeExchangeCall *expectedOIDCAuthcodeExchange wantGitHubAuthcodeExchangeCall *expectedGitHubAuthcodeExchange }{ @@ -795,7 +795,7 @@ func TestCallbackEndpoint(t *testing.T) { { name: "upstream IDP's configured groups claim in the ID token is a slice of interfaces", idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( - happyOIDCUpstream().WithIDTokenClaim(oidcUpstreamGroupsClaim, []interface{}{"group1", "group2"}).Build(), + happyOIDCUpstream().WithIDTokenClaim(oidcUpstreamGroupsClaim, []any{"group1", "group2"}).Build(), ), method: http.MethodGet, path: newRequestPath().WithState(happyOIDCState).String(), @@ -1675,7 +1675,7 @@ func TestCallbackEndpoint(t *testing.T) { { name: "upstream ID token contains groups claim where one element is invalid", idps: testidplister.NewUpstreamIDPListerBuilder().WithOIDC( - happyOIDCUpstream().WithIDTokenClaim(oidcUpstreamGroupsClaim, []interface{}{"foo", 7}).Build(), + happyOIDCUpstream().WithIDTokenClaim(oidcUpstreamGroupsClaim, []any{"foo", 7}).Build(), ), method: http.MethodGet, path: newRequestPath().WithState(happyOIDCState).String(), diff --git a/internal/federationdomain/endpoints/token/token_handler_test.go b/internal/federationdomain/endpoints/token/token_handler_test.go index 577d7442f..1d07aded5 100644 --- a/internal/federationdomain/endpoints/token/token_handler_test.go +++ b/internal/federationdomain/endpoints/token/token_handler_test.go @@ -305,7 +305,7 @@ type tokenEndpointResponseExpectedValues struct { wantUpstreamOIDCValidateTokenCall *expectedOIDCUpstreamValidateTokens wantCustomSessionDataStored *psession.CustomSessionData wantWarnings []RecordedWarning - wantAdditionalClaims map[string]interface{} + wantAdditionalClaims map[string]any // The expected lifetime of the ID tokens issued by authcode exchange and refresh, but not token exchange. // When zero, will assume that the test wants the default value for ID token lifetime. wantIDTokenLifetimeSeconds int diff --git a/internal/federationdomain/resolvedprovider/resolvedgithub/resolved_github_provider.go b/internal/federationdomain/resolvedprovider/resolvedgithub/resolved_github_provider.go index eb846b3e4..9bec7de01 100644 --- a/internal/federationdomain/resolvedprovider/resolvedgithub/resolved_github_provider.go +++ b/internal/federationdomain/resolvedprovider/resolvedgithub/resolved_github_provider.go @@ -58,14 +58,14 @@ func (p *FederationDomainResolvedGitHubIdentityProvider) GetTransforms() *idtran return p.Transforms } -func (p *FederationDomainResolvedGitHubIdentityProvider) CloneIDPSpecificSessionDataFromSession(session *psession.CustomSessionData) interface{} { +func (p *FederationDomainResolvedGitHubIdentityProvider) CloneIDPSpecificSessionDataFromSession(session *psession.CustomSessionData) any { if session.GitHub == nil { return nil } return session.GitHub.Clone() } -func (p *FederationDomainResolvedGitHubIdentityProvider) ApplyIDPSpecificSessionDataToSession(session *psession.CustomSessionData, idpSpecificSessionData interface{}) { +func (p *FederationDomainResolvedGitHubIdentityProvider) ApplyIDPSpecificSessionDataToSession(session *psession.CustomSessionData, idpSpecificSessionData any) { session.GitHub = idpSpecificSessionData.(*psession.GitHubSessionData) } diff --git a/internal/federationdomain/upstreamprovider/upstream_provider.go b/internal/federationdomain/upstreamprovider/upstream_provider.go index 5ca624892..070de4594 100644 --- a/internal/federationdomain/upstreamprovider/upstream_provider.go +++ b/internal/federationdomain/upstreamprovider/upstream_provider.go @@ -10,7 +10,7 @@ import ( "golang.org/x/oauth2" "k8s.io/apimachinery/pkg/types" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/authenticators" "go.pinniped.dev/internal/setutil" "go.pinniped.dev/pkg/oidcclient/nonce" @@ -162,12 +162,12 @@ type UpstreamGithubIdentityProviderI interface { // GetUsernameAttribute returns the attribute from the GitHub API user response to use for the downstream username. // See https://docs.github.com/en/rest/users/users?apiVersion=2022-11-28#get-the-authenticated-user. // Note that this is a constructed value - do not expect that the result will exactly match one of the JSON fields. - GetUsernameAttribute() v1alpha1.GitHubUsernameAttribute + GetUsernameAttribute() idpv1alpha1.GitHubUsernameAttribute // GetGroupNameAttribute returns the attribute from the GitHub API team response to use for the downstream group names. // See https://docs.github.com/en/rest/teams/teams?apiVersion=2022-11-28#list-teams-for-the-authenticated-user. // Note that this is a constructed value - do not expect that the result will exactly match one of the JSON fields. - GetGroupNameAttribute() v1alpha1.GitHubGroupNameAttribute + GetGroupNameAttribute() idpv1alpha1.GitHubGroupNameAttribute // GetAllowedOrganizations returns a list of organizations configured to allow authentication. // If this list has contents, a user must have membership in at least one of these organizations to log in, diff --git a/internal/testutil/oidctestutil/testgithubprovider.go b/internal/testutil/oidctestutil/testgithubprovider.go index aa8d1bc76..dea7fa9ff 100644 --- a/internal/testutil/oidctestutil/testgithubprovider.go +++ b/internal/testutil/oidctestutil/testgithubprovider.go @@ -8,7 +8,7 @@ import ( "k8s.io/apimachinery/pkg/types" - "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/federationdomain/upstreamprovider" "go.pinniped.dev/internal/idtransform" "go.pinniped.dev/internal/setutil" @@ -37,8 +37,8 @@ type TestUpstreamGitHubIdentityProviderBuilder struct { scopes []string displayNameForFederationDomain string transformsForFederationDomain *idtransform.TransformationPipeline - usernameAttribute v1alpha1.GitHubUsernameAttribute - groupNameAttribute v1alpha1.GitHubGroupNameAttribute + usernameAttribute idpv1alpha1.GitHubUsernameAttribute + groupNameAttribute idpv1alpha1.GitHubGroupNameAttribute allowedOrganizations *setutil.CaseInsensitiveSet authorizationURL string authcodeExchangeErr error @@ -72,12 +72,12 @@ func (u *TestUpstreamGitHubIdentityProviderBuilder) WithDisplayNameForFederation return u } -func (u *TestUpstreamGitHubIdentityProviderBuilder) WithUsernameAttribute(value v1alpha1.GitHubUsernameAttribute) *TestUpstreamGitHubIdentityProviderBuilder { +func (u *TestUpstreamGitHubIdentityProviderBuilder) WithUsernameAttribute(value idpv1alpha1.GitHubUsernameAttribute) *TestUpstreamGitHubIdentityProviderBuilder { u.usernameAttribute = value return u } -func (u *TestUpstreamGitHubIdentityProviderBuilder) WithGroupNameAttribute(value v1alpha1.GitHubGroupNameAttribute) *TestUpstreamGitHubIdentityProviderBuilder { +func (u *TestUpstreamGitHubIdentityProviderBuilder) WithGroupNameAttribute(value idpv1alpha1.GitHubGroupNameAttribute) *TestUpstreamGitHubIdentityProviderBuilder { u.groupNameAttribute = value return u } @@ -163,8 +163,8 @@ type TestUpstreamGitHubIdentityProvider struct { Scopes []string DisplayNameForFederationDomain string TransformsForFederationDomain *idtransform.TransformationPipeline - UsernameAttribute v1alpha1.GitHubUsernameAttribute - GroupNameAttribute v1alpha1.GitHubGroupNameAttribute + UsernameAttribute idpv1alpha1.GitHubUsernameAttribute + GroupNameAttribute idpv1alpha1.GitHubGroupNameAttribute AllowedOrganizations *setutil.CaseInsensitiveSet AuthorizationURL string GetUserFunc func(ctx context.Context, accessToken string) (*upstreamprovider.GitHubUser, error) @@ -195,11 +195,11 @@ func (u *TestUpstreamGitHubIdentityProvider) GetClientID() string { return u.ClientID } -func (u *TestUpstreamGitHubIdentityProvider) GetUsernameAttribute() v1alpha1.GitHubUsernameAttribute { +func (u *TestUpstreamGitHubIdentityProvider) GetUsernameAttribute() idpv1alpha1.GitHubUsernameAttribute { return u.UsernameAttribute } -func (u *TestUpstreamGitHubIdentityProvider) GetGroupNameAttribute() v1alpha1.GitHubGroupNameAttribute { +func (u *TestUpstreamGitHubIdentityProvider) GetGroupNameAttribute() idpv1alpha1.GitHubGroupNameAttribute { return u.GroupNameAttribute } diff --git a/internal/upstreamgithub/upstreamgithub.go b/internal/upstreamgithub/upstreamgithub.go index 6660787a1..dc8e2e56b 100644 --- a/internal/upstreamgithub/upstreamgithub.go +++ b/internal/upstreamgithub/upstreamgithub.go @@ -13,7 +13,7 @@ import ( "golang.org/x/oauth2" "k8s.io/apimachinery/pkg/types" - supervisoridpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/federationdomain/downstreamsubject" "go.pinniped.dev/internal/federationdomain/upstreamprovider" "go.pinniped.dev/internal/githubclient" @@ -31,8 +31,8 @@ type ProviderConfig struct { // or https://HOSTNAME/api/v3/ for Enterprise Server. APIBaseURL string - UsernameAttribute supervisoridpv1alpha1.GitHubUsernameAttribute - GroupNameAttribute supervisoridpv1alpha1.GitHubGroupNameAttribute + UsernameAttribute idpv1alpha1.GitHubUsernameAttribute + GroupNameAttribute idpv1alpha1.GitHubGroupNameAttribute // AllowedOrganizations, when empty, means to allow users from all orgs. AllowedOrganizations *setutil.CaseInsensitiveSet @@ -82,11 +82,11 @@ func (p *Provider) GetScopes() []string { return p.c.OAuth2Config.Scopes } -func (p *Provider) GetUsernameAttribute() supervisoridpv1alpha1.GitHubUsernameAttribute { +func (p *Provider) GetUsernameAttribute() idpv1alpha1.GitHubUsernameAttribute { return p.c.UsernameAttribute } -func (p *Provider) GetGroupNameAttribute() supervisoridpv1alpha1.GitHubGroupNameAttribute { +func (p *Provider) GetGroupNameAttribute() idpv1alpha1.GitHubGroupNameAttribute { return p.c.GroupNameAttribute } @@ -131,11 +131,11 @@ func (p *Provider) GetUser(ctx context.Context, accessToken string, idpDisplayNa githubUser.DownstreamSubject = downstreamsubject.GitHub(p.c.APIBaseURL, idpDisplayName, userInfo.Login, userInfo.ID) switch p.c.UsernameAttribute { - case supervisoridpv1alpha1.GitHubUsernameLoginAndID: + case idpv1alpha1.GitHubUsernameLoginAndID: githubUser.Username = fmt.Sprintf("%s:%s", userInfo.Login, userInfo.ID) - case supervisoridpv1alpha1.GitHubUsernameLogin: + case idpv1alpha1.GitHubUsernameLogin: githubUser.Username = userInfo.Login - case supervisoridpv1alpha1.GitHubUsernameID: + case idpv1alpha1.GitHubUsernameID: githubUser.Username = userInfo.ID default: return nil, fmt.Errorf("bad configuration: unknown GitHub username attribute: %s", p.c.UsernameAttribute) @@ -172,9 +172,9 @@ func (p *Provider) GetUser(ctx context.Context, accessToken string, idpDisplayNa downstreamGroup := "" switch p.c.GroupNameAttribute { - case supervisoridpv1alpha1.GitHubUseTeamNameForGroupName: + case idpv1alpha1.GitHubUseTeamNameForGroupName: downstreamGroup = fmt.Sprintf("%s/%s", team.Org, team.Name) - case supervisoridpv1alpha1.GitHubUseTeamSlugForGroupName: + case idpv1alpha1.GitHubUseTeamSlugForGroupName: downstreamGroup = fmt.Sprintf("%s/%s", team.Org, team.Slug) default: return nil, fmt.Errorf("bad configuration: unknown GitHub group name attribute: %s", p.c.GroupNameAttribute) diff --git a/internal/upstreamgithub/upstreamgithub_test.go b/internal/upstreamgithub/upstreamgithub_test.go index f2dd1263d..a1b9af26c 100644 --- a/internal/upstreamgithub/upstreamgithub_test.go +++ b/internal/upstreamgithub/upstreamgithub_test.go @@ -19,7 +19,7 @@ import ( "k8s.io/apimachinery/pkg/util/rand" "k8s.io/client-go/util/cert" - supervisoridpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" + idpv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idp/v1alpha1" "go.pinniped.dev/internal/federationdomain/upstreamprovider" "go.pinniped.dev/internal/githubclient" "go.pinniped.dev/internal/mocks/mockgithubclient" @@ -78,8 +78,8 @@ func TestGitHubProvider(t *testing.T) { require.Equal(t, types.UID("resource-uid-12345"), subject.GetResourceUID()) require.Equal(t, "fake-client-id", subject.GetClientID()) require.Equal(t, "fake-client-id", subject.GetClientID()) - require.Equal(t, supervisoridpv1alpha1.GitHubUsernameAttribute("fake-username-attribute"), subject.GetUsernameAttribute()) - require.Equal(t, supervisoridpv1alpha1.GitHubGroupNameAttribute("fake-group-name-attribute"), subject.GetGroupNameAttribute()) + require.Equal(t, idpv1alpha1.GitHubUsernameAttribute("fake-username-attribute"), subject.GetUsernameAttribute()) + require.Equal(t, idpv1alpha1.GitHubGroupNameAttribute("fake-group-name-attribute"), subject.GetGroupNameAttribute()) require.Equal(t, setutil.NewCaseInsensitiveSet("fake-org", "fake-org2"), subject.GetAllowedOrganizations()) require.Equal(t, "https://fake-authorization-url", subject.GetAuthorizationURL()) require.Equal(t, &http.Client{ @@ -213,7 +213,7 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameLoginAndID, + UsernameAttribute: idpv1alpha1.GitHubUsernameLoginAndID, }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { mockGitHubInterface.EXPECT().GetUserInfo(someContext).Return(&githubclient.UserInfo{ @@ -233,7 +233,7 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameLogin, + UsernameAttribute: idpv1alpha1.GitHubUsernameLogin, }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { mockGitHubInterface.EXPECT().GetUserInfo(someContext).Return(&githubclient.UserInfo{ @@ -253,7 +253,7 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameID, + UsernameAttribute: idpv1alpha1.GitHubUsernameID, }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { mockGitHubInterface.EXPECT().GetUserInfo(someContext).Return(&githubclient.UserInfo{ @@ -273,7 +273,7 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameLoginAndID, + UsernameAttribute: idpv1alpha1.GitHubUsernameLoginAndID, AllowedOrganizations: setutil.NewCaseInsensitiveSet("ALLOWED-ORG1", "ALLOWED-ORG2"), }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { @@ -294,7 +294,7 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameID, + UsernameAttribute: idpv1alpha1.GitHubUsernameID, AllowedOrganizations: setutil.NewCaseInsensitiveSet("allowed-org"), }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { @@ -311,9 +311,9 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameLoginAndID, + UsernameAttribute: idpv1alpha1.GitHubUsernameLoginAndID, AllowedOrganizations: setutil.NewCaseInsensitiveSet("allowed-org1", "allowed-org2"), - GroupNameAttribute: supervisoridpv1alpha1.GitHubUseTeamNameForGroupName, + GroupNameAttribute: idpv1alpha1.GitHubUseTeamNameForGroupName, }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { mockGitHubInterface.EXPECT().GetUserInfo(someContext).Return(&githubclient.UserInfo{ @@ -350,9 +350,9 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameLoginAndID, + UsernameAttribute: idpv1alpha1.GitHubUsernameLoginAndID, AllowedOrganizations: setutil.NewCaseInsensitiveSet("allowed-org1", "allowed-org2"), - GroupNameAttribute: supervisoridpv1alpha1.GitHubUseTeamSlugForGroupName, + GroupNameAttribute: idpv1alpha1.GitHubUseTeamSlugForGroupName, }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { mockGitHubInterface.EXPECT().GetUserInfo(someContext).Return(&githubclient.UserInfo{ @@ -409,7 +409,7 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameLoginAndID, + UsernameAttribute: idpv1alpha1.GitHubUsernameLoginAndID, }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { mockGitHubInterface.EXPECT().GetUserInfo(someContext).Return(&githubclient.UserInfo{}, nil) @@ -422,7 +422,7 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameLoginAndID, + UsernameAttribute: idpv1alpha1.GitHubUsernameLoginAndID, }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { mockGitHubInterface.EXPECT().GetUserInfo(someContext).Return(&githubclient.UserInfo{}, nil) @@ -451,7 +451,7 @@ func TestGetUser(t *testing.T) { providerConfig: ProviderConfig{ APIBaseURL: "https://some-url", HttpClient: someHttpClient, - UsernameAttribute: supervisoridpv1alpha1.GitHubUsernameLoginAndID, + UsernameAttribute: idpv1alpha1.GitHubUsernameLoginAndID, GroupNameAttribute: "this-is-not-legal-value-from-the-enum", }, buildMockResponses: func(mockGitHubInterface *mockgithubclient.MockGitHubInterface) { diff --git a/test/integration/e2e_test.go b/test/integration/e2e_test.go index 4175f69fc..66aa863a2 100644 --- a/test/integration/e2e_test.go +++ b/test/integration/e2e_test.go @@ -399,7 +399,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { _, err = ptyFile.WriteString(authCode + "\n") require.NoError(t, err) - // Read all of the remaining output from the subprocess until EOF. + // Read all the remaining output from the subprocess until EOF. 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. @@ -487,7 +487,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { kubectlCmd.Env = slices.Concat(os.Environ(), env.ProxyEnv()) var kubectlStdoutPipe io.ReadCloser if runtime.GOOS != "darwin" { - // For some unknown reason this breaks the pty library on some MacOS machines. + // For some unknown reason this breaks the pty library on some macOS machines. // The problem doesn't reproduce for everyone, so this is just a workaround. kubectlStdoutPipe, err = kubectlCmd.StdoutPipe() require.NoError(t, err) @@ -529,7 +529,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { _, err = ptyFile.WriteString(authCode + "\n") require.NoError(t, err) - // Read all of the remaining output from the subprocess until EOF. + // Read all the remaining output from the subprocess until EOF. 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. @@ -539,10 +539,10 @@ func TestE2EFullIntegration_Browser(t *testing.T) { 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. + // On macOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. requireKubectlGetNamespaceOutput(t, env, string(kubectlPtyOutputBytes)) } - // Due to the GOOS check in the code above, on MacOS the pty will include stdout, and other platforms it will not. + // Due to the GOOS check in the code above, on macOS the pty will include stdout, and other platforms it will not. // This warning message is supposed to be printed by the CLI on stderr. require.Contains(t, string(kubectlPtyOutputBytes), "Access token from identity provider has lifetime of less than 3 hours. Expect frequent prompts to log in.") @@ -1253,8 +1253,8 @@ func TestE2EFullIntegration_Browser(t *testing.T) { ).Name, }, }, idpv1alpha1.GitHubPhaseReady) - testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, configv1alpha1.FederationDomainPhaseReady) - testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authv1alpha.JWTAuthenticatorPhaseReady) + testlib.WaitForFederationDomainStatusPhase(testCtx, t, federationDomain.Name, supervisorconfigv1alpha1.FederationDomainPhaseReady) + testlib.WaitForJWTAuthenticatorStatusPhase(testCtx, t, authenticator.Name, authenticationv1alpha1.JWTAuthenticatorPhaseReady) // Use a specific session cache for this test. sessionCachePath := tempDir + "/test-sessions.yaml" @@ -1582,7 +1582,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { ) require.NoError(t, err) - // Wait for the status conditions to have observed the current spec generation so we can be sure that the + // Wait for the status conditions to have observed the current spec generation, so we can be sure that the // controller has observed our latest update. testlib.RequireEventually(t, func(requireEventually *require.Assertions) { fd, err := federationDomainsClient.Get(testCtx, federationDomain.Name, metav1.GetOptions{}) diff --git a/test/integration/supervisor_login_test.go b/test/integration/supervisor_login_test.go index b41fa4099..442985c8a 100644 --- a/test/integration/supervisor_login_test.go +++ b/test/integration/supervisor_login_test.go @@ -76,7 +76,7 @@ type supervisorLoginTestcase struct { // Optionally specify the identityProviders part of the FederationDomain's spec by returning it from this function. // Also return the displayName of the IDP that should be used during authentication (or empty string for no IDP name in the auth request). // This function takes the name of the IDP CR which was returned by createIDP() as as argument. - federationDomainIDPs func(t *testing.T, idpName string) (idps []configv1alpha1.FederationDomainIdentityProvider, useIDPDisplayName string) + federationDomainIDPs func(t *testing.T, idpName string) (idps []supervisorconfigv1alpha1.FederationDomainIdentityProvider, useIDPDisplayName string) // Optionally create an OIDCClient CR for the test to use. Return the client ID and client secret for the // test to use. When not set, the test will default to using the "pinniped-cli" static client with no secret. @@ -119,7 +119,7 @@ type supervisorLoginTestcase struct { wantDownstreamIDTokenGroups []string // The expected ID token additional claims, which will be nested under claim "additionalClaims", // for the original ID token and the refreshed ID token. - wantDownstreamIDTokenAdditionalClaims map[string]interface{} + wantDownstreamIDTokenAdditionalClaims map[string]any // The expected ID token lifetime, as calculated by token claim 'exp' subtracting token claim 'iat'. // ID tokens issued through authcode exchange or token refresh should have the configured lifetime (or default if not configured). // ID tokens issued through a token exchange should have the default lifetime. @@ -814,7 +814,7 @@ func TestSupervisorLogin_Browser(t *testing.T) { requestAuthorizationUsingCLIPasswordFlow(t, downstreamAuthorizeURL, env.SupervisorUpstreamLDAP.TestUserMailAttributeValue, // username to present to server during login - "incorrect", // password to present to server during login + "incorrect", // password to present to server during login httpClient, true, ) @@ -2358,9 +2358,9 @@ func supervisorLoginGithubTestcases( } return testlib.CreateTestGitHubIdentityProvider(t, spec, idpv1alpha1.GitHubPhaseReady).Name }, - federationDomainIDPs: func(t *testing.T, idpName string) ([]configv1alpha1.FederationDomainIdentityProvider, string) { + federationDomainIDPs: func(t *testing.T, idpName string) ([]supervisorconfigv1alpha1.FederationDomainIdentityProvider, string) { displayName := "some-github-identity-provider-name" - return []configv1alpha1.FederationDomainIdentityProvider{ + return []supervisorconfigv1alpha1.FederationDomainIdentityProvider{ { DisplayName: displayName, ObjectRef: corev1.TypedLocalObjectReference{ @@ -2392,7 +2392,7 @@ func supervisorLoginGithubTestcases( } } -func wantGroupsInAdditionalClaimsIfGroupsExist(additionalClaims map[string]interface{}, wantGroupsAdditionalClaimName string, wantGroups []string) map[string]interface{} { +func wantGroupsInAdditionalClaimsIfGroupsExist(additionalClaims map[string]any, wantGroupsAdditionalClaimName string, wantGroups []string) map[string]any { if len(wantGroups) > 0 { var wantGroupsAnyType []any for _, group := range wantGroups { diff --git a/test/testlib/client.go b/test/testlib/client.go index 748ddd98f..504ef0bdf 100644 --- a/test/testlib/client.go +++ b/test/testlib/client.go @@ -620,7 +620,7 @@ func CreateTestGitHubIdentityProviderWithObjectMeta(t *testing.T, spec idpv1alph t.Cleanup(func() { t.Logf("cleaning up test GitHubIdentityProvider %s/%s", created.Namespace, created.Name) err := upstreams.Delete(context.Background(), created.Name, metav1.DeleteOptions{}) - notFound := k8serrors.IsNotFound(err) + notFound := apierrors.IsNotFound(err) // It's okay if it is not found, because it might have been deleted by another part of this test. if !notFound { require.NoErrorf(t, err, "could not cleanup test GitHubIdentityProvider %s/%s", created.Namespace, created.Name)