Documentation
¶
Overview ¶
Package clientauth lets any Go CLI authenticate against a theauth-go server with the RFC 8628 device grant, keep the resulting API token in a local store, and call the server with it.
Index ¶
Constants ¶
const ( // DefaultAuthPath is where theauth-go mounts its routes. DefaultAuthPath = "/auth" // DefaultInterval is the RFC 8628 section 3.2 default polling interval. DefaultInterval = 5 * time.Second // SlowDownStep is the increase RFC 8628 section 3.5 requires on slow_down. SlowDownStep = 5 * time.Second )
Variables ¶
var ( ErrAccessDenied = errors.New("clientauth: login was denied") ErrDeviceExpired = errors.New("clientauth: device code expired before it was approved") )
Errors returned by DeviceLogin, named after their RFC 8628 error codes.
var ErrKeychainNotFound = errors.New("clientauth: keychain item not found")
ErrKeychainNotFound is what a KeychainBackend returns for a missing item.
var ErrNotLoggedIn = errors.New("clientauth: not logged in")
ErrNotLoggedIn means the store holds no credential for the server.
var ErrReloginRequired = errors.New("clientauth: session expired, log in again")
ErrReloginRequired means the stored token is expired or no longer accepted; run the login flow again.
Functions ¶
func NormalizeServerURL ¶
NormalizeServerURL canonicalizes a server URL so store keys compare equal.
Types ¶
type Client ¶
type Client struct {
ServerURL string
// AuthPath is the route prefix on the server. Default DefaultAuthPath.
AuthPath string
Store TokenStore
// HTTPClient defaults to http.DefaultClient.
HTTPClient *http.Client
// Now defaults to time.Now.
Now func() time.Time
// SelfPath is the bearer-authenticated route for Whoami and Logout,
// relative to the auth path. Default "/tokens/current".
SelfPath string
}
Client sends authenticated requests to one theauth-go server.
func NewClient ¶
func NewClient(serverURL string, store TokenStore) (*Client, error)
NewClient returns a Client for serverURL backed by store.
func (*Client) Do ¶
Do attaches the stored bearer token and sends req. It returns ErrNotLoggedIn without a credential and ErrReloginRequired when the token is expired locally or the server answers 401. Requests to any other origin are refused so the token cannot leak.
func (*Client) Logout ¶
Logout revokes the token on the server, then deletes it locally. The local copy is removed even when revocation fails, and that failure is returned.
type Credential ¶
type Credential struct {
ServerURL string `json:"server_url"`
AccessToken string `json:"access_token"`
TokenType string `json:"token_type,omitempty"`
Scope string `json:"scope,omitempty"`
IssuedAt time.Time `json:"issued_at"`
// ExpiresAt is zero when the server reported no lifetime.
ExpiresAt time.Time `json:"expires_at,omitempty"`
}
Credential is one stored login.
func DeviceLogin ¶
func DeviceLogin(ctx context.Context, opts DeviceOptions) (Credential, error)
DeviceLogin runs the client side of the RFC 8628 device grant and returns the issued credential.
type DeviceOptions ¶
type DeviceOptions struct {
// ServerURL is the theauth-go base URL, for example https://app.example.com.
ServerURL string
// AuthPath is the route prefix on the server. Default DefaultAuthPath.
AuthPath string
// ClientName is shown to the approver. Default: the host name.
ClientName string
// Scopes are the abilities to request. Empty uses the server default.
Scopes []string
// HTTPClient defaults to http.DefaultClient.
HTTPClient *http.Client
// Prompt shows the verification details. Default: print to Out.
Prompt func(DevicePrompt)
// Out receives the default prompt. Default os.Stderr.
Out io.Writer
// OpenBrowser, when set, is called with the complete verification URI.
// Its failure is ignored because the printed prompt is the fallback.
OpenBrowser func(url string) error
// Store, when set, receives the credential on success.
Store TokenStore
// DefaultInterval is used when the server omits one. Default DefaultInterval.
DefaultInterval time.Duration
// Sleep waits between polls and must honor ctx. Default: a timer.
Sleep func(ctx context.Context, d time.Duration) error
// Now defaults to time.Now.
Now func() time.Time
}
DeviceOptions configures DeviceLogin. Only ServerURL is required.
type DevicePrompt ¶
type DevicePrompt struct {
VerificationURI string
VerificationURIComplete string
UserCode string
ExpiresIn time.Duration
}
DevicePrompt is what the user must do to approve a login.
type FileStore ¶
type FileStore struct {
// LockTimeout bounds the wait for the cross-process lock file. Default 5s.
LockTimeout time.Duration
// LockStale is the age after which a lock file is treated as abandoned. Default 30s.
LockStale time.Duration
// contains filtered or unexported fields
}
FileStore keeps credentials for many servers in one 0600 JSON file.
func NewFileStore ¶
NewFileStore stores credentials in os.UserConfigDir()/<app>/credentials.json.
func NewFileStoreAt ¶
NewFileStoreAt stores credentials at an explicit path.
type Identity ¶
type Identity struct {
ID string `json:"id"`
OwnerID string `json:"ownerId"`
OwnerKind string `json:"ownerKind"`
Name string `json:"name"`
Kind string `json:"kind"`
AgentName string `json:"agentName"`
Abilities []string `json:"abilities"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt *time.Time `json:"expiresAt"`
LastUsedAt *time.Time `json:"lastUsedAt"`
}
Identity describes the stored token as the server sees it.
type KeychainBackend ¶
type KeychainBackend interface {
Get(service, user string) (string, error)
Set(service, user, secret string) error
Delete(service, user string) error
}
KeychainBackend is the minimal OS keychain surface. The functions of github.com/zalando/go-keyring (Get, Set, Delete) fit it directly, which keeps cgo and platform dependencies out of this package.
type KeychainStore ¶
type KeychainStore struct {
// contains filtered or unexported fields
}
KeychainStore keeps each credential as one keychain item.
func NewKeychainStore ¶
func NewKeychainStore(service string, backend KeychainBackend) *KeychainStore
NewKeychainStore wraps backend, using service as the keychain service name.
func (*KeychainStore) Delete ¶
func (s *KeychainStore) Delete(_ context.Context, serverURL string) error
Delete implements TokenStore and is a no-op for an unknown server.
func (*KeychainStore) Load ¶
func (s *KeychainStore) Load(_ context.Context, serverURL string) (Credential, error)
Load implements TokenStore.
func (*KeychainStore) Save ¶
func (s *KeychainStore) Save(_ context.Context, cred Credential) error
Save implements TokenStore.
type ServerError ¶
ServerError is a non-success response from the server.
func (*ServerError) Error ¶
func (e *ServerError) Error() string
type TokenStore ¶
type TokenStore interface {
// Load returns ErrNotLoggedIn when no credential exists for serverURL.
Load(ctx context.Context, serverURL string) (Credential, error)
Save(ctx context.Context, cred Credential) error
Delete(ctx context.Context, serverURL string) error
}
TokenStore persists credentials keyed by server URL. Implementations must be safe for concurrent use.