Skip to content
61 changes: 17 additions & 44 deletions pkg/auth/federation_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (

"github.com/kernel/cli/pkg/util"
"github.com/kernel/kernel-go-sdk/lib/credentials"
"github.com/zalando/go-keyring"
)

// EnvFederationTokenCache turns the on-disk cache of workload identity access
Expand Down Expand Up @@ -138,37 +137,31 @@ func digest(parts ...string) string {
return hex.EncodeToString(sum[:])
}

func (c *federationCache) filePath() (string, error) {
dir := c.dir
if dir == "" {
var err error
if dir, err = getConfigDir(); err != nil {
return "", err
// store is where the entry is kept.
func (c *federationCache) store() secretStore {
return secretStore{account: c.name, fileOnly: c.dir != "", writeFile: writeFileAtomically, path: func() (string, error) {
dir := c.dir
if dir == "" {
var err error
if dir, err = getConfigDir(); err != nil {
return "", err
}
}
}
return filepath.Join(dir, c.name+".json"), nil
return filepath.Join(dir, c.name+".json"), nil
}}
}

// copies returns the entry from each store that holds one.
func (c *federationCache) copies() (fromKeyring, fromFile *federationCacheEntry) {
parse := func(data []byte) *federationCacheEntry {
var entry federationCacheEntry
if json.Unmarshal(data, &entry) != nil {
if data == nil || json.Unmarshal(data, &entry) != nil {
return nil
}
return &entry
}
if c.dir == "" {
if data, err := keyring.Get(KeyringService, c.name); err == nil {
fromKeyring = parse([]byte(data))
}
}
if path, err := c.filePath(); err == nil {
if data, err := os.ReadFile(path); err == nil {
fromFile = parse(data)
}
}
return fromKeyring, fromFile
keychainData, fileData, _ := c.store().read()
return parse(keychainData), parse(fileData)
}

// load returns the cached token when this workload may still use it.
Expand Down Expand Up @@ -199,25 +192,7 @@ func (c *federationCache) save(token *credentials.Token) error {
if err != nil {
return err
}
path, pathErr := c.filePath()
if c.dir == "" {
if err := setKeyring(KeyringService, c.name, string(data)); err == nil {
if pathErr == nil {
_ = os.Remove(path)
}
return nil
}
}
if pathErr != nil {
return pathErr
}
if err := writeFileAtomically(path, data); err != nil {
return err
}
if c.dir == "" {
_ = keyring.Delete(KeyringService, c.name)
}
return nil
return c.store().save(data)
}

// writeFileAtomically replaces path with data, readable by the owner only. A
Expand Down Expand Up @@ -251,11 +226,9 @@ func writeFileAtomically(path string, data []byte) error {
func (c *federationCache) forget(accessToken string) {
fromKeyring, fromFile := c.copies()
if fromKeyring != nil && fromKeyring.AccessToken == accessToken {
_ = keyring.Delete(KeyringService, c.name)
_ = c.store().deleteFromKeychain()
}
if fromFile != nil && fromFile.AccessToken == accessToken {
if path, err := c.filePath(); err == nil {
_ = os.Remove(path)
}
_ = c.store().deleteFile()
}
}
24 changes: 23 additions & 1 deletion pkg/auth/federation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,28 @@ func TestCachedTokenIsNotSharedAcrossRulesServersOrWorkloads(t *testing.T) {
}
}

// A GitHub Actions job keeps its token in its temporary directory only. It
// neither uses nor removes a keychain entry of the same name.
func TestGitHubActionsJobLeavesTheKeychainAlone(t *testing.T) {
s := federationFixture(t)
cache, _ := federationCacheFromEnv("wifr_test")
inKeychain, err := json.Marshal(federationCacheEntry{AccessToken: "keychain-token", ExpiresAt: time.Now().Add(time.Hour), Binding: cache.binding})
if err != nil {
t.Fatal(err)
}
if err := keyring.Set(KeyringService, cache.name, string(inKeychain)); err != nil {
t.Fatal(err)
}

mustCallAPI(t, newProcess(t))
if got := s.seenByAPI(); len(got) != 1 || got[0] != "Bearer access-token-1" {
t.Fatalf("API saw %q, want a token this job exchanged", got)
}
if data, err := keyring.Get(KeyringService, cache.name); err != nil || data != string(inKeychain) {
t.Fatalf("keychain entry = %q, %v, want it left as it was", data, err)
}
}

func TestTokenFromAFileSourceIsCachedLikeALogin(t *testing.T) {
s := federationFixture(t)
useTokenFile(t, "identity-token-from-file")
Expand Down Expand Up @@ -772,7 +794,7 @@ func TestParallelProcessesNeverReadAPartialEntry(t *testing.T) {
setKeyring = func(string, string, string) error { return keyring.ErrSetDataTooBig }
}
cache, _ := federationCacheFromEnv("wifr_test")
path, err := cache.filePath()
path, err := cache.store().path()
if err != nil {
t.Fatal(err)
}
Expand Down
80 changes: 80 additions & 0 deletions pkg/auth/secret_store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package auth

import (
"os"

"github.com/zalando/go-keyring"
)

// setKeyring is keyring.Set, replaceable in tests that need it to fail.
var setKeyring = keyring.Set

// secretStore keeps one small document in the OS keychain, or in a file only
// its owner can read when the keychain refuses it (for example when it is too
// large) or is not used. A save leaves the document in one of the two; which
// copy is current when both exist is for the caller to decide.
type secretStore struct {
// account is the keychain account the document is stored under.
account string
// path returns the file the document falls back to.
path func() (string, error)
// fileOnly keeps the document out of the keychain.
fileOnly bool
// writeFile writes the document to the file at path.
writeFile func(path string, data []byte) error
}

// read returns the document from each place that holds one. fileErr is why
// the file could not be read, including when it does not exist.
func (s secretStore) read() (fromKeychain, fromFile []byte, fileErr error) {
if !s.fileOnly {
if data, err := keyring.Get(KeyringService, s.account); err == nil {
fromKeychain = []byte(data)
}
}
path, err := s.path()
if err != nil {
return fromKeychain, nil, err
}
fromFile, fileErr = os.ReadFile(path)
return fromKeychain, fromFile, fileErr
}

// save stores the document in the keychain, or in the file when the keychain
// refuses it, and removes the copy it did not write.
func (s secretStore) save(data []byte) error {
path, pathErr := s.path()
if !s.fileOnly {
if err := setKeyring(KeyringService, s.account, string(data)); err == nil {
if pathErr == nil {
_ = os.Remove(path)
}
return nil
}
}
if pathErr != nil {
return pathErr
}
if err := s.writeFile(path, data); err != nil {
return err
}
// The keychain may still hold an older copy. Callers prefer the newer one
// even if this delete fails.
_ = s.deleteFromKeychain()
return nil
}

func (s secretStore) deleteFromKeychain() error {
if s.fileOnly {
return nil
}
return keyring.Delete(KeyringService, s.account)
}

func (s secretStore) deleteFile() error {
path, err := s.path()
if err != nil {
return err
}
return os.Remove(path)
}
119 changes: 39 additions & 80 deletions pkg/auth/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,24 @@ func (t *TokenStorage) IsExpired() bool {
return time.Now().Add(5 * time.Minute).After(t.ExpiresAt)
}

// setKeyring is keyring.Set, replaceable in tests that need it to fail.
var setKeyring = keyring.Set
// loginStore is where the saved login lives.
var loginStore = secretStore{account: KeyringUser, writeFile: writeCredentialsFile, path: func() (string, error) {
configDir, err := getConfigDir()
if err != nil {
return "", fmt.Errorf("failed to get config directory: %w", err)
}
return filepath.Join(configDir, "credentials"), nil
}}

// writeCredentialsFile writes the saved login to the file at path in place,
// keeping what the file already has: a symbolic link or a mount it is reached
// through, and access control set on it that a new file would not get.
func writeCredentialsFile(path string, data []byte) error {
if err := os.WriteFile(path, data, 0600); err != nil {
return fmt.Errorf("failed to write tokens to file: %w", err)
}
return nil
}

// Token storage sources, as reported in TokenStorage.Source.
const (
Expand Down Expand Up @@ -107,19 +123,7 @@ func saveTokens(tokens *TokenStorage) error {
return fmt.Errorf("failed to marshal tokens: %w", err)
}

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
return loginStore.save(data)
}

// LoadTokens retrieves authentication tokens from the keychain or the
Expand All @@ -135,8 +139,17 @@ func LoadTokens() (*TokenStorage, error) {
}

func loadTokens() (*TokenStorage, error) {
fromKeyring, keyringErr := loadTokensFromKeyring()
fromFile, fileErr := loadTokensFromFile()
keychainData, fileData, fileErr := loginStore.read()
fromKeyring, keyringErr := parseTokens(keychainData, "keychain", SourceKeychain)
var fromFile *TokenStorage
switch {
case os.IsNotExist(fileErr):
fileErr = fmt.Errorf("no stored credentials found")
case fileErr != nil:
fileErr = fmt.Errorf("failed to read tokens from file: %w", fileErr)
default:
fromFile, fileErr = parseTokens(fileData, "file", SourceFile)
}
switch {
case keyringErr == nil && fileErr == nil && preferFile(fromFile, fromKeyring):
return fromFile, nil
Expand All @@ -149,16 +162,16 @@ func loadTokens() (*TokenStorage, error) {
}
}

func loadTokensFromKeyring() (*TokenStorage, error) {
data, err := keyring.Get(KeyringService, KeyringUser)
if err != nil {
return nil, err
// parseTokens decodes a stored login. A store that holds nothing is an error.
func parseTokens(data []byte, store, source string) (*TokenStorage, error) {
if data == nil {
return nil, keyring.ErrNotFound
}
var tokens TokenStorage
if err := json.Unmarshal([]byte(data), &tokens); err != nil {
return nil, fmt.Errorf("failed to unmarshal tokens from keychain: %w", err)
if err := json.Unmarshal(data, &tokens); err != nil {
return nil, fmt.Errorf("failed to unmarshal tokens from %s: %w", store, err)
}
tokens.Source = SourceKeychain
tokens.Source = source
return &tokens, nil
}

Expand All @@ -176,10 +189,10 @@ func preferFile(file, keychain *TokenStorage) bool {
func DeleteTokens() error {
return withCredentialsLock(func() error {
// Try to delete from keychain
err := keyring.Delete(KeyringService, KeyringUser)
err := loginStore.deleteFromKeychain()

// Also try to delete file storage (ignore errors)
_ = deleteTokensFile()
_ = loginStore.deleteFile()

// Return keychain error if it exists and it's not "not found"
if err != nil && err != keyring.ErrNotFound {
Expand All @@ -204,57 +217,3 @@ func getConfigDir() (string, error) {

return configDir, nil
}

// saveTokensToFile saves tokens to a file with restrictive permissions as fallback
func saveTokensToFile(data []byte) error {
configDir, err := getConfigDir()
if err != nil {
return fmt.Errorf("failed to get config directory: %w", err)
}

tokenFile := filepath.Join(configDir, "credentials")

// Write with restrictive permissions (only owner can read/write)
if err := os.WriteFile(tokenFile, data, 0600); err != nil {
return fmt.Errorf("failed to write tokens to file: %w", err)
}

return nil
}

// loadTokensFromFile loads tokens from file as fallback
func loadTokensFromFile() (*TokenStorage, error) {
configDir, err := getConfigDir()
if err != nil {
return nil, fmt.Errorf("failed to get config directory: %w", err)
}

tokenFile := filepath.Join(configDir, "credentials")

data, err := os.ReadFile(tokenFile)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("no stored credentials found")
}
return nil, fmt.Errorf("failed to read tokens from file: %w", err)
}

var tokens TokenStorage
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
}

// deleteTokensFile removes the token file
func deleteTokensFile() error {
configDir, err := getConfigDir()
if err != nil {
return err
}

tokenFile := filepath.Join(configDir, "credentials")
return os.Remove(tokenFile)
}
Loading
Loading