oauth

package
v0.40.4 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultOAuthPort = 54321

DefaultOAuthPort is the default port for the OAuth callback server Can be overridden with MCP_GATEWAY_OAUTH_PORT environment variable

View Source
const DefaultRedirectURI = "https://mcp.docker.com/oauth/callback"

DefaultRedirectURI is the OAuth callback endpoint

Variables

This section is empty.

Functions

func GetDCRClientFromDockerPass added in v0.40.4

func GetDCRClientFromDockerPass(ctx context.Context, serverName string) (dcr.Client, error)

GetDCRClientFromDockerPass retrieves a DCR client from docker pass via the Secrets Engine. The value is base64-encoded JSON of dcr.Client stored at docker/mcp/oauth-dcr/{serverName}.

func GetTokenFromDockerPass added in v0.40.4

func GetTokenFromDockerPass(ctx context.Context, serverName string) (*oauth2.Token, error)

GetTokenFromDockerPass retrieves the full oauth2.Token from docker pass via the Secrets Engine. Used by the refresh loop to get the current token (including refresh_token) before refreshing.

func HelperBinaryName added in v0.28.0

func HelperBinaryName(credsStore string) string

HelperBinaryName returns credential helper binary name

func IsCEMode added in v0.28.0

func IsCEMode() bool

IsCEMode returns true if running in Docker CE mode (standalone OAuth flows). When false, uses Docker Desktop for OAuth orchestration.

This uses the same logic as the feature flag system (features.IsRunningInDockerDesktop): - Container mode → CE mode (skip Desktop) - Windows/macOS → assume Docker Desktop (not CE mode) - Linux → check if Docker Desktop is running

Set DOCKER_MCP_USE_CE=true to force CE mode.

func NewReadWriteCredentialHelper added in v0.28.0

func NewReadWriteCredentialHelper() credentials.Helper

NewReadWriteCredentialHelper creates a READ-WRITE credential helper for CE mode This is used for DCR client storage and token storage operations

func RegisterProviderForDynamicDiscovery added in v0.40.1

func RegisterProviderForDynamicDiscovery(ctx context.Context, serverName, serverURL string) error

RegisterProviderForDynamicDiscovery probes a remote server for OAuth support and creates a pending DCR entry if the server requires OAuth. This is used for community servers that lack oauth.providers metadata in the catalog. Idempotent - safe to call multiple times for the same server.

func RegisterProviderForLazySetup added in v0.22.0

func RegisterProviderForLazySetup(ctx context.Context, serverName string) error

RegisterProviderForLazySetup registers a DCR provider with Docker Desktop This allows 'docker mcp oauth authorize' to work before full DCR is complete Idempotent - safe to call multiple times for the same server

func RegisterProviderWithSnapshot added in v0.38.0

func RegisterProviderWithSnapshot(ctx context.Context, serverName, providerName string) error

RegisterProviderWithSnapshot registers a DCR provider using OAuth metadata from the server snapshot This avoids querying the catalog since the snapshot already contains all necessary OAuth information Idempotent - safe to call multiple times for the same server

func SaveDCRClientToDockerPass added in v0.40.4

func SaveDCRClientToDockerPass(ctx context.Context, serverName string, client dcr.Client) error

SaveDCRClientToDockerPass stores a DCR client in docker pass as base64-encoded JSON at docker/mcp/oauth-dcr/{serverName}. Used by the authorize flow for community servers in Desktop mode.

func SaveTokenToDockerPass added in v0.40.4

func SaveTokenToDockerPass(ctx context.Context, serverName string, token *oauth2.Token) error

SaveTokenToDockerPass stores an oauth2.Token in docker pass as base64-encoded JSON at docker/mcp/oauth/{serverName}. Used by the authorize flow and the refresh loop for community servers in Desktop mode.

func ShouldUseGatewayOAuth added in v0.40.4

func ShouldUseGatewayOAuth(ctx context.Context, isCommunity bool) bool

ShouldUseGatewayOAuth returns true when the Gateway should own the OAuth lifecycle for a server (localhost callback, PKCE, token storage via credential helper or docker pass). This is a convenience wrapper around DetermineMode -- Gateway owns OAuth for every mode except ModeDesktop.

IsCEMode() remains the global decision for the notification monitor (pkg/gateway/run.go). This function is the per-server decision used by MCPT-483 through MCPT-486 call sites.

func ValidateCredsStore added in v0.28.0

