From f2686b976218c494c9142fe4b1a912acbd04a326 Mon Sep 17 00:00:00 2001 From: Tim Walsh Date: Tue, 17 Nov 2026 23:47:37 -0700 Subject: [PATCH] fix(auth): use the configured workspace token in the API client GetCurrentToken always read the "default" keyring account, so after `cu auth login -w ` every API command reported not-authenticated while `cu auth status` (which honoured default_workspace) said otherwise. Add auth.CurrentWorkspace(), which resolves config default_workspace (or CU_DEFAULT_WORKSPACE) and falls back to DefaultWorkspace, and route GetCurrentToken, `auth status` and `auth logout` through it. `auth login` now records the workspace on both the --token and interactive paths (previously only interactive), and logging in to the default workspace after a named one switches back to it. Closes #23 Co-Authored-By: Claude Opus 5.5 --- docs/site/commands/cu_auth_login.md | 3 + internal/auth/auth.go | 16 ++++- internal/auth/auth_test.go | 83 ++++++++++++++++++++++++ internal/cmd/auth.go | 43 ++++++++----- internal/cmd/auth_workspace_test.go | 97 +++++++++++++++++++++++++++++ 5 files changed, 223 insertions(+), 19 deletions(-) create mode 100644 internal/auth/auth_test.go create mode 100644 internal/cmd/auth_workspace_test.go diff --git a/docs/site/commands/cu_auth_login.md b/docs/site/commands/cu_auth_login.md index 8d3e4e3..a6ce80f 100644 --- a/docs/site/commands/cu_auth_login.md +++ b/docs/site/commands/cu_auth_login.md @@ -6,6 +6,9 @@ Authenticate with ClickUp Authenticate with ClickUp using a personal API token. The token is stored securely in your operating system's credential store. +With --workspace, the token is stored under that name and the workspace becomes +the default (config default_workspace) that all other commands authenticate with. + ``` cu auth login [flags] ``` diff --git a/internal/auth/auth.go b/internal/auth/auth.go index a429f57..f0d2cf7 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/timimsms/cu/internal/config" "github.com/timimsms/cu/internal/errors" "github.com/zalando/go-keyring" ) @@ -109,8 +110,19 @@ func (m *Manager) IsAuthenticated(workspace string) bool { return err == nil } +// CurrentWorkspace returns the workspace whose token cu authenticates with: +// the config `default_workspace` value (which `cu auth login -w` records, and +// CU_DEFAULT_WORKSPACE overrides), falling back to DefaultWorkspace. The API +// client and `cu auth status`/`logout` all resolve through here so they can +// never disagree about which keyring account is in use. +func CurrentWorkspace() string { + if ws := config.GetString("default_workspace"); ws != "" { + return ws + } + return DefaultWorkspace +} + // GetCurrentToken gets the token for the current workspace func (m *Manager) GetCurrentToken() (*Token, error) { - // TODO: Get current workspace from config - return m.GetToken(DefaultWorkspace) + return m.GetToken(CurrentWorkspace()) } diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go new file mode 100644 index 0000000..19eea55 --- /dev/null +++ b/internal/auth/auth_test.go @@ -0,0 +1,83 @@ +package auth + +import ( + "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/timimsms/cu/internal/config" + cuerrors "github.com/timimsms/cu/internal/errors" + "github.com/zalando/go-keyring" +) + +// isolate swaps the OS keyring for go-keyring's in-memory mock and points the +// config at an empty temp directory, so nothing touches the real keychain or +// ~/.config/cu. +func isolate(t *testing.T) { + t.Helper() + keyring.MockInit() + t.Setenv("CU_DEFAULT_WORKSPACE", "") + + viper.Reset() + old := config.DefaultConfigDir + config.DefaultConfigDir = t.TempDir() + t.Chdir(t.TempDir()) + t.Cleanup(func() { config.DefaultConfigDir = old; viper.Reset() }) + require.NoError(t, config.Init("")) +} + +func TestCurrentWorkspace(t *testing.T) { + t.Run("unset config falls back to default", func(t *testing.T) { + isolate(t) + assert.Equal(t, DefaultWorkspace, CurrentWorkspace()) + }) + + t.Run("honours default_workspace", func(t *testing.T) { + isolate(t) + config.Set("default_workspace", "prod") + assert.Equal(t, "prod", CurrentWorkspace()) + }) + + t.Run("environment overrides config", func(t *testing.T) { + isolate(t) + config.Set("default_workspace", "prod") + viper.Reset() + t.Setenv("CU_DEFAULT_WORKSPACE", "staging") + require.NoError(t, config.Init("")) + assert.Equal(t, "staging", CurrentWorkspace()) + }) +} + +func TestGetCurrentToken(t *testing.T) { + t.Run("named workspace login is used", func(t *testing.T) { + isolate(t) + m := NewManager() + require.NoError(t, m.SaveToken("prod", &Token{Value: "prod-token", Workspace: "prod"})) + config.Set("default_workspace", "prod") + + token, err := m.GetCurrentToken() + require.NoError(t, err) + assert.Equal(t, "prod-token", token.Value) + }) + + t.Run("named token is not read without default_workspace", func(t *testing.T) { + isolate(t) + m := NewManager() + require.NoError(t, m.SaveToken("prod", &Token{Value: "prod-token"})) + + _, err := m.GetCurrentToken() + assert.ErrorIs(t, err, cuerrors.ErrNotAuthenticated) + }) + + t.Run("unset config falls back to default account", func(t *testing.T) { + isolate(t) + m := NewManager() + require.NoError(t, m.SaveToken("", &Token{Value: "default-token"})) + require.NoError(t, m.SaveToken("prod", &Token{Value: "prod-token"})) + + token, err := m.GetCurrentToken() + require.NoError(t, err) + assert.Equal(t, "default-token", token.Value) + }) +} diff --git a/internal/cmd/auth.go b/internal/cmd/auth.go index c5d69f9..ee41b8e 100644 --- a/internal/cmd/auth.go +++ b/internal/cmd/auth.go @@ -21,7 +21,10 @@ var authCmd = &cobra.Command{ var authLoginCmd = &cobra.Command{ Use: "login", Short: "Authenticate with ClickUp", - Long: `Authenticate with ClickUp using a personal API token. The token is stored securely in your operating system's credential store.`, + Long: `Authenticate with ClickUp using a personal API token. The token is stored securely in your operating system's credential store. + +With --workspace, the token is stored under that name and the workspace becomes +the default (config default_workspace) that all other commands authenticate with.`, Run: func(cmd *cobra.Command, args []string) { token, _ := cmd.Flags().GetString("token") workspace, _ := cmd.Flags().GetString("workspace") @@ -39,6 +42,7 @@ var authLoginCmd = &cobra.Command{ fmt.Fprintf(os.Stderr, "Failed to save token: %v\n", err) os.Exit(1) } + rememberWorkspace(workspace) fmt.Println("Successfully authenticated!") return @@ -73,20 +77,31 @@ var authLoginCmd = &cobra.Command{ os.Exit(1) } - // Save workspace as default if it's the first one - if workspace != "" && workspace != auth.DefaultWorkspace { - config.Set("default_workspace", workspace) - if err := config.Save(); err != nil { - // Log warning but don't fail - the auth is already saved - fmt.Fprintf(os.Stderr, "Warning: failed to save default workspace: %v\n", err) - } - } + rememberWorkspace(workspace) fmt.Println("\nSuccessfully authenticated!") fmt.Println("You can now use cu commands to interact with ClickUp.") }, } +// rememberWorkspace makes the workspace just logged in to the one every other +// command authenticates with, so the token that was saved is the token used. +// Nothing is written when it is already current, which keeps a plain +// `cu auth login` from creating a config file it does not need. +func rememberWorkspace(workspace string) { + if workspace == "" { + workspace = auth.DefaultWorkspace + } + if workspace == auth.CurrentWorkspace() { + return + } + config.Set("default_workspace", workspace) + if err := config.Save(); err != nil { + // Log warning but don't fail - the auth is already saved + fmt.Fprintf(os.Stderr, "Warning: failed to save default workspace: %v\n", err) + } +} + // authStatus is the machine-readable form of `cu auth status`. type authStatus struct { Authenticated bool `json:"authenticated" yaml:"authenticated"` @@ -101,10 +116,7 @@ var authStatusCmd = &cobra.Command{ Long: `Display the current authentication status and user information.`, Run: func(cmd *cobra.Command, args []string) { authMgr := auth.NewManager() - workspace := config.GetString("default_workspace") - if workspace == "" { - workspace = auth.DefaultWorkspace - } + workspace := auth.CurrentWorkspace() token, err := authMgr.GetToken(workspace) @@ -152,10 +164,7 @@ var authLogoutCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { workspace, _ := cmd.Flags().GetString("workspace") if workspace == "" { - workspace = config.GetString("default_workspace") - if workspace == "" { - workspace = auth.DefaultWorkspace - } + workspace = auth.CurrentWorkspace() } authMgr := auth.NewManager() diff --git a/internal/cmd/auth_workspace_test.go b/internal/cmd/auth_workspace_test.go new file mode 100644 index 0000000..1f912c0 --- /dev/null +++ b/internal/cmd/auth_workspace_test.go @@ -0,0 +1,97 @@ +package cmd + +import ( + "os" + "path/filepath" + "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/timimsms/cu/internal/api" + "github.com/timimsms/cu/internal/auth" + "github.com/timimsms/cu/internal/config" + "github.com/zalando/go-keyring" +) + +// isolateAuth swaps the OS keyring for go-keyring's in-memory mock and points +// the config at an empty temp directory, so the login/status/logout commands +// run end to end without touching the real keychain or ~/.config/cu. +func isolateAuth(t *testing.T) string { + t.Helper() + keyring.MockInit() + t.Setenv("CU_DEFAULT_WORKSPACE", "") + + viper.Reset() + cfgDir := t.TempDir() + old := config.DefaultConfigDir + config.DefaultConfigDir = cfgDir + t.Chdir(t.TempDir()) + t.Cleanup(func() { config.DefaultConfigDir = old; viper.Reset() }) + require.NoError(t, config.Init("")) + return cfgDir +} + +func setLoginFlag(t *testing.T, name, value string) { + t.Helper() + require.NoError(t, authLoginCmd.Flags().Set(name, value)) + t.Cleanup(func() { _ = authLoginCmd.Flags().Set(name, "") }) +} + +func TestAuthLoginNamedWorkspaceIsUsedByClient(t *testing.T) { + cfgDir := isolateAuth(t) + setLoginFlag(t, "workspace", "prod") + setLoginFlag(t, "token", "prod-token") + + captureStdout(t, func() { authLoginCmd.Run(authLoginCmd, nil) }) + + assert.Equal(t, "prod", auth.CurrentWorkspace()) + written, err := os.ReadFile(filepath.Join(cfgDir, config.ConfigFileName+"."+config.ConfigType)) + require.NoError(t, err) + assert.Contains(t, string(written), "default_workspace: prod", "the named workspace must persist for later invocations") + + token, err := auth.NewManager().GetCurrentToken() + require.NoError(t, err) + assert.Equal(t, "prod-token", token.Value) + + _, err = api.NewClient() + assert.NoError(t, err, "the API client must authenticate with the token just saved") + + prev := outputFormat + outputFormat = "json" + t.Cleanup(func() { outputFormat = prev }) + out := captureStdout(t, func() { authStatusCmd.Run(authStatusCmd, nil) }) + assert.Contains(t, out, `"workspace": "prod"`) + assert.Contains(t, out, `"authenticated": true`) + + captureStdout(t, func() { authLogoutCmd.Run(authLogoutCmd, nil) }) + _, err = api.NewClient() + assert.Error(t, err, "logout without -w must remove the token the client was using") +} + +func TestAuthLoginDefaultWorkspaceWritesNoConfig(t *testing.T) { + cfgDir := isolateAuth(t) + setLoginFlag(t, "token", "default-token") + + captureStdout(t, func() { authLoginCmd.Run(authLoginCmd, nil) }) + + assert.Equal(t, auth.DefaultWorkspace, auth.CurrentWorkspace()) + _, err := os.Stat(filepath.Join(cfgDir, config.ConfigFileName+"."+config.ConfigType)) + assert.True(t, os.IsNotExist(err), "a plain login should not create a config file") + + _, err = api.NewClient() + assert.NoError(t, err) +} + +func TestAuthLoginDefaultAfterNamedSwitchesBack(t *testing.T) { + isolateAuth(t) + config.Set("default_workspace", "prod") + setLoginFlag(t, "token", "default-token") + + captureStdout(t, func() { authLoginCmd.Run(authLoginCmd, nil) }) + + assert.Equal(t, auth.DefaultWorkspace, auth.CurrentWorkspace()) + token, err := auth.NewManager().GetCurrentToken() + require.NoError(t, err) + assert.Equal(t, "default-token", token.Value) +}