From 827bdd8c6e0e9431926bc185f1c4cbe4c9d4cc3d Mon Sep 17 00:00:00 2001 From: Marcel Jacek <72880145+marceljk@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:54:08 +0100 Subject: [PATCH 1/4] fix(authentication): service account authentication becomes invalid on mac when the Service Account Key is too big for keychain --- internal/pkg/auth/service_account.go | 7 + internal/pkg/auth/storage.go | 85 ++++++-- internal/pkg/auth/storage_test.go | 283 +++++++++++++++++++++++++++ 3 files changed, 357 insertions(+), 18 deletions(-) diff --git a/internal/pkg/auth/service_account.go b/internal/pkg/auth/service_account.go index 2b5b3c2a3..42edc5e6a 100644 --- a/internal/pkg/auth/service_account.go +++ b/internal/pkg/auth/service_account.go @@ -107,6 +107,13 @@ func AuthenticateServiceAccount(p *print.Printer, rt http.RoundTripper, disableW authFields[IDP_TOKEN_ENDPOINT] = "" if !disableWriting { + // Clean up user credentials to avoid stale fields + _ = DeleteAuthField(USER_EMAIL) + _ = DeleteAuthField(REFRESH_TOKEN) + _ = DeleteAuthField(SERVICE_ACCOUNT_TOKEN) + _ = DeleteAuthField(SERVICE_ACCOUNT_KEY) + _ = DeleteAuthField(PRIVATE_KEY) + err = SetAuthFlow(authFlowType) if err != nil { return "", "", fmt.Errorf("set auth flow type: %w", err) diff --git a/internal/pkg/auth/storage.go b/internal/pkg/auth/storage.go index 9f8b512e1..36d989696 100644 --- a/internal/pkg/auth/storage.go +++ b/internal/pkg/auth/storage.go @@ -106,6 +106,12 @@ func setAuthFieldWithProfile(profile string, key authFieldKey, value string) err if errFallback != nil { return fmt.Errorf("write to keyring failed (%w), try writing to encoded text file: %w", err, errFallback) } + // If writing to the text file succeeded as a fallback, clean up any stale key in the keyring + // so GetAuthField won't return outdated credentials. + _ = deleteAuthFieldInKeyring(profile, key) + } else { + // If writing to the keyring succeeded, clean up any old entry from the encoded text file. + _ = deleteAuthFieldInEncodedTextFile(profile, key) } return nil @@ -130,31 +136,34 @@ func DeleteAuthField(key authFieldKey) error { } func deleteAuthFieldWithProfile(profile string, key authFieldKey) error { + var errKeyring, errFile error + err := deleteAuthFieldInKeyring(profile, key) + if err != nil && !errors.Is(err, keyring.ErrNotFound) { + errKeyring = err + } + + err = deleteAuthFieldInEncodedTextFile(profile, key) if err != nil { - // if the key is not found, we can ignore the error - if !errors.Is(err, keyring.ErrNotFound) { - errFallback := deleteAuthFieldInEncodedTextFile(profile, key) - if errFallback != nil { - return fmt.Errorf("delete from keyring failed (%w), try deleting from encoded text file: %w", err, errFallback) - } - } + errFile = err + } + + if errKeyring != nil && errFile != nil { + return fmt.Errorf("delete from keyring: %w, delete from encoded text file: %w", errKeyring, errFile) } return nil } func deleteAuthFieldInEncodedTextFile(activeProfile string, key authFieldKey) error { - err := createEncodedTextFile(activeProfile) - if err != nil { - return err - } - textFileDir := config.GetProfileFolderPath(activeProfile) textFilePath := filepath.Join(textFileDir, textFileName) contentEncoded, err := os.ReadFile(textFilePath) if err != nil { + if os.IsNotExist(err) { + return nil + } return fmt.Errorf("read file: %w", err) } @@ -170,8 +179,21 @@ func deleteAuthFieldInEncodedTextFile(activeProfile string, key authFieldKey) er return fmt.Errorf("unmarshal file: %w", err) } + if _, ok := content[key]; !ok { + return nil + } + delete(content, key) + if len(content) == 0 { + err = os.Remove(textFilePath) + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("remove empty encoded text file: %w", err) + } + + return nil + } + contentBytes, err = json.Marshal(content) if err != nil { return fmt.Errorf("marshal file: %w", err) @@ -291,11 +313,6 @@ func getAuthFieldFromKeyring(activeProfile string, key authFieldKey) (string, er } func getAuthFieldFromEncodedTextFile(activeProfile string, key authFieldKey) (string, error) { - err := createEncodedTextFile(activeProfile) - if err != nil { - return "", err - } - textFileDir := config.GetProfileFolderPath(activeProfile) textFilePath := filepath.Join(textFileDir, textFileName) @@ -403,6 +420,17 @@ func GetAuthEmail() (string, error) { } func LoginUser(email, accessToken, refreshToken, sessionExpiresAtUnix string) error { + // Clean up any service account credentials that might be present + saFields := []authFieldKey{ + SERVICE_ACCOUNT_KEY, + PRIVATE_KEY, + SERVICE_ACCOUNT_TOKEN, + SERVICE_ACCOUNT_EMAIL, + } + for _, key := range saFields { + _ = DeleteAuthField(key) + } + authFields := map[authFieldKey]string{ SESSION_EXPIRES_AT_UNIX: sessionExpiresAtUnix, ACCESS_TOKEN: accessToken, @@ -419,13 +447,26 @@ func LoginUser(email, accessToken, refreshToken, sessionExpiresAtUnix string) er } func LogoutUser() error { - for _, key := range loginAuthFieldKeys { + for _, key := range authFieldKeys { err := DeleteAuthField(key) if err != nil { return fmt.Errorf("delete auth field \"%s\": %w", key, err) } } + activeProfile, err := config.GetProfile() + if err != nil { + return fmt.Errorf("get profile: %w", err) + } + + textFileDir := config.GetProfileFolderPath(activeProfile) + textFilePath := filepath.Join(textFileDir, textFileName) + + err = os.Remove(textFilePath) + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("remove auth storage file: %w", err) + } + return nil } @@ -446,5 +487,13 @@ func DeleteProfileAuth(profile string) error { } } + textFileDir := config.GetProfileFolderPath(profile) + textFilePath := filepath.Join(textFileDir, textFileName) + + err = os.Remove(textFilePath) + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("remove auth storage file: %w", err) + } + return nil } diff --git a/internal/pkg/auth/storage_test.go b/internal/pkg/auth/storage_test.go index 3aac14307..69979d0ca 100644 --- a/internal/pkg/auth/storage_test.go +++ b/internal/pkg/auth/storage_test.go @@ -3,6 +3,7 @@ package auth import ( "fmt" "os" + "path/filepath" "testing" "time" @@ -1228,3 +1229,285 @@ func TestAuthorizeDeauthorizeUserProfileAuth(t *testing.T) { }) } } + +func TestStaleKeychainCleanupOnFallback(t *testing.T) { + keyring.MockInit() + + profile, err := config.GetProfile() + if err != nil { + t.Fatalf("get profile: %v", err) + } + + oldKeyringVal := "stale_rsa_2048_key" + newFileVal := "new_rsa_4096_key" + + // 1. Initially set the old key in keyring + err = setAuthFieldInKeyring(profile, PRIVATE_KEY, oldKeyringVal) + if err != nil { + t.Fatalf("set in keyring: %v", err) + } + + // Verify keyring has it + got, err := getAuthFieldFromKeyring(profile, PRIVATE_KEY) + if err != nil || got != oldKeyringVal { + t.Fatalf("expected %s in keyring, got %s (err: %v)", oldKeyringVal, got, err) + } + + // 2. Simulate what setAuthFieldWithProfile does when keyring write fails: + // It writes to encoded text file and deletes from keyring + err = setAuthFieldInEncodedTextFile(profile, PRIVATE_KEY, newFileVal) + if err != nil { + t.Fatalf("set in text file: %v", err) + } + + err = deleteAuthFieldInKeyring(profile, PRIVATE_KEY) + if err != nil { + t.Fatalf("delete from keyring: %v", err) + } + + // 3. Now GetAuthField should return newFileVal, NOT the stale oldKeyringVal! + val, err := GetAuthField(PRIVATE_KEY) + if err != nil { + t.Fatalf("GetAuthField failed: %v", err) + } + + if val != newFileVal { + t.Errorf("GetAuthField returned stale value %q, expected %q", val, newFileVal) + } + + // Cleanup + _ = DeleteAuthField(PRIVATE_KEY) +} + +func TestFileNotCreatedOnReadOrDelete(t *testing.T) { + keyring.MockInit() + + profile, err := config.GetProfile() + if err != nil { + t.Fatalf("get profile: %v", err) + } + + textFilePath := filepath.Join(config.GetProfileFolderPath(profile), textFileName) + _ = os.Remove(textFilePath) + + // Ensure file doesn't exist + if _, err := os.Stat(textFilePath); !os.IsNotExist(err) { + t.Fatalf("expected file to not exist before test") + } + + nonExistingField := authFieldKey("non_existent_field_12345") + + // Call GetAuthField for a non-existent field + _, err = GetAuthField(nonExistingField) + if err == nil { + t.Errorf("expected error from GetAuthField for non-existent field") + } + + // Verify file was NOT created + if _, err := os.Stat(textFilePath); !os.IsNotExist(err) { + t.Errorf("cli-auth-storage.txt was created on GetAuthField for non-existent field") + } + + // Call DeleteAuthField for a non-existent field + _ = DeleteAuthField(nonExistingField) + + // Verify file was still NOT created + if _, err := os.Stat(textFilePath); !os.IsNotExist(err) { + t.Errorf("cli-auth-storage.txt was created on DeleteAuthField for non-existent field") + } +} + +func TestFileRemovedWhenEmpty(t *testing.T) { + profile, err := config.GetProfile() + if err != nil { + t.Fatalf("get profile: %v", err) + } + + textFilePath := filepath.Join(config.GetProfileFolderPath(profile), textFileName) + _ = os.Remove(textFilePath) + + field1 := authFieldKey("test-cleanup-field-1") + field2 := authFieldKey("test-cleanup-field-2") + + // Write two fields to text file + if err := setAuthFieldInEncodedTextFile(profile, field1, "val1"); err != nil { + t.Fatalf("failed to set field1: %v", err) + } + + if err := setAuthFieldInEncodedTextFile(profile, field2, "val2"); err != nil { + t.Fatalf("failed to set field2: %v", err) + } + + if _, err := os.Stat(textFilePath); os.IsNotExist(err) { + t.Fatalf("expected file to exist after writing fields") + } + + // Delete field1 + if err := deleteAuthFieldInEncodedTextFile(profile, field1); err != nil { + t.Fatalf("failed to delete field1: %v", err) + } + + if _, err := os.Stat(textFilePath); os.IsNotExist(err) { + t.Fatalf("expected file to still exist with field2 remaining") + } + + // Delete field2 + if err := deleteAuthFieldInEncodedTextFile(profile, field2); err != nil { + t.Fatalf("failed to delete field2: %v", err) + } + + // Now file should be removed + if _, err := os.Stat(textFilePath); !os.IsNotExist(err) { + t.Errorf("expected cli-auth-storage.txt to be removed when empty, but it still exists") + } +} + +func TestLogoutCleansUpAllCredentialsAndFile(t *testing.T) { + keyring.MockInit() + + profile, err := config.GetProfile() + if err != nil { + t.Fatalf("get profile: %v", err) + } + + textFilePath := filepath.Join(config.GetProfileFolderPath(profile), textFileName) + + // Set user credentials + if err := SetAuthField(USER_EMAIL, "[EMAIL_REDACTED]"); err != nil { + t.Fatalf("set user email: %v", err) + } + + if err := SetAuthField(ACCESS_TOKEN, "user-access-token"); err != nil { + t.Fatalf("set access token: %v", err) + } + + // Set service account credentials + if err := SetAuthField(SERVICE_ACCOUNT_EMAIL, "[EMAIL_REDACTED]"); err != nil { + t.Fatalf("set sa email: %v", err) + } + + if err := SetAuthField(SERVICE_ACCOUNT_KEY, `{"id":"test"}`); err != nil { + t.Fatalf("set sa key: %v", err) + } + + // Also simulate fallback text file having a field + if err := setAuthFieldInEncodedTextFile(profile, PRIVATE_KEY, "some-private-key"); err != nil { + t.Fatalf("set private key in text file: %v", err) + } + + // Ensure text file exists + if _, err := os.Stat(textFilePath); os.IsNotExist(err) { + t.Fatalf("expected text file to exist") + } + + // Perform logout + if err := LogoutUser(); err != nil { + t.Fatalf("LogoutUser() failed: %v", err) + } + + // Verify user fields are deleted + if _, err := GetAuthField(USER_EMAIL); err == nil { + t.Errorf("USER_EMAIL still exists after logout") + } + + if _, err := GetAuthField(ACCESS_TOKEN); err == nil { + t.Errorf("ACCESS_TOKEN still exists after logout") + } + + // Verify service account fields are deleted + if _, err := GetAuthField(SERVICE_ACCOUNT_EMAIL); err == nil { + t.Errorf("SERVICE_ACCOUNT_EMAIL still exists after logout") + } + + if _, err := GetAuthField(SERVICE_ACCOUNT_KEY); err == nil { + t.Errorf("SERVICE_ACCOUNT_KEY still exists after logout") + } + + if _, err := GetAuthField(PRIVATE_KEY); err == nil { + t.Errorf("PRIVATE_KEY still exists after logout") + } + + // Verify text file was removed + if _, err := os.Stat(textFilePath); !os.IsNotExist(err) { + t.Errorf("cli-auth-storage.txt was not removed after logout") + } +} + +func TestLoginUserCleansUpServiceAccountCredentials(t *testing.T) { + keyring.MockInit() + + // Set SA credentials + if err := SetAuthField(SERVICE_ACCOUNT_EMAIL, "[EMAIL_REDACTED]"); err != nil { + t.Fatalf("set sa email: %v", err) + } + + if err := SetAuthField(SERVICE_ACCOUNT_KEY, `{"id":"test"}`); err != nil { + t.Fatalf("set sa key: %v", err) + } + + if err := SetAuthField(PRIVATE_KEY, "private-key-data"); err != nil { + t.Fatalf("set private key: %v", err) + } + + // Now call LoginUser + if err := LoginUser("[EMAIL_REDACTED]", "user-token", "refresh-token", "1234567890"); err != nil { + t.Fatalf("LoginUser failed: %v", err) + } + + // Verify SA fields were cleaned up + if val, err := GetAuthField(SERVICE_ACCOUNT_EMAIL); err == nil && val != "" { + t.Errorf("SERVICE_ACCOUNT_EMAIL still exists after LoginUser: %s", val) + } + + if val, err := GetAuthField(SERVICE_ACCOUNT_KEY); err == nil && val != "" { + t.Errorf("SERVICE_ACCOUNT_KEY still exists after LoginUser: %s", val) + } + + if val, err := GetAuthField(PRIVATE_KEY); err == nil && val != "" { + t.Errorf("PRIVATE_KEY still exists after LoginUser: %s", val) + } + + // Verify user fields are present + if val, err := GetAuthField(USER_EMAIL); err != nil || val != "[EMAIL_REDACTED]" { + t.Errorf("expected USER_EMAIL '[EMAIL_REDACTED]', got %q (err: %v)", val, err) + } + + // Cleanup + _ = LogoutUser() +} + +func TestKeyringWriteCleansUpTextFile(t *testing.T) { + keyring.MockInit() + + profile, err := config.GetProfile() + if err != nil { + t.Fatalf("get profile: %v", err) + } + + key := authFieldKey("test-sync-key") + + // Simulate old value in text file + if err := setAuthFieldInEncodedTextFile(profile, key, "old-file-value"); err != nil { + t.Fatalf("set in text file: %v", err) + } + + // Now set with setAuthFieldWithProfile (which succeeds in keyring) + if err := setAuthFieldWithProfile(profile, key, "new-keyring-value"); err != nil { + t.Fatalf("setAuthFieldWithProfile failed: %v", err) + } + + // Keyring has new value + val, err := getAuthFieldFromKeyring(profile, key) + if err != nil || val != "new-keyring-value" { + t.Errorf("expected new-keyring-value in keyring, got %q (err: %v)", val, err) + } + + // Text file should no longer have the old key + _, err = getAuthFieldFromEncodedTextFile(profile, key) + if err == nil { + t.Errorf("expected key to be removed from text file when set in keyring") + } + + // Cleanup + _ = deleteAuthFieldWithProfile(profile, key) +} From fba65b4e71d1acf74717f7086fc1214b7c97db0b Mon Sep 17 00:00:00 2001 From: Marcel Jacek <72880145+marceljk@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:15:02 +0100 Subject: [PATCH 2/4] review feedback --- internal/pkg/auth/service_account.go | 24 ++++++++++++++++++----- internal/pkg/auth/service_account_test.go | 16 +++++++++++++++ internal/pkg/auth/storage_test.go | 5 ++--- internal/pkg/config/config.go | 11 ++++++++++- 4 files changed, 47 insertions(+), 9 deletions(-) diff --git a/internal/pkg/auth/service_account.go b/internal/pkg/auth/service_account.go index 42edc5e6a..a630c3598 100644 --- a/internal/pkg/auth/service_account.go +++ b/internal/pkg/auth/service_account.go @@ -108,11 +108,25 @@ func AuthenticateServiceAccount(p *print.Printer, rt http.RoundTripper, disableW if !disableWriting { // Clean up user credentials to avoid stale fields - _ = DeleteAuthField(USER_EMAIL) - _ = DeleteAuthField(REFRESH_TOKEN) - _ = DeleteAuthField(SERVICE_ACCOUNT_TOKEN) - _ = DeleteAuthField(SERVICE_ACCOUNT_KEY) - _ = DeleteAuthField(PRIVATE_KEY) + if err = DeleteAuthField(USER_EMAIL); err != nil { + p.Debug(print.ErrorLevel, "failed to delete auth field %s: %v", USER_EMAIL, err) + } + + if err = DeleteAuthField(REFRESH_TOKEN); err != nil { + p.Debug(print.ErrorLevel, "failed to delete auth field %s: &v", USER_EMAIL, err) + } + + if err = DeleteAuthField(SERVICE_ACCOUNT_TOKEN); err != nil { + p.Debug(print.ErrorLevel, "failed to delete auth field %s: &v", REFRESH_TOKEN, err) + } + + if err = DeleteAuthField(SERVICE_ACCOUNT_KEY); err != nil { + p.Debug(print.ErrorLevel, "failed to delete auth field %s: &v", SERVICE_ACCOUNT_TOKEN, err) + } + + if err = DeleteAuthField(PRIVATE_KEY); err != nil { + p.Debug(print.ErrorLevel, "failed to delete auth field %s: &v", SERVICE_ACCOUNT_KEY, err) + } err = SetAuthFlow(authFlowType) if err != nil { diff --git a/internal/pkg/auth/service_account_test.go b/internal/pkg/auth/service_account_test.go index 57f1e43b7..a04f9ff12 100644 --- a/internal/pkg/auth/service_account_test.go +++ b/internal/pkg/auth/service_account_test.go @@ -3,6 +3,7 @@ package auth import ( "fmt" "net/http" + "os" "testing" "github.com/stackitcloud/stackit-cli/internal/pkg/config" @@ -28,6 +29,21 @@ type keyFlowMocked struct { tokenInvalid bool } +// TestMain will be executed before all tests in the "auth" package. +// It's used to configure a temp directory for the CLI configuration files. +func TestMain(m *testing.M) { + tempDir, err := os.MkdirTemp("", "stackit-auth-test-*") + if err != nil { + fmt.Printf("could not create temp dir: %v", err) + os.Exit(1) + } + defer os.RemoveAll(tempDir) + + config.SetDefaultConfigFolderPath(tempDir) + + m.Run() +} + func (f *keyFlowMocked) GetAccessToken() (string, error) { if f.getAccessTokenFail { return "", fmt.Errorf("error") diff --git a/internal/pkg/auth/storage_test.go b/internal/pkg/auth/storage_test.go index 69979d0ca..64e2382ab 100644 --- a/internal/pkg/auth/storage_test.go +++ b/internal/pkg/auth/storage_test.go @@ -271,7 +271,7 @@ func TestSetGetAuthFieldWithProfile(t *testing.T) { for _, tt := range tests { t.Run(tt.description, func(t *testing.T) { - // Apppend random string to profile name to avoid conflicts + // Append random string to profile name to avoid conflicts tt.activeProfile = makeProfileNameUnique(tt.activeProfile) // Make sure profile name is valid @@ -1288,7 +1288,6 @@ func TestFileNotCreatedOnReadOrDelete(t *testing.T) { } textFilePath := filepath.Join(config.GetProfileFolderPath(profile), textFileName) - _ = os.Remove(textFilePath) // Ensure file doesn't exist if _, err := os.Stat(textFilePath); !os.IsNotExist(err) { @@ -1318,13 +1317,13 @@ func TestFileNotCreatedOnReadOrDelete(t *testing.T) { } func TestFileRemovedWhenEmpty(t *testing.T) { + profile, err := config.GetProfile() if err != nil { t.Fatalf("get profile: %v", err) } textFilePath := filepath.Join(config.GetProfileFolderPath(profile), textFileName) - _ = os.Remove(textFilePath) field1 := authFieldKey("test-cleanup-field-1") field2 := authFieldKey("test-cleanup-field-2") diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index cf5856032..49acb6ad6 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -141,7 +141,11 @@ var configFolderPath string var profileFilePath string func InitConfig() { - initConfig(getInitialConfigDir()) + dir := defaultConfigFolderPath + if dir == "" { + dir = getInitialConfigDir() + } + initConfig(dir) } func initConfig(configPath string) { @@ -254,3 +258,8 @@ func getInitialProfileFilePath() string { return filepath.Join(configFolderPath, fmt.Sprintf("%s.%s", profileFileName, profileFileExtension)) } + +// SetDefaultConfigFolderPath overrides the default config folder path. Intended for testing. +func SetDefaultConfigFolderPath(path string) { + defaultConfigFolderPath = path +} From 1d5e99c7ebaa08c46dc75d7cd9b370256a56fb00 Mon Sep 17 00:00:00 2001 From: Marcel Jacek <72880145+marceljk@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:43:58 +0100 Subject: [PATCH 3/4] review feedback: improve error handling in setAuthFieldWithProfile --- internal/pkg/auth/service_account_test.go | 2 +- internal/pkg/auth/storage.go | 32 ++++- internal/pkg/auth/storage_test.go | 139 +++++++++++++++++----- internal/pkg/config/config.go | 1 + 4 files changed, 141 insertions(+), 33 deletions(-) diff --git a/internal/pkg/auth/service_account_test.go b/internal/pkg/auth/service_account_test.go index a04f9ff12..6925473de 100644 --- a/internal/pkg/auth/service_account_test.go +++ b/internal/pkg/auth/service_account_test.go @@ -37,7 +37,7 @@ func TestMain(m *testing.M) { fmt.Printf("could not create temp dir: %v", err) os.Exit(1) } - defer os.RemoveAll(tempDir) + defer os.RemoveAll(tempDir) // nolint:errcheck // at this point removing the temp dir is not relevant config.SetDefaultConfigFolderPath(tempDir) diff --git a/internal/pkg/auth/storage.go b/internal/pkg/auth/storage.go index 36d989696..d97b60cf7 100644 --- a/internal/pkg/auth/storage.go +++ b/internal/pkg/auth/storage.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "github.com/stackitcloud/stackit-cli/internal/pkg/config" pkgErrors "github.com/stackitcloud/stackit-cli/internal/pkg/errors" @@ -108,15 +109,42 @@ func setAuthFieldWithProfile(profile string, key authFieldKey, value string) err } // If writing to the text file succeeded as a fallback, clean up any stale key in the keyring // so GetAuthField won't return outdated credentials. - _ = deleteAuthFieldInKeyring(profile, key) + errDelete := deleteAuthFieldInKeyring(profile, key) + if errDelete != nil && !errors.Is(errDelete, keyring.ErrNotFound) && !isKeyringUnavailable(errDelete) { + return fmt.Errorf("cleanup stale key from keyring: %w", errDelete) + } } else { // If writing to the keyring succeeded, clean up any old entry from the encoded text file. - _ = deleteAuthFieldInEncodedTextFile(profile, key) + errCleanup := deleteAuthFieldInEncodedTextFile(profile, key) + if errCleanup != nil { + return fmt.Errorf("saved to keyring, but failed to clean up legacy fallback file: %w", errCleanup) + } } return nil } +// isKeyringUnavailable returns true if the error indicates that no operational +// OS keyring service is available on the system (e.g. headless CI, Docker, or +// minimal server environments), allowing the CLI to fall back cleanly. +func isKeyringUnavailable(err error) bool { + if err == nil { + return false + } + // Fallback provider error when compiled for or running on platforms without keyring support + if errors.Is(err, keyring.ErrUnsupportedPlatform) { + return true + } + + errStr := strings.ToLower(err.Error()) + + return strings.Contains(errStr, "dbus") || // Linux: D-Bus session bus missing or unreachable (e.g. headless CI, Docker containers, remote SSH) + strings.Contains(errStr, "no secret service") || // Linux: D-Bus is running, but no Secret Service daemon (e.g. gnome-keyring, keepassxc) is registered + strings.Contains(errStr, "cannot connect") || // Generic IPC/socket connection failure to the system credential daemon + strings.Contains(errStr, "not supported") || // Environment or platform does not support the credential service + strings.Contains(errStr, "unavailable") // Explicit service unavailable errors (including unit tests with mock keyrings) +} + func setAuthFieldInKeyring(activeProfile string, key authFieldKey, value string) error { if activeProfile != config.DefaultProfileName { activeProfileKeyring := filepath.Join(keyringService, activeProfile) diff --git a/internal/pkg/auth/storage_test.go b/internal/pkg/auth/storage_test.go index 64e2382ab..6b452da27 100644 --- a/internal/pkg/auth/storage_test.go +++ b/internal/pkg/auth/storage_test.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "testing" "time" @@ -1276,7 +1277,10 @@ func TestStaleKeychainCleanupOnFallback(t *testing.T) { } // Cleanup - _ = DeleteAuthField(PRIVATE_KEY) + err = DeleteAuthField(PRIVATE_KEY) + if err != nil { + t.Fatalf("DeleteAuthField failed: %v", err) + } } func TestFileNotCreatedOnReadOrDelete(t *testing.T) { @@ -1317,7 +1321,6 @@ func TestFileNotCreatedOnReadOrDelete(t *testing.T) { } func TestFileRemovedWhenEmpty(t *testing.T) { - profile, err := config.GetProfile() if err != nil { t.Fatalf("get profile: %v", err) @@ -1472,41 +1475,117 @@ func TestLoginUserCleansUpServiceAccountCredentials(t *testing.T) { } // Cleanup - _ = LogoutUser() + err := LogoutUser() + if err != nil { + t.Fatalf("LogoutUser() failed: %v", err) + } } -func TestKeyringWriteCleansUpTextFile(t *testing.T) { - keyring.MockInit() - - profile, err := config.GetProfile() - if err != nil { - t.Fatalf("get profile: %v", err) +func TestSetAuthFieldWithProfile(t *testing.T) { + tests := []struct { + description string + keyringMockErr error + setupCorruptFile bool + setupStaleFileVal string + key authFieldKey + value string + wantErr bool + errContains string + verifyInKeyring bool + verifyInFile bool + }{ + { + description: "keyring write succeeds and cleans up stale text file entry", + setupStaleFileVal: "old-file-val", + key: "test-sync-key", + value: "new-keyring-val", + wantErr: false, + verifyInKeyring: true, + }, + { + description: "keyring write succeeds but fallback file cleanup fails", + setupCorruptFile: true, + key: "test-corrupt-file-key", + value: "value", + wantErr: true, + errContains: "saved to keyring, but failed to clean up legacy fallback file", + }, + { + description: "keyring write fails and keyring cleanup fails with unexpected error", + keyringMockErr: fmt.Errorf("access denied to secure enclave"), + key: "test-keyring-delete-fail", + value: "value", + wantErr: true, + errContains: "cleanup stale key from keyring", + }, + { + description: "keyring write fails and keyring cleanup is ignored when keyring is unavailable", + keyringMockErr: fmt.Errorf("dbus daemon unavailable"), + key: "test-keyring-unavailable", + value: "value", + wantErr: false, + verifyInFile: true, + }, } - key := authFieldKey("test-sync-key") + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + profile, err := config.GetProfile() + if err != nil { + t.Fatalf("get profile: %v", err) + } + + if tt.keyringMockErr != nil { + keyring.MockInitWithError(tt.keyringMockErr) + } else { + keyring.MockInit() + } - // Simulate old value in text file - if err := setAuthFieldInEncodedTextFile(profile, key, "old-file-value"); err != nil { - t.Fatalf("set in text file: %v", err) - } + textFilePath := filepath.Join(config.GetProfileFolderPath(profile), textFileName) + if tt.setupCorruptFile { + if err := os.WriteFile(textFilePath, []byte("invalid-base64!!!"), 0o600); err != nil { + t.Fatalf("failed to write corrupt file: %v", err) + } + defer func() { + _ = os.Remove(textFilePath) + }() + } else if tt.setupStaleFileVal != "" { + if err := setAuthFieldInEncodedTextFile(profile, tt.key, tt.setupStaleFileVal); err != nil { + t.Fatalf("failed to set stale file value: %v", err) + } + } - // Now set with setAuthFieldWithProfile (which succeeds in keyring) - if err := setAuthFieldWithProfile(profile, key, "new-keyring-value"); err != nil { - t.Fatalf("setAuthFieldWithProfile failed: %v", err) - } + defer func() { + _ = deleteAuthFieldInEncodedTextFile(profile, tt.key) + _ = deleteAuthFieldInKeyring(profile, tt.key) + }() - // Keyring has new value - val, err := getAuthFieldFromKeyring(profile, key) - if err != nil || val != "new-keyring-value" { - t.Errorf("expected new-keyring-value in keyring, got %q (err: %v)", val, err) - } + err = setAuthFieldWithProfile(profile, tt.key, tt.value) + if (err != nil) != tt.wantErr { + t.Fatalf("setAuthFieldWithProfile() error = %v, wantErr %v", err, tt.wantErr) + } - // Text file should no longer have the old key - _, err = getAuthFieldFromEncodedTextFile(profile, key) - if err == nil { - t.Errorf("expected key to be removed from text file when set in keyring") - } + if tt.errContains != "" && !strings.Contains(err.Error(), tt.errContains) { + t.Errorf("expected error containing %q, got: %v", tt.errContains, err) + } - // Cleanup - _ = deleteAuthFieldWithProfile(profile, key) + if tt.verifyInKeyring { + got, err := getAuthFieldFromKeyring(profile, tt.key) + if err != nil || got != tt.value { + t.Errorf("expected %q in keyring, got %q (err: %v)", tt.value, got, err) + } + + if _, err := getAuthFieldFromEncodedTextFile(profile, tt.key); err == nil { + t.Errorf("expected key to be removed from text file") + } + } + + if tt.verifyInFile { + got, err := getAuthFieldFromEncodedTextFile(profile, tt.key) + if err != nil || got != tt.value { + t.Errorf("expected %q in text file, got %q (err: %v)", tt.value, got, err) + } + } + }) + } } diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index 49acb6ad6..934b33ceb 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -145,6 +145,7 @@ func InitConfig() { if dir == "" { dir = getInitialConfigDir() } + initConfig(dir) } From 817c8e0ba49369821610e6338584c78e3a2bb108 Mon Sep 17 00:00:00 2001 From: Marcel Jacek <72880145+marceljk@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:03:11 +0100 Subject: [PATCH 4/4] fix broken tests in CI --- internal/pkg/auth/storage.go | 34 ++++++++++--------------------- internal/pkg/auth/storage_test.go | 16 +++++++-------- 2 files changed, 19 insertions(+), 31 deletions(-) diff --git a/internal/pkg/auth/storage.go b/internal/pkg/auth/storage.go index d97b60cf7..dc3b7a4e4 100644 --- a/internal/pkg/auth/storage.go +++ b/internal/pkg/auth/storage.go @@ -7,7 +7,6 @@ import ( "fmt" "os" "path/filepath" - "strings" "github.com/stackitcloud/stackit-cli/internal/pkg/config" pkgErrors "github.com/stackitcloud/stackit-cli/internal/pkg/errors" @@ -110,7 +109,17 @@ func setAuthFieldWithProfile(profile string, key authFieldKey, value string) err // If writing to the text file succeeded as a fallback, clean up any stale key in the keyring // so GetAuthField won't return outdated credentials. errDelete := deleteAuthFieldInKeyring(profile, key) - if errDelete != nil && !errors.Is(errDelete, keyring.ErrNotFound) && !isKeyringUnavailable(errDelete) { + if errDelete != nil { + // Ignore if key was not found or platform does not support keyring + if errors.Is(errDelete, keyring.ErrNotFound) || errors.Is(errDelete, keyring.ErrUnsupportedPlatform) { + return nil + } + // If delete failed for the same reason as write (e.g. D-Bus missing, daemon unavailable, + // or headless CI/Docker environment), ignore as the keyring service is non-functional. + if errDelete.Error() == err.Error() { + return nil + } + return fmt.Errorf("cleanup stale key from keyring: %w", errDelete) } } else { @@ -124,27 +133,6 @@ func setAuthFieldWithProfile(profile string, key authFieldKey, value string) err return nil } -// isKeyringUnavailable returns true if the error indicates that no operational -// OS keyring service is available on the system (e.g. headless CI, Docker, or -// minimal server environments), allowing the CLI to fall back cleanly. -func isKeyringUnavailable(err error) bool { - if err == nil { - return false - } - // Fallback provider error when compiled for or running on platforms without keyring support - if errors.Is(err, keyring.ErrUnsupportedPlatform) { - return true - } - - errStr := strings.ToLower(err.Error()) - - return strings.Contains(errStr, "dbus") || // Linux: D-Bus session bus missing or unreachable (e.g. headless CI, Docker containers, remote SSH) - strings.Contains(errStr, "no secret service") || // Linux: D-Bus is running, but no Secret Service daemon (e.g. gnome-keyring, keepassxc) is registered - strings.Contains(errStr, "cannot connect") || // Generic IPC/socket connection failure to the system credential daemon - strings.Contains(errStr, "not supported") || // Environment or platform does not support the credential service - strings.Contains(errStr, "unavailable") // Explicit service unavailable errors (including unit tests with mock keyrings) -} - func setAuthFieldInKeyring(activeProfile string, key authFieldKey, value string) error { if activeProfile != config.DefaultProfileName { activeProfileKeyring := filepath.Join(keyringService, activeProfile) diff --git a/internal/pkg/auth/storage_test.go b/internal/pkg/auth/storage_test.go index 6b452da27..adc108afe 100644 --- a/internal/pkg/auth/storage_test.go +++ b/internal/pkg/auth/storage_test.go @@ -1511,17 +1511,17 @@ func TestSetAuthFieldWithProfile(t *testing.T) { errContains: "saved to keyring, but failed to clean up legacy fallback file", }, { - description: "keyring write fails and keyring cleanup fails with unexpected error", - keyringMockErr: fmt.Errorf("access denied to secure enclave"), - key: "test-keyring-delete-fail", + description: "keyring write fails (dbus unavailable) and cleanup is safely ignored", + keyringMockErr: fmt.Errorf("dbus daemon unavailable"), + key: "test-keyring-unavailable", value: "value", - wantErr: true, - errContains: "cleanup stale key from keyring", + wantErr: false, + verifyInFile: true, }, { - description: "keyring write fails and keyring cleanup is ignored when keyring is unavailable", - keyringMockErr: fmt.Errorf("dbus daemon unavailable"), - key: "test-keyring-unavailable", + description: "keyring write fails (org.freedesktop.secrets missing) and cleanup is safely ignored", + keyringMockErr: fmt.Errorf("The name org.freedesktop.secrets was not provided by any .service files"), + key: "test-secrets-service-missing", value: "value", wantErr: false, verifyInFile: true,