auth

package
v0.3.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLoginSessionNotFound reports a missing or superseded OAuth session.
	ErrLoginSessionNotFound = errors.New("mcp auth: login session not found")
	// ErrLoginSessionExpired reports an OAuth session past its daemon-owned TTL.
	ErrLoginSessionExpired = errors.New("mcp auth: login session expired")
	// ErrLoginSessionStale reports a session whose server definition changed after begin.
	ErrLoginSessionStale = errors.New("mcp auth: login session server definition changed")
	// ErrInvalidExchange reports a malformed manual or callback completion.
	ErrInvalidExchange = errors.New("mcp auth: invalid exchange")
	// ErrTokenMutationStale reports a durable token mutation superseded by a newer action.
	ErrTokenMutationStale = errors.New("mcp auth: token mutation superseded")
	// ErrMutationGenerationUnavailable reports a missing mutation coordinator.
	ErrMutationGenerationUnavailable = errors.New("mcp auth: mutation generation is unavailable")
)
View Source
var ErrTokenNotFound = errors.New("mcp auth: token not found")

ErrTokenNotFound reports missing persisted MCP auth state for one server.

Functions

func ServerDefinitionFingerprint

func ServerDefinitionFingerprint(cfg ServerConfig) (string, error)

ServerDefinitionFingerprint binds OAuth state to one exact remote and auth definition. Resolved secret plaintext is intentionally excluded; its stable configured ref is included.

func ValidateDefinitionFingerprint

func ValidateDefinitionFingerprint(value string) error

ValidateDefinitionFingerprint rejects unbound or malformed durable token records.

Types

type BeginResult

type BeginResult struct {
	AuthorizationURL string    `json:"authorization_url"`
	State            string    `json:"state"`
	ExpiresAt        time.Time `json:"expires_at"`
	CallbackURL      string    `json:"callback_url"`
	ManualSupported  bool      `json:"manual_supported"`
}

BeginResult is the verifier-free authorization handoff returned to callers.

type ExchangeInput

type ExchangeInput struct {
	Code        string
	RedirectURL string
}

ExchangeInput accepts exactly one manual completion representation.

type LifecycleAction

type LifecycleAction string

LifecycleAction identifies one operator-visible OAuth mutation.

const (
	LifecycleBegin    LifecycleAction = "begin"
	LifecycleExchange LifecycleAction = "exchange"
	LifecycleLogout   LifecycleAction = "logout"
)

type LifecycleNotifier

type LifecycleNotifier interface {
	NotifyMCPAuth(context.Context, LifecycleOutcome)
}

LifecycleNotifier receives secret-free OAuth lifecycle outcomes.

type LifecycleOutcome

type LifecycleOutcome struct {
	Action     LifecycleAction
	Target     Target
	Outcome    string
	ErrorClass string
}

LifecycleOutcome is a secret-free OAuth lifecycle event.

type LoginState

type LoginState struct {
	Target           Target
	RedirectURL      string
	State            string
	Verifier         string
	AuthorizationURL string
	Metadata         Metadata
	Config           ServerConfig
}

LoginState holds the short-lived in-memory authorization flow state.

type Manager

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

Manager owns short-lived PKCE state and delegates protocol operations to Service.

func NewManager

func NewManager(service *Service, opts ...ManagerOption) (*Manager, error)

NewManager constructs one process-wide MCP OAuth manager.

func (*Manager) Begin

func (m *Manager) Begin(
	ctx context.Context,
	cfg ServerConfig,
	callbackURL string,
) (result BeginResult, err error)

Begin creates and stores one verifier-bearing session, superseding the prior target session.

func (*Manager) CallbackTarget

func (m *Manager) CallbackTarget(callbackURL string) (Target, error)

CallbackTarget resolves a callback to its unexpired pending target without consuming it.

func (*Manager) Exchange

func (m *Manager) Exchange(
	ctx context.Context,
	cfg ServerConfig,
	input ExchangeInput,
) (status Status, err error)

Exchange completes one target's active session using a code or full redirect URL.

func (*Manager) ExchangeCallback

func (m *Manager) ExchangeCallback(
	ctx context.Context,
	cfg ServerConfig,
	callbackURL string,
) (status Status, err error)

ExchangeCallback completes one active session selected only by callback state.

func (*Manager) Invalidate

func (m *Manager) Invalidate(target Target) error

Invalidate discards pending sessions and advances the target definition revision. Durable token state is intentionally left untouched.

func (*Manager) Logout

func (m *Manager) Logout(ctx context.Context, cfg ServerConfig) (status Status, err error)

Logout revokes remotely when possible and always removes local scoped state.

