diff --git a/cli/core/pkg/auth/tkg/kube_config.go b/cli/core/pkg/auth/tkg/kube_config.go index 4ae9a6329b..23f3e139f2 100644 --- a/cli/core/pkg/auth/tkg/kube_config.go +++ b/cli/core/pkg/auth/tkg/kube_config.go @@ -4,42 +4,27 @@ package tkgauth import ( - "encoding/base64" "encoding/json" - "fmt" "os" "path/filepath" - "time" "github.com/pkg/errors" + "k8s.io/client-go/discovery" - clientauthenticationv1beta1 "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1" "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" kubeutils "github.com/vmware-tanzu/tanzu-framework/cli/core/pkg/auth/utils/kubeconfig" - "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" + + pinnipedkubeconfig "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/kubeconfig" ) const ( - // ConciergeAuthenticatorType is the pinniped concierge authenticator type - ConciergeAuthenticatorType = "jwt" - - // ConciergeAuthenticatorName is the pinniped concierge authenticator object name - ConciergeAuthenticatorName = "tkg-jwt-authenticator" - - // PinnipedOIDCScopes are the scopes of pinniped oidc - PinnipedOIDCScopes = "offline_access,openid,pinniped:request-audience" - // TanzuLocalKubeDir is the local config directory TanzuLocalKubeDir = ".kube-tanzu" // TanzuKubeconfigFile is the name the of the kubeconfig file TanzuKubeconfigFile = "config" - // DefaultPinnipedLoginTimeout is the default login timeout - DefaultPinnipedLoginTimeout = time.Minute - // DefaultClusterInfoConfigMap is the default ConfigMap looked up in the kube-public namespace when generating a kubeconfig. DefaultClusterInfoConfigMap = "cluster-info" ) @@ -76,7 +61,7 @@ func KubeconfigWithPinnipedAuthLoginPlugin(endpoint string, options *KubeConfigO return } - config, err := GetPinnipedKubeconfig(clusterInfo, pinnipedInfo, pinnipedInfo.ClusterName, pinnipedInfo.Issuer) + config, err := pinnipedkubeconfig.GetPinnipedKubeconfig(clusterInfo, pinnipedInfo, pinnipedInfo.ClusterName, pinnipedInfo.Issuer) if err != nil { err = errors.Wrap(err, "unable to get the kubeconfig") return @@ -121,7 +106,7 @@ func GetServerKubernetesVersion(kubeconfigPath, context string) (string, error) return "", errors.Errorf("Unable to set up rest config due to : %v", err) } // set the timeout to give user sufficient time to enter the login credentials - restConfig.Timeout = DefaultPinnipedLoginTimeout + restConfig.Timeout = pinnipedkubeconfig.DefaultPinnipedLoginTimeout discoveryClient, err = discovery.NewDiscoveryClientForConfig(restConfig) if err != nil { @@ -148,52 +133,6 @@ func loadKubeconfigAndEnsureContext(kubeConfigPath, context string) ([]byte, err return clientcmd.Write(*config) } -// GetPinnipedKubeconfig generate kubeconfig given cluster-info and pinniped-info and the requested audience -func GetPinnipedKubeconfig(cluster *clientcmdapi.Cluster, pinnipedInfo *pinnipedinfo.PinnipedInfo, clustername, audience string) (*clientcmdapi.Config, error) { - execConfig := clientcmdapi.ExecConfig{ - APIVersion: clientauthenticationv1beta1.SchemeGroupVersion.String(), - Args: []string{}, - Env: []clientcmdapi.ExecEnvVar{}, - } - - execConfig.Command = "tanzu" - execConfig.Args = append([]string{"pinniped-auth", "login"}, execConfig.Args...) - - conciergeEndpoint := cluster.Server - if pinnipedInfo.ConciergeEndpoint != "" { - conciergeEndpoint = pinnipedInfo.ConciergeEndpoint - } - - // configure concierge - execConfig.Args = append(execConfig.Args, - "--enable-concierge", - "--concierge-authenticator-name="+ConciergeAuthenticatorName, - "--concierge-authenticator-type="+ConciergeAuthenticatorType, - "--concierge-endpoint="+conciergeEndpoint, - "--concierge-ca-bundle-data="+base64.StdEncoding.EncodeToString(cluster.CertificateAuthorityData), - "--issuer="+pinnipedInfo.Issuer, // configure OIDC - "--scopes="+PinnipedOIDCScopes, - "--ca-bundle-data="+pinnipedInfo.IssuerCABundleData, - "--request-audience="+audience, - ) - - if os.Getenv("TANZU_CLI_PINNIPED_AUTH_LOGIN_SKIP_BROWSER") != "" { - execConfig.Args = append(execConfig.Args, "--skip-browser") - } - - username := "tanzu-cli-" + clustername - contextName := fmt.Sprintf("%s@%s", username, clustername) - - return &clientcmdapi.Config{ - Kind: "Config", - APIVersion: clientcmdapi.SchemeGroupVersion.Version, - Clusters: map[string]*clientcmdapi.Cluster{clustername: cluster}, - AuthInfos: map[string]*clientcmdapi.AuthInfo{username: {Exec: &execConfig}}, - Contexts: map[string]*clientcmdapi.Context{contextName: {Cluster: clustername, AuthInfo: username}}, - CurrentContext: contextName, - }, nil -} - // TanzuLocalKubeConfigPath returns the local tanzu kubeconfig path func TanzuLocalKubeConfigPath() (path string, err error) { home, err := os.UserHomeDir() diff --git a/cli/core/pkg/auth/tkg/kube_config_test.go b/cli/core/pkg/auth/tkg/kube_config_test.go index db6b462e4f..787324aa41 100644 --- a/cli/core/pkg/auth/tkg/kube_config_test.go +++ b/cli/core/pkg/auth/tkg/kube_config_test.go @@ -13,9 +13,6 @@ import ( "path/filepath" "testing" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/ghttp" clientauthenticationv1beta1 "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1" "k8s.io/client-go/tools/clientcmd" @@ -23,6 +20,8 @@ import ( tkgauth "github.com/vmware-tanzu/tanzu-framework/cli/core/pkg/auth/tkg" "github.com/vmware-tanzu/tanzu-framework/cli/core/pkg/fakes/helper" + pinnipedkubeconfig "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/kubeconfig" + "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" ) @@ -197,12 +196,12 @@ func getExpectedExecConfig(endpoint string, issuer string, issuerCA string, serv args := []string{ "pinniped-auth", "login", "--enable-concierge", - "--concierge-authenticator-name=" + tkgauth.ConciergeAuthenticatorName, - "--concierge-authenticator-type=" + tkgauth.ConciergeAuthenticatorType, + "--concierge-authenticator-name=" + pinnipedkubeconfig.ConciergeAuthenticatorName, + "--concierge-authenticator-type=" + pinnipedkubeconfig.ConciergeAuthenticatorType, "--concierge-endpoint=" + endpoint, "--concierge-ca-bundle-data=" + base64.StdEncoding.EncodeToString(certBytes), "--issuer=" + issuer, - "--scopes=" + tkgauth.PinnipedOIDCScopes, + "--scopes=" + pinnipedkubeconfig.PinnipedOIDCScopes, "--ca-bundle-data=" + issuerCA, "--request-audience=" + issuer, } diff --git a/cmd/cli/plugin/cluster/kubeconfig_get.go b/cmd/cli/plugin/cluster/kubeconfig_get.go index 29d93e7159..e106017273 100644 --- a/cmd/cli/plugin/cluster/kubeconfig_get.go +++ b/cmd/cli/plugin/cluster/kubeconfig_get.go @@ -12,10 +12,10 @@ import ( configapi "github.com/vmware-tanzu/tanzu-framework/cli/runtime/apis/config/v1alpha1" "github.com/vmware-tanzu/tanzu-framework/cli/runtime/config" - tkgauth "github.com/vmware-tanzu/tanzu-framework/tkg/auth" - tkgclient "github.com/vmware-tanzu/tanzu-framework/tkg/client" "github.com/vmware-tanzu/tanzu-framework/tkg/tkgctl" + + pinnipedkubeconfig "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/kubeconfig" ) type getClusterKubeconfigOptions struct { @@ -102,8 +102,12 @@ func getPinnipedKubeconfig(tkgctlClient tkgctl.TKGClient, workloadClusterName st audience = *clusterPinnipedInfo.ClusterAudience } - kubeconfig, err := tkgauth.GetPinnipedKubeconfig(clusterPinnipedInfo.ClusterInfo, clusterPinnipedInfo.PinnipedInfo, - clusterPinnipedInfo.ClusterName, audience) + kubeconfig, err := pinnipedkubeconfig.GetPinnipedKubeconfig( + clusterPinnipedInfo.ClusterInfo, + clusterPinnipedInfo.PinnipedInfo, + clusterPinnipedInfo.ClusterName, + audience, + ) if err != nil { return errors.Wrap(err, "unable to get kubeconfig") diff --git a/cmd/cli/plugin/login/main.go b/cmd/cli/plugin/login/main.go index d0ae3891d2..c0a190e830 100644 --- a/cmd/cli/plugin/login/main.go +++ b/cmd/cli/plugin/login/main.go @@ -377,6 +377,8 @@ func createServerWithEndpoint() (server *configapi.Server, err error) { return nil, err } } else { + // TODO(BEN): this func has more complicated dependencies, but is obviouisly pinniped related, and it is + // duplicated. we need to decide how to factor it out. kubeConfig, kubecontext, err = tkgauth.KubeconfigWithPinnipedAuthLoginPlugin(endpoint, nil, tkgauth.DiscoveryStrategy{ClusterInfoConfigMap: tkgauth.DefaultClusterInfoConfigMap}) if err != nil { log.Fatalf("Error creating kubeconfig with tanzu pinniped-auth login plugin: %v", err) @@ -528,6 +530,8 @@ func getDiscoveryHTTPClient() *http.Client { func vSphereSupervisorLogin(endpoint string) (mergeFilePath, currentContext string, err error) { port := 443 + // TODO(BEN): this func is trickier, it has more dependencies on things that we likely don't + // want to pull into /pinniped-components/common. kubeConfig, kubecontext, err := tkgauth.KubeconfigWithPinnipedAuthLoginPlugin(endpoint, nil, tkgauth.DiscoveryStrategy{DiscoveryPort: &port, ClusterInfoConfigMap: wcpauth.SupervisorVIPConfigMapName}) if err != nil { log.Fatalf("Error creating kubeconfig with tanzu pinniped-auth login plugin: %v", err) diff --git a/cmd/cli/plugin/managementcluster/kubeconfig_get.go b/cmd/cli/plugin/managementcluster/kubeconfig_get.go index 60fe21ed2e..b608fe4b3e 100644 --- a/cmd/cli/plugin/managementcluster/kubeconfig_get.go +++ b/cmd/cli/plugin/managementcluster/kubeconfig_get.go @@ -16,7 +16,8 @@ import ( configapi "github.com/vmware-tanzu/tanzu-framework/cli/runtime/apis/config/v1alpha1" "github.com/vmware-tanzu/tanzu-framework/cli/runtime/config" - tkgauth "github.com/vmware-tanzu/tanzu-framework/tkg/auth" + + pinnipedkubeconfig "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/kubeconfig" ) type getClusterKubeconfigOptions struct { @@ -102,8 +103,12 @@ func getPinnipedKubeconfig(tkgctlClient tkgctl.TKGClient, mcClustername string) // for management cluster the audience would be set to IssuerURL audience := clusterPinnipedInfo.PinnipedInfo.Issuer - kubeconfig, _ := tkgauth.GetPinnipedKubeconfig(clusterPinnipedInfo.ClusterInfo, clusterPinnipedInfo.PinnipedInfo, - clusterPinnipedInfo.ClusterName, audience) + kubeconfig, _ := pinnipedkubeconfig.GetPinnipedKubeconfig( + clusterPinnipedInfo.ClusterInfo, + clusterPinnipedInfo.PinnipedInfo, + clusterPinnipedInfo.ClusterName, + audience, + ) kubeconfigbytes, err := json.Marshal(kubeconfig) if err != nil { diff --git a/pinniped-components/common/go.mod b/pinniped-components/common/go.mod index d84dc9f3cf..997e1c4470 100644 --- a/pinniped-components/common/go.mod +++ b/pinniped-components/common/go.mod @@ -2,4 +2,37 @@ module github.com/vmware-tanzu/tanzu-framework/pinniped-components/common go 1.18 -require github.com/pkg/errors v0.9.1 +require ( + github.com/onsi/ginkgo v1.16.5 + github.com/onsi/gomega v1.24.1 + github.com/pkg/errors v0.9.1 + k8s.io/client-go v0.26.3 +) + +require ( + github.com/fsnotify/fsnotify v1.5.4 // indirect + github.com/go-logr/logr v1.2.3 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/google/go-cmp v0.5.9 // indirect + github.com/google/gofuzz v1.2.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/kr/pretty v0.3.0 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/nxadm/tail v1.4.8 // indirect + github.com/rogpeppe/go-internal v1.6.2 // indirect + github.com/stretchr/testify v1.8.1 // indirect + golang.org/x/net v0.8.0 // indirect + golang.org/x/sys v0.6.0 // indirect + golang.org/x/text v0.8.0 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/apimachinery v0.26.3 // indirect + k8s.io/klog/v2 v2.80.1 // indirect + k8s.io/utils v0.0.0-20221107191617-1a15be271d1d // indirect + sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect +) diff --git a/pinniped-components/common/go.sum b/pinniped-components/common/go.sum index 7c401c3f58..955c6e09f2 100644 --- a/pinniped-components/common/go.sum +++ b/pinniped-components/common/go.sum @@ -1,2 +1,160 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= +github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= +github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/ginkgo/v2 v2.5.0 h1:TRtrvv2vdQqzkwrQ1ke6vtXf7IK34RBUJafIy1wMwls= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.24.1 h1:KORJXNNTzJXzu4ScJWssJfJMnJ+2QJqhoQSRwNlze9E= +github.com/onsi/gomega v1.24.1/go.mod h1:3AOiACssS3/MajrniINInwbfOOtfZvplPzuRSmvt1jM= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.6.2 h1:aIihoIOHCiLZHxyoNQ+ABL4NKhFTgKLBdMLyEAh98m0= +github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +k8s.io/apimachinery v0.26.3 h1:dQx6PNETJ7nODU3XPtrwkfuubs6w7sX0M8n61zHIV/k= +k8s.io/apimachinery v0.26.3/go.mod h1:ats7nN1LExKHvJ9TmwootT00Yz05MuYqPXEXaVeOy5I= +k8s.io/client-go v0.26.3 h1:k1UY+KXfkxV2ScEL3gilKcF7761xkYsSD6BC9szIu8s= +k8s.io/client-go v0.26.3/go.mod h1:ZPNu9lm8/dbRIPAgteN30RSXea6vrCpFvq+MateTUuQ= +k8s.io/klog/v2 v2.80.1 h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4= +k8s.io/klog/v2 v2.80.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= +k8s.io/utils v0.0.0-20221107191617-1a15be271d1d h1:0Smp/HP1OH4Rvhe+4B8nWGERtlqAGSftbSbbmm45oFs= +k8s.io/utils v0.0.0-20221107191617-1a15be271d1d/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 h1:iXTIw73aPyC+oRdyqqvVJuloN1p0AC/kzH07hu3NE+k= +sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= +sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= +sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= +sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= diff --git a/pinniped-components/common/pkg/kubeconfig/doc.go b/pinniped-components/common/pkg/kubeconfig/doc.go new file mode 100644 index 0000000000..763cc1c699 --- /dev/null +++ b/pinniped-components/common/pkg/kubeconfig/doc.go @@ -0,0 +1,5 @@ +// Copyright 2023 VMware, Inc. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Package pinnipedinfo contains common code related to the Pinniped Info config map +package kubeconfig diff --git a/pinniped-components/common/pkg/kubeconfig/kubeconfig.go b/pinniped-components/common/pkg/kubeconfig/kubeconfig.go new file mode 100644 index 0000000000..aacf61b61d --- /dev/null +++ b/pinniped-components/common/pkg/kubeconfig/kubeconfig.go @@ -0,0 +1,76 @@ +package kubeconfig + +import ( + "encoding/base64" + "fmt" + "os" + "time" + + "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1" + "k8s.io/client-go/tools/clientcmd/api" + + "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" +) + +const ( + // ConciergeNamespace is the namespace where pinniped concierge is deployed + ConciergeNamespace = "pinniped-concierge" + + // ConciergeAuthenticatorType is the pinniped concierge authenticator type + ConciergeAuthenticatorType = "jwt" + + // ConciergeAuthenticatorName is the pinniped concierge authenticator object name + ConciergeAuthenticatorName = "tkg-jwt-authenticator" + + // PinnipedOIDCScopes are the scopes of pinniped oidc + PinnipedOIDCScopes = "offline_access,openid,pinniped:request-audience" + + // DefaultPinnipedLoginTimeout is the default login timeout + DefaultPinnipedLoginTimeout = time.Minute +) + +// GetPinnipedKubeconfig generate kubeconfig given cluster-info and pinniped-info and the requested audience +func GetPinnipedKubeconfig(cluster *api.Cluster, pinnipedInfo *pinnipedinfo.PinnipedInfo, clustername, audience string) (*api.Config, error) { + execConfig := api.ExecConfig{ + APIVersion: v1beta1.SchemeGroupVersion.String(), + Args: []string{}, + Env: []api.ExecEnvVar{}, + } + + execConfig.Command = "tanzu" + execConfig.Args = append([]string{"pinniped-auth", "login"}, execConfig.Args...) + + conciergeEndpoint := cluster.Server + if pinnipedInfo.ConciergeEndpoint != "" { + conciergeEndpoint = pinnipedInfo.ConciergeEndpoint + } + + // configure concierge + execConfig.Args = append(execConfig.Args, + "--enable-concierge", + "--concierge-authenticator-name="+ConciergeAuthenticatorName, + "--concierge-authenticator-type="+ConciergeAuthenticatorType, + "--concierge-endpoint="+conciergeEndpoint, + "--concierge-ca-bundle-data="+base64.StdEncoding.EncodeToString(cluster.CertificateAuthorityData), + "--issuer="+pinnipedInfo.Issuer, // configure OIDC + "--scopes="+PinnipedOIDCScopes, + "--ca-bundle-data="+pinnipedInfo.IssuerCABundleData, + "--request-audience="+audience, + ) + + if os.Getenv("TANZU_CLI_PINNIPED_AUTH_LOGIN_SKIP_BROWSER") != "" { + execConfig.Args = append(execConfig.Args, "--skip-browser") + } + + username := "tanzu-cli-" + clustername + contextName := fmt.Sprintf("%s@%s", username, clustername) + + return &api.Config{ + Kind: "Config", + APIVersion: api.SchemeGroupVersion.Version, + Clusters: map[string]*api.Cluster{clustername: cluster}, + AuthInfos: map[string]*api.AuthInfo{username: {Exec: &execConfig}}, + Contexts: map[string]*api.Context{contextName: {Cluster: clustername, AuthInfo: username}}, + CurrentContext: contextName, + }, nil +} diff --git a/pinniped-components/common/pkg/kubeconfig/kubeconfig_test.go b/pinniped-components/common/pkg/kubeconfig/kubeconfig_test.go new file mode 100644 index 0000000000..129678c613 --- /dev/null +++ b/pinniped-components/common/pkg/kubeconfig/kubeconfig_test.go @@ -0,0 +1,4 @@ +package kubeconfig + +// TODO: we factored the function out as-is, which had no direct tests. +// we will come back and add some tests diff --git a/pinniped-components/common/pkg/net/set_port.go b/pinniped-components/common/pkg/net/set_port.go new file mode 100644 index 0000000000..58c4311129 --- /dev/null +++ b/pinniped-components/common/pkg/net/set_port.go @@ -0,0 +1,34 @@ +// Copyright 2022 VMware, Inc. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Package net provides helpers to work with network addresses. +package net + +import ( + "fmt" + "net/url" + "strings" +) + +// SetPort takes a URL and returns it with the HTTPS scheme and the +// given port. +// If the endpoint is missing an HTTP(S) scheme, assumes input of the form +// host[:port]. +// This is mainly meant to handle the typical case of a user entering either +// just a host, host:port, or http(s)://host:port +func SetPort(endpoint string, portOverride int) (string, error) { + prefix := "" + // Preprocess the string depending on whether it has a scheme or not. + if strings.HasPrefix(endpoint, "https:") || strings.HasPrefix(endpoint, "http:") { + u, err := url.Parse(endpoint) + if err != nil { + return "", err + } + prefix = u.Hostname() + } else { + // No scheme. Strip out a port if it exists. + prefix = strings.Split(endpoint, ":")[0] + } + + return fmt.Sprintf("https://%s:%d", prefix, portOverride), nil +} diff --git a/pinniped-components/common/pkg/net/set_port_test.go b/pinniped-components/common/pkg/net/set_port_test.go new file mode 100644 index 0000000000..e86fa25b31 --- /dev/null +++ b/pinniped-components/common/pkg/net/set_port_test.go @@ -0,0 +1,50 @@ +// Copyright 2022 VMware, Inc. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package net + +import ( + "testing" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +func TestNetUtil(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Net util suite") +} + +var _ = Describe("Overriding ports in an endpoint", func() { + Context("when a port is provided", func() { + It("should override the port", func() { + endpoint := "https://foo.com:1234" + result, err := SetPort(endpoint, 443) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(Equal("https://foo.com:443")) + }) + }) + Context("when no scheme is provided", func() { + It("should override the port", func() { + endpoint := "foo.com" + result, err := SetPort(endpoint, 443) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(Equal("https://foo.com:443")) + }) + }) + Context("when no scheme is provided, but a port is set", func() { + It("should override the port", func() { + endpoint := "foo.com:6443" + result, err := SetPort(endpoint, 443) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(Equal("https://foo.com:443")) + }) + }) + Context("when a port with the same value as the overridden value is in the endpoint", func() { + It("should preserve the port", func() { + endpoint := "https://foo.com:443" + result, err := SetPort(endpoint, 443) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(Equal("https://foo.com:443")) + }) + }) +}) diff --git a/pinniped-components/common/pkg/pinnipedinfo/pinnipedinfo.go b/pinniped-components/common/pkg/pinnipedinfo/pinnipedinfo.go index 04c0749128..c19bb3ff52 100644 --- a/pinniped-components/common/pkg/pinnipedinfo/pinnipedinfo.go +++ b/pinniped-components/common/pkg/pinnipedinfo/pinnipedinfo.go @@ -4,9 +4,24 @@ package pinnipedinfo import ( + "crypto/tls" + "crypto/x509" "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" "github.com/pkg/errors" + "k8s.io/client-go/tools/clientcmd/api" + + "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/net" +) + +const ( + KubePublicNamespace = "kube-public" + PinnipedInfoConfigmapName = "pinniped-info" ) // PinnipedInfo contains settings for the supervisor. @@ -32,3 +47,53 @@ func ByteArrayToPinnipedInfo(responseBody []byte) (*PinnipedInfo, error) { return &pinnipedConfigMapInfo.Data, nil } + +// GetPinnipedInfoFromCluster gets the Pinniped Info by accessing the pinniped-info configMap in kube-public namespace +// 'discoveryPort' is used to optionally override the port used for discovery. This may be needed on setups that expose +// discovery information to unauthenticated users on a different port (for instance, to avoid the need to anonymous auth +// on the apiserver). By default, the endpoint from the cluster-info is used. +func GetPinnipedInfoFromCluster(clusterInfo *api.Cluster, discoveryPort *int) (*PinnipedInfo, error) { + endpoint := strings.TrimRight(clusterInfo.Server, " /") + var err error + if discoveryPort != nil { + endpoint, err = net.SetPort(clusterInfo.Server, *discoveryPort) + if err != nil { + return nil, errors.Wrap(err, "failed to override discovery port") + } + } + pinnipedInfoURL := endpoint + fmt.Sprintf("/api/v1/namespaces/%s/configmaps/pinniped-info", KubePublicNamespace) + //nolint:noctx + req, _ := http.NewRequest("GET", pinnipedInfoURL, http.NoBody) + pool := x509.NewCertPool() + pool.AppendCertsFromPEM(clusterInfo.CertificateAuthorityData) + clusterClient := &http.Client{ + Transport: &http.Transport{ + Proxy: http.ProxyFromEnvironment, + TLSClientConfig: &tls.Config{ + RootCAs: pool, + MinVersion: tls.VersionTLS12, + }, + }, + Timeout: time.Second * 10, + } + + response, err := clusterClient.Do(req) + if err != nil { + return nil, errors.Wrap(err, "failed to get pinniped-info from the cluster") + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + if response.StatusCode == http.StatusNotFound { + return nil, nil + } + return nil, fmt.Errorf("failed to get pinniped-info from the cluster. Status code: %+v", response.StatusCode) + } + + responseBody, err := io.ReadAll(response.Body) + if err != nil { + return nil, errors.Wrap(err, "failed to read the response body") + } + + return ByteArrayToPinnipedInfo(responseBody) +} diff --git a/pinniped-components/common/pkg/pinnipedinfo/pinnipedinfo_test.go b/pinniped-components/common/pkg/pinnipedinfo/pinnipedinfo_test.go new file mode 100644 index 0000000000..29d5d4bb07 --- /dev/null +++ b/pinniped-components/common/pkg/pinnipedinfo/pinnipedinfo_test.go @@ -0,0 +1 @@ +package pinnipedinfo diff --git a/tkg/auth/kube_config.go b/tkg/auth/kube_config.go index 994153d20b..2fa09fb19f 100644 --- a/tkg/auth/kube_config.go +++ b/tkg/auth/kube_config.go @@ -4,33 +4,22 @@ package auth import ( - "encoding/base64" "encoding/json" - "fmt" "os" "path/filepath" - "time" "github.com/pkg/errors" "k8s.io/client-go/discovery" - clientauthenticationv1beta1 "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1" "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" tkgclient "github.com/vmware-tanzu/tanzu-framework/tkg/client" tkgutils "github.com/vmware-tanzu/tanzu-framework/tkg/utils" + + pinnipedkubeconfig "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/kubeconfig" + "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" ) const ( - // ConciergeAuthenticatorType is the pinniped concierge authenticator type - ConciergeAuthenticatorType = "jwt" - - // ConciergeAuthenticatorName is the pinniped concierge authenticator object name - ConciergeAuthenticatorName = "tkg-jwt-authenticator" - - // PinnipedOIDCScopes are the scopes of pinniped oidc - PinnipedOIDCScopes = "offline_access,openid,pinniped:request-audience" // TanzuLocalKubeDir is the local config directory TanzuLocalKubeDir = ".kube-tanzu" @@ -38,9 +27,6 @@ const ( // TanzuKubeconfigFile is the name the of the kubeconfig file TanzuKubeconfigFile = "config" - // DefaultPinnipedLoginTimeout is the default login timeout - DefaultPinnipedLoginTimeout = time.Minute - // DefaultClusterInfoConfigMap is the default ConfigMap looked up in the kube-public namespace when generating a kubeconfig. DefaultClusterInfoConfigMap = "cluster-info" ) @@ -66,7 +52,7 @@ func KubeconfigWithPinnipedAuthLoginPlugin(endpoint string, options *KubeConfigO return } - pinnipedInfo, err := tkgutils.GetPinnipedInfoFromCluster(clusterInfo, discoveryStrategy.DiscoveryPort) + pinnipedInfo, err := pinnipedinfo.GetPinnipedInfoFromCluster(clusterInfo, discoveryStrategy.DiscoveryPort) if err != nil { err = errors.Wrap(err, "failed to get pinniped-info") return @@ -77,7 +63,7 @@ func KubeconfigWithPinnipedAuthLoginPlugin(endpoint string, options *KubeConfigO return } - config, err := GetPinnipedKubeconfig(clusterInfo, pinnipedInfo, pinnipedInfo.ClusterName, pinnipedInfo.Issuer) + config, err := pinnipedkubeconfig.GetPinnipedKubeconfig(clusterInfo, pinnipedInfo, pinnipedInfo.ClusterName, pinnipedInfo.Issuer) if err != nil { err = errors.Wrap(err, "unable to get the kubeconfig") return @@ -122,7 +108,7 @@ func GetServerKubernetesVersion(kubeconfigPath, context string) (string, error) return "", errors.Errorf("Unable to set up rest config due to : %v", err) } // set the timeout to give user sufficient time to enter the login credentials - restConfig.Timeout = DefaultPinnipedLoginTimeout + restConfig.Timeout = pinnipedkubeconfig.DefaultPinnipedLoginTimeout discoveryClient, err = discovery.NewDiscoveryClientForConfig(restConfig) if err != nil { @@ -149,52 +135,6 @@ func loadKubeconfigAndEnsureContext(kubeConfigPath, context string) ([]byte, err return clientcmd.Write(*config) } -// GetPinnipedKubeconfig generate kubeconfig given cluster-info and pinniped-info and the requested audience -func GetPinnipedKubeconfig(cluster *clientcmdapi.Cluster, pinnipedInfo *pinnipedinfo.PinnipedInfo, clustername, audience string) (*clientcmdapi.Config, error) { - execConfig := clientcmdapi.ExecConfig{ - APIVersion: clientauthenticationv1beta1.SchemeGroupVersion.String(), - Args: []string{}, - Env: []clientcmdapi.ExecEnvVar{}, - } - - execConfig.Command = "tanzu" - execConfig.Args = append([]string{"pinniped-auth", "login"}, execConfig.Args...) - - conciergeEndpoint := cluster.Server - if pinnipedInfo.ConciergeEndpoint != "" { - conciergeEndpoint = pinnipedInfo.ConciergeEndpoint - } - - // configure concierge - execConfig.Args = append(execConfig.Args, - "--enable-concierge", - "--concierge-authenticator-name="+ConciergeAuthenticatorName, - "--concierge-authenticator-type="+ConciergeAuthenticatorType, - "--concierge-endpoint="+conciergeEndpoint, - "--concierge-ca-bundle-data="+base64.StdEncoding.EncodeToString(cluster.CertificateAuthorityData), - "--issuer="+pinnipedInfo.Issuer, // configure OIDC - "--scopes="+PinnipedOIDCScopes, - "--ca-bundle-data="+pinnipedInfo.IssuerCABundleData, - "--request-audience="+audience, - ) - - if os.Getenv("TANZU_CLI_PINNIPED_AUTH_LOGIN_SKIP_BROWSER") != "" { - execConfig.Args = append(execConfig.Args, "--skip-browser") - } - - username := "tanzu-cli-" + clustername - contextName := fmt.Sprintf("%s@%s", username, clustername) - - return &clientcmdapi.Config{ - Kind: "Config", - APIVersion: clientcmdapi.SchemeGroupVersion.Version, - Clusters: map[string]*clientcmdapi.Cluster{clustername: cluster}, - AuthInfos: map[string]*clientcmdapi.AuthInfo{username: {Exec: &execConfig}}, - Contexts: map[string]*clientcmdapi.Context{contextName: {Cluster: clustername, AuthInfo: username}}, - CurrentContext: contextName, - }, nil -} - // TanzuLocalKubeConfigPath returns the local tanzu kubeconfig path func TanzuLocalKubeConfigPath() (path string, err error) { home, err := os.UserHomeDir() diff --git a/tkg/auth/kube_config_test.go b/tkg/auth/kube_config_test.go index 4a1ab1d7f3..2d6d861f75 100644 --- a/tkg/auth/kube_config_test.go +++ b/tkg/auth/kube_config_test.go @@ -20,9 +20,12 @@ import ( "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" - tkgauth "github.com/vmware-tanzu/tanzu-framework/tkg/auth" + tkgauth "github.com/vmware-tanzu/tanzu-framework/cli/core/pkg/auth/tkg" + "github.com/vmware-tanzu/tanzu-framework/tkg/auth" "github.com/vmware-tanzu/tanzu-framework/tkg/fakes/helper" + + pinnipedkubeconfig "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/kubeconfig" + "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" ) var testingDir string @@ -66,7 +69,8 @@ var _ = Describe("Unit tests for tkg auth", func() { ghttp.RespondWith(http.StatusNotFound, "not found"), ), ) - _, _, err = tkgauth.KubeconfigWithPinnipedAuthLoginPlugin(endpoint, nil, tkgauth.DiscoveryStrategy{ClusterInfoConfigMap: tkgauth.DefaultClusterInfoConfigMap}) + + _, _, err = auth.KubeconfigWithPinnipedAuthLoginPlugin(endpoint, nil, auth.DiscoveryStrategy{ClusterInfoConfigMap: auth.DefaultClusterInfoConfigMap}) }) It("should return the error", func() { Expect(err).To(HaveOccurred()) @@ -177,12 +181,12 @@ func getExpectedExecConfig(endpoint string, issuer string, issuerCA string, serv args := []string{ "pinniped-auth", "login", "--enable-concierge", - "--concierge-authenticator-name=" + tkgauth.ConciergeAuthenticatorName, - "--concierge-authenticator-type=" + tkgauth.ConciergeAuthenticatorType, + "--concierge-authenticator-name=" + pinnipedkubeconfig.ConciergeAuthenticatorName, + "--concierge-authenticator-type=" + pinnipedkubeconfig.ConciergeAuthenticatorType, "--concierge-endpoint=" + endpoint, "--concierge-ca-bundle-data=" + base64.StdEncoding.EncodeToString(certBytes), "--issuer=" + issuer, - "--scopes=" + tkgauth.PinnipedOIDCScopes, + "--scopes=" + pinnipedkubeconfig.PinnipedOIDCScopes, "--ca-bundle-data=" + issuerCA, "--request-audience=" + issuer, } diff --git a/tkg/client/get_cluster_pinniped_info.go b/tkg/client/get_cluster_pinniped_info.go index f44aefebf4..0ed797ec16 100644 --- a/tkg/client/get_cluster_pinniped_info.go +++ b/tkg/client/get_cluster_pinniped_info.go @@ -15,10 +15,11 @@ import ( clientcmdapi "k8s.io/client-go/tools/clientcmd/api" capi "sigs.k8s.io/cluster-api/api/v1beta1" - "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" "github.com/vmware-tanzu/tanzu-framework/tkg/clusterclient" "github.com/vmware-tanzu/tanzu-framework/tkg/region" "github.com/vmware-tanzu/tanzu-framework/tkg/utils" + + "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" ) // GetClusterPinnipedInfoOptions contains options supported by GetClusterPinnipedInfo @@ -95,7 +96,7 @@ func (c *TkgClient) GetWCClusterPinnipedInfo( // be constructed from an existing ConfigMap. configMap := corev1.ConfigMap{} - if err := regionalClusterClient.GetResource(&configMap, utils.PinnipedInfoConfigMapName, utils.KubePublicNamespace, nil, nil); err != nil { + if err := regionalClusterClient.GetResource(&configMap, pinnipedinfo.PinnipedInfoConfigmapName, utils.KubePublicNamespace, nil, nil); err != nil { return nil, errors.New("failed to get pinniped-info from management cluster") } @@ -158,7 +159,7 @@ func (c *TkgClient) GetMCClusterPinnipedInfo(regionalClusterClient clusterclient if err != nil { return nil, errors.Wrap(err, "failed to get cluster information") } - pinnipedInfo, err := utils.GetPinnipedInfoFromCluster(clusterInfo, nil) + pinnipedInfo, err := pinnipedinfo.GetPinnipedInfoFromCluster(clusterInfo, nil) if err != nil { return nil, errors.Wrap(err, "failed to get pinniped-info from cluster") } diff --git a/tkg/utils/kubeconfig.go b/tkg/utils/kubeconfig.go index db3584c48c..5f3450906b 100644 --- a/tkg/utils/kubeconfig.go +++ b/tkg/utils/kubeconfig.go @@ -5,7 +5,6 @@ package utils import ( "crypto/tls" - "crypto/x509" "encoding/json" "fmt" "io" @@ -17,14 +16,10 @@ import ( "github.com/pkg/errors" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - - "github.com/vmware-tanzu/tanzu-framework/pinniped-components/common/pkg/pinnipedinfo" - netutil "github.com/vmware-tanzu/tanzu-framework/tkg/utils/net" ) const ( - KubePublicNamespace = "kube-public" - PinnipedInfoConfigMapName = "pinniped-info" + KubePublicNamespace = "kube-public" ) type clusterInfoConfig struct { @@ -143,53 +138,3 @@ func GetClusterInfoFromCluster(clusterAPIServerURL, configmapName string) (*clie return cluster, nil } - -// GetPinnipedInfoFromCluster gets the Pinniped Info by accessing the pinniped-info configMap in kube-public namespace -// 'discoveryPort' is used to optionally override the port used for discovery. This may be needed on setups that expose -// discovery information to unauthenticated users on a different port (for instance, to avoid the need to anonymous auth -// on the apiserver). By default, the endpoint from the cluster-info is used. -func GetPinnipedInfoFromCluster(clusterInfo *clientcmdapi.Cluster, discoveryPort *int) (*pinnipedinfo.PinnipedInfo, error) { - endpoint := strings.TrimRight(clusterInfo.Server, " /") - var err error - if discoveryPort != nil { - endpoint, err = netutil.SetPort(clusterInfo.Server, *discoveryPort) - if err != nil { - return nil, errors.Wrap(err, "failed to override discovery port") - } - } - pinnipedInfoURL := endpoint + fmt.Sprintf("/api/v1/namespaces/%s/configmaps/pinniped-info", KubePublicNamespace) - //nolint:noctx - req, _ := http.NewRequest("GET", pinnipedInfoURL, http.NoBody) - pool := x509.NewCertPool() - pool.AppendCertsFromPEM(clusterInfo.CertificateAuthorityData) - clusterClient := &http.Client{ - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - TLSClientConfig: &tls.Config{ - RootCAs: pool, - MinVersion: tls.VersionTLS12, - }, - }, - Timeout: time.Second * 10, - } - - response, err := clusterClient.Do(req) - if err != nil { - return nil, errors.Wrap(err, "failed to get pinniped-info from the cluster") - } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - if response.StatusCode == http.StatusNotFound { - return nil, nil - } - return nil, fmt.Errorf("failed to get pinniped-info from the cluster. Status code: %+v", response.StatusCode) - } - - responseBody, err := io.ReadAll(response.Body) - if err != nil { - return nil, errors.Wrap(err, "failed to read the response body") - } - - return pinnipedinfo.ByteArrayToPinnipedInfo(responseBody) -} diff --git a/tkg/utils/kubeconfig_test.go b/tkg/utils/kubeconfig_test.go index 09561011ab..06ab2caf63 100644 --- a/tkg/utils/kubeconfig_test.go +++ b/tkg/utils/kubeconfig_test.go @@ -201,7 +201,7 @@ var _ = Describe("Kubeconfig Tests", func() { cluster.Server = endpoint certBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: servCert.Raw}) cluster.CertificateAuthorityData = certBytes - gotPinnipedInfo, err = utils.GetPinnipedInfoFromCluster(&cluster, nil) + gotPinnipedInfo, err = pinnipedinfo.GetPinnipedInfoFromCluster(&cluster, nil) }) It("should not return an error", func() { Expect(err).ToNot(HaveOccurred()) @@ -220,7 +220,7 @@ var _ = Describe("Kubeconfig Tests", func() { cluster.Server = endpoint certBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: servCert.Raw}) cluster.CertificateAuthorityData = certBytes - _, err = utils.GetPinnipedInfoFromCluster(&cluster, nil) + _, err = pinnipedinfo.GetPinnipedInfoFromCluster(&cluster, nil) }) It("should return the pinniped-info successfully", func() { Expect(err).To(HaveOccurred()) @@ -248,7 +248,7 @@ var _ = Describe("Kubeconfig Tests", func() { cluster.Server = endpoint certBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: servCert.Raw}) cluster.CertificateAuthorityData = certBytes - gotPinnipedInfo, err = utils.GetPinnipedInfoFromCluster(&cluster, nil) + gotPinnipedInfo, err = pinnipedinfo.GetPinnipedInfoFromCluster(&cluster, nil) }) It("should return the pinniped-info successfully", func() { Expect(err).ToNot(HaveOccurred()) @@ -289,7 +289,7 @@ var _ = Describe("Kubeconfig Tests", func() { cluster.Server = endpoint certBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: servCert.Raw}) cluster.CertificateAuthorityData = certBytes - gotPinnipedInfo, err = utils.GetPinnipedInfoFromCluster(&cluster, &discoveryPort) + gotPinnipedInfo, err = pinnipedinfo.GetPinnipedInfoFromCluster(&cluster, &discoveryPort) }) It("should return the pinniped-info successfully", func() { Expect(err).ToNot(HaveOccurred()) @@ -322,7 +322,7 @@ var _ = Describe("Kubeconfig Tests", func() { cluster.Server = endpoint certBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: servCert.Raw}) cluster.CertificateAuthorityData = certBytes - gotPinnipedInfo, err = utils.GetPinnipedInfoFromCluster(&cluster, nil) + gotPinnipedInfo, err = pinnipedinfo.GetPinnipedInfoFromCluster(&cluster, nil) }) It("should return the pinniped-info successfully", func() { Expect(err).ToNot(HaveOccurred())