diff --git a/cmd/auth.go b/cmd/auth.go index acafd179..9a1f338c 100644 --- a/cmd/auth.go +++ b/cmd/auth.go @@ -10,7 +10,6 @@ import ( "github.com/kernel/cli/pkg/util" "github.com/pterm/pterm" "github.com/spf13/cobra" - "github.com/zalando/go-keyring" ) // JWTClaims represents the claims in a JWT token @@ -103,11 +102,7 @@ func runAuth(cmd *cobra.Command, args []string) error { pterm.Info.Printf("API URL: %s\n", util.GetBaseURL()) pterm.Info.Printf("Auth URL: %s\n", tokenAuthBaseURLForDisplay(tokens)) pterm.Info.Printf("OAuth client ID: %s\n", maskClientID(tokenOAuthClientIDForDisplay(tokens))) - if tokens.AccessScope == "project" && tokens.ProjectID != "" { - pterm.Info.Printf("Access scope: project %s\n", tokens.ProjectID) - } else { - pterm.Info.Println("Access scope: organization-wide") - } + pterm.Info.Printf("Access scope: %s\n", accessScopeLabel(tokens)) // Extract info from JWT token if claims, err := parseJWT(tokens.AccessToken); err == nil && claims != nil { @@ -135,12 +130,7 @@ func runAuth(cmd *cobra.Command, args []string) error { } } - // Storage method - if _, err := keyring.Get(auth.KeyringService, auth.KeyringUser); err == nil { - logger.Debug("Storage method", logger.Args("method", "OS Keychain")) - } else { - logger.Debug("Storage method", logger.Args("method", "Local file (~/.config/kernel/credentials)")) - } + logger.Debug("Storage method", logger.Args("method", tokens.Source)) return nil } @@ -165,3 +155,22 @@ func maskClientID(clientID string) string { } return clientID[:4] + "..." + clientID[len(clientID)-4:] } + +// accessScopeLabel describes where the stored credentials may act: one +// project, the projects a native grant is limited to, or the organization. +// Credentials saved by older CLI versions did not record the projects, so +// their scope is unknown until they are refreshed or replaced. +func accessScopeLabel(tokens *auth.TokenStorage) string { + switch { + case tokens.AccessScope == "project" && tokens.ProjectID != "": + return "project " + tokens.ProjectID + case len(tokens.Projects) == 1: + return "project " + tokens.Projects[0] + case len(tokens.Projects) > 1: + return "projects " + strings.Join(tokens.Projects, ", ") + case !tokens.ScopeRecorded: + return "unknown (saved by an older CLI version; run 'kernel login --force' to record it)" + default: + return "organization-wide" + } +} diff --git a/cmd/auth_scope_test.go b/cmd/auth_scope_test.go new file mode 100644 index 00000000..f943f4a4 --- /dev/null +++ b/cmd/auth_scope_test.go @@ -0,0 +1,25 @@ +package cmd + +import ( + "testing" + + "github.com/kernel/cli/pkg/auth" +) + +func TestAccessScopeLabel(t *testing.T) { + for _, tc := range []struct { + name string + tokens auth.TokenStorage + want string + }{ + {"legacy project scope", auth.TokenStorage{AccessScope: "project", ProjectID: "proj_1"}, "project proj_1"}, + {"native grant for one project", auth.TokenStorage{AccessScope: "organization", Projects: []string{"proj_a"}}, "project proj_a"}, + {"native grant for several projects", auth.TokenStorage{AccessScope: "organization", Projects: []string{"proj_a", "proj_b"}}, "projects proj_a, proj_b"}, + {"every project", auth.TokenStorage{AccessScope: "organization", ScopeRecorded: true}, "organization-wide"}, + {"saved by an older CLI", auth.TokenStorage{AccessScope: "organization"}, "unknown (saved by an older CLI version; run 'kernel login --force' to record it)"}, + } { + if got := accessScopeLabel(&tc.tokens); got != tc.want { + t.Errorf("%s: accessScopeLabel() = %q, want %q", tc.name, got, tc.want) + } + } +} diff --git a/cmd/project_scope_test.go b/cmd/project_scope_test.go index 048bfd87..d8372667 100644 --- a/cmd/project_scope_test.go +++ b/cmd/project_scope_test.go @@ -131,6 +131,9 @@ func TestDeployGithubProjectScope(t *testing.T) { cmd := projectTestCommand(t, server.URL, tt.flag) if tt.oauth { t.Setenv("KERNEL_API_KEY", "") + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) keyring.MockInit() t.Cleanup(keyring.MockInit) require.NoError(t, auth.SaveTokens(&auth.TokenStorage{ diff --git a/go.mod b/go.mod index 71da086e..c149ce8d 100644 --- a/go.mod +++ b/go.mod @@ -22,6 +22,7 @@ require ( golang.org/x/crypto v0.52.0 golang.org/x/oauth2 v0.30.0 golang.org/x/sync v0.20.0 + golang.org/x/sys v0.45.0 golang.org/x/term v0.43.0 gopkg.in/yaml.v3 v3.0.1 ) @@ -59,6 +60,5 @@ require ( github.com/tidwall/pretty v1.2.1 // indirect github.com/tidwall/sjson v1.2.5 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - golang.org/x/sys v0.45.0 // indirect golang.org/x/text v0.37.0 // indirect ) diff --git a/pkg/auth/client.go b/pkg/auth/client.go index 64469670..0b07cee7 100644 --- a/pkg/auth/client.go +++ b/pkg/auth/client.go @@ -27,22 +27,13 @@ func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error if err == nil { // Check if access token is expired and refresh if needed if tokens.IsExpired() && tokens.RefreshToken != "" { - pterm.Debug.Println("Access token expired, attempting refresh...") - - refreshedTokens, refreshErr := RefreshTokens(context.Background(), tokens) + refreshed, refreshErr := refreshStoredTokens(context.Background()) if refreshErr != nil { pterm.Warning.Printf("Failed to refresh tokens: %v\n", refreshErr) pterm.Info.Println("Please run 'kernel login' to re-authenticate") return nil, fmt.Errorf("expired credentials, please re-authenticate: %w", refreshErr) } - - // Save refreshed tokens - if saveErr := SaveTokens(refreshedTokens); saveErr != nil { - pterm.Warning.Printf("Failed to save refreshed tokens: %v\n", saveErr) - } - - tokens = refreshedTokens - pterm.Debug.Println("Successfully refreshed access token") + tokens = refreshed } // Use JWT token for authentication via Authorization header @@ -54,3 +45,33 @@ func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error // No authentication available return nil, fmt.Errorf("no authentication available. Please run 'kernel login' or set KERNEL_API_KEY environment variable") } + +// refreshStoredTokens refreshes the stored credentials while holding the +// credentials lock. It re-reads them first, so when another CLI process has +// already refreshed, its tokens are used and the consumed refresh token is +// never presented again. +func refreshStoredTokens(ctx context.Context) (*TokenStorage, error) { + var tokens *TokenStorage + err := withCredentialsLock(func() error { + current, err := loadTokens() + if err != nil { + return err + } + if !current.IsExpired() || current.RefreshToken == "" { + tokens = current + return nil + } + pterm.Debug.Println("Access token expired, attempting refresh...") + refreshed, err := RefreshTokens(ctx, current) + if err != nil { + return err + } + if err := saveTokens(refreshed); err != nil { + pterm.Warning.Printf("Failed to save refreshed tokens: %v\n", err) + } + pterm.Debug.Println("Successfully refreshed access token") + tokens = refreshed + return nil + }) + return tokens, err +} diff --git a/pkg/auth/lock_unix.go b/pkg/auth/lock_unix.go new file mode 100644 index 00000000..bd496894 --- /dev/null +++ b/pkg/auth/lock_unix.go @@ -0,0 +1,21 @@ +//go:build !windows + +package auth + +import ( + "errors" + "os" + "syscall" +) + +func tryLockFile(f *os.File) (bool, error) { + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if errors.Is(err, syscall.EWOULDBLOCK) { + return false, nil + } + return err == nil, err +} + +func unlockFile(f *os.File) error { + return syscall.Flock(int(f.Fd()), syscall.LOCK_UN) +} diff --git a/pkg/auth/lock_windows.go b/pkg/auth/lock_windows.go new file mode 100644 index 00000000..ed09e725 --- /dev/null +++ b/pkg/auth/lock_windows.go @@ -0,0 +1,24 @@ +//go:build windows + +package auth + +import ( + "errors" + "os" + + "golang.org/x/sys/windows" +) + +func tryLockFile(f *os.File) (bool, error) { + var overlapped windows.Overlapped + err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overlapped) + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { + return false, nil + } + return err == nil, err +} + +func unlockFile(f *os.File) error { + var overlapped windows.Overlapped + return windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, &overlapped) +} diff --git a/pkg/auth/oauth.go b/pkg/auth/oauth.go index 7e6da263..d59a1b9b 100644 --- a/pkg/auth/oauth.go +++ b/pkg/auth/oauth.go @@ -257,8 +257,12 @@ func (oc *OAuthConfig) exchangeCodeForTokens(ctx context.Context, code, orgID, a if value, ok := token.Extra("org_id").(string); ok && value != "" { orgID = value } + // A response that states the access scope also lists the projects a + // grant is limited to, so its scope is recorded. + scopeRecorded := false if value, ok := token.Extra("access_scope").(string); ok && value != "" { accessScope = value + scopeRecorded = true } if value, ok := token.Extra("project_id").(string); ok { projectID = value @@ -269,6 +273,7 @@ func (oc *OAuthConfig) exchangeCodeForTokens(ctx context.Context, code, orgID, a if accessScope == "organization" { projectID = "" } + projects, _ := projectsFromResponse(token.Extra("projects")) return &TokenStorage{ AccessToken: token.AccessToken, @@ -277,6 +282,8 @@ func (oc *OAuthConfig) exchangeCodeForTokens(ctx context.Context, code, orgID, a OrgID: orgID, AccessScope: accessScope, ProjectID: projectID, + Projects: projects, + ScopeRecorded: scopeRecorded, AuthBaseURL: oc.AuthBaseURL, OAuthClientID: oc.OAuthClientID, }, nil @@ -341,8 +348,10 @@ func RefreshTokens(ctx context.Context, tokens *TokenStorage) (*TokenStorage, er orgID = value } accessScope := tokens.AccessScope + scopeRecorded := tokens.ScopeRecorded if value, ok := tokenResponse["access_scope"].(string); ok && value != "" { accessScope = value + scopeRecorded = true } if accessScope == "" { accessScope = "organization" @@ -354,6 +363,10 @@ func RefreshTokens(ctx context.Context, tokens *TokenStorage) (*TokenStorage, er if accessScope == "organization" { projectID = "" } + projects := tokens.Projects + if value, ok := projectsFromResponse(tokenResponse["projects"]); ok { + projects = value + } return &TokenStorage{ AccessToken: newToken.AccessToken, @@ -362,11 +375,28 @@ func RefreshTokens(ctx context.Context, tokens *TokenStorage) (*TokenStorage, er OrgID: orgID, AccessScope: accessScope, ProjectID: projectID, + Projects: projects, + ScopeRecorded: scopeRecorded, AuthBaseURL: tokenAuthBaseURL(tokens), OAuthClientID: tokenOAuthClientID(tokens), }, nil } +// projectsFromResponse reads the projects a token response limits the grant +// to. ok reports whether the response carried the field at all. +func projectsFromResponse(value interface{}) (projects []string, ok bool) { + items, ok := value.([]interface{}) + if !ok { + return nil, false + } + for _, item := range items { + if id, isString := item.(string); isString && id != "" { + projects = append(projects, id) + } + } + return projects, true +} + // generateCodeVerifier generates a cryptographically secure random string for PKCE func generateCodeVerifier() (string, error) { bytes := make([]byte, 32) diff --git a/pkg/auth/oauth_test.go b/pkg/auth/oauth_test.go index daab36e6..5b707b58 100644 --- a/pkg/auth/oauth_test.go +++ b/pkg/auth/oauth_test.go @@ -6,6 +6,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "strings" "testing" "time" @@ -223,6 +224,9 @@ func TestRefreshLegacyTokensRemainOrganizationWide(t *testing.T) { if tokens.ProjectID != "" { t.Fatalf("ProjectID = %q, want empty", tokens.ProjectID) } + if tokens.ScopeRecorded { + t.Fatal("ScopeRecorded = true for a response that does not state the scope") + } } func TestLegacyTokenRefreshConfigUsesProdDefaults(t *testing.T) { @@ -238,3 +242,87 @@ func TestLegacyTokenRefreshConfigUsesProdDefaults(t *testing.T) { t.Fatalf("tokenOAuthClientID = %q, want %q", got, want) } } + +func TestTokensKeepNativeProjects(t *testing.T) { + refreshed := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + body := map[string]interface{}{ + "access_token": "access-token", + "refresh_token": "refresh-token", + "token_type": "Bearer", + "expires_in": 3600, + "org_id": "org_1", + "access_scope": "organization", + } + if !refreshed { + body["projects"] = []string{"proj_a", "proj_b"} + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(body) + })) + defer server.Close() + + config := &OAuthConfig{ + Config: &oauth2.Config{ + ClientID: "client-id", + RedirectURL: "http://localhost/callback", + Endpoint: oauth2.Endpoint{TokenURL: server.URL, AuthStyle: oauth2.AuthStyleInParams}, + }, + Verifier: "verifier", + AuthBaseURL: server.URL, + OAuthClientID: "client-id", + } + tokens, err := config.exchangeCodeForTokens(context.Background(), "code", "org_1", "", "") + if err != nil { + t.Fatalf("exchangeCodeForTokens() error = %v", err) + } + if got, want := strings.Join(tokens.Projects, ","), "proj_a,proj_b"; got != want { + t.Fatalf("Projects = %q, want %q", got, want) + } + if !tokens.ScopeRecorded { + t.Fatal("ScopeRecorded = false after login") + } + + // A refresh response without the field keeps the grant's projects. + refreshed = true + tokens, err = RefreshTokens(context.Background(), tokens) + if err != nil { + t.Fatalf("RefreshTokens() error = %v", err) + } + if got, want := strings.Join(tokens.Projects, ","), "proj_a,proj_b"; got != want { + t.Fatalf("Projects after refresh = %q, want %q", got, want) + } + if !tokens.ScopeRecorded { + t.Fatal("ScopeRecorded = false after refresh") + } +} + +func TestRefreshRecordsScopeForOlderCredentials(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "access-new", + "refresh_token": "refresh-new", + "token_type": "Bearer", + "expires_in": 600, + "access_scope": "organization", + "projects": []string{"proj_a"}, + }) + })) + defer server.Close() + + // Saved by a CLI that did not record projects or ScopeRecorded. + tokens, err := RefreshTokens(context.Background(), &TokenStorage{ + RefreshToken: "refresh-old", + OrgID: "org_1", + AccessScope: "organization", + AuthBaseURL: server.URL, + OAuthClientID: "client-id", + }) + if err != nil { + t.Fatalf("RefreshTokens() error = %v", err) + } + if !tokens.ScopeRecorded || strings.Join(tokens.Projects, ",") != "proj_a" { + t.Fatalf("after refresh: ScopeRecorded = %v, Projects = %v", tokens.ScopeRecorded, tokens.Projects) + } +} diff --git a/pkg/auth/storage.go b/pkg/auth/storage.go index 0a79fc8a..a5820f9f 100644 --- a/pkg/auth/storage.go +++ b/pkg/auth/storage.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "path/filepath" + "sync" "time" "github.com/zalando/go-keyring" @@ -25,6 +26,15 @@ type TokenStorage struct { ProjectID string `json:"project_id,omitempty"` AuthBaseURL string `json:"auth_base_url,omitempty"` OAuthClientID string `json:"oauth_client_id,omitempty"` + Projects []string `json:"projects,omitempty"` // projects a native grant is limited to; empty means all + // ScopeRecorded is set by CLI versions that record Projects. Credentials + // saved without it may be limited to projects the CLI does not know about. + ScopeRecorded bool `json:"scope_recorded,omitempty"` + // SavedAt tells which of the keyring and the credentials file is current + // when both hold credentials. + SavedAt time.Time `json:"saved_at,omitzero"` + // Source is where LoadTokens found the credentials; it is not stored. + Source string `json:"-"` } // IsExpired checks if the access token is expired (with 5 minute buffer) @@ -32,54 +42,152 @@ func (t *TokenStorage) IsExpired() bool { return time.Now().Add(5 * time.Minute).After(t.ExpiresAt) } -// SaveTokens stores authentication tokens securely in the OS keychain +// setKeyring is keyring.Set, replaceable in tests that need it to fail. +var setKeyring = keyring.Set + +// Token storage sources, as reported in TokenStorage.Source. +const ( + SourceKeychain = "OS Keychain" + SourceFile = "Local file (~/.config/kernel/credentials)" +) + +// credentialsLockTimeout bounds how long one CLI process waits while another +// saves or refreshes credentials; a refresh takes at most tokenExchangeTimeout. +const credentialsLockTimeout = tokenExchangeTimeout + 10*time.Second + +// credentialsMu serializes credential access within one process; the lock +// file serializes it across processes. +var credentialsMu sync.Mutex + +// withCredentialsLock runs fn while holding a lock file in the config +// directory, so CLI processes read, save, and refresh credentials one at a +// time. +func withCredentialsLock(fn func() error) error { + credentialsMu.Lock() + defer credentialsMu.Unlock() + configDir, err := getConfigDir() + if err != nil { + return fmt.Errorf("failed to get config directory: %w", err) + } + f, err := os.OpenFile(filepath.Join(configDir, "credentials.lock"), os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return fmt.Errorf("failed to open credentials lock: %w", err) + } + defer f.Close() + deadline := time.Now().Add(credentialsLockTimeout) + for { + locked, err := tryLockFile(f) + if err != nil { + return fmt.Errorf("failed to lock credentials: %w", err) + } + if locked { + break + } + if time.Now().After(deadline) { + return fmt.Errorf("timed out waiting for another kernel process to update credentials") + } + time.Sleep(50 * time.Millisecond) + } + defer func() { _ = unlockFile(f) }() + return fn() +} + +// SaveTokens stores authentication tokens in the OS keychain, or in the +// credentials file when the keychain refuses them (for example when they are +// too large). Whichever store is written becomes the one LoadTokens reads. func SaveTokens(tokens *TokenStorage) error { - data, err := json.Marshal(tokens) + return withCredentialsLock(func() error { return saveTokens(tokens) }) +} + +func saveTokens(tokens *TokenStorage) error { + stamped := *tokens + stamped.SavedAt = time.Now().UTC() + data, err := json.Marshal(stamped) if err != nil { return fmt.Errorf("failed to marshal tokens: %w", err) } - // Try to store in OS keychain - err = keyring.Set(KeyringService, KeyringUser, string(data)) - if err != nil { - // Fallback to file storage with restrictive permissions - return saveTokensToFile(data) + if err := setKeyring(KeyringService, KeyringUser, string(data)); err == nil { + _ = deleteTokensFile() + return nil } + // Fallback to file storage with restrictive permissions + if err := saveTokensToFile(data); err != nil { + return err + } + // The keychain may still hold older credentials. LoadTokens prefers the + // newer copy even if this delete fails. + _ = keyring.Delete(KeyringService, KeyringUser) return nil } -// LoadTokens retrieves authentication tokens from secure storage +// LoadTokens retrieves authentication tokens from the keychain or the +// credentials file. When both hold credentials, the newer copy wins. func LoadTokens() (*TokenStorage, error) { - // Try to load from OS keychain first + var tokens *TokenStorage + err := withCredentialsLock(func() error { + var err error + tokens, err = loadTokens() + return err + }) + return tokens, err +} + +func loadTokens() (*TokenStorage, error) { + fromKeyring, keyringErr := loadTokensFromKeyring() + fromFile, fileErr := loadTokensFromFile() + switch { + case keyringErr == nil && fileErr == nil && preferFile(fromFile, fromKeyring): + return fromFile, nil + case keyringErr == nil: + return fromKeyring, nil + case fileErr == nil: + return fromFile, nil + default: + return nil, fileErr + } +} + +func loadTokensFromKeyring() (*TokenStorage, error) { data, err := keyring.Get(KeyringService, KeyringUser) if err != nil { - // Fallback to file storage - return loadTokensFromFile() + return nil, err } - var tokens TokenStorage if err := json.Unmarshal([]byte(data), &tokens); err != nil { return nil, fmt.Errorf("failed to unmarshal tokens from keychain: %w", err) } - + tokens.Source = SourceKeychain return &tokens, nil } +// preferFile reports whether the credentials file is newer than the keychain +// entry. Only copies stamped by SaveTokens can be compared; when neither is +// stamped the keychain wins, as it did before SavedAt existed. +func preferFile(file, keychain *TokenStorage) bool { + if file.SavedAt.IsZero() || keychain.SavedAt.IsZero() { + return !file.SavedAt.IsZero() + } + return file.SavedAt.After(keychain.SavedAt) +} + // DeleteTokens removes stored authentication tokens func DeleteTokens() error { - // Try to delete from keychain - err := keyring.Delete(KeyringService, KeyringUser) + return withCredentialsLock(func() error { + // Try to delete from keychain + err := keyring.Delete(KeyringService, KeyringUser) - // Also try to delete file storage (ignore errors) - _ = deleteTokensFile() + // Also try to delete file storage (ignore errors) + _ = deleteTokensFile() - // Return keychain error if it exists and it's not "not found" - if err != nil && err != keyring.ErrNotFound { - return fmt.Errorf("failed to delete tokens from keychain: %w", err) - } + // Return keychain error if it exists and it's not "not found" + if err != nil && err != keyring.ErrNotFound { + return fmt.Errorf("failed to delete tokens from keychain: %w", err) + } - return nil + return nil + }) } // getConfigDir returns the CLI configuration directory @@ -135,6 +243,7 @@ func loadTokensFromFile() (*TokenStorage, error) { if err := json.Unmarshal(data, &tokens); err != nil { return nil, fmt.Errorf("failed to unmarshal tokens from file: %w", err) } + tokens.Source = SourceFile return &tokens, nil } diff --git a/pkg/auth/storage_test.go b/pkg/auth/storage_test.go new file mode 100644 index 00000000..eef52077 --- /dev/null +++ b/pkg/auth/storage_test.go @@ -0,0 +1,230 @@ +package auth + +import ( + "bufio" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/zalando/go-keyring" +) + +func storageFixture(t *testing.T) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + keyring.MockInit() + t.Cleanup(func() { setKeyring = keyring.Set }) +} + +func credentialsFile(t *testing.T) string { + t.Helper() + dir, err := getConfigDir() + if err != nil { + t.Fatal(err) + } + return filepath.Join(dir, "credentials") +} + +func TestSaveTokensFallbackReplacesStaleKeyring(t *testing.T) { + storageFixture(t) + if err := SaveTokens(&TokenStorage{AccessToken: "old"}); err != nil { + t.Fatalf("SaveTokens(old) error = %v", err) + } + + // The keychain refuses the next save, as Windows does above 2,560 bytes. + setKeyring = func(string, string, string) error { return keyring.ErrSetDataTooBig } + if err := SaveTokens(&TokenStorage{AccessToken: "new", Projects: []string{"proj_a"}}); err != nil { + t.Fatalf("SaveTokens(new) error = %v", err) + } + if _, err := keyring.Get(KeyringService, KeyringUser); err != keyring.ErrNotFound { + t.Fatalf("stale keychain entry remains: err = %v", err) + } + loaded, err := LoadTokens() + if err != nil { + t.Fatalf("LoadTokens() error = %v", err) + } + if loaded.AccessToken != "new" { + t.Fatalf("LoadTokens() = %q, want the credentials saved to disk", loaded.AccessToken) + } + + // Once the keychain accepts credentials again, the file is removed. + setKeyring = keyring.Set + if err := SaveTokens(&TokenStorage{AccessToken: "newest"}); err != nil { + t.Fatalf("SaveTokens(newest) error = %v", err) + } + if _, err := os.Stat(credentialsFile(t)); !os.IsNotExist(err) { + t.Fatalf("credentials file remains after a keychain save: err = %v", err) + } + if loaded, err = LoadTokens(); err != nil || loaded.AccessToken != "newest" { + t.Fatalf("LoadTokens() = %+v, %v", loaded, err) + } +} + +func TestLoadTokensPrefersNewerCopy(t *testing.T) { + now := time.Now().UTC() + write := func(t *testing.T, keyringTokens, fileTokens TokenStorage) { + t.Helper() + data, _ := json.Marshal(keyringTokens) + if err := keyring.Set(KeyringService, KeyringUser, string(data)); err != nil { + t.Fatal(err) + } + data, _ = json.Marshal(fileTokens) + if err := saveTokensToFile(data); err != nil { + t.Fatal(err) + } + } + for _, tc := range []struct { + name string + keyringTokens, file TokenStorage + want string + }{ + {"file saved later", TokenStorage{AccessToken: "keyring", SavedAt: now.Add(-time.Hour)}, TokenStorage{AccessToken: "file", SavedAt: now}, "file"}, + {"keychain saved later", TokenStorage{AccessToken: "keyring", SavedAt: now}, TokenStorage{AccessToken: "file", SavedAt: now.Add(-time.Hour)}, "keyring"}, + // An older CLI left a long-lived token for one organization on disk and + // saved a shorter-lived one for another in the keychain, which it used. + {"neither stamped keeps the keychain", TokenStorage{AccessToken: "keyring", OrgID: "org_b", ExpiresAt: now}, TokenStorage{AccessToken: "file", OrgID: "org_a", ExpiresAt: now.Add(24 * time.Hour)}, "keyring"}, + {"only the file stamped", TokenStorage{AccessToken: "keyring", ExpiresAt: now.Add(time.Hour)}, TokenStorage{AccessToken: "file", SavedAt: now}, "file"}, + {"only the keychain stamped", TokenStorage{AccessToken: "keyring", SavedAt: now}, TokenStorage{AccessToken: "file", ExpiresAt: now.Add(time.Hour)}, "keyring"}, + } { + t.Run(tc.name, func(t *testing.T) { + storageFixture(t) + write(t, tc.keyringTokens, tc.file) + loaded, err := LoadTokens() + if err != nil { + t.Fatalf("LoadTokens() error = %v", err) + } + if loaded.AccessToken != tc.want { + t.Fatalf("LoadTokens() = %q, want %q", loaded.AccessToken, tc.want) + } + }) + } +} + +func TestConcurrentSavesKeepOneCopy(t *testing.T) { + storageFixture(t) + // The keychain refuses large credentials and accepts small ones, so the + // two saves below take different paths and each cleans up the other store. + setKeyring = func(service, user, data string) error { + if strings.Contains(data, "large") { + return keyring.ErrSetDataTooBig + } + return keyring.Set(service, user, data) + } + for round := range 25 { + var wg sync.WaitGroup + for _, token := range []string{"large", "small"} { + wg.Add(1) + go func() { + defer wg.Done() + if err := SaveTokens(&TokenStorage{AccessToken: token}); err != nil { + t.Errorf("SaveTokens(%s) error = %v", token, err) + } + }() + } + wg.Wait() + loaded, err := LoadTokens() + if err != nil { + t.Fatalf("round %d: LoadTokens() error = %v", round, err) + } + if loaded.AccessToken != "large" && loaded.AccessToken != "small" { + t.Fatalf("round %d: LoadTokens() = %q", round, loaded.AccessToken) + } + } +} + +func TestConcurrentCommandsRefreshOnce(t *testing.T) { + storageFixture(t) + t.Setenv("KERNEL_API_KEY", "") + var mu sync.Mutex + valid, generation, requests := "refresh-0", 0, 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + time.Sleep(20 * time.Millisecond) + mu.Lock() + defer mu.Unlock() + requests++ + w.Header().Set("Content-Type", "application/json") + if r.Form.Get("refresh_token") != valid { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"}) + return + } + generation++ + valid = fmt.Sprintf("refresh-%d", generation) + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": fmt.Sprintf("access-%d", generation), "refresh_token": valid, + "token_type": "Bearer", "expires_in": 600, "access_scope": "organization", + }) + })) + defer server.Close() + if err := SaveTokens(&TokenStorage{ + AccessToken: "access-0", RefreshToken: "refresh-0", ExpiresAt: time.Now().Add(-time.Minute), + AuthBaseURL: server.URL, OAuthClientID: "client-id", + }); err != nil { + t.Fatal(err) + } + + var wg sync.WaitGroup + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + if _, err := GetAuthenticatedClient(); err != nil { + t.Errorf("GetAuthenticatedClient() error = %v", err) + } + }() + } + wg.Wait() + if requests != 1 { + t.Fatalf("token requests = %d, want 1: commands that start together refresh once", requests) + } + loaded, err := LoadTokens() + if err != nil || loaded.RefreshToken != "refresh-1" { + t.Fatalf("LoadTokens() = %+v, %v", loaded, err) + } +} + +// TestCredentialsLockExcludesOtherProcesses holds the lock in a child process +// and checks that this process waits for it. +func TestCredentialsLockExcludesOtherProcesses(t *testing.T) { + if os.Getenv("KERNEL_TEST_HOLD_CREDENTIALS_LOCK") == "1" { + _ = withCredentialsLock(func() error { + fmt.Println("locked") + time.Sleep(500 * time.Millisecond) + return nil + }) + return + } + storageFixture(t) + child := exec.Command(os.Args[0], "-test.run=^TestCredentialsLockExcludesOtherProcesses$") + child.Env = append(os.Environ(), "KERNEL_TEST_HOLD_CREDENTIALS_LOCK=1") + out, err := child.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := child.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = child.Wait() }) + line, err := bufio.NewReader(out).ReadString('\n') + if err != nil || strings.TrimSpace(line) != "locked" { + t.Fatalf("child did not take the lock: %q, %v", line, err) + } + start := time.Now() + if err := withCredentialsLock(func() error { return nil }); err != nil { + t.Fatal(err) + } + if waited := time.Since(start); waited < 300*time.Millisecond { + t.Fatalf("took the lock after %s while another process held it", waited) + } +}