auth

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 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 auth resolves provider credentials and manages authentication transports and OAuth sessions for the TaskSmith gateway.

Index

Constants

View Source
const PlaceholderSDKCredential = "auth-none"

PlaceholderSDKCredential is what a provider SDK receives when auth.type is "none" but the SDK refuses to build a client without any key at all. The transport deletes the header it produces, so it never leaves the process.

Variables

View Source
var (
	ErrUnsupportedProvider = errors.New("auth: oauth not supported for provider")
	ErrInvalidCallback     = errors.New("auth: invalid callback input")
	ErrNoFlowInProgress    = errors.New("auth: no provider auth flow in progress")
	ErrBrowserHostOnly     = errors.New("auth: browser sign-in must be completed on the daemon host")
	ErrInvalidProviderName = errors.New("auth: provider name is required")
)

Sentinel errors returned by Manager and callback parsing so transport layers can map them onto HTTP status codes without parsing error text.

View Source
var ErrMissingCredential = errors.New("gateway: missing required authentication credential")

ErrMissingCredential indicates that the provider needs authentication.

Functions

func Account

func Account(providerType, providerName string) (string, bool)

Account queries the active OAuth account using the package-registered drivers.

func BuildHTTPTransport

func BuildHTTPTransport(base http.RoundTripper, auth *Config, token string, customHeaders map[string]string, providerType string) http.RoundTripper

BuildHTTPTransport creates an http.RoundTripper that attaches configured headers and authentication tokens to all outgoing requests. Configured headers win over any the provider SDK sets, since the transport is the last layer before the wire.

func CloseBrowserOAuthDrivers

func CloseBrowserOAuthDrivers() error

func CredentialDigest

func CredentialDigest(path string) string

CredentialDigest returns a short hex digest of a credential file's contents so configuration fingerprints change when a token is rotated, without ever placing the secret itself into the hashed payload. A missing or unreadable file digests its error text instead, so creating the file also invalidates any cached configuration.

func CredentialRevision

func CredentialRevision(providerType, providerName string) string

CredentialRevision queries the OAuth credential revision using the package-registered drivers.

func DeleteProviderToken

func DeleteProviderToken(provider string, account string) (bool, error)

DeleteProviderToken removes the persisted OAuth credentials for provider. When account is non-empty, only that account is forgotten from the multi-account registry (and the active token when it was the active account); otherwise the entire credential file is removed. It reports whether any credential material was actually deleted.

func ExtractEmailFromToken

func ExtractEmailFromToken(tok *oauth2.Token) string

ExtractEmailFromToken extracts the email address from a Google OAuth2 token if an id_token was included.

func HasOAuth

func HasOAuth(providerType string) bool

HasOAuth reports whether an OAuth driver is registered for providerType.

func HasOAuthDriver

func HasOAuthDriver(provider string) bool

HasOAuthDriver reports whether an OAuth driver is registered for a provider.

func HasProviderToken

func HasProviderToken(provider string) bool

HasProviderToken reports whether an on-disk OAuth token exists for provider.

func IsCanonicalBrowserOnly

func IsCanonicalBrowserOnly(providerType string) bool

IsCanonicalBrowserOnly reports whether providerType uses a browser-only driver.

func LoadProviderToken

func LoadProviderToken(provider string) (*oauth2.Token, string, error)

LoadProviderToken reads the persisted OAuth2 token and active account email.

func LoginLabel

func LoginLabel(providerType string) string

LoginLabel queries the browser sign-in label using the package-registered drivers.

func NewRefreshOnUnauthorizedTransport

func NewRefreshOnUnauthorizedTransport(base http.RoundTripper, refresh RefreshFunc) http.RoundTripper

NewRefreshOnUnauthorizedTransport wraps base so that a single HTTP 401 Unauthorized response triggers refresh once and replays the request with the rotated Bearer token. Streaming responses that already returned HTTP 200 are never replayed, and a second 401 is returned directly without looping.

func OAuthCredentialDigest

func OAuthCredentialDigest(provider string) string

OAuthCredentialDigest returns a stable hex digest of the stored OAuth identity for provider so Config.Fingerprint changes on sign-in, sign-out, or account switch without rebuilding pooled gateways on routine access-token refreshes.

func ParseCallbackInput

func ParseCallbackInput(raw string) (code, state string, err error)

ParseCallbackInput extracts the authorization code and optional state from a callback URL pasted by hand. It accepts a full callback URL, a query string, a fragment parameter list, or a bare authorization code.