func ValidateCredsStore(credsStore string) error

ValidateCredsStore validates credential store name

Types

type CallbackData added in v0.28.0

type CallbackData struct {
	Code  string
	State string
}

CallbackData represents the data received from an OAuth callback

type CallbackServer added in v0.28.0

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

CallbackServer is a temporary HTTP server that receives OAuth callbacks on localhost

func NewCallbackServer added in v0.28.0

func NewCallbackServer() (*CallbackServer, error)

NewCallbackServer creates a new callback server on a fixed port (default 54321) The port can be customized via MCP_GATEWAY_OAUTH_PORT environment variable

func (*CallbackServer) Port added in v0.28.0

func (s *CallbackServer) Port() int

Port returns the port the server is listening on

func (*CallbackServer) Shutdown added in v0.28.0

func (s *CallbackServer) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the callback server

func (*CallbackServer) Start added in v0.28.0

func (s *CallbackServer) Start() error

Start starts the HTTP server Should be called in a goroutine

func (*CallbackServer) URL added in v0.28.0

func (s *CallbackServer) URL() string

URL returns the full callback URL Uses 127.0.0.1 explicitly to avoid localhost resolving to ::1 (IPv6) when the server only binds to the IPv4 loopback interface.

func (*CallbackServer) Wait added in v0.28.0

func (s *CallbackServer) Wait(ctx context.Context) (code string, state string, err error)

Wait blocks until a callback is received, an error occurs, or the context is cancelled Returns the authorization code and state parameter

type CommandChecker added in v0.28.0

type CommandChecker interface {
	CommandExists(cmd string) bool
}

CommandChecker checks command existence

type ConfigReader added in v0.28.0

type ConfigReader interface {
	ReadConfig() ([]byte, error)
}

ConfigReader reads Docker config

type CredentialHelper

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

CredentialHelper provides secure access to OAuth tokens via credential helpers. The mode field controls which storage backend is used: Secrets Engine (Desktop catalog), credential helper (CE), or docker pass (Desktop community).

func NewOAuthCredentialHelper

func NewOAuthCredentialHelper() *CredentialHelper

NewOAuthCredentialHelper creates a new OAuth credential helper with auto-detected mode (preserves existing behavior for callers that have not been updated to pass an explicit mode).

func NewOAuthCredentialHelperWithMode added in v0.40.4

func NewOAuthCredentialHelperWithMode(mode Mode) *CredentialHelper

NewOAuthCredentialHelperWithMode creates a credential helper that uses the specified storage mode. Use this when the caller knows whether the server is Desktop-catalog, CE, or Desktop-community.

func (*CredentialHelper) GetHelper added in v0.28.0

func (h *CredentialHelper) GetHelper() credentials.Helper

GetHelper returns the underlying credential helper

func (*CredentialHelper) GetOAuthToken

func (h *CredentialHelper) GetOAuthToken(ctx context.Context, serverName string) (string, error)

GetOAuthToken retrieves an OAuth token for the specified server. Routes to the appropriate storage backend based on the resolved mode:

  • CE: credential helper (base64-encoded JSON)
  • Desktop: Secrets Engine (raw access token)
  • Community: docker pass via Secrets Engine (base64-encoded JSON)

func (*CredentialHelper) GetTokenStatus added in v0.22.0

func (h *CredentialHelper) GetTokenStatus(ctx context.Context, serverName string) (TokenStatus, error)

GetTokenStatus checks token validity and expiry for refresh scheduling. Routes to the appropriate storage backend based on the resolved mode:

  • CE: reads token JSON from credential helper, parses expiry
  • Desktop: queries Secrets Engine, reads ExpiryAt from response metadata
  • Community: reads token JSON from docker pass via Secrets Engine, parses expiry

func (*CredentialHelper) TokenExists added in v0.39.0

func (h *CredentialHelper) TokenExists(ctx context.Context, serverName string) (bool, error)

TokenExists checks if an OAuth token exists for the specified server. Routes to the appropriate storage backend based on the resolved mode.

type DCRProvider added in v0.28.0

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

DCRProvider represents a dynamically registered OAuth provider Implements public client + PKCE for security

func NewDCRProvider added in v0.28.0

func NewDCRProvider(dcrClient dcr.Client, redirectURL string) *DCRProvider

NewDCRProvider creates a new DCR provider from a registered DCR client

func (*DCRProvider) Config added in v0.28.0

