auth

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 22 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 ErrRegistrationNotFound = errors.New("mcp auth: client registration not found")

ErrRegistrationNotFound reports missing durable OAuth client registration state.

View Source
var ErrTokenBindingInvalid = errors.New("mcp auth: token binding is invalid")

ErrTokenBindingInvalid reports token material that is not bound to the active server definition.

View Source
var ErrTokenExpired = errors.New("mcp auth: token is expired")

ErrTokenExpired reports a bearer token that cannot be used for a new request.

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 ClientRegistration

type ClientRegistration struct {
	Target                     Target
	DefinitionFingerprint      string
	ResourceURL                string
	Issuer                     string
	ClientID                   string
	RegistrationClientURI      string
	ClientSecretRef            string
	RegistrationAccessTokenRef string
	ClientIDIssuedAt           time.Time
	ClientSecretExpiresAt      time.Time
	TokenEndpointAuthMethod    string
	RedirectURL                string
	Scopes                     []string
	UpdatedAt                  time.Time
}

ClientRegistration is durable, target-scoped OAuth registration state. Secret material is addressed only by Vault references.

type ExchangeInput

type ExchangeInput struct {
	RedirectURL string
}

ExchangeInput accepts the complete authorization redirect URL.

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
	ResourceURL      string
}

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) BeginStepUp

func (m *Manager) BeginStepUp(
	ctx context.Context,
	cfg ServerConfig,
	callbackURL string,
	approvedScopes []string,
	approved bool,
) (BeginResult, error)

BeginStepUp starts an explicitly approved scope escalation for one target.

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) DeleteState

func (m *Manager) DeleteState(ctx context.Context, target Target) error

DeleteState invalidates pending flows and removes all durable authorization state.

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 from a complete authorization 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"`
	IssuerParameterSupported      bool     `json:"authorization_response_iss_parameter_supported,omitzero"`
}

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

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 RegistrationSecrets

type RegistrationSecrets struct {
	ClientSecret            string
	RegistrationAccessToken string
}

RegistrationSecrets carries DCR material only across the atomic persistence boundary.

type RegistrationStore

type RegistrationStore interface {
	GetMCPAuthRegistration(context.Context, Target) (ClientRegistration, error)
	SaveMCPAuthRegistration(
		context.Context,
		ClientRegistration,
		RegistrationSecrets,
	) (ClientRegistration, error)
	DeleteMCPAuthRegistration(context.Context, Target) error
}

RegistrationStore persists target-scoped OAuth client registrations.

type RegistrationStrategy

type RegistrationStrategy string

RegistrationStrategy identifies how an OAuth client is registered.

const (
	// RegistrationAuto attempts CIMD before one DCR fallback.
	RegistrationAuto RegistrationStrategy = "auto"
	// RegistrationPreRegistered uses operator-provided client credentials.
	RegistrationPreRegistered RegistrationStrategy = "pre_registered"
)

type Scope

type Scope string

Scope identifies the owner of one MCP OAuth credential set.

const (
	// ScopeUser identifies a user-owned MCP server.
	ScopeUser Scope = "user"
	// ScopeWorkspace identifies a workspace-owned MCP server.
	ScopeWorkspace Scope = "workspace"
	// ScopeProfile identifies a profile-owned MCP server.
	ScopeProfile Scope = "profile"
	// ScopeWorkspaceProfile identifies a workspace-and-profile-owned MCP server.
	ScopeWorkspaceProfile Scope = "workspace_profile"
)

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
	CatalogEntry            string
	Type                    string
	IssuerURL               string
	ClientID                string
	ClientSecret            string
	ClientSecretRef         string
	Scopes                  []string
	Registration            RegistrationStrategy
	ResourceURL             string
	PRMURL                  string
	TokenEndpointAuthMethod 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) AuthorizationToken

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

AuthorizationToken returns bearer material only after full definition, registration, and scope binding validation.

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) DeleteAuthorizationState

func (s *Service) DeleteAuthorizationState(ctx context.Context, target Target) error

DeleteAuthorizationState atomically removes token, registration, and Vault state for one target.

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 WithClientMetadataURL

func WithClientMetadataURL(raw string) ServiceOption

WithClientMetadataURL overrides the public CIMD URL for self-hosted deployments.

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.

func WithRegistrationStore

func WithRegistrationStore(store RegistrationStore) ServiceOption

WithRegistrationStore enables durable DCR client registration storage.

func WithSecretRefResolver

func WithSecretRefResolver(resolve SecretRefResolver) ServiceOption

WithSecretRefResolver supplies Vault secret resolution for durable DCR registrations.

func WithSecureHTTPClient

func WithSecureHTTPClient(client *securehttp.Client) ServiceOption

WithSecureHTTPClient uses Compozy's policy-enforcing remote client for OAuth calls.

type Status

type Status struct {
	Owner        string      `json:"owner"`
	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"`
	Diagnostic   string      `json:"diagnostic,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 {
	Owner       string `json:"owner"`
	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.

func (Target) VaultTarget

func (t Target) VaultTarget() vault.MCPSecretTarget

VaultTarget preserves the full credential owner at the Vault boundary.

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
	DeleteMCPAuthorizationState(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