func ProviderTokenPath

func ProviderTokenPath(provider string) (string, error)

ProviderTokenPath returns the absolute path to ~/.local/share/tasksmith/credentials/<provider>.json.

func ProviderTokenSource

func ProviderTokenSource(ctx context.Context, provider, providerType, token string) (oauth2.TokenSource, bool, error)

ProviderTokenSource uses an explicit token or builds a source that refreshes stored OAuth credentials. The boolean indicates whether credentials exist.

func RegisterBrowserOAuthDriver

func RegisterBrowserOAuthDriver(provider string, driver BrowserOAuthDriver)

RegisterBrowserOAuthDriver registers a driver for a provider name.

func RegisterOAuthDriver

func RegisterOAuthDriver(provider string, driver OAuthDriver)

RegisterOAuthDriver registers an OAuth driver for a provider name.

func ResolveCredential

func ResolveCredential(auth *Config, env map[string]string) (string, error)

ResolveCredential extracts credentials from the injected in-memory env map, falling back to os.Getenv, or reading from an explicit file path. Providers declaring the "none" scheme never carry a credential.

func SaveProviderToken

func SaveProviderToken(provider string, tok *oauth2.Token, account string) error

SaveProviderToken persists an OAuth2 token and associates it with the active account. It also records the account in the multi-account registry.

func SecretRevision

func SecretRevision(secret string) string

SecretRevision returns a SHA-256 hex digest of secret (trimmed) so runtime auth health entries can detect credential rotation without storing raw secrets in memory. Returns "" when secret is empty.

func SwitchProviderAccount

func SwitchProviderAccount(provider string, account string) error

SwitchProviderAccount switches the active token to a previously authorized account.

func VendorAuthError

func VendorAuthError(ctx context.Context, vendor, action string) error

VendorAuthError returns ctx.Err() when canceled, or a redacted error that never leaks vendor CLI stderr/stdout.

Types

type BrowserOAuthDriver

type BrowserOAuthDriver interface {
	LoginLabel() string
	Authorize(context.Context) (commit func() (account string, err error), err error)
	Account() (string, bool)
	Logout() (bool, error)
	CredentialRevision() string
}

BrowserOAuthDriver handles a provider-owned browser callback and credential store.

func GetBrowserOAuthDriver

func GetBrowserOAuthDriver(provider string) (BrowserOAuthDriver, bool)

GetBrowserOAuthDriver looks up a driver that owns its browser callback.

type BrowserSessionOption

type BrowserSessionOption[C any] func(*BrowserSessionStore[C])

BrowserSessionOption configures optional behaviors on BrowserSessionStore.

func WithBrowserSessionExpire

func WithBrowserSessionExpire[C any](fn func(*C)) BrowserSessionOption[C]

WithBrowserSessionExpire supplies a callback that mutates a copy of stored credentials so newSource treats the access token as expired and performs a refresh_token grant on the next Token call.

func WithBrowserSessionExpiredCheck

func WithBrowserSessionExpiredCheck[C any](fn func(C) bool) BrowserSessionOption[C]

WithBrowserSessionExpiredCheck supplies a predicate reporting whether stored credentials on disk are statically expired with no refresh path.

type BrowserSessionStore

type BrowserSessionStore[C any] struct {
	// contains filtered or unexported fields
}

BrowserSessionStore keeps one rotating source per active registration. Its lock serializes token refresh with sign-in and sign-out.

func NewBrowserSessionStore

func NewBrowserSessionStore[C any](
	provider string,
	accountName func(C) string,
	newSource func(context.Context, *C, func(C) error) (oauth2.TokenSource, error),
	opts ...BrowserSessionOption[C],
) *BrowserSessionStore[C]

NewBrowserSessionStore manages registrations for a provider. The token source must save refreshed credentials synchronously during Token.

func (*BrowserSessionStore[C]) Account

func (s *BrowserSessionStore[C]) Account() (string, bool)

Account returns the name of the active account and whether it exists.

func (*BrowserSessionStore[C]) CredentialRevision

func (s *BrowserSessionStore[C]) CredentialRevision() string

CredentialRevision changes when the active registration changes.

func (*BrowserSessionStore[C]) ForceRefresh

func (s *BrowserSessionStore[C]) ForceRefresh(ctx context.Context, failedAccessToken string) (*oauth2.Token, error)