func (p *DCRProvider) Config() *oauth2.Config

Config returns the OAuth2 configuration

func (*DCRProvider) GeneratePKCE added in v0.28.0

func (p *DCRProvider) GeneratePKCE() string

GeneratePKCE generates a new PKCE code verifier The challenge is automatically computed by oauth2 library when using S256ChallengeOption

func (*DCRProvider) Name added in v0.28.0

func (p *DCRProvider) Name() string

Name returns the provider name

func (*DCRProvider) ResourceURL added in v0.28.0

func (p *DCRProvider) ResourceURL() string

ResourceURL returns the resource URL for RFC 8707 token audience binding

type DockerConfig added in v0.28.0

type DockerConfig struct {
	CredsStore string `json:"credsStore"`
}

DockerConfig represents Docker's config.json

func ParseDockerConfig added in v0.28.0

func ParseDockerConfig(data []byte) (*DockerConfig, error)

ParseDockerConfig parses config JSON

type Event added in v0.22.0

type Event struct {
	Type     EventType
	Provider string
	Message  string
	Error    string
}

Event represents a parsed OAuth notification event

type EventType added in v0.22.0

type EventType string

EventType represents the type of OAuth event from Docker Desktop

const (
	EventLoginStart    EventType = "login-start"
	EventCodeReceived  EventType = "code-received"
	EventLoginSuccess  EventType = "login-success"
	EventTokenRefresh  EventType = "token-refresh"
	EventLogoutSuccess EventType = "logout-success"
	EventError         EventType = "error"
)

type Manager added in v0.28.0

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

Manager orchestrates OAuth flows for DCR-based providers

func NewManager added in v0.28.0

func NewManager(credHelper credentials.Helper) *Manager

NewManager creates a new OAuth manager for CE mode

func (*Manager) BuildAuthorizationURL added in v0.28.0

func (m *Manager) BuildAuthorizationURL(_ context.Context, serverName string, scopes []string, callbackURL string) (string, string, string, error)

BuildAuthorizationURL generates the OAuth authorization URL with PKCE If callbackURL is provided, extracts port and embeds in state for mcp-oauth proxy routing Returns: authURL, baseState, verifier, error

func (*Manager) DeleteDCRClient added in v0.28.0

func (m *Manager) DeleteDCRClient(serverName string) error

DeleteDCRClient removes a DCR client registration

func (*Manager) EnsureDCRClient added in v0.28.0

func (m *Manager) EnsureDCRClient(ctx context.Context, serverName string, scopes string) error

EnsureDCRClient ensures a DCR client is registered for the server If no client exists or it's incomplete, performs discovery and registration

func (*Manager) ExchangeCode added in v0.28.0

func (m *Manager) ExchangeCode(ctx context.Context, code string, state string) error

ExchangeCode exchanges an authorization code for an access token

func (*Manager) RevokeToken added in v0.28.0

func (m *Manager) RevokeToken(_ context.Context, serverName string) error

RevokeToken revokes an OAuth token for a server

func (*Manager) SetRedirectURI added in v0.28.0

func (m *Manager) SetRedirectURI(uri string)

SetRedirectURI sets a custom redirect URI (for testing or custom deployments)

type Mode added in v0.40.4

type Mode int

Mode determines which credential storage backend to use for a server.

const (
	// ModeAuto auto-detects mode at runtime: IsCEMode() -> CE, else Desktop.
	// Used for backward compatibility when callers have not yet been updated
	// to pass an explicit mode.
	ModeAuto Mode = iota
	// ModeDesktop reads/writes via Secrets Engine (Desktop catalog servers).
	ModeDesktop
	// ModeCE reads/writes via the system credential helper (CE standalone).
	ModeCE
	// ModeCommunity reads/writes via docker pass (Desktop community servers).
	ModeCommunity
)

func DetermineMode added in v0.40.4

func DetermineMode(ctx context.Context, isCommunity bool) Mode

DetermineMode returns the credential storage mode for a server.

  • CE mode (no Desktop): ModeCE
  • Desktop + catalog server: ModeDesktop
  • Desktop + community server + McpGatewayOAuth flag ON: ModeCommunity
  • Desktop + community server + flag OFF/error: ModeDesktop (fallback)

func (Mode) String added in v0.40.4

func (m Mode) String() string

String returns a human-readable label for the mode.

type ModeDetector added in v0.28.0

type ModeDetector interface {
	IsCEMode() bool
}