func (*Manager) Status

func (m *Manager) Status(ctx context.Context, cfg ServerConfig) (Status, error)

Status returns redacted durable state for one scoped server.

type ManagerOption

type ManagerOption func(*Manager)

ManagerOption configures the daemon-owned OAuth session manager.

func WithLifecycleNotifier

func WithLifecycleNotifier(notifier LifecycleNotifier) ManagerOption

WithLifecycleNotifier registers the secret-free lifecycle event sink.

func WithLoginSessionTTL

func WithLoginSessionTTL(ttl time.Duration) ManagerOption

WithLoginSessionTTL overrides the five-minute session TTL for tests.

func WithManagerNow

func WithManagerNow(now func() time.Time) ManagerOption

WithManagerNow overrides the manager clock for deterministic tests.

type Metadata

type Metadata struct {
	Issuer                        string   `json:"issuer,omitempty"`
	AuthorizationEndpoint         string   `json:"authorization_endpoint"`
	TokenEndpoint                 string   `json:"token_endpoint"`
	RevocationEndpoint            string   `json:"revocation_endpoint,omitempty"`
	CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
	ScopesSupported               []string `json:"scopes_supported,omitempty"`
}

Metadata is the OAuth authorization server metadata needed for PKCE flows.

func (Metadata) Validate

func (m Metadata) Validate() error

Validate checks OAuth metadata required by authorization code with PKCE.

type MutationGeneration

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

MutationGeneration coordinates durable token mutations across Service instances.

func NewMutationGeneration

func NewMutationGeneration() *MutationGeneration

NewMutationGeneration constructs a process-wide token mutation coordinator.

func (*MutationGeneration) Advance

func (g *MutationGeneration) Advance(target Target) (uint64, error)

Advance supersedes every mutation that started in an earlier generation.

func (*MutationGeneration) CommitAndAdvanceIfCurrent

func (g *MutationGeneration) CommitAndAdvanceIfCurrent(
	target Target,
	expected uint64,
	commit func() error,
) (bool, error)

CommitAndAdvanceIfCurrent commits one replacement token and atomically supersedes every mutation that observed the replaced generation.

func (*MutationGeneration) CommitIfCurrent

func (g *MutationGeneration) CommitIfCurrent(
	target Target,
	expected uint64,
	commit func() error,
) (bool, error)

CommitIfCurrent runs commit atomically with respect to generation changes.

func (*MutationGeneration) Snapshot

func (g *MutationGeneration) Snapshot(target Target) (uint64, error)

Snapshot returns the current generation for one normalized target.

type PKCEPair

type PKCEPair struct {
	Verifier  string
	Challenge string
	Method    string
}

PKCEPair holds the generated verifier and S256 code challenge. The verifier is secret and must not be logged.

type Scope

type Scope string

Scope identifies the owner of one MCP OAuth credential set.

const (
	// ScopeGlobal identifies a daemon-global MCP server.
	ScopeGlobal Scope = "global"
	// ScopeWorkspace identifies a workspace-owned MCP server.
	ScopeWorkspace Scope = "workspace"
)

type SecretRefResolver

type SecretRefResolver func(ctx context.Context, ref string) (string, error)

SecretRefResolver resolves configured env: or vault: refs to plaintext for OAuth token requests.

type ServerConfig

type ServerConfig struct {
	Target           Target
	Transport        string
	RemoteURL        string
	Type             string
	IssuerURL        string
	MetadataURL      string
	AuthorizationURL string
	TokenURL         string
	RevocationURL    string
	ClientID         string
	ClientSecret     string
	ClientSecretRef  string
	Scopes           []string
}

ServerConfig is the token-free auth configuration used by the OAuth service.

func ServerConfigFromMCP

func ServerConfigFromMCP(
	ctx context.Context,
	target Target,
	server compozyconfig.MCPServer,
	resolveSecret SecretRefResolver,
) (ServerConfig, error)

ServerConfigFromMCP converts a config MCP server into token-free auth service input. resolveSecret receives the configured client_secret_ref and returns the actual secret value when present.

func ServerConfigsFromMCP

func ServerConfigsFromMCP(
	ctx context.Context,
	servers map[Target]compozyconfig.MCPServer,
	resolveSecret SecretRefResolver,
) ([]ServerConfig, error)

ServerConfigsFromMCP returns auth service configs for every auth-enabled MCP server in the supplied list.

func (ServerConfig) Validate

func (c ServerConfig) Validate() error

Validate checks whether a server config is sufficient for auth actions.

type Service

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

Service executes OAuth 2.1 authorization-code flows for remote MCP servers.

func NewService