ForceRefresh exchanges the stored refresh token for a fresh access token after an upstream 401 response. Concurrent callers presenting the same failed access token share a single refresh and reuse the rotated token.

func (*BrowserSessionStore[C]) IsExpired

func (s *BrowserSessionStore[C]) IsExpired() bool

IsExpired reports whether stored credentials on disk are statically expired with no refresh path.

func (*BrowserSessionStore[C]) LoadAccount

func (s *BrowserSessionStore[C]) LoadAccount() (C, error)

LoadAccount returns the stored credentials for the active registration.

func (*BrowserSessionStore[C]) Logout

func (s *BrowserSessionStore[C]) Logout() (bool, error)

Logout removes the active registration and revokes its token source.

func (*BrowserSessionStore[C]) Save

func (s *BrowserSessionStore[C]) Save(account C) error

Save replaces the active registration and revokes its previous token source.

func (*BrowserSessionStore[C]) TokenSource

func (s *BrowserSessionStore[C]) TokenSource() (oauth2.TokenSource, error)

TokenSource returns the shared source for the active registration.

type CLISessionConfig

type CLISessionConfig[R io.Closer] struct {
	Provider string
	Label    string
	NewCLI   func(dir string) (VendorCLI, error)
	Login    func(context.Context, VendorCLI) error
	Account  func(context.Context, VendorCLI) (string, bool, error)
	Logout   func(context.Context, VendorCLI) (bool, error)
	Build    func(VendorCLI) (R, error)
}

CLISessionConfig wires provider-specific CLI operations into a generic CLISessionStore.

type CLISessionStore

type CLISessionStore[R io.Closer] struct {
	// contains filtered or unexported fields
}

CLISessionStore manages isolated per-account profile directories, atomic active.json registration swaps, and one shared runtime instance per active registration for a vendor CLI provider.

func NewCLISessionStore

func NewCLISessionStore[R io.Closer](cfg CLISessionConfig[R]) *CLISessionStore[R]

NewCLISessionStore constructs a CLISessionStore from cfg.

func (*CLISessionStore[R]) Account

func (s *CLISessionStore[R]) Account() (string, bool)

Account returns the active account identifier and whether a registration exists.

func (*CLISessionStore[R]) Authorize

func (s *CLISessionStore[R]) Authorize(ctx context.Context) (func() (string, error), error)

Authorize signs in inside a freshly created isolated profile directory and returns a commit function that atomically activates it and retires any previous profile.

func (*CLISessionStore[R]) Close

func (s *CLISessionStore[R]) Close() error

Close closes the cached shared runtime without modifying saved registrations.

func (*CLISessionStore[R]) CredentialRevision

func (s *CLISessionStore[R]) CredentialRevision() string

CredentialRevision changes whenever the active profile directory changes.

func (*CLISessionStore[R]) LoginLabel

func (s *CLISessionStore[R]) LoginLabel() string

LoginLabel returns the UI label for browser sign-in.

func (*CLISessionStore[R]) Logout

func (s *CLISessionStore[R]) Logout() (bool, error)

Logout removes the active registration, closes any cached runtime, and performs best-effort vendor sign-out and profile cleanup.

func (*CLISessionStore[R]) SharedRuntime

func (s *CLISessionStore[R]) SharedRuntime() (R, error)

SharedRuntime returns the shared runtime instance for the active registration, building it lazily or replacing it when the active profile on disk changed.

type Config

type Config struct {
	Type     Type              `json:"type,omitempty"`
	Header   string            `json:"header,omitempty"` // Custom HTTP header (defaults to Authorization)
	Token    *CredentialSource `json:"token,omitempty"`
	Username string            `json:"username,omitempty"`
	Password *CredentialSource `json:"password,omitempty"`
}

Config defines authentication parameters for a provider.

func (*Config) Scheme

func (a *Config) Scheme() Type

Scheme returns the configured auth scheme, defaulting to "bearer" when auth is nil or auth.type is omitted.

type CredentialSource

type CredentialSource struct {
	Env  string `json:"env,omitempty"`  // Key name in the injected environment map
	File string `json:"file,omitempty"` // Explicit path to credential file
}

CredentialSource locates a static secret value in an environment variable or in a file on disk.

func (*CredentialSource) IsZero

func (c *CredentialSource) IsZero() bool

IsZero reports whether the source declares neither an env key nor a file path.

type ExpiryChecker

type ExpiryChecker interface {
	IsExpired() bool
}

