From 2e53dd1eff7064f34557a276aa42aa9b7f712178 Mon Sep 17 00:00:00 2001 From: Yuqing Bai Date: Mon, 9 Nov 2026 10:46:42 +0800 Subject: [PATCH 1/2] fix: add optional secure API key storage --- README.md | 37 +++++ docs/generate_doc/ticloud_config_create.md | 1 + docs/generate_doc/ticloud_config_set.md | 3 +- internal/cli/auth/login.go | 4 +- internal/cli/auth/whoami.go | 4 +- internal/cli/config/create.go | 6 +- internal/cli/config/delete.go | 12 +- internal/cli/config/secure_storage_test.go | 76 +++++++++ internal/cli/config/set.go | 13 +- internal/cli/root.go | 6 +- internal/config/credentials_test.go | 179 +++++++++++++++++++++ internal/config/profile.go | 46 +++++- internal/config/store/api_key.go | 47 ++++++ internal/prop/property.go | 7 +- internal/service/github/version.go | 2 +- internal/service/github/version_test.go | 62 +++++++ 16 files changed, 485 insertions(+), 20 deletions(-) create mode 100644 internal/cli/config/secure_storage_test.go create mode 100644 internal/config/credentials_test.go create mode 100644 internal/config/store/api_key.go create mode 100644 internal/service/github/version_test.go diff --git a/README.md b/README.md index dc54372a..30deea9f 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ The `ticloud` command line tool brings deploy cluster requests, and other TiDB C - [Config a profile](#config-a-profile) - [Create a cluster](#create-a-cluster) - [Documentation](#documentation) + - [Credential storage](#credential-storage) - [Telemetry](#telemetry) - [Roadmap](#roadmap) @@ -75,6 +76,42 @@ tiup cloud serverless create Please check the CLI help for more information. +## Credential storage + +API private keys are stored in `~/.ticloud/config` by default for compatibility +with existing scripts and environments without an OS credential store. On +Unix-like systems, the CLI restricts the directory to `0700` and the config +file to `0600`. These permissions do not encrypt the file. + +To store a new profile's API private key in the OS credential store, use: + +```shell +ticloud config create --secure-storage +``` + +To move an existing profile's private key to the credential store, set it again: + +```shell +ticloud config set private-key --secure-storage +``` + +Add `-P ` to select a different profile. A successful secure write +removes the plaintext private key from the config. The public key and a +`private-key-storage = "keyring"` marker remain in the config. Existing profiles +are not migrated automatically. Later private-key updates continue to use the +credential store even without `--secure-storage`, and deleting the profile +also removes its stored private key. Secure writes and reads report credential +store errors rather than silently falling back to plaintext or OAuth. + +Secure storage requires a working OS credential store; copying the config alone +does not transfer the private key. To clear an API private key, use +`ticloud config set private-key ''`. + +OAuth tokens use the OS credential store by default. `auth login --insecure-storage` +explicitly enables plaintext token storage. When both stores +contain a token, the credential store takes precedence; plaintext remains usable +when no token can be loaded from the credential store. + ## Telemetry See [here](/docs/telemetry.md) diff --git a/docs/generate_doc/ticloud_config_create.md b/docs/generate_doc/ticloud_config_create.md index 2e753dd3..16825241 100644 --- a/docs/generate_doc/ticloud_config_create.md +++ b/docs/generate_doc/ticloud_config_create.md @@ -30,6 +30,7 @@ ticloud config create [flags] --private-key string The private key of the TiDB Cloud API. (optional) --profile-name string The name of the profile, must not contain periods. --public-key string The public key of the TiDB Cloud API. (optional) + --secure-storage Store the API private key in the OS credential store instead of the config file. ``` ### Options inherited from parent commands diff --git a/docs/generate_doc/ticloud_config_set.md b/docs/generate_doc/ticloud_config_set.md index b531c4c6..767c0638 100644 --- a/docs/generate_doc/ticloud_config_set.md +++ b/docs/generate_doc/ticloud_config_set.md @@ -27,7 +27,8 @@ ticloud config set [flags] ### Options ``` - -h, --help help for set + -h, --help help for set + --secure-storage Store the API private key in the OS credential store instead of the config file. ``` ### Options inherited from parent commands diff --git a/internal/cli/auth/login.go b/internal/cli/auth/login.go index e74dfb7c..7b2b37e1 100644 --- a/internal/cli/auth/login.go +++ b/internal/cli/auth/login.go @@ -65,7 +65,9 @@ func LoginCmd(h *internal.Helper) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() - if config.GetPublicKey() != "" && config.GetPrivateKey() != "" { + // This is advisory; an unavailable API key must not prevent OAuth login. + privateKey, _ := config.GetPrivateKey() + if config.GetPublicKey() != "" && privateKey != "" { color.HiYellow("\nDetect an API key already set in %s profile! Note it will take precedence over auth token\n\n", config.ActiveProfileName()) prompt := &survey.Confirm{ Message: color.BlueString("The login will not take effect, continue to login?"), diff --git a/internal/cli/auth/whoami.go b/internal/cli/auth/whoami.go index ecbce683..41c13eca 100644 --- a/internal/cli/auth/whoami.go +++ b/internal/cli/auth/whoami.go @@ -107,7 +107,9 @@ func WhoamiCmd(h *internal.Helper) *cobra.Command { fmt.Fprintln(h.IOStreams.Out, "User Name:", userInfo.Username) fmt.Fprintln(h.IOStreams.Out, "Org Name:", orgInfo.Orgname) - if config.GetPublicKey() != "" && config.GetPrivateKey() != "" { + // This is advisory; an unavailable API key does not invalidate OAuth. + privateKey, _ := config.GetPrivateKey() + if config.GetPublicKey() != "" && privateKey != "" { color.HiYellow("\nDetect an API key already set in %s profile! Note it will take precedence over auth token.", config.ActiveProfileName()) color.HiYellow(fmt.Sprintf("Use `%s config create --profile-name ` to create a new profile and login again.", config.CliName)) } diff --git a/internal/cli/config/create.go b/internal/cli/config/create.go index beb52188..6df0698e 100644 --- a/internal/cli/config/create.go +++ b/internal/cli/config/create.go @@ -55,6 +55,7 @@ func (c CreateOpts) NonInteractiveFlags() []string { } func CreateCmd(h *internal.Helper) *cobra.Command { + var secureStorage bool opts := CreateOpts{ interactive: true, } @@ -164,8 +165,10 @@ func CreateCmd(h *internal.Helper) *cobra.Command { return fmt.Errorf("profile %s already exists, use `config set` to modify", profileName) } + if err := config.SetPrivateKey(profileName, privateKey, secureStorage); err != nil { + return err + } viper.Set(fmt.Sprintf("%s.%s", profileName, prop.PublicKey), publicKey) - viper.Set(fmt.Sprintf("%s.%s", profileName, prop.PrivateKey), privateKey) viper.Set(prop.CurProfile, profileName) err = viper.WriteConfig() if err != nil { @@ -182,6 +185,7 @@ func CreateCmd(h *internal.Helper) *cobra.Command { createCmd.Flags().String(flag.ProfileName, "", "The name of the profile, must not contain periods.") createCmd.Flags().String(flag.PublicKey, "", "The public key of the TiDB Cloud API. (optional)") createCmd.Flags().String(flag.PrivateKey, "", "The private key of the TiDB Cloud API. (optional)") + createCmd.Flags().BoolVar(&secureStorage, "secure-storage", false, "Store the API private key in the OS credential store instead of the config file.") return createCmd } diff --git a/internal/cli/config/delete.go b/internal/cli/config/delete.go index 293fcaef..95296ac8 100644 --- a/internal/cli/config/delete.go +++ b/internal/cli/config/delete.go @@ -21,6 +21,7 @@ import ( "github.com/tidbcloud/tidbcloud-cli/internal" "github.com/tidbcloud/tidbcloud-cli/internal/config" + "github.com/tidbcloud/tidbcloud-cli/internal/config/store" "github.com/tidbcloud/tidbcloud-cli/internal/flag" "github.com/tidbcloud/tidbcloud-cli/internal/prop" "github.com/tidbcloud/tidbcloud-cli/internal/util" @@ -128,13 +129,20 @@ func DeleteCmd(h *internal.Helper) *cobra.Command { return errors.Trace(err) } - defer file.Close() - s := t.String() _, err = file.WriteString(s) + closeErr := file.Close() if err != nil { return errors.Trace(err) } + if closeErr != nil { + return errors.Trace(closeErr) + } + if viper.GetString(fmt.Sprintf("%s.%s", curProfileName, prop.PrivateKeyStorage)) == "keyring" { + if err := store.DeleteAPIPrivateKey(curProfileName); err != nil { + return errors.Annotate(err, "profile deleted, but its API private key could not be removed from the credential store") + } + } fmt.Fprintln(h.IOStreams.Out, color.GreenString("Profile %s deleted successfully", curProfileName)) return nil diff --git a/internal/cli/config/secure_storage_test.go b/internal/cli/config/secure_storage_test.go new file mode 100644 index 00000000..1a3daf6f --- /dev/null +++ b/internal/cli/config/secure_storage_test.go @@ -0,0 +1,76 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/tidbcloud/tidbcloud-cli/internal" + appconfig "github.com/tidbcloud/tidbcloud-cli/internal/config" + "github.com/tidbcloud/tidbcloud-cli/internal/config/store" + "github.com/tidbcloud/tidbcloud-cli/internal/iostream" + + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + "github.com/zalando/go-keyring" +) + +func TestSecureStorageLifecycle(t *testing.T) { + viper.Reset() + t.Cleanup(viper.Reset) + keyring.MockInit() + file := filepath.Join(t.TempDir(), "config") + viper.SetConfigFile(file) + viper.SetConfigType("toml") + viper.SetConfigPermissions(0600) + require.NoError(t, viper.WriteConfig()) + h := &internal.Helper{IOStreams: iostream.Test()} + create := CreateCmd(h) + create.SetArgs([]string{"--profile-name", "secure", "--public-key", "public", "--private-key", "first-secret", "--secure-storage"}) + require.NoError(t, create.Execute()) + appconfig.SetActiveProfile("secure") + data, err := os.ReadFile(file) + require.NoError(t, err) + require.NotContains(t, string(data), "first-secret") + require.Equal(t, "public", appconfig.GetPublicKey()) + value, err := appconfig.GetPrivateKey() + require.NoError(t, err) + require.Equal(t, "first-secret", value) + + set := SetCmd(h) + set.SetArgs([]string{"private-key", "second-secret"}) + require.NoError(t, set.Execute()) + value, err = appconfig.GetPrivateKey() + require.NoError(t, err) + require.Equal(t, "second-secret", value) + data, err = os.ReadFile(file) + require.NoError(t, err) + require.NotContains(t, string(data), "second-secret") + + deleteCmd := DeleteCmd(h) + deleteCmd.SetArgs([]string{"secure", "--force"}) + require.NoError(t, deleteCmd.Execute()) + _, err = store.GetAPIPrivateKey("secure") + require.ErrorIs(t, err, keyring.ErrNotFound) +} + +func TestSetSecureStorageRequiresPrivateKey(t *testing.T) { + h := &internal.Helper{IOStreams: iostream.Test()} + cmd := SetCmd(h) + cmd.SetArgs([]string{"public-key", "public", "--secure-storage"}) + require.ErrorContains(t, cmd.Execute(), "only supported for private-key") +} diff --git a/internal/cli/config/set.go b/internal/cli/config/set.go index 654cccd8..659a8dbc 100644 --- a/internal/cli/config/set.go +++ b/internal/cli/config/set.go @@ -30,6 +30,7 @@ import ( ) func SetCmd(h *internal.Helper) *cobra.Command { + var secureStorage bool var setCmd = &cobra.Command{ Use: "set ", Short: "Configure specific properties of the active profile", @@ -47,6 +48,9 @@ If not, the config in the active profile will be set`, prop.ProfileProperties()) RunE: func(cmd *cobra.Command, args []string) error { propertyName := args[0] value := args[1] + if secureStorage && propertyName != prop.PrivateKey { + return fmt.Errorf("--secure-storage is only supported for private-key") + } var res string if slices.Contains(prop.ProfileProperties(), propertyName) { @@ -61,7 +65,13 @@ If not, the config in the active profile will be set`, prop.ProfileProperties()) return err } } - viper.Set(fmt.Sprintf("%s.%s", curP, propertyName), value) + if propertyName == prop.PrivateKey { + if err := config.SetPrivateKey(curP, value, secureStorage); err != nil { + return err + } + } else { + viper.Set(fmt.Sprintf("%s.%s", curP, propertyName), value) + } res = fmt.Sprintf("Set profile `%s` property `%s` to value `%s` successfully", curP, propertyName, redact.Value(propertyName, value)) } else { return fmt.Errorf("unrecognized property `%s`, use `config set --help` to find available properties", propertyName) @@ -77,5 +87,6 @@ If not, the config in the active profile will be set`, prop.ProfileProperties()) }, } + setCmd.Flags().BoolVar(&secureStorage, "secure-storage", false, "Store the API private key in the OS credential store instead of the config file.") return setCmd } diff --git a/internal/cli/root.go b/internal/cli/root.go index dd498c0b..b28bf3a4 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -56,7 +56,11 @@ var ErrMissingCredentials = errors.New("this action requires authentication") func Execute(ctx context.Context) { h := &internal.Helper{ Client: func() (cloud.TiDBCloudClient, error) { - publicKey, privateKey := config.GetPublicKey(), config.GetPrivateKey() + publicKey := config.GetPublicKey() + privateKey, err := config.GetPrivateKey() + if err != nil { + return nil, err + } serverlessEndpoint := config.GetServerlessEndpoint() if serverlessEndpoint == "" { serverlessEndpoint = cloud.DefaultServerlessEndpoint diff --git a/internal/config/credentials_test.go b/internal/config/credentials_test.go new file mode 100644 index 00000000..7f05f20a --- /dev/null +++ b/internal/config/credentials_test.go @@ -0,0 +1,179 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package config + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/tidbcloud/tidbcloud-cli/internal/config/store" + "github.com/tidbcloud/tidbcloud-cli/internal/prop" + + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + "github.com/zalando/go-keyring" +) + +func credentialConfig(t *testing.T) string { + t.Helper() + viper.Reset() + t.Cleanup(viper.Reset) + file := filepath.Join(t.TempDir(), "config") + viper.SetConfigFile(file) + viper.SetConfigType("toml") + viper.SetConfigPermissions(0600) + require.NoError(t, viper.WriteConfig()) + return file +} + +func TestPrivateKeyStorage(t *testing.T) { + for _, profile := range []string{"default", "other", "'special'", `"special"`} { + t.Run(profile, func(t *testing.T) { + file := credentialConfig(t) + keyring.MockInitWithError(errors.New("keyring unavailable")) + p := &Profile{name: profile} + require.NoError(t, SetPrivateKey(profile, "legacy-secret", false)) + require.NoError(t, viper.WriteConfig()) + value, err := p.GetPrivateKey() + require.NoError(t, err) + require.Equal(t, "legacy-secret", value) + + // An explicit secure write must not fall back to plaintext on failure. + require.ErrorContains(t, SetPrivateKey(profile, "new-secret", true), "failed to save") + require.Equal(t, "legacy-secret", viper.GetString(profile+"."+prop.PrivateKey)) + require.Empty(t, viper.GetString(profile+"."+prop.PrivateKeyStorage)) + + keyring.MockInit() + require.NoError(t, keyring.Set("ticloud_access_token", profile, "oauth-secret")) + require.NoError(t, SetPrivateKey(profile, "keyring-secret", true)) + require.NoError(t, viper.WriteConfig()) + data, err := os.ReadFile(file) + require.NoError(t, err) + require.NotContains(t, string(data), "legacy-secret") + require.NotContains(t, string(data), "keyring-secret") + + // Reload from disk to verify a later invocation can find the private key. + viper.Reset() + viper.SetConfigFile(file) + viper.SetConfigType("toml") + require.NoError(t, viper.ReadInConfig()) + value, err = p.GetPrivateKey() + require.NoError(t, err) + require.Equal(t, "keyring-secret", value) + viper.Set(profile+"."+prop.PrivateKey, "stale-plaintext") + value, err = p.GetPrivateKey() + require.NoError(t, err) + require.Equal(t, "keyring-secret", value) + oauth, err := keyring.Get("ticloud_access_token", profile) + require.NoError(t, err) + require.Equal(t, "oauth-secret", oauth) + unrelated, err := (&Profile{name: "unrelated"}).GetPrivateKey() + require.NoError(t, err) + require.Empty(t, unrelated) + + // Once opted in, an ordinary update must remain in the keyring. + require.NoError(t, SetPrivateKey(profile, "rotated-secret", false)) + require.NoError(t, viper.WriteConfig()) + value, err = p.GetPrivateKey() + require.NoError(t, err) + require.Equal(t, "rotated-secret", value) + data, err = os.ReadFile(file) + require.NoError(t, err) + require.NotContains(t, string(data), "rotated-secret") + + require.NoError(t, store.DeleteAPIPrivateKey(profile)) + _, err = p.GetPrivateKey() + require.ErrorIs(t, err, keyring.ErrNotFound) + // A missing keyring entry must not silently disable API-key authentication. + require.ErrorContains(t, err, "failed to load API private key") + viper.Set(profile+"."+prop.PrivateKey, "stale-plaintext") + _, err = p.GetPrivateKey() + require.ErrorIs(t, err, keyring.ErrNotFound) + }) + } +} + +func TestAccessTokenStoragePriority(t *testing.T) { + tests := []struct { + name string + plaintext string + secure string + loadErr error + want string + }{ + {name: "prefer keyring", plaintext: "stale", secure: "secure", want: "secure"}, + {name: "insecure storage", plaintext: "plaintext", loadErr: keyring.ErrNotFound, want: "plaintext"}, + {name: "unsupported keyring", plaintext: "plaintext", loadErr: store.ErrNotSupported, want: "plaintext"}, + {name: "locked keyring preserves legacy access", plaintext: "plaintext", loadErr: errors.New("locked"), want: "plaintext"}, + {name: "empty keyring", plaintext: "plaintext", want: "plaintext"}, + {name: "missing token", loadErr: keyring.ErrNotFound}, + {name: "keyring error without plaintext", loadErr: errors.New("locked")}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + credentialConfig(t) + viper.Set("test."+prop.AccessToken, tc.plaintext) + p := &Profile{name: "test"} + got, err := p.getAccessToken(func(profile string) (string, error) { + require.Equal(t, "test", profile) + return tc.secure, tc.loadErr + }) + require.Equal(t, tc.want, got) + if tc.want == "" { + require.ErrorIs(t, err, tc.loadErr) + } else { + require.NoError(t, err) + } + }) + } +} + +func TestDeleteAccessTokenClearsViperOverrides(t *testing.T) { + file := credentialConfig(t) + keyring.MockInit() + p := &Profile{name: "target"} + // Values written during this process live in Viper's override map. + viper.Set("target."+prop.AccessToken, "old-secret") + viper.Set("target."+prop.TokenType, "Bearer") + viper.Set("target."+prop.TokenExpiredAt, time.Now().Add(time.Hour)) + viper.Set("unrelated."+prop.AccessToken, "keep-secret") + require.NoError(t, viper.WriteConfig()) + require.NoError(t, p.DeleteAccessToken()) + require.Empty(t, viper.GetString("target."+prop.AccessToken)) + require.Equal(t, "keep-secret", viper.GetString("unrelated."+prop.AccessToken)) + require.NoError(t, viper.WriteConfig()) + data, err := os.ReadFile(file) + require.NoError(t, err) + require.NotContains(t, string(data), "old-secret") +} + +func TestSaveAccessTokenUsesReceiverProfile(t *testing.T) { + credentialConfig(t) + keyring.MockInit() + previous := activeProfile + activeProfile = &Profile{name: "active"} + t.Cleanup(func() { activeProfile = previous }) + viper.Set("active."+prop.AccessToken, "keep-secret") + viper.Set("target."+prop.AccessToken, "old-secret") + require.NoError(t, viper.WriteConfig()) + p := &Profile{name: "target"} + require.NoError(t, p.SaveAccessToken(time.Now().Add(time.Hour), "Bearer", "new-secret", true)) + require.Equal(t, "keep-secret", viper.GetString("active."+prop.AccessToken)) + require.Equal(t, "new-secret", viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.AccessToken))) +} diff --git a/internal/config/profile.go b/internal/config/profile.go index 8736052c..3a072ef9 100644 --- a/internal/config/profile.go +++ b/internal/config/profile.go @@ -107,10 +107,27 @@ func (p *Profile) GetPublicKey() (publicKey string) { return } -func GetPrivateKey() (privateKey string) { return activeProfile.GetPrivateKey() } -func (p *Profile) GetPrivateKey() (privateKey string) { - privateKey = viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.PrivateKey)) - return +func GetPrivateKey() (string, error) { return activeProfile.GetPrivateKey() } +func (p *Profile) GetPrivateKey() (string, error) { + if viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.PrivateKeyStorage)) == "keyring" { + return store.GetAPIPrivateKey(p.name) + } + return viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.PrivateKey)), nil +} + +// SetPrivateKey preserves legacy storage unless secure storage was requested or +// the profile already uses it. The caller persists the config with WriteConfig. +func SetPrivateKey(profile, privateKey string, secureStorage bool) error { + if secureStorage || viper.GetString(fmt.Sprintf("%s.%s", profile, prop.PrivateKeyStorage)) == "keyring" { + if err := store.SetAPIPrivateKey(profile, privateKey); err != nil { + return err + } + viper.Set(fmt.Sprintf("%s.%s", profile, prop.PrivateKeyStorage), "keyring") + viper.Set(fmt.Sprintf("%s.%s", profile, prop.PrivateKey), "") + return nil + } + viper.Set(fmt.Sprintf("%s.%s", profile, prop.PrivateKey), privateKey) + return nil } func GetServerlessEndpoint() (apiUrl string) { return activeProfile.GetServerlessEndpoint() } @@ -156,7 +173,7 @@ func SaveAccessToken(expireAt time.Time, tokenType string, token string, insecur } func (p *Profile) SaveAccessToken(expireAt time.Time, tokenType string, token string, insecureStorageUsed bool) error { // Clean up the previous oauth_token from the config file or keyring, if there were one - err := DeleteAccessToken() + err := p.DeleteAccessToken() if err != nil { return err } @@ -189,12 +206,21 @@ func GetAccessToken() (string, error) { return activeProfile.GetAccessToken() } func (p *Profile) GetAccessToken() (string, error) { - token := viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.AccessToken)) - if token != "" { + return p.getAccessToken(store.Get) +} + +func (p *Profile) getAccessToken(load func(string) (string, error)) (string, error) { + token, err := load(p.name) + if err == nil && token != "" { return token, nil } - return store.Get(p.name) + // Preserve --insecure-storage and configurations used on hosts without a + // usable keyring, while preferring a securely stored token when available. + if plaintext := viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.AccessToken)); plaintext != "" { + return plaintext, nil + } + return token, err } func ValidateToken() error { @@ -266,6 +292,10 @@ func (p *Profile) DeleteAccessToken() error { if err != nil { return err } + // ReadInConfig does not clear values previously set with viper.Set. + for _, property := range []string{prop.AccessToken, prop.TokenType, prop.TokenExpiredAt} { + viper.Set(fmt.Sprintf("%s.%s", p.name, property), nil) + } err = store.Delete(p.name) if !stderrors.Is(err, store.ErrNotSupported) { diff --git a/internal/config/store/api_key.go b/internal/config/store/api_key.go new file mode 100644 index 00000000..7b7bf3ea --- /dev/null +++ b/internal/config/store/api_key.go @@ -0,0 +1,47 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package store + +import ( + "errors" + "fmt" + + "github.com/zalando/go-keyring" +) + +// Keep API private keys separate from OAuth access tokens. +const apiPrivateKeyNamespace = "ticloud_api_private_key" + +func GetAPIPrivateKey(profile string) (string, error) { + value, err := keyring.Get(apiPrivateKeyNamespace, profile) + if err != nil { + return "", fmt.Errorf("failed to load API private key from credential store: %w", err) + } + return value, nil +} + +func SetAPIPrivateKey(profile, value string) error { + if err := keyring.Set(apiPrivateKeyNamespace, profile, value); err != nil { + return fmt.Errorf("failed to save API private key to credential store: %w", err) + } + return nil +} + +func DeleteAPIPrivateKey(profile string) error { + if err := keyring.Delete(apiPrivateKeyNamespace, profile); err != nil && !errors.Is(err, keyring.ErrNotFound) { + return fmt.Errorf("failed to delete API private key from credential store: %w", err) + } + return nil +} diff --git a/internal/prop/property.go b/internal/prop/property.go index 19a08fbc..57a49f55 100644 --- a/internal/prop/property.go +++ b/internal/prop/property.go @@ -32,9 +32,10 @@ const ( TelemetryEnabled string = "telemetry-enabled" // shall not be set by user - TokenExpiredAt string = "token-expired-at" - TokenType string = "token-type" - AccessToken string = "access-token" + TokenExpiredAt string = "token-expired-at" + TokenType string = "token-type" + AccessToken string = "access-token" + PrivateKeyStorage string = "private-key-storage" ) func GlobalProperties() []string { diff --git a/internal/service/github/version.go b/internal/service/github/version.go index 6f2edb97..761b5184 100644 --- a/internal/service/github/version.go +++ b/internal/service/github/version.go @@ -121,7 +121,7 @@ func setStateEntry(stateFilePath string, t time.Time, r ReleaseInfo) error { return err } - err = os.MkdirAll(filepath.Dir(stateFilePath), 0755) + err = os.MkdirAll(filepath.Dir(stateFilePath), 0700) if err != nil { return err } diff --git a/internal/service/github/version_test.go b/internal/service/github/version_test.go new file mode 100644 index 00000000..04be0615 --- /dev/null +++ b/internal/service/github/version_test.go @@ -0,0 +1,62 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package github + +import ( + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestSetStateEntryPermissions(t *testing.T) { + for _, existing := range []bool{false, true} { + name := "new directory" + if existing { + name = "existing private directory" + } + t.Run(name, func(t *testing.T) { + dir := filepath.Join(t.TempDir(), ".ticloud") + if existing { + require.NoError(t, os.Mkdir(dir, 0700)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config"), []byte("dummy-config"), 0600)) + } + file := filepath.Join(dir, "state.yml") + checked := time.Now().UTC().Truncate(time.Second) + require.NoError(t, setStateEntry(file, checked, ReleaseInfo{Version: "v1.0.0"})) + state, err := getStateEntry(file) + require.NoError(t, err) + require.Equal(t, "v1.0.0", state.LatestRelease.Version) + require.True(t, checked.Equal(state.CheckedForUpdateAt)) + if runtime.GOOS == "windows" { + return + } + info, err := os.Stat(dir) + require.NoError(t, err) + require.Zero(t, info.Mode().Perm() & ^os.FileMode(0700)) + info, err = os.Stat(file) + require.NoError(t, err) + require.Zero(t, info.Mode().Perm() & ^os.FileMode(0600)) + if existing { + info, err = os.Stat(filepath.Join(dir, "config")) + require.NoError(t, err) + require.Zero(t, info.Mode().Perm() & ^os.FileMode(0600)) + } + }) + } +} From fa3c4fb2b4aab731d450cce17c457bf57af60528 Mon Sep 17 00:00:00 2001 From: Yuqing Bai Date: Mon, 9 Nov 2026 13:10:18 +0800 Subject: [PATCH 2/2] fix: limit scope to update-state directory permissions --- README.md | 37 ----- docs/generate_doc/ticloud_config_create.md | 1 - docs/generate_doc/ticloud_config_set.md | 3 +- internal/cli/auth/login.go | 4 +- internal/cli/auth/whoami.go | 4 +- internal/cli/config/create.go | 6 +- internal/cli/config/delete.go | 12 +- internal/cli/config/secure_storage_test.go | 76 --------- internal/cli/config/set.go | 13 +- internal/cli/root.go | 6 +- internal/config/credentials_test.go | 179 --------------------- internal/config/profile.go | 46 +----- internal/config/store/api_key.go | 47 ------ internal/prop/property.go | 7 +- 14 files changed, 19 insertions(+), 422 deletions(-) delete mode 100644 internal/cli/config/secure_storage_test.go delete mode 100644 internal/config/credentials_test.go delete mode 100644 internal/config/store/api_key.go diff --git a/README.md b/README.md index 30deea9f..dc54372a 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,6 @@ The `ticloud` command line tool brings deploy cluster requests, and other TiDB C - [Config a profile](#config-a-profile) - [Create a cluster](#create-a-cluster) - [Documentation](#documentation) - - [Credential storage](#credential-storage) - [Telemetry](#telemetry) - [Roadmap](#roadmap) @@ -76,42 +75,6 @@ tiup cloud serverless create Please check the CLI help for more information. -## Credential storage - -API private keys are stored in `~/.ticloud/config` by default for compatibility -with existing scripts and environments without an OS credential store. On -Unix-like systems, the CLI restricts the directory to `0700` and the config -file to `0600`. These permissions do not encrypt the file. - -To store a new profile's API private key in the OS credential store, use: - -```shell -ticloud config create --secure-storage -``` - -To move an existing profile's private key to the credential store, set it again: - -```shell -ticloud config set private-key --secure-storage -``` - -Add `-P ` to select a different profile. A successful secure write -removes the plaintext private key from the config. The public key and a -`private-key-storage = "keyring"` marker remain in the config. Existing profiles -are not migrated automatically. Later private-key updates continue to use the -credential store even without `--secure-storage`, and deleting the profile -also removes its stored private key. Secure writes and reads report credential -store errors rather than silently falling back to plaintext or OAuth. - -Secure storage requires a working OS credential store; copying the config alone -does not transfer the private key. To clear an API private key, use -`ticloud config set private-key ''`. - -OAuth tokens use the OS credential store by default. `auth login --insecure-storage` -explicitly enables plaintext token storage. When both stores -contain a token, the credential store takes precedence; plaintext remains usable -when no token can be loaded from the credential store. - ## Telemetry See [here](/docs/telemetry.md) diff --git a/docs/generate_doc/ticloud_config_create.md b/docs/generate_doc/ticloud_config_create.md index 16825241..2e753dd3 100644 --- a/docs/generate_doc/ticloud_config_create.md +++ b/docs/generate_doc/ticloud_config_create.md @@ -30,7 +30,6 @@ ticloud config create [flags] --private-key string The private key of the TiDB Cloud API. (optional) --profile-name string The name of the profile, must not contain periods. --public-key string The public key of the TiDB Cloud API. (optional) - --secure-storage Store the API private key in the OS credential store instead of the config file. ``` ### Options inherited from parent commands diff --git a/docs/generate_doc/ticloud_config_set.md b/docs/generate_doc/ticloud_config_set.md index 767c0638..b531c4c6 100644 --- a/docs/generate_doc/ticloud_config_set.md +++ b/docs/generate_doc/ticloud_config_set.md @@ -27,8 +27,7 @@ ticloud config set [flags] ### Options ``` - -h, --help help for set - --secure-storage Store the API private key in the OS credential store instead of the config file. + -h, --help help for set ``` ### Options inherited from parent commands diff --git a/internal/cli/auth/login.go b/internal/cli/auth/login.go index 7b2b37e1..e74dfb7c 100644 --- a/internal/cli/auth/login.go +++ b/internal/cli/auth/login.go @@ -65,9 +65,7 @@ func LoginCmd(h *internal.Helper) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() - // This is advisory; an unavailable API key must not prevent OAuth login. - privateKey, _ := config.GetPrivateKey() - if config.GetPublicKey() != "" && privateKey != "" { + if config.GetPublicKey() != "" && config.GetPrivateKey() != "" { color.HiYellow("\nDetect an API key already set in %s profile! Note it will take precedence over auth token\n\n", config.ActiveProfileName()) prompt := &survey.Confirm{ Message: color.BlueString("The login will not take effect, continue to login?"), diff --git a/internal/cli/auth/whoami.go b/internal/cli/auth/whoami.go index 41c13eca..ecbce683 100644 --- a/internal/cli/auth/whoami.go +++ b/internal/cli/auth/whoami.go @@ -107,9 +107,7 @@ func WhoamiCmd(h *internal.Helper) *cobra.Command { fmt.Fprintln(h.IOStreams.Out, "User Name:", userInfo.Username) fmt.Fprintln(h.IOStreams.Out, "Org Name:", orgInfo.Orgname) - // This is advisory; an unavailable API key does not invalidate OAuth. - privateKey, _ := config.GetPrivateKey() - if config.GetPublicKey() != "" && privateKey != "" { + if config.GetPublicKey() != "" && config.GetPrivateKey() != "" { color.HiYellow("\nDetect an API key already set in %s profile! Note it will take precedence over auth token.", config.ActiveProfileName()) color.HiYellow(fmt.Sprintf("Use `%s config create --profile-name ` to create a new profile and login again.", config.CliName)) } diff --git a/internal/cli/config/create.go b/internal/cli/config/create.go index 6df0698e..beb52188 100644 --- a/internal/cli/config/create.go +++ b/internal/cli/config/create.go @@ -55,7 +55,6 @@ func (c CreateOpts) NonInteractiveFlags() []string { } func CreateCmd(h *internal.Helper) *cobra.Command { - var secureStorage bool opts := CreateOpts{ interactive: true, } @@ -165,10 +164,8 @@ func CreateCmd(h *internal.Helper) *cobra.Command { return fmt.Errorf("profile %s already exists, use `config set` to modify", profileName) } - if err := config.SetPrivateKey(profileName, privateKey, secureStorage); err != nil { - return err - } viper.Set(fmt.Sprintf("%s.%s", profileName, prop.PublicKey), publicKey) + viper.Set(fmt.Sprintf("%s.%s", profileName, prop.PrivateKey), privateKey) viper.Set(prop.CurProfile, profileName) err = viper.WriteConfig() if err != nil { @@ -185,7 +182,6 @@ func CreateCmd(h *internal.Helper) *cobra.Command { createCmd.Flags().String(flag.ProfileName, "", "The name of the profile, must not contain periods.") createCmd.Flags().String(flag.PublicKey, "", "The public key of the TiDB Cloud API. (optional)") createCmd.Flags().String(flag.PrivateKey, "", "The private key of the TiDB Cloud API. (optional)") - createCmd.Flags().BoolVar(&secureStorage, "secure-storage", false, "Store the API private key in the OS credential store instead of the config file.") return createCmd } diff --git a/internal/cli/config/delete.go b/internal/cli/config/delete.go index 95296ac8..293fcaef 100644 --- a/internal/cli/config/delete.go +++ b/internal/cli/config/delete.go @@ -21,7 +21,6 @@ import ( "github.com/tidbcloud/tidbcloud-cli/internal" "github.com/tidbcloud/tidbcloud-cli/internal/config" - "github.com/tidbcloud/tidbcloud-cli/internal/config/store" "github.com/tidbcloud/tidbcloud-cli/internal/flag" "github.com/tidbcloud/tidbcloud-cli/internal/prop" "github.com/tidbcloud/tidbcloud-cli/internal/util" @@ -129,20 +128,13 @@ func DeleteCmd(h *internal.Helper) *cobra.Command { return errors.Trace(err) } + defer file.Close() + s := t.String() _, err = file.WriteString(s) - closeErr := file.Close() if err != nil { return errors.Trace(err) } - if closeErr != nil { - return errors.Trace(closeErr) - } - if viper.GetString(fmt.Sprintf("%s.%s", curProfileName, prop.PrivateKeyStorage)) == "keyring" { - if err := store.DeleteAPIPrivateKey(curProfileName); err != nil { - return errors.Annotate(err, "profile deleted, but its API private key could not be removed from the credential store") - } - } fmt.Fprintln(h.IOStreams.Out, color.GreenString("Profile %s deleted successfully", curProfileName)) return nil diff --git a/internal/cli/config/secure_storage_test.go b/internal/cli/config/secure_storage_test.go deleted file mode 100644 index 1a3daf6f..00000000 --- a/internal/cli/config/secure_storage_test.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2026 PingCAP, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "os" - "path/filepath" - "testing" - - "github.com/tidbcloud/tidbcloud-cli/internal" - appconfig "github.com/tidbcloud/tidbcloud-cli/internal/config" - "github.com/tidbcloud/tidbcloud-cli/internal/config/store" - "github.com/tidbcloud/tidbcloud-cli/internal/iostream" - - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - "github.com/zalando/go-keyring" -) - -func TestSecureStorageLifecycle(t *testing.T) { - viper.Reset() - t.Cleanup(viper.Reset) - keyring.MockInit() - file := filepath.Join(t.TempDir(), "config") - viper.SetConfigFile(file) - viper.SetConfigType("toml") - viper.SetConfigPermissions(0600) - require.NoError(t, viper.WriteConfig()) - h := &internal.Helper{IOStreams: iostream.Test()} - create := CreateCmd(h) - create.SetArgs([]string{"--profile-name", "secure", "--public-key", "public", "--private-key", "first-secret", "--secure-storage"}) - require.NoError(t, create.Execute()) - appconfig.SetActiveProfile("secure") - data, err := os.ReadFile(file) - require.NoError(t, err) - require.NotContains(t, string(data), "first-secret") - require.Equal(t, "public", appconfig.GetPublicKey()) - value, err := appconfig.GetPrivateKey() - require.NoError(t, err) - require.Equal(t, "first-secret", value) - - set := SetCmd(h) - set.SetArgs([]string{"private-key", "second-secret"}) - require.NoError(t, set.Execute()) - value, err = appconfig.GetPrivateKey() - require.NoError(t, err) - require.Equal(t, "second-secret", value) - data, err = os.ReadFile(file) - require.NoError(t, err) - require.NotContains(t, string(data), "second-secret") - - deleteCmd := DeleteCmd(h) - deleteCmd.SetArgs([]string{"secure", "--force"}) - require.NoError(t, deleteCmd.Execute()) - _, err = store.GetAPIPrivateKey("secure") - require.ErrorIs(t, err, keyring.ErrNotFound) -} - -func TestSetSecureStorageRequiresPrivateKey(t *testing.T) { - h := &internal.Helper{IOStreams: iostream.Test()} - cmd := SetCmd(h) - cmd.SetArgs([]string{"public-key", "public", "--secure-storage"}) - require.ErrorContains(t, cmd.Execute(), "only supported for private-key") -} diff --git a/internal/cli/config/set.go b/internal/cli/config/set.go index 659a8dbc..654cccd8 100644 --- a/internal/cli/config/set.go +++ b/internal/cli/config/set.go @@ -30,7 +30,6 @@ import ( ) func SetCmd(h *internal.Helper) *cobra.Command { - var secureStorage bool var setCmd = &cobra.Command{ Use: "set ", Short: "Configure specific properties of the active profile", @@ -48,9 +47,6 @@ If not, the config in the active profile will be set`, prop.ProfileProperties()) RunE: func(cmd *cobra.Command, args []string) error { propertyName := args[0] value := args[1] - if secureStorage && propertyName != prop.PrivateKey { - return fmt.Errorf("--secure-storage is only supported for private-key") - } var res string if slices.Contains(prop.ProfileProperties(), propertyName) { @@ -65,13 +61,7 @@ If not, the config in the active profile will be set`, prop.ProfileProperties()) return err } } - if propertyName == prop.PrivateKey { - if err := config.SetPrivateKey(curP, value, secureStorage); err != nil { - return err - } - } else { - viper.Set(fmt.Sprintf("%s.%s", curP, propertyName), value) - } + viper.Set(fmt.Sprintf("%s.%s", curP, propertyName), value) res = fmt.Sprintf("Set profile `%s` property `%s` to value `%s` successfully", curP, propertyName, redact.Value(propertyName, value)) } else { return fmt.Errorf("unrecognized property `%s`, use `config set --help` to find available properties", propertyName) @@ -87,6 +77,5 @@ If not, the config in the active profile will be set`, prop.ProfileProperties()) }, } - setCmd.Flags().BoolVar(&secureStorage, "secure-storage", false, "Store the API private key in the OS credential store instead of the config file.") return setCmd } diff --git a/internal/cli/root.go b/internal/cli/root.go index b28bf3a4..dd498c0b 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -56,11 +56,7 @@ var ErrMissingCredentials = errors.New("this action requires authentication") func Execute(ctx context.Context) { h := &internal.Helper{ Client: func() (cloud.TiDBCloudClient, error) { - publicKey := config.GetPublicKey() - privateKey, err := config.GetPrivateKey() - if err != nil { - return nil, err - } + publicKey, privateKey := config.GetPublicKey(), config.GetPrivateKey() serverlessEndpoint := config.GetServerlessEndpoint() if serverlessEndpoint == "" { serverlessEndpoint = cloud.DefaultServerlessEndpoint diff --git a/internal/config/credentials_test.go b/internal/config/credentials_test.go deleted file mode 100644 index 7f05f20a..00000000 --- a/internal/config/credentials_test.go +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2026 PingCAP, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "testing" - "time" - - "github.com/tidbcloud/tidbcloud-cli/internal/config/store" - "github.com/tidbcloud/tidbcloud-cli/internal/prop" - - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - "github.com/zalando/go-keyring" -) - -func credentialConfig(t *testing.T) string { - t.Helper() - viper.Reset() - t.Cleanup(viper.Reset) - file := filepath.Join(t.TempDir(), "config") - viper.SetConfigFile(file) - viper.SetConfigType("toml") - viper.SetConfigPermissions(0600) - require.NoError(t, viper.WriteConfig()) - return file -} - -func TestPrivateKeyStorage(t *testing.T) { - for _, profile := range []string{"default", "other", "'special'", `"special"`} { - t.Run(profile, func(t *testing.T) { - file := credentialConfig(t) - keyring.MockInitWithError(errors.New("keyring unavailable")) - p := &Profile{name: profile} - require.NoError(t, SetPrivateKey(profile, "legacy-secret", false)) - require.NoError(t, viper.WriteConfig()) - value, err := p.GetPrivateKey() - require.NoError(t, err) - require.Equal(t, "legacy-secret", value) - - // An explicit secure write must not fall back to plaintext on failure. - require.ErrorContains(t, SetPrivateKey(profile, "new-secret", true), "failed to save") - require.Equal(t, "legacy-secret", viper.GetString(profile+"."+prop.PrivateKey)) - require.Empty(t, viper.GetString(profile+"."+prop.PrivateKeyStorage)) - - keyring.MockInit() - require.NoError(t, keyring.Set("ticloud_access_token", profile, "oauth-secret")) - require.NoError(t, SetPrivateKey(profile, "keyring-secret", true)) - require.NoError(t, viper.WriteConfig()) - data, err := os.ReadFile(file) - require.NoError(t, err) - require.NotContains(t, string(data), "legacy-secret") - require.NotContains(t, string(data), "keyring-secret") - - // Reload from disk to verify a later invocation can find the private key. - viper.Reset() - viper.SetConfigFile(file) - viper.SetConfigType("toml") - require.NoError(t, viper.ReadInConfig()) - value, err = p.GetPrivateKey() - require.NoError(t, err) - require.Equal(t, "keyring-secret", value) - viper.Set(profile+"."+prop.PrivateKey, "stale-plaintext") - value, err = p.GetPrivateKey() - require.NoError(t, err) - require.Equal(t, "keyring-secret", value) - oauth, err := keyring.Get("ticloud_access_token", profile) - require.NoError(t, err) - require.Equal(t, "oauth-secret", oauth) - unrelated, err := (&Profile{name: "unrelated"}).GetPrivateKey() - require.NoError(t, err) - require.Empty(t, unrelated) - - // Once opted in, an ordinary update must remain in the keyring. - require.NoError(t, SetPrivateKey(profile, "rotated-secret", false)) - require.NoError(t, viper.WriteConfig()) - value, err = p.GetPrivateKey() - require.NoError(t, err) - require.Equal(t, "rotated-secret", value) - data, err = os.ReadFile(file) - require.NoError(t, err) - require.NotContains(t, string(data), "rotated-secret") - - require.NoError(t, store.DeleteAPIPrivateKey(profile)) - _, err = p.GetPrivateKey() - require.ErrorIs(t, err, keyring.ErrNotFound) - // A missing keyring entry must not silently disable API-key authentication. - require.ErrorContains(t, err, "failed to load API private key") - viper.Set(profile+"."+prop.PrivateKey, "stale-plaintext") - _, err = p.GetPrivateKey() - require.ErrorIs(t, err, keyring.ErrNotFound) - }) - } -} - -func TestAccessTokenStoragePriority(t *testing.T) { - tests := []struct { - name string - plaintext string - secure string - loadErr error - want string - }{ - {name: "prefer keyring", plaintext: "stale", secure: "secure", want: "secure"}, - {name: "insecure storage", plaintext: "plaintext", loadErr: keyring.ErrNotFound, want: "plaintext"}, - {name: "unsupported keyring", plaintext: "plaintext", loadErr: store.ErrNotSupported, want: "plaintext"}, - {name: "locked keyring preserves legacy access", plaintext: "plaintext", loadErr: errors.New("locked"), want: "plaintext"}, - {name: "empty keyring", plaintext: "plaintext", want: "plaintext"}, - {name: "missing token", loadErr: keyring.ErrNotFound}, - {name: "keyring error without plaintext", loadErr: errors.New("locked")}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - credentialConfig(t) - viper.Set("test."+prop.AccessToken, tc.plaintext) - p := &Profile{name: "test"} - got, err := p.getAccessToken(func(profile string) (string, error) { - require.Equal(t, "test", profile) - return tc.secure, tc.loadErr - }) - require.Equal(t, tc.want, got) - if tc.want == "" { - require.ErrorIs(t, err, tc.loadErr) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestDeleteAccessTokenClearsViperOverrides(t *testing.T) { - file := credentialConfig(t) - keyring.MockInit() - p := &Profile{name: "target"} - // Values written during this process live in Viper's override map. - viper.Set("target."+prop.AccessToken, "old-secret") - viper.Set("target."+prop.TokenType, "Bearer") - viper.Set("target."+prop.TokenExpiredAt, time.Now().Add(time.Hour)) - viper.Set("unrelated."+prop.AccessToken, "keep-secret") - require.NoError(t, viper.WriteConfig()) - require.NoError(t, p.DeleteAccessToken()) - require.Empty(t, viper.GetString("target."+prop.AccessToken)) - require.Equal(t, "keep-secret", viper.GetString("unrelated."+prop.AccessToken)) - require.NoError(t, viper.WriteConfig()) - data, err := os.ReadFile(file) - require.NoError(t, err) - require.NotContains(t, string(data), "old-secret") -} - -func TestSaveAccessTokenUsesReceiverProfile(t *testing.T) { - credentialConfig(t) - keyring.MockInit() - previous := activeProfile - activeProfile = &Profile{name: "active"} - t.Cleanup(func() { activeProfile = previous }) - viper.Set("active."+prop.AccessToken, "keep-secret") - viper.Set("target."+prop.AccessToken, "old-secret") - require.NoError(t, viper.WriteConfig()) - p := &Profile{name: "target"} - require.NoError(t, p.SaveAccessToken(time.Now().Add(time.Hour), "Bearer", "new-secret", true)) - require.Equal(t, "keep-secret", viper.GetString("active."+prop.AccessToken)) - require.Equal(t, "new-secret", viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.AccessToken))) -} diff --git a/internal/config/profile.go b/internal/config/profile.go index 3a072ef9..8736052c 100644 --- a/internal/config/profile.go +++ b/internal/config/profile.go @@ -107,27 +107,10 @@ func (p *Profile) GetPublicKey() (publicKey string) { return } -func GetPrivateKey() (string, error) { return activeProfile.GetPrivateKey() } -func (p *Profile) GetPrivateKey() (string, error) { - if viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.PrivateKeyStorage)) == "keyring" { - return store.GetAPIPrivateKey(p.name) - } - return viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.PrivateKey)), nil -} - -// SetPrivateKey preserves legacy storage unless secure storage was requested or -// the profile already uses it. The caller persists the config with WriteConfig. -func SetPrivateKey(profile, privateKey string, secureStorage bool) error { - if secureStorage || viper.GetString(fmt.Sprintf("%s.%s", profile, prop.PrivateKeyStorage)) == "keyring" { - if err := store.SetAPIPrivateKey(profile, privateKey); err != nil { - return err - } - viper.Set(fmt.Sprintf("%s.%s", profile, prop.PrivateKeyStorage), "keyring") - viper.Set(fmt.Sprintf("%s.%s", profile, prop.PrivateKey), "") - return nil - } - viper.Set(fmt.Sprintf("%s.%s", profile, prop.PrivateKey), privateKey) - return nil +func GetPrivateKey() (privateKey string) { return activeProfile.GetPrivateKey() } +func (p *Profile) GetPrivateKey() (privateKey string) { + privateKey = viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.PrivateKey)) + return } func GetServerlessEndpoint() (apiUrl string) { return activeProfile.GetServerlessEndpoint() } @@ -173,7 +156,7 @@ func SaveAccessToken(expireAt time.Time, tokenType string, token string, insecur } func (p *Profile) SaveAccessToken(expireAt time.Time, tokenType string, token string, insecureStorageUsed bool) error { // Clean up the previous oauth_token from the config file or keyring, if there were one - err := p.DeleteAccessToken() + err := DeleteAccessToken() if err != nil { return err } @@ -206,21 +189,12 @@ func GetAccessToken() (string, error) { return activeProfile.GetAccessToken() } func (p *Profile) GetAccessToken() (string, error) { - return p.getAccessToken(store.Get) -} - -func (p *Profile) getAccessToken(load func(string) (string, error)) (string, error) { - token, err := load(p.name) - if err == nil && token != "" { + token := viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.AccessToken)) + if token != "" { return token, nil } - // Preserve --insecure-storage and configurations used on hosts without a - // usable keyring, while preferring a securely stored token when available. - if plaintext := viper.GetString(fmt.Sprintf("%s.%s", p.name, prop.AccessToken)); plaintext != "" { - return plaintext, nil - } - return token, err + return store.Get(p.name) } func ValidateToken() error { @@ -292,10 +266,6 @@ func (p *Profile) DeleteAccessToken() error { if err != nil { return err } - // ReadInConfig does not clear values previously set with viper.Set. - for _, property := range []string{prop.AccessToken, prop.TokenType, prop.TokenExpiredAt} { - viper.Set(fmt.Sprintf("%s.%s", p.name, property), nil) - } err = store.Delete(p.name) if !stderrors.Is(err, store.ErrNotSupported) { diff --git a/internal/config/store/api_key.go b/internal/config/store/api_key.go deleted file mode 100644 index 7b7bf3ea..00000000 --- a/internal/config/store/api_key.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2026 PingCAP, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "errors" - "fmt" - - "github.com/zalando/go-keyring" -) - -// Keep API private keys separate from OAuth access tokens. -const apiPrivateKeyNamespace = "ticloud_api_private_key" - -func GetAPIPrivateKey(profile string) (string, error) { - value, err := keyring.Get(apiPrivateKeyNamespace, profile) - if err != nil { - return "", fmt.Errorf("failed to load API private key from credential store: %w", err) - } - return value, nil -} - -func SetAPIPrivateKey(profile, value string) error { - if err := keyring.Set(apiPrivateKeyNamespace, profile, value); err != nil { - return fmt.Errorf("failed to save API private key to credential store: %w", err) - } - return nil -} - -func DeleteAPIPrivateKey(profile string) error { - if err := keyring.Delete(apiPrivateKeyNamespace, profile); err != nil && !errors.Is(err, keyring.ErrNotFound) { - return fmt.Errorf("failed to delete API private key from credential store: %w", err) - } - return nil -} diff --git a/internal/prop/property.go b/internal/prop/property.go index 57a49f55..19a08fbc 100644 --- a/internal/prop/property.go +++ b/internal/prop/property.go @@ -32,10 +32,9 @@ const ( TelemetryEnabled string = "telemetry-enabled" // shall not be set by user - TokenExpiredAt string = "token-expired-at" - TokenType string = "token-type" - AccessToken string = "access-token" - PrivateKeyStorage string = "private-key-storage" + TokenExpiredAt string = "token-expired-at" + TokenType string = "token-type" + AccessToken string = "access-token" ) func GlobalProperties() []string {