func NewService(store TokenStore, opts ...ServiceOption) (*Service, error)

NewService constructs an MCP auth service.

func (*Service) BeginLogin

func (s *Service) BeginLogin(
	ctx context.Context,
	cfg ServerConfig,
	redirectURL string,
) (LoginState, error)

BeginLogin discovers metadata, generates PKCE state, and returns the URL the operator must open. The returned verifier is sensitive and must stay in memory.

func (*Service) Exchange

func (s *Service) Exchange(ctx context.Context, state LoginState, callbackURL string) (Status, error)

Exchange validates the OAuth callback and stores the token response.

func (*Service) Logout

func (s *Service) Logout(ctx context.Context, cfg ServerConfig) (Status, error)

Logout revokes the refresh token when revocation metadata is configured, then deletes local durable token state.

func (*Service) Refresh

func (s *Service) Refresh(ctx context.Context, cfg ServerConfig) (Status, error)

Refresh refreshes a persisted token and updates durable storage.

func (*Service) Status

func (s *Service) Status(ctx context.Context, cfg ServerConfig) (Status, error)

Status returns redacted durable auth state for one server.

type ServiceOption

type ServiceOption func(*Service)

ServiceOption configures the OAuth service.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ServiceOption

WithHTTPClient overrides the HTTP client used for metadata and token calls.

func WithMutationGeneration

func WithMutationGeneration(generation *MutationGeneration) ServiceOption

WithMutationGeneration shares token mutation ordering across Service instances.

func WithNow

func WithNow(now func() time.Time) ServiceOption

WithNow overrides the clock for tests.

func WithRandom

func WithRandom(random io.Reader) ServiceOption

WithRandom overrides the entropy source for tests.

type Status

type Status struct {
	ServerName       string      `json:"server_name"`
	Scope            Scope       `json:"scope"`
	WorkspaceID      string      `json:"workspace_id,omitempty"`
	Status           StatusValue `json:"status"`
	RemoteURL        string      `json:"remote_url,omitempty"`
	AuthType         string      `json:"auth_type,omitempty"`
	ClientID         string      `json:"client_id,omitempty"`
	Issuer           string      `json:"issuer,omitempty"`
	Scopes           []string    `json:"scopes,omitempty"`
	ExpiresAt        *time.Time  `json:"expires_at,omitempty"`
	UpdatedAt        *time.Time  `json:"updated_at,omitempty"`
	Refreshable      bool        `json:"refreshable"`
	TokenPresent     bool        `json:"token_present"`
	RevocationURL    string      `json:"revocation_url,omitempty"`
	Diagnostic       string      `json:"diagnostic,omitempty"`
	AuthorizationURL string      `json:"authorization_url,omitempty"`
}

Status is the token-redacted state used by CLI and settings APIs.

type StatusValue

type StatusValue string

StatusValue is the redacted operator-facing authentication state.

const (
	StatusUnconfigured  StatusValue = "unconfigured"
	StatusNeedsLogin    StatusValue = "needs_login"
	StatusAuthenticated StatusValue = "authenticated"
	StatusExpired       StatusValue = "expired"
	StatusInvalid       StatusValue = "invalid"
)

type Target

type Target struct {
	Scope       Scope  `json:"scope"`
	WorkspaceID string `json:"workspace_id,omitempty"`
	ServerName  string `json:"server_name"`
}

Target is the complete identity of one MCP OAuth credential set.

func (Target) Key

func (t Target) Key() (string, error)

Key returns a collision-safe in-memory identity after validation.

func (Target) Normalize

func (t Target) Normalize() Target

Normalize trims target fields without changing their meaning.

func (Target) Validate

func (t Target) Validate() error

Validate ensures the target has one unambiguous owner.

type TokenRecord

type TokenRecord struct {
	Target                Target
	DefinitionFingerprint string
	Issuer                string
	ClientID              string
	Scopes                []string
	AccessToken           string
	RefreshToken          string
	TokenType             string
	ExpiresAt             time.Time
	ObtainedAt            time.Time
	UpdatedAt             time.Time
}

TokenRecord is the durable token-store row. It must never be rendered directly in public API or CLI output.

type TokenStore

type TokenStore interface {
	SaveMCPAuthToken(ctx context.Context, token TokenRecord) error
	GetMCPAuthToken(ctx context.Context, target Target) (TokenRecord, error)
	ListMCPAuthTokens(ctx context.Context) ([]TokenRecord, error)
	DeleteMCPAuthToken(ctx context.Context, target Target) error
}

TokenStore persists OAuth token material behind a narrow boundary.

Jump to

Keyboard shortcuts

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