ExpiryChecker is optionally implemented by BrowserOAuthDriver values that can report whether stored credentials on disk are statically expired with no refresh path.

type FlowSnapshot

type FlowSnapshot struct {
	Provider string
	AuthURL  string
	Status   string
	Account  string
	Error    string
}

FlowSnapshot captures the observable state of an interactive provider authentication flow at a point in time.

type HealthState

type HealthState string

HealthState classifies the runtime authentication health of a provider.

const (
	HealthOK      HealthState = ""
	HealthExpired HealthState = "expired_auth"
	HealthInvalid HealthState = "invalid_auth"
)

type HealthStatus

type HealthStatus struct {
	State     HealthState
	Reason    string
	Revision  string
	UpdatedAt time.Time
}

HealthStatus records the most recent observed runtime auth failure for a provider along with the credential revision that failed.

type Manager

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

Manager owns interactive provider OAuth flows (PKCE loopback listeners, manual callback completion, and provider-owned browser sign-in commits) and provides uniform credential queries across both OAuth driver styles.

func NewManager

func NewManager(cfg ManagerConfig) *Manager

NewManager constructs a provider authentication Manager.

func (*Manager) Account

func (m *Manager) Account(providerType, providerName string) (string, bool)

Account returns the active account identifier and whether credentials exist for the given provider type and manifest name.

func (*Manager) ClearHealth

func (m *Manager) ClearHealth(providerName string)

ClearHealth removes any recorded runtime authentication failure for providerName.

func (*Manager) Close

func (m *Manager) Close() error

Close cancels all in-flight auth flows and closes browser OAuth drivers.

func (*Manager) Complete

func (m *Manager) Complete(ctx context.Context, provider, callbackInput string) (*FlowSnapshot, error)

Complete finishes an in-flight PKCE flow using a manually pasted callback URL or authorization code.

func (*Manager) CredentialRevision

func (m *Manager) CredentialRevision(providerType, providerName string) string

CredentialRevision returns a stable identity digest/revision for the provider's OAuth credentials so configuration fingerprints detect sign-in, sign-out, and account switches.

func (*Manager) FlowStatus

func (m *Manager) FlowStatus(provider string) (*FlowSnapshot, bool)

FlowStatus returns the current snapshot of an active or settled flow for provider if one is tracked.

func (*Manager) HasOAuth

func (m *Manager) HasOAuth(providerType string) bool

HasOAuth reports whether any OAuth driver (browser or PKCE) is registered for providerType.

func (*Manager) Health

func (m *Manager) Health(providerName, currentRevision string) (HealthStatus, bool)

Health returns the recorded runtime authentication failure for providerName, automatically clearing and suppressing stale entries when currentRevision differs from the revision that failed.

func (*Manager) IsCanonicalBrowserOnly

func (m *Manager) IsCanonicalBrowserOnly(providerType string) bool

IsCanonicalBrowserOnly reports whether providerType uses a canonical browser-only driver whose credentials are keyed strictly by provider type.

func (*Manager) LoginLabel

func (m *Manager) LoginLabel(providerType string) string

LoginLabel returns the browser sign-in button label for browser-only drivers, or "" for other providers.

func (*Manager) Logout

func (m *Manager) Logout(providerType, providerName string) (bool, error)

Logout cancels any in-flight OAuth flow and deletes stored credentials for the provider, reporting whether any credential material was removed.

func (*Manager) OAuthHealth

func (m *Manager) OAuthHealth(providerType, providerName string) (HealthStatus, bool)

OAuthHealth reports whether the named OAuth provider has a runtime auth failure or statically expired unrefreshable credentials on disk.

func (*Manager) RecordAuthFailure

func (m *Manager) RecordAuthFailure(providerName, providerType string, state HealthState, revision, reason string)

RecordAuthFailure records a runtime authentication failure, mirroring it to the canonical browser provider key when a manifest uses a browser-only type.

func (*Manager) RecordAuthSuccess

func (m *Manager) RecordAuthSuccess(providerName string)

RecordAuthSuccess clears any recorded runtime authentication failure for providerName.

func (*Manager) RecordFailure

func (m *Manager) RecordFailure(providerName string, state HealthState, revision, reason string)

RecordFailure records a runtime authentication failure for providerName. When state is HealthExpired, any settled non-authorizing flow snapshot is cleared so Manager.Status surfaces expired_auth instead of a stale authenticated flow.

