clientauth

package
v2.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 12 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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

View Source
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.

View Source
var ErrKeychainNotFound = errors.New("clientauth: keychain item not found")

ErrKeychainNotFound is what a KeychainBackend returns for a missing item.

View Source
var ErrNotLoggedIn = errors.New("clientauth: not logged in")

ErrNotLoggedIn means the store holds no credential for the server.

View Source
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

func NormalizeServerURL(raw string) (string, error)

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

func (c *Client) Do(req *http.Request) (*http.Response, error)

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

func (c *Client) Logout(ctx context.Context) error

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.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error)

NewRequest builds a request for a path on the server.

func (*Client) Whoami

func (c *Client) Whoami(ctx context.Context) (Identity, error)

Whoami asks the server which token and owner the stored credential maps to.

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.

func (Credential) Expired

func (c Credential) Expired(now time.Time) bool

Expired reports whether the credential is past its expiry at now.

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

func NewFileStore(app string) (*FileStore, error)

NewFileStore stores credentials in os.UserConfigDir()/<app>/credentials.json.

func NewFileStoreAt

func NewFileStoreAt(path string) *FileStore

NewFileStoreAt stores credentials at an explicit path.

func (*FileStore) Delete

func (s *FileStore) Delete(ctx context.Context, serverURL string) error

Delete implements TokenStore and is a no-op for an unknown server.

func (*FileStore) Load

func (s *FileStore) Load(_ context.Context, serverURL string) (Credential, error)

Load implements TokenStore.

func (*FileStore) Path

func (s *FileStore) Path() string

Path returns the credentials file path.

func (*FileStore) Save

func (s *FileStore) Save(ctx context.Context, cred Credential) error

Save implements TokenStore.

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

type ServerError struct {
	Status      int
	Code        string
	Description string
}

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL