// Package secret keeps NetBox API tokens in the operating system's keyring // (Secret Service on Linux, Keychain on macOS) instead of the config file. package secret import ( "errors" "fmt" "github.com/zalando/go-keyring" ) // Service is the keyring service name of all netssh entries. const Service = "netssh" // ErrNotFound means the keyring has no token for the account. var ErrNotFound = errors.New("no token in the system keyring") // Get returns the token stored for account. func Get(account string) (string, error) { token, err := keyring.Get(Service, account) if errors.Is(err, keyring.ErrNotFound) { return "", fmt.Errorf("%w for %q (store one with: netssh token set %s)", ErrNotFound, account, account) } if err != nil { return "", fmt.Errorf("system keyring: %w", err) } return token, nil } // Set stores token for account, replacing an existing one. func Set(account, token string) error { if err := keyring.Set(Service, account, token); err != nil { return fmt.Errorf("system keyring: %w", err) } return nil } // Delete removes the token of account; a missing entry is not an error. func Delete(account string) error { err := keyring.Delete(Service, account) if err != nil && !errors.Is(err, keyring.ErrNotFound) { return fmt.Errorf("system keyring: %w", err) } return nil } // MockInit replaces the system keyring with an in-memory one, for tests. func MockInit() { keyring.MockInit() }