ModeDetector detects CE vs Desktop mode

type NotificationMonitor added in v0.22.0

type NotificationMonitor struct {
	OnOAuthEvent func(event Event)
	// contains filtered or unexported fields
}

NotificationMonitor subscribes to Docker Desktop's OAuth notification stream

func NewNotificationMonitor added in v0.22.0

func NewNotificationMonitor() *NotificationMonitor

NewNotificationMonitor creates a new notification monitor

func (*NotificationMonitor) Start added in v0.22.0

func (m *NotificationMonitor) Start(ctx context.Context)

Start begins monitoring OAuth notifications from Docker Desktop

type Provider added in v0.22.0

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

Provider manages OAuth token lifecycle for a single MCP server. This is used for background token refresh loops in the gateway.

The mode field (cached at construction) determines behavior:

  • ModeAuto: runtime IsCEMode() detection (backward compat)
  • ModeDesktop: triggers refresh via GetOAuthApp Desktop API; SSE events interrupt the timer, trigger reload, and reset retry counters.
  • ModeCE: refreshes tokens directly via oauth2 library using the credential helper, then reloads.
  • ModeCommunity: refreshes tokens directly via oauth2 library using docker pass for storage, then reloads.

func NewProvider added in v0.22.0

func NewProvider(name string, mode Mode, reloadFn func(context.Context, string) error) *Provider

NewProvider creates a new OAuth provider for token refresh. The mode parameter controls which credential storage backend is used. Pass ModeAuto to preserve the existing IsCEMode() runtime behavior.

func (*Provider) Run added in v0.22.0

func (p *Provider) Run(ctx context.Context)

Run starts the provider's background loop. Loop dynamically adjusts timing based on token expiry.

func (*Provider) SendEvent added in v0.22.0

func (p *Provider) SendEvent(event Event)

SendEvent sends an SSE event to this provider's event channel

func (*Provider) Stop added in v0.22.0

func (p *Provider) Stop()

Stop signals the provider to shutdown gracefully

type Resolver added in v0.28.0

type Resolver struct {
	ConfigReader   ConfigReader
	CommandChecker CommandChecker
	ModeDetector   ModeDetector
}

Resolver resolves credential helper names

func NewResolver added in v0.28.0

func NewResolver() *Resolver

NewResolver creates resolver with production dependencies

func (*Resolver) Resolve added in v0.28.0

func (r *Resolver) Resolve() (string, error)

Resolve determines credential helper to use

type StateManager added in v0.28.0

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

StateManager manages OAuth state parameters and PKCE verifiers States and verifiers are stored in memory and cleared after use

func NewStateManager added in v0.28.0

func NewStateManager() *StateManager

NewStateManager creates a new state manager

func (*StateManager) Clear added in v0.28.0

func (s *StateManager) Clear(state string)

Clear removes a state and its associated verifier without validation Useful for cleanup on errors

func (*StateManager) Generate added in v0.28.0

func (s *StateManager) Generate(serverName string, verifier string) string

Generate creates a new state parameter and stores the associated server name and PKCE verifier Returns the state UUID

func (*StateManager) Validate added in v0.28.0

func (s *StateManager) Validate(state string) (serverName string, verifier string, err error)

Validate checks if a state parameter is valid and returns the associated server name and verifier The state and verifier are removed after validation (single-use)

type TokenStatus added in v0.22.0

type TokenStatus struct {
	Valid        bool
	ExpiresAt    time.Time
	NeedsRefresh bool
}

TokenStatus represents the validity status of an OAuth token

type TokenStore added in v0.28.0

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

TokenStore provides storage for OAuth tokens via credential helper

func NewTokenStore added in v0.28.0

func NewTokenStore(credentialHelper credentials.Helper) *TokenStore

NewTokenStore creates a new token store

func (*TokenStore) Delete added in v0.28.0

func (t *TokenStore) Delete(dcrClient dcr.Client) error

Delete removes an OAuth token from the credential helper

func (*TokenStore) Retrieve added in v0.28.0

func (t *TokenStore) Retrieve(dcrClient dcr.Client) (*oauth2.Token, error)

Retrieve retrieves an OAuth token from the credential helper

func (*TokenStore) Save added in v0.28.0

func (t *TokenStore) Save(dcrClient dcr.Client, token *oauth2.Token) error

Save stores an OAuth token in the credential helper Key format: {authorizationEndpoint}/{providerName}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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