From f8569ae913053c8ba4cd9ca72c9c237dd83200c0 Mon Sep 17 00:00:00 2001 From: Saravanan Balasubramanian <33908564+sarabala1979@users.noreply.github.com> Date: Tue, 21 Jan 2020 13:07:47 -0800 Subject: [PATCH] feat: Auth refactoring to support single version token (#1998) --- cmd/argo/commands/archive/delete.go | 2 +- cmd/argo/commands/archive/get.go | 2 +- cmd/argo/commands/archive/list.go | 2 +- cmd/argo/commands/client/conn.go | 6 +- cmd/argo/commands/common.go | 2 +- cmd/argo/commands/template/common.go | 2 +- cmd/server/auth/gatekeeper.go | 22 +- test/e2e/argo_server_test.go | 20 +- test/e2e/cli_test.go | 5 +- test/e2e/fixtures/e2e_suite.go | 26 ++- test/e2e/fixtures/env.go | 8 +- test/e2e/fixtures/util.go | 3 + test/e2e/manifests/postgres.yaml | 3 - .../overlays/argo-server-deployment.yaml | 6 +- ui/src/app/shared/services/requests.ts | 3 +- util/kubeconfig/kubeconfig.go | 192 +++++------------- util/kubeconfig/kubeconfig_test.go | 21 -- util/kubeconfig/token.go | 44 ---- util/kubeconfig/token_test.go | 49 ++--- 19 files changed, 149 insertions(+), 269 deletions(-) delete mode 100644 util/kubeconfig/kubeconfig_test.go delete mode 100644 util/kubeconfig/token.go diff --git a/cmd/argo/commands/archive/delete.go b/cmd/argo/commands/archive/delete.go index e4c00fb8b0da..5cb67b8858b5 100644 --- a/cmd/argo/commands/archive/delete.go +++ b/cmd/argo/commands/archive/delete.go @@ -16,7 +16,7 @@ func NewDeleteCommand() *cobra.Command { Run: func(cmd *cobra.Command, args []string) { for _, uid := range args { conn := client.GetClientConn() - ctx := client.ContextWithAuthorization() + ctx := client.GetContext() client := workflowarchive.NewArchivedWorkflowServiceClient(conn) _, err := client.DeleteArchivedWorkflow(ctx, &workflowarchive.DeleteArchivedWorkflowRequest{ Uid: uid, diff --git a/cmd/argo/commands/archive/get.go b/cmd/argo/commands/archive/get.go index 37eca0c1de9f..b8978433e7e6 100644 --- a/cmd/argo/commands/archive/get.go +++ b/cmd/argo/commands/archive/get.go @@ -27,7 +27,7 @@ func NewGetCommand() *cobra.Command { } uid := args[0] conn := client.GetClientConn() - ctx := client.ContextWithAuthorization() + ctx := client.GetContext() client := workflowarchive.NewArchivedWorkflowServiceClient(conn) wf, err := client.GetArchivedWorkflow(ctx, &workflowarchive.GetArchivedWorkflowRequest{ Uid: uid, diff --git a/cmd/argo/commands/archive/list.go b/cmd/argo/commands/archive/list.go index 488dca822c6e..28b6f7729c53 100644 --- a/cmd/argo/commands/archive/list.go +++ b/cmd/argo/commands/archive/list.go @@ -24,7 +24,7 @@ func NewListCommand() *cobra.Command { Use: "list", Run: func(cmd *cobra.Command, args []string) { conn := client.GetClientConn() - ctx := client.ContextWithAuthorization() + ctx := client.GetContext() client := workflowarchive.NewArchivedWorkflowServiceClient(conn) resp, err := client.ListArchivedWorkflows(ctx, &workflowarchive.ListArchivedWorkflowsRequest{ ListOptions: &metav1.ListOptions{FieldSelector: "metadata.namespace=" + namespace}, diff --git a/cmd/argo/commands/client/conn.go b/cmd/argo/commands/client/conn.go index 5fac5f981469..42550e10fad6 100644 --- a/cmd/argo/commands/client/conn.go +++ b/cmd/argo/commands/client/conn.go @@ -39,7 +39,11 @@ func GetClientConn() *grpc.ClientConn { return conn } -func ContextWithAuthorization() context.Context { +func GetContext() context.Context { + token := GetBearerToken() + if token == "" { + return context.Background() + } return metadata.NewOutgoingContext(context.Background(), metadata.Pairs("grpcgateway-authorization", "Bearer "+GetBearerToken())) } diff --git a/cmd/argo/commands/common.go b/cmd/argo/commands/common.go index 808cb85dead5..d19f6554f798 100644 --- a/cmd/argo/commands/common.go +++ b/cmd/argo/commands/common.go @@ -142,5 +142,5 @@ func (c LazyWorkflowTemplateGetter) Get(name string) (*wfv1.WorkflowTemplate, er var _ templateresolution.WorkflowTemplateNamespacedGetter = &LazyWorkflowTemplateGetter{} func GetWFApiServerGRPCClient(conn *grpc.ClientConn) (wfApiServer.WorkflowServiceClient, context.Context) { - return wfApiServer.NewWorkflowServiceClient(conn), client.ContextWithAuthorization() + return wfApiServer.NewWorkflowServiceClient(conn), client.GetContext() } diff --git a/cmd/argo/commands/template/common.go b/cmd/argo/commands/template/common.go index d60911383612..d6d04c36db05 100644 --- a/cmd/argo/commands/template/common.go +++ b/cmd/argo/commands/template/common.go @@ -78,5 +78,5 @@ func (c LazyWorkflowTemplateGetter) Get(name string) (*wfv1.WorkflowTemplate, er var _ templateresolution.WorkflowTemplateNamespacedGetter = &LazyWorkflowTemplateGetter{} func GetWFtmplApiServerGRPCClient(conn *grpc.ClientConn) (wftmplApiServer.WorkflowTemplateServiceClient, context.Context) { - return wftmplApiServer.NewWorkflowTemplateServiceClient(conn), client.ContextWithAuthorization() + return wftmplApiServer.NewWorkflowTemplateServiceClient(conn), client.GetContext() } diff --git a/cmd/server/auth/gatekeeper.go b/cmd/server/auth/gatekeeper.go index 306c5abfbfdf..285ab847184f 100644 --- a/cmd/server/auth/gatekeeper.go +++ b/cmd/server/auth/gatekeeper.go @@ -85,14 +85,14 @@ func (s Gatekeeper) useHybridAuth() bool { return s.authType == Hybrid } -func (s Gatekeeper) useClientAuth(md metadata.MD) (bool, error) { - if s.authType == Client && len(md.Get("grpcgateway-authorization")) == 0 { - return false, status.Error(codes.Unauthenticated, "Auth Token is not found") +func (s Gatekeeper) useClientAuth(md metadata.MD) bool { + if s.authType == Client { + return true } if s.useHybridAuth() && len(md.Get("grpcgateway-authorization")) > 0 { - return true, nil + return true } - return true, nil + return false } func (s Gatekeeper) getClients(ctx context.Context) (versioned.Interface, kubernetes.Interface, error) { @@ -106,16 +106,16 @@ func (s Gatekeeper) getClients(ctx context.Context) (versioned.Interface, kubern } return nil, nil, status.Error(codes.Unauthenticated, "unable to get metadata from incoming context") } - useClientAuth, err := s.useClientAuth(md) - if err != nil { - return nil, nil, status.Errorf(codes.Unauthenticated, "auth token is not present in the request: %v", err) - } - if !useClientAuth { + + if !s.useClientAuth(md) { return s.wfClient, s.kubeClient, nil } + token := "" authorization := md.Get("grpcgateway-authorization") - token := strings.TrimPrefix(authorization[0], "Bearer ") + if len(authorization) > 0 { + token = strings.TrimPrefix(authorization[0], "Bearer ") + } restConfig, err := kubeconfig.GetRestConfig(token) if err != nil { diff --git a/test/e2e/argo_server_test.go b/test/e2e/argo_server_test.go index fbd66e51fc1a..760482088f02 100644 --- a/test/e2e/argo_server_test.go +++ b/test/e2e/argo_server_test.go @@ -9,6 +9,8 @@ import ( "testing" "time" + wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" + "github.com/argoproj/argo/test/e2e/fixtures" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" @@ -17,10 +19,6 @@ import ( rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - - wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" - "github.com/argoproj/argo/test/e2e/fixtures" - "github.com/argoproj/argo/util/kubeconfig" ) const baseUrl = "http://localhost:2746" @@ -35,10 +33,11 @@ type ArgoServerSuite struct { func (s *ArgoServerSuite) BeforeTest(suiteName, testName string) { s.E2ESuite.BeforeTest(suiteName, testName) var err error - s.bearerToken, err = kubeconfig.GetBearerToken(s.RestConfig) + s.bearerToken, err = s.GetServiceAccountToken() if err != nil { panic(err) } + } func (s *ArgoServerSuite) AfterTest(suiteName, testName string) { @@ -75,7 +74,7 @@ func (s *ArgoServerSuite) TestInfo() { func (s *ArgoServerSuite) TestUnauthorized() { token := s.bearerToken defer func() { s.bearerToken = token }() - s.bearerToken = "" + s.bearerToken = "test-token" s.e(s.T()).GET("/api/v1/workflows/argo"). Expect(). Status(401) @@ -578,7 +577,7 @@ func (s *ArgoServerSuite) TestWorkflowStream() { When(). SubmitWorkflow() - time.Sleep(1 * time.Second) + time.Sleep(2 * time.Second) // use the watch to make sure that the workflow has succeeded s.Run("Watch", func(t *testing.T) { @@ -589,7 +588,12 @@ func (s *ArgoServerSuite) TestWorkflowStream() { req.Close = true resp, err := http.DefaultClient.Do(req) assert.NoError(t, err) - defer func() { _ = resp.Body.Close() }() + assert.NotNil(t, resp) + defer func() { + if resp != nil { + _ = resp.Body.Close() + } + }() if assert.Equal(t, 200, resp.StatusCode) { assert.Equal(t, resp.Header.Get("Content-Type"), "text/event-stream") s := bufio.NewScanner(resp.Body) diff --git a/test/e2e/cli_test.go b/test/e2e/cli_test.go index a90f0e20006e..044ba105ff19 100644 --- a/test/e2e/cli_test.go +++ b/test/e2e/cli_test.go @@ -19,6 +19,7 @@ type CLISuite struct { func (s *CLISuite) BeforeTest(suiteName, testName string) { s.E2ESuite.BeforeTest(suiteName, testName) + } func (s *CLISuite) AfterTest(suiteName, testName string) { @@ -35,7 +36,9 @@ func (s *CLISuite) TestCompletion() { func (s *CLISuite) TestToken() { s.Given().RunCli([]string{"token"}, func(t *testing.T, output string, err error) { assert.NoError(t, err) - assert.Equal(t, "v2:password", output) + token, err := s.GetServiceAccountToken() + assert.NoError(t, err) + assert.Equal(t, token, output) }) } diff --git a/test/e2e/fixtures/e2e_suite.go b/test/e2e/fixtures/e2e_suite.go index ed22a4b675c8..4704fca75667 100644 --- a/test/e2e/fixtures/e2e_suite.go +++ b/test/e2e/fixtures/e2e_suite.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "testing" "time" @@ -60,13 +61,18 @@ func (s *E2ESuite) SetupSuite() { } func (s *E2ESuite) BeforeTest(_, _ string) { - s.SetEnv() + s.Diagnostics = &Diagnostics{} var err error s.RestConfig, err = kubeconfig.DefaultRestConfig() if err != nil { panic(err) } + token, err := s.GetServiceAccountToken() + if err != nil { + panic(err) + } + s.SetEnv(token) s.KubeClient, err = kubernetes.NewForConfig(s.RestConfig) if err != nil { panic(err) @@ -176,6 +182,24 @@ func (s *E2ESuite) BeforeTest(_, _ string) { _ = db.Close() } +func (s *E2ESuite) GetServiceAccountToken() (string, error) { + // create the clientset + clientset, err := kubernetes.NewForConfig(s.RestConfig) + if err != nil { + return "", err + } + secretList, err := clientset.CoreV1().Secrets("argo").List(metav1.ListOptions{}) + if err != nil { + return "", err + } + for _, sec := range secretList.Items { + if strings.HasPrefix(sec.Name, "argo-server-token") { + return string(sec.Data["token"]), nil + } + } + return "", nil +} + func (s *E2ESuite) Run(name string, f func(t *testing.T)) { t := s.T() if t.Failed() { diff --git a/test/e2e/fixtures/env.go b/test/e2e/fixtures/env.go index ac473f20867e..feb2bde538c7 100644 --- a/test/e2e/fixtures/env.go +++ b/test/e2e/fixtures/env.go @@ -5,13 +5,11 @@ import "os" type Env struct { } -func (s *Env) SetEnv() { +func (s *Env) SetEnv(token string) { _ = os.Setenv("ARGO_SERVER", "localhost:2746") - _ = os.Setenv("ARGO_TOKEN_VERSION", "v2") - _ = os.Setenv("ARGO_V2_TOKEN", "password") + _ = os.Setenv("ARGO_TOKEN", token) } func (s *Env) UnsetEnv() { _ = os.Unsetenv("ARGO_SERVER") - _ = os.Unsetenv("ARGO_TOKEN_VERSION") - _ = os.Unsetenv("ARGO_V2_TOKEN") + _ = os.Unsetenv("ARGO_TOKEN") } diff --git a/test/e2e/fixtures/util.go b/test/e2e/fixtures/util.go index 7ef0a0cc48d1..5c20940a83aa 100644 --- a/test/e2e/fixtures/util.go +++ b/test/e2e/fixtures/util.go @@ -1,6 +1,7 @@ package fixtures import ( + "os" "os/exec" log "github.com/sirupsen/logrus" @@ -8,6 +9,8 @@ import ( func runCli(diagnostics *Diagnostics, args []string) (string, error) { runArgs := append([]string{"-n", Namespace}, args...) + cmd := exec.Command("../../dist/argo", runArgs...) + cmd.Env = os.Environ() output, err := exec.Command("../../dist/argo", runArgs...).CombinedOutput() stringOutput := string(output) diagnostics.Log(log.Fields{"args": args, "output": stringOutput, "err": err}, "Run CLI") diff --git a/test/e2e/manifests/postgres.yaml b/test/e2e/manifests/postgres.yaml index 6ce065ea3694..b1bfb9b89643 100644 --- a/test/e2e/manifests/postgres.yaml +++ b/test/e2e/manifests/postgres.yaml @@ -367,9 +367,6 @@ spec: - client - --loglevel - debug - env: - - name: ARGO_V2_TOKEN - value: password image: argoproj/argocli:latest imagePullPolicy: Never name: argo-server diff --git a/test/e2e/manifests/postgres/overlays/argo-server-deployment.yaml b/test/e2e/manifests/postgres/overlays/argo-server-deployment.yaml index 39ea60066077..864a7e781223 100644 --- a/test/e2e/manifests/postgres/overlays/argo-server-deployment.yaml +++ b/test/e2e/manifests/postgres/overlays/argo-server-deployment.yaml @@ -13,8 +13,4 @@ - op: add path: /spec/template/spec/containers/0/args/- value: debug -- op: add - path: /spec/template/spec/containers/0/env - value: - - name: ARGO_V2_TOKEN - value: password + diff --git a/ui/src/app/shared/services/requests.ts b/ui/src/app/shared/services/requests.ts index 044dec66d31f..d8d0d89ce9f4 100644 --- a/ui/src/app/shared/services/requests.ts +++ b/ui/src/app/shared/services/requests.ts @@ -18,7 +18,8 @@ const getToken = () => localStorage.getItem('token'); const auth = (req: SuperAgentRequest) => { const token = getToken(); - return (token !== null ? req.auth(token, {type: 'bearer'}) : req).on('error', handle); + + return (token !== null && token !== '' ? req.auth(token, {type: 'bearer'}) : req).on('error', handle); }; const handle = (err: any) => { diff --git a/util/kubeconfig/kubeconfig.go b/util/kubeconfig/kubeconfig.go index f323c5bd1069..500ddef8bfb8 100644 --- a/util/kubeconfig/kubeconfig.go +++ b/util/kubeconfig/kubeconfig.go @@ -1,19 +1,16 @@ package kubeconfig import ( - "encoding/base64" - "encoding/json" - "fmt" - "io/ioutil" "net/http" + "os" "strings" + "github.com/pkg/errors" + "k8s.io/client-go/plugin/pkg/client/auth/exec" restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/transport" - - "github.com/argoproj/argo/pkg/apis/workflow" ) // get the default one from the filesystem @@ -25,92 +22,66 @@ func DefaultRestConfig() (*restclient.Config, error) { // convert a bearer token into a REST config func GetRestConfig(token string) (*restclient.Config, error) { - version, tokenBody, err := parseToken(token) + + restConfig, err := DefaultRestConfig() if err != nil { return nil, err } - switch version { - case tokenVersion0: - restConfigBytes, err := base64.StdEncoding.DecodeString(tokenBody) - if err != nil { - return nil, err - } - restConfig := &restclient.Config{} - err = json.Unmarshal(restConfigBytes, restConfig) - if err != nil { - return nil, err - } - return restConfig, nil - case tokenVersion1: - restConfig, err := DefaultRestConfig() - if err != nil { - return nil, err - } - restConfig.BearerToken = tokenBody - restConfig.BearerTokenFile = "" - return restConfig, nil - case tokenVersion2: - value, err := getV2TokenBody() - if err != nil { - return nil, err - } - if tokenBody != value { - return nil, fmt.Errorf("v2 token invalid") - } - restConfig, err := DefaultRestConfig() - if err != nil { - return nil, err - } - return restConfig, nil + restConfig.BearerToken = "" + restConfig.BearerTokenFile = "" + restConfig.Username = "" + restConfig.Password = "" + if token != "" { + restConfig.BearerToken = token } - return nil, fmt.Errorf("invalid token tokenVersion") + return restConfig, nil } // convert the REST config into a bearer token func GetBearerToken(in *restclient.Config) (string, error) { - switch getDefaultTokenVersion() { - case tokenVersion0: - tlsClientConfig, err := tlsClientConfig(in) + + if token := getEnvToken(); token != "" { + return token, nil + } + + if in == nil { + return "", errors.Errorf("RestClient can't be nil") + } + if in.ExecProvider != nil { + tc, err := in.TransportConfig() if err != nil { - return "", err + return "", nil } - clientConfig := &workflow.ClientConfig{ - Host: in.Host, - APIPath: in.APIPath, - ContentConfig: restclient.ContentConfig{ - AcceptContentTypes: in.ContentConfig.AcceptContentTypes, - ContentType: in.ContentConfig.ContentType, - GroupVersion: in.ContentConfig.GroupVersion, - }, - Username: in.Username, - Password: in.Password, - BearerToken: in.BearerToken, - Impersonate: in.Impersonate, - AuthProvider: in.AuthProvider, - TLSClientConfig: tlsClientConfig, - UserAgent: in.UserAgent, - QPS: in.QPS, - Burst: in.Burst, - Timeout: in.Timeout, + + auth, err := exec.GetAuthenticator(in.ExecProvider) + if err != nil { + return "", nil } - configByte, err := json.Marshal(clientConfig) + + err = auth.UpdateTransportConfig(tc) if err != nil { - return "", err + return "", nil } - return formatToken(0, base64.StdEncoding.EncodeToString(configByte)), nil - case tokenVersion1: - if in.ExecProvider != nil { - tc, err := in.TransportConfig() - if err != nil { - return "", err - } - auth, err := exec.GetAuthenticator(in.ExecProvider) + rt, err := transport.New(tc) + if err != nil { + return "", nil + } + req := http.Request{Header: map[string][]string{}} + + _, _ = rt.RoundTrip(&req) + + token := req.Header.Get("Authorization") + return strings.TrimPrefix(token, "Bearer "), nil + } + if in.AuthProvider != nil { + if in.AuthProvider.Name == "gcp" { + tc, err := in.TransportConfig() if err != nil { return "", err } - err = auth.UpdateTransportConfig(tc) + auth, err := restclient.GetAuthProvider(in.Host, in.AuthProvider, in.AuthConfigPersister) if err != nil { return "", err } @@ -119,78 +90,19 @@ func GetBearerToken(in *restclient.Config) (string, error) { if err != nil { return "", err } - + rt = auth.WrapTransport(rt) req := http.Request{Header: map[string][]string{}} _, _ = rt.RoundTrip(&req) - token := req.Header.Get("Authorization") - return formatToken(1, strings.TrimPrefix(token, "Bearer ")), nil - } - if in.AuthProvider != nil { - if in.AuthProvider.Name == "gcp" { - tc, err := in.TransportConfig() - if err != nil { - return "", err - } - - auth, err := restclient.GetAuthProvider(in.Host, in.AuthProvider, in.AuthConfigPersister) - if err != nil { - return "", err - } - - rt, err := transport.New(tc) - if err != nil { - return "", err - } - rt = auth.WrapTransport(rt) - req := http.Request{Header: map[string][]string{}} - - _, _ = rt.RoundTrip(&req) - - token := in.AuthProvider.Config["access-token"] - return formatToken(1, strings.TrimPrefix(token, "Bearer ")), nil - } - return "", nil + token := in.AuthProvider.Config["access-token"] + return strings.TrimPrefix(token, "Bearer "), nil } - case tokenVersion2: - v2TokenBody, err := getV2TokenBody() - if err != nil { - return "", err - } - return formatToken(2, v2TokenBody), nil } - return "", fmt.Errorf("invalid token version") + return in.BearerToken, nil } -func tlsClientConfig(in *restclient.Config) (restclient.TLSClientConfig, error) { - c := restclient.TLSClientConfig{ - Insecure: in.TLSClientConfig.Insecure, - ServerName: in.TLSClientConfig.ServerName, - CertData: in.TLSClientConfig.CertData, - KeyData: in.TLSClientConfig.KeyData, - CAData: in.TLSClientConfig.CAData, - } - if in.TLSClientConfig.CAFile != "" { - data, err := ioutil.ReadFile(in.TLSClientConfig.CAFile) - if err != nil { - return c, err - } - c.CAData = data - } - if in.TLSClientConfig.CertFile != "" { - data, err := ioutil.ReadFile(in.TLSClientConfig.CertFile) - if err != nil { - return c, err - } - c.CertData = data - } - if in.TLSClientConfig.KeyFile != "" { - data, err := ioutil.ReadFile(in.TLSClientConfig.KeyFile) - if err != nil { - return c, err - } - c.KeyData = data - } - return c, nil +// Get the Auth token from environment variable +func getEnvToken() string { + return os.Getenv("ARGO_TOKEN") } diff --git a/util/kubeconfig/kubeconfig_test.go b/util/kubeconfig/kubeconfig_test.go deleted file mode 100644 index 1b4658e56c59..000000000000 --- a/util/kubeconfig/kubeconfig_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package kubeconfig - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_parseToken(t *testing.T) { - t.Run("Invalid", func(t *testing.T) { - _, _, err := parseToken("") - assert.Error(t, err) - }) - t.Run("Valid", func(t *testing.T) { - version, tokenBody, err := parseToken("v1:tokenBody") - if assert.NoError(t, err) { - assert.Equal(t, tokenVersion1, version) - assert.Equal(t, "tokenBody", tokenBody) - } - }) -} diff --git a/util/kubeconfig/token.go b/util/kubeconfig/token.go deleted file mode 100644 index a1dd011d7fae..000000000000 --- a/util/kubeconfig/token.go +++ /dev/null @@ -1,44 +0,0 @@ -package kubeconfig - -import ( - "fmt" - "os" - "regexp" -) - -type tokenVersion = string - -const ( - tokenVersion0 tokenVersion = "v0" - tokenVersion1 tokenVersion = "v1" - tokenVersion2 tokenVersion = "v2" -) - -func getDefaultTokenVersion() tokenVersion { - value, ok := os.LookupEnv("ARGO_TOKEN_VERSION") - if !ok { - return tokenVersion0 - } - return value -} - -func getV2TokenBody() (string, error) { - token := os.Getenv("ARGO_V2_TOKEN") - if token == "" { - return "", fmt.Errorf("no v2 token defined") - } - return token, nil -} - -func parseToken(token string) (tokenVersion, string, error) { - rx := regexp.MustCompile("(v[0-9]):(.*)") - find := rx.FindStringSubmatch(token) - if len(find) == 0 { - return tokenVersion0, "", fmt.Errorf("token not found") - } - return find[1], find[2], nil -} - -func formatToken(version int, token string) string { - return fmt.Sprintf("v%d:%s", version, token) -} diff --git a/util/kubeconfig/token_test.go b/util/kubeconfig/token_test.go index bea249ecf8e1..82b40f3b6480 100644 --- a/util/kubeconfig/token_test.go +++ b/util/kubeconfig/token_test.go @@ -1,38 +1,41 @@ package kubeconfig import ( + "k8s.io/client-go/tools/clientcmd" "os" "testing" "github.com/stretchr/testify/assert" ) + func Test_getDefaultTokenVersion(t *testing.T) { - t.Run("v2", func(t *testing.T) { - _ = os.Setenv("ARGO_TOKEN_VERSION", "v2") - defer func() { _ = os.Unsetenv("ARGO_TOKEN_VERSION") }() - _ = os.Setenv("ARGO_V2_TOKEN", "token") - defer func() { _ = os.Unsetenv("ARGO_V2_TOKEN") }() - assert.Equal(t, tokenVersion2, getDefaultTokenVersion()) - token, err := GetBearerToken(nil) - if assert.NoError(t, err) { - assert.Equal(t, "v2:token", token) - } + t.Run("No token", func(t *testing.T) { + restConfig, err := clientcmd.DefaultClientConfig.ClientConfig() + os.Unsetenv("ARGO_TOKEN") + assert.NoError(t, err) + token, err := GetBearerToken(restConfig) + assert.NoError(t, err) + assert.Equal(t,restConfig.BearerToken, token) }) -} - -func Test_getV2TokenBody(t *testing.T) { - t.Run("Undefined", func(t *testing.T) { - _, err := getV2TokenBody() - assert.Error(t, err) + t.Run("Env token", func(t *testing.T) { + restConfig, err := clientcmd.DefaultClientConfig.ClientConfig() + assert.NoError(t, err) + restConfig.BearerToken="test12" + os.Setenv("ARGO_TOKEN", "test") + defer os.Unsetenv("ARGO_TOKEN") + token, err := GetBearerToken(restConfig) + assert.NoError(t, err) + assert.Equal(t,"test", token) }) - t.Run("Defined", func(t *testing.T) { - _ = os.Setenv("ARGO_V2_TOKEN", "token") - defer func() { _ = os.Unsetenv("ARGO_V2_TOKEN") }() - token, err := getV2TokenBody() - if assert.NoError(t, err) { - assert.Equal(t, "token", token) - } + t.Run("RestConfig token", func(t *testing.T) { + restConfig, err := clientcmd.DefaultClientConfig.ClientConfig() + os.Unsetenv("ARGO_TOKEN") + assert.NoError(t, err) + restConfig.BearerToken = "test" + token, err := GetBearerToken(restConfig) + assert.NoError(t, err) + assert.Equal(t, restConfig.BearerToken, token) }) }