func (*Manager) Start

func (m *Manager) Start(_ context.Context, provider string) (*FlowSnapshot, error)

Start begins an interactive OAuth sign-in flow for provider.

func (*Manager) Status

func (m *Manager) Status(provider string) (*FlowSnapshot, error)

Status returns the flow status if one is active, or falls back to the stored account status for provider.

type ManagerConfig

type ManagerConfig struct {
	// OnAuthenticated is invoked after credentials are persisted so callers
	// (such as the daemon) can reload active workspaces. Optional.
	OnAuthenticated func(context.Context)

	// OAuthDrivers overrides the package-registered PKCE OAuthDriver map when
	// non-nil, allowing tests to run isolated managers without mutating globals.
	OAuthDrivers map[string]OAuthDriver

	// BrowserDrivers overrides the package-registered BrowserOAuthDriver map
	// when non-nil, allowing tests to run isolated managers without mutating globals.
	BrowserDrivers map[string]BrowserOAuthDriver
}

ManagerConfig configures an instance-owned provider authentication Manager.

type OAuthAccount

type OAuthAccount struct {
	Email        string    `json:"email"`
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	Expiry       time.Time `json:"expiry"`
	LastUsedAt   time.Time `json:"last_used_at"`
}

OAuthAccount stores credentials and metadata for an authorized account.

func ListProviderAccounts

func ListProviderAccounts(provider string) ([]OAuthAccount, string, error)

ListProviderAccounts returns all stored accounts and the active email.

type OAuthDriver

type OAuthDriver interface {
	OAuthConfig() *oauth2.Config
	ExtractAccount(tok *oauth2.Token) string
}

OAuthDriver provides provider-specific OAuth2 configuration and account extraction.

func GetOAuthDriver

func GetOAuthDriver(provider string) (OAuthDriver, bool)

GetOAuthDriver looks up the OAuth driver for a provider name.

type OAuthToken

type OAuthToken struct {
	AccessToken  string                  `json:"access_token"`
	TokenType    string                  `json:"token_type,omitempty"`
	RefreshToken string                  `json:"refresh_token,omitempty"`
	Expiry       time.Time               `json:"expiry"`
	Email        string                  `json:"email,omitempty"`
	Accounts     map[string]OAuthAccount `json:"accounts,omitempty"`
}

OAuthToken encapsulates persisted OAuth2 token details, the active account email, and any previously authorized accounts for a provider.

type RefreshFunc

type RefreshFunc func(ctx context.Context, failedAccessToken string) (*oauth2.Token, error)

RefreshFunc exchanges a failed access token for a refreshed OAuth token.

type RefreshableTokenSource

type RefreshableTokenSource interface {
	oauth2.TokenSource
	ForceRefresh(ctx context.Context, failedAccessToken string) (*oauth2.Token, error)
}

RefreshableTokenSource is an oauth2.TokenSource that can force a token refresh when an upstream API rejects the current access token with HTTP 401.

type Type

type Type string

Type describes the HTTP authentication scheme.

const (
	// TypeBearer sends "Authorization: Bearer <token>".
	// It is the default scheme when auth.type is omitted.
	TypeBearer Type = "bearer"
	// TypeAPIKey sends the raw token, un-prefixed.
	TypeAPIKey Type = "api-key"
	// TypeBasic sends "Basic base64(<token>)", where the token is typically "user:pass".
	TypeBasic Type = "basic"
	// TypeNone disables credential lookup and authentication headers entirely.
	TypeNone Type = "none"
	// TypeOAuth2 indicates an interactive OAuth2 flow (e.g. Antigravity PKCE).
	TypeOAuth2 Type = "oauth2"
)

type VendorCLI

type VendorCLI struct {
	Executable string
	ProfileDir string
	WorkDir    string
	Env        []string
}

VendorCLI describes an isolated vendor CLI execution environment rooted in a TaskSmith-managed profile directory under the daemon credential store.

func NewVendorCLI

func NewVendorCLI(binary, configKey, dir string, extraEnv ...string) (VendorCLI, error)

NewVendorCLI resolves binary from PATH, prepares isolated work/home/tmp subdirectories under dir, and builds an allowlisted child environment bound to configKey=dir.

func (VendorCLI) Command

func (c VendorCLI) Command(ctx context.Context, args ...string) *exec.Cmd

Command builds an exec.Cmd configured with the isolated working directory and environment.

Jump to

Keyboard shortcuts

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