auth

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: May 29, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultOpenBrowser

func DefaultOpenBrowser(rawURL string) error

DefaultOpenBrowser opens url in the system default browser.

func FreePort

func FreePort() (string, error)

FreePort returns an available local TCP port as a string. Exported for use in integration tests.

func RedirectPortFrom

func RedirectPortFrom(authURL string) string

RedirectPortFrom extracts the port from the redirect_uri param of a full authorization URL. Exported for use in integration tests.

func StateFrom

func StateFrom(authURL string) string

StateFrom extracts the state parameter from a full authorization URL. Exported for use in integration tests.

func TriggerCallback

func TriggerCallback(port, code, state string) error

TriggerCallback makes a GET request to the local callback server with the given port, code, and state. Used in tests to simulate the browser redirect.

Types

type APIKey

type APIKey struct{}

APIKey implements OpenAPI-style API key authentication in a header, query parameter, or cookie.

func (*APIKey) Authenticate

func (h *APIKey) Authenticate(_ context.Context, req *http.Request, ac AuthContext) error

func (*APIKey) Parameters

func (h *APIKey) Parameters() []Param

type AuthContext

type AuthContext struct {
	APIName     string
	ProfileName string
	BaseURL     string
	CacheKey    string
	Params      map[string]string // user-supplied only
	TokenStore  TokenStore
	Prompter    Prompter
	Stderr      io.Writer
	HTTPClient  *http.Client
	Logger      Logger
	Force       bool // bypass cached access tokens for a single retry
}

AuthContext carries the request-scoped auth environment into a handler.

type AuthorizationCode

type AuthorizationCode struct {
	// Cache stores fetched tokens.
	Cache TokenStore
	// HTTPClient is used for token requests. Defaults to http.DefaultClient when nil.
	HTTPClient *http.Client
	// OpenBrowser is called with the authorization URL. When nil the default
	// system browser opener is used.
	OpenBrowser func(url string) error
	// Stderr receives status messages during the browser flow.
	Stderr io.Writer
	// Prompt is used to read a pasted authorization code for headless fallback.
	Prompt func(prompt string) (string, error)
	// CanPrompt reports whether manual code entry is safe for this invocation.
	CanPrompt bool
	// NoBrowser skips automatic browser launch and immediately falls back to
	// printing the auth URL for manual use.
	NoBrowser bool
	// Verbose prints the full authorization URL before browser launch.
	Verbose bool
	// CallbackSuccessColor customizes the browser callback success background.
	// Invalid values fall back to the built-in v1 callback color.
	CallbackSuccessColor string
	// CallbackFailureColor customizes the browser callback failure background.
	// Invalid values fall back to the built-in v1 callback color.
	CallbackFailureColor string
	// CallbackSuccessHTML customizes the browser callback success page. When
	// empty, Restish renders the built-in animated page.
	CallbackSuccessHTML string
	// CallbackErrorHTML customizes the browser callback failure page. When
	// empty, Restish renders the built-in animated page. $ERROR, $TITLE, and
	// $DETAILS placeholders are replaced with escaped callback values.
	CallbackErrorHTML string
}

AuthorizationCode implements the OAuth2 authorization code flow with PKCE (RFC 7636). On first use it opens a browser and waits for the redirect callback. Subsequent requests use the cached token; when expired the refresh token is used (if available), otherwise a new browser flow is started.

func (*AuthorizationCode) Authenticate

func (h *AuthorizationCode) Authenticate(ctx context.Context, req *http.Request, ac AuthContext) error

func (*AuthorizationCode) OnRequest

func (h *AuthorizationCode) OnRequest(req *http.Request, params map[string]string) error

func (*AuthorizationCode) Parameters

func (h *AuthorizationCode) Parameters() []Param

func (*AuthorizationCode) SupportsForce

func (h *AuthorizationCode) SupportsForce()

type Bearer

type Bearer struct{}

Bearer implements static HTTP Bearer token authentication.

func (*Bearer) Authenticate

func (h *Bearer) Authenticate(_ context.Context, req *http.Request, ac AuthContext) error

func (*Bearer) Parameters

func (h *Bearer) Parameters() []Param

type CachedToken

type CachedToken struct {
	AccessToken  string    `cbor:"access_token" json:"access_token"`
	TokenType    string    `cbor:"token_type,omitempty" json:"token_type,omitempty"`
	RefreshToken string    `cbor:"refresh_token,omitempty" json:"refresh_token,omitempty"`
	Expiry       time.Time `cbor:"expiry,omitempty" json:"expiry,omitempty"`
}

CachedToken holds a cached OAuth2 access token and optional refresh token.

func FetchToken

func FetchToken(ctx context.Context, client *http.Client, tokenURL string, form url.Values, params map[string]string) (CachedToken, error)

FetchToken posts a token request to tokenURL and returns a CachedToken. Pass nil for client to use http.DefaultClient.

func (*CachedToken) IsExpired

func (t *CachedToken) IsExpired() bool

IsExpired reports whether the token is expired (or will expire within 30s).

type ClientCredentials

type ClientCredentials struct {
	// Cache stores fetched tokens. If nil, tokens are not cached.
	Cache TokenStore
	// HTTPClient is used for token requests. Defaults to http.DefaultClient when nil.
	HTTPClient *http.Client
}

ClientCredentials implements the OAuth2 client credentials flow (RFC 6749 §4.4). The token is cached in Cache under params["_cache_key"]. When the cached token is expired the handler fetches a new one.

func (*ClientCredentials) Authenticate

func (h *ClientCredentials) Authenticate(ctx context.Context, req *http.Request, ac AuthContext) error

func (*ClientCredentials) OnRequest

func (h *ClientCredentials) OnRequest(req *http.Request, params map[string]string) error

func (*ClientCredentials) Parameters

func (h *ClientCredentials) Parameters() []Param

func (*ClientCredentials) SupportsForce

func (h *ClientCredentials) SupportsForce()

type DeviceCode

type DeviceCode struct {
	Cache      TokenStore
	HTTPClient *http.Client
	Stderr     io.Writer
}

DeviceCode implements OAuth 2.0 Device Authorization Grant (RFC 8628).

func (*DeviceCode) Authenticate

func (h *DeviceCode) Authenticate(ctx context.Context, req *http.Request, ac AuthContext) error

func (*DeviceCode) OnRequest

func (h *DeviceCode) OnRequest(req *http.Request, params map[string]string) error

func (*DeviceCode) Parameters

func (h *DeviceCode) Parameters() []Param

func (*DeviceCode) SupportsForce

func (h *DeviceCode) SupportsForce()

type ExternalTool

type ExternalTool struct {
	Stderr  io.Writer
	Timeout time.Duration
}

ExternalTool delegates authentication to an external program. The program receives the outbound request as JSON on stdin and returns header updates (and optionally a new URI) as JSON on stdout.

Config params:

commandline  (required) shell command to run; executed via cmd /c on
             Windows or /bin/sh -c on other platforms
omitbody     (optional) "true" skips sending the request body to the tool;
             use for binary bodies because body is v1-compatible JSON text
output       (optional) "bearer-token" treats stdout as a bearer token

Wire format (stdin → tool):

{"method":"GET","uri":"https://...","headers":{...},"body":"..."}

Wire format (tool → stdout):

{"headers":{"X-Sig":"..."}}          — merge headers only
{"uri":"https://...","headers":{...}} — also rewrite the URI

An empty or absent stdout response is a no-op (tool declined to mutate). Compatible with the v1 external-tool auth wire format.

func (*ExternalTool) Authenticate

func (a *ExternalTool) Authenticate(ctx context.Context, req *http.Request, ac AuthContext) error

func (*ExternalTool) OnRequest

func (a *ExternalTool) OnRequest(req *http.Request, params map[string]string) error

func (*ExternalTool) Parameters

func (a *ExternalTool) Parameters() []Param

type ForceCapable

type ForceCapable interface {
	SupportsForce()
}

ForceCapable marks handlers that can meaningfully bypass cached credentials after a 401 and retry once with fresh auth state.

type HTTPBasic

type HTTPBasic struct {
	// Prompter is called when "password" is absent from params.
	// It receives the prompt string and must return the secret value.
	// If nil, a missing password causes an error.
	Prompter func(prompt string) (string, error)
}

HTTPBasic implements HTTP Basic authentication (RFC 7617).

func (*HTTPBasic) Authenticate

func (h *HTTPBasic) Authenticate(_ context.Context, req *http.Request, ac AuthContext) error

func (*HTTPBasic) OnRequest

func (h *HTTPBasic) OnRequest(req *http.Request, params map[string]string) error

func (*HTTPBasic) Parameters

func (h *HTTPBasic) Parameters() []Param

type Handler

type Handler interface {
	// Parameters returns the list of configuration parameters this handler needs.
	Parameters() []Param
	// Authenticate mutates req to add authentication credentials.
	Authenticate(ctx context.Context, req *http.Request, ac AuthContext) error
}

Handler is implemented by each auth mechanism.

type Logger

type Logger interface {
	Printf(format string, v ...any)
}

Logger is the minimal logging surface auth handlers use for diagnostics.

type OIDCConfig

type OIDCConfig struct {
	AuthorizationEndpoint       string `json:"authorization_endpoint"`
	DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
	TokenEndpoint               string `json:"token_endpoint"`
}

OIDCConfig holds the fields we use from an OIDC discovery document.

func DiscoverOIDC

func DiscoverOIDC(ctx context.Context, client *http.Client, issuerURL string) (*OIDCConfig, error)

DiscoverOIDC fetches issuerURL+"/.well-known/openid-configuration". Pass nil for client to use http.DefaultClient.

type Param

type Param struct {
	Name        string
	Description string
	Required    bool
	Secret      bool // true -> don't echo when prompting
}

Param describes a configuration parameter required by an auth handler.

type Prompter

type Prompter interface {
	Prompt(prompt string) (string, error)
	PromptSecret(prompt string) (string, error)
}

Prompter reads interactive values from the user.

type TokenCache

type TokenCache struct {
	// contains filtered or unexported fields
}

TokenCache persists OAuth2 tokens as a flat CBOR map at a given file path. All operations are safe for concurrent use.

func NewTokenCache

func NewTokenCache(path string) *TokenCache

NewTokenCache returns a TokenCache that stores tokens at path.

func (*TokenCache) Delete

func (c *TokenCache) Delete(key string) error

Delete removes the entry for key. Returns nil when key is absent.

func (*TokenCache) DeletePrefix

func (c *TokenCache) DeletePrefix(prefix string) error

DeletePrefix removes every cached token whose key begins with prefix.

func (*TokenCache) Get

func (c *TokenCache) Get(key string) (*CachedToken, error)

Get returns the cached token for key, or (nil, nil) if not found.

func (*TokenCache) Refresh

func (c *TokenCache) Refresh(key string, force bool, refresh func(CachedToken) (CachedToken, error)) (*CachedToken, bool, error)

Refresh serializes a cached OAuth refresh for key across processes. It re-reads the cache under the sibling file lock, skips refresh when another process already stored a valid token, then stores the refreshed token before releasing the lock.

func (*TokenCache) Set

func (c *TokenCache) Set(key string, token CachedToken) error

Set stores token under key, creating or updating the cache file.

type TokenStore

type TokenStore interface {
	Get(key string) (*CachedToken, error)
	Set(key string, token CachedToken) error
	Delete(key string) error
	DeletePrefix(prefix string) error
}

TokenStore persists OAuth-style bearer tokens keyed by API/profile.

Jump to

Keyboard shortcuts

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