Documentation
¶
Overview ¶
Package oauth provides OAuth 2.1 authentication support for MCP servers. This file implements OAuth flow coordination to prevent race conditions.
Package oauth provides OAuth 2.1 authentication support for MCP servers. This file implements correlation ID tracking for OAuth flow traceability.
Package oauth provides OAuth authentication functionality for MCP servers.
Package oauth provides OAuth 2.1 authentication support for MCP servers. This file implements enhanced logging utilities with sensitive data redaction.
Package oauth provides OAuth 2.1 authentication support for MCP servers. This file implements proactive token refresh management.
Package oauth provides OAuth authentication functionality for MCP servers.
Index ¶
- Constants
- Variables
- func ArgvFlagKey(flag string) string
- func AuditMaskValue(v string) string
- func BeginManualFlow(serverName string, window time.Duration) (release func())
- func BuildRFC8414MetadataURLs(authServerURL string) []string
- func CheckArgvMaskEcho(field string, incoming, stored []string) error
- func CheckServerWriteMasks(what string, v interface{}) error
- func ContainsMaskMarker(s string) bool
- func CorrelationLogger(ctx context.Context, logger *zap.Logger) *zap.Logger
- func CorrelationLoggerWithFlow(ctx context.Context, logger *zap.Logger) *zap.Logger
- func CreateOAuthConfig(serverConfig *config.ServerConfig, storage *storage.BoltDB) *client.OAuthConfig
- func CreateOAuthConfigWithExtraParams(ctx context.Context, serverConfig *config.ServerConfig, ...) (*client.OAuthConfig, map[string]string)
- func CreateOAuthConfigWithExtraParamsAndLogger(ctx context.Context, serverConfig *config.ServerConfig, ...) (*client.OAuthConfig, map[string]string, error)
- func CreateOAuthConfigWithLogger(serverConfig *config.ServerConfig, storage *storage.BoltDB, logger *zap.Logger) (*client.OAuthConfig, error)
- func DetectOAuthAvailability(baseURL string, timeout time.Duration) bool
- func DiscoverAuthServerURL(serverURL string, timeout time.Duration) string
- func DiscoverScopesFromAuthorizationServer(baseURL string, timeout time.Duration) ([]string, error)
- func DiscoverScopesFromProtectedResource(metadataURL string, timeout time.Duration) ([]string, error)
- func ExtractResourceMetadataURL(wwwAuthHeader string) string
- func FindMaskMarker(path string, v interface{}) (string, bool)
- func FindWorkingMetadataURL(serverURL string, timeout time.Duration) (string, error)
- func GenerateServerKey(serverName, serverURL string) string
- func GetCorrelationID(ctx context.Context) string
- func GetPersistedRefreshToken(serverName, serverURL string, boltStorage *storage.BoltDB) string
- func HasPersistedToken(serverName, serverURL string, boltStorage *storage.BoltDB) (hasToken bool, hasRefreshToken bool, isExpired bool)
- func IsArgvFieldName(key string) bool
- func IsArgvFlag(token string) bool
- func IsConfigReference(v string) bool
- func IsEnvFieldName(key string) bool
- func IsHeadersFieldName(key string) bool
- func IsManualFlowActive(serverName string) bool
- func IsOAuthCapable(serverConfig *config.ServerConfig) bool
- func IsOAuthConfigured(serverConfig *config.ServerConfig) bool
- func IsOAuthError(err string) bool
- func IsSensitiveHeaderName(name string) bool
- func IsSensitiveKeyName(name string) bool
- func LogActualTokenRefreshAttempt(logger *zap.Logger, serverName string, tokenAge time.Duration)
- func LogActualTokenRefreshResult(logger *zap.Logger, serverName string, success bool, duration time.Duration, ...)
- func LogClientConnectionAttempt(logger *zap.Logger, attempt int, maxAttempts int)
- func LogClientConnectionFailure(logger *zap.Logger, attempt int, err error)
- func LogClientConnectionSuccess(logger *zap.Logger, duration time.Duration)
- func LogOAuthFlowEnd(logger *zap.Logger, serverName string, correlationID string, success bool, ...)
- func LogOAuthFlowStart(logger *zap.Logger, serverName string, correlationID string)
- func LogOAuthRequest(logger *zap.Logger, method, url string, headers http.Header)
- func LogOAuthResponse(logger *zap.Logger, statusCode int, headers http.Header, ...)
- func LogOAuthResponseError(logger *zap.Logger, statusCode int, errorMsg string, duration time.Duration)
- func LogSafeCallbackQuery(rawQuery string) string
- func LogSafeErrorText(err error) string
- func LogSafeURL(rawURL string) string
- func LogTokenMetadata(logger *zap.Logger, metadata TokenMetadata)
- func LogTokenRefreshAttempt(logger *zap.Logger, attempt int, maxAttempts int)deprecated
- func LogTokenRefreshFailure(logger *zap.Logger, attempt int, err error)deprecated
- func LogTokenRefreshSuccess(logger *zap.Logger, duration time.Duration)deprecated
- func MaskDetectedSecrets(s string) string
- func MaskValue(v string) string
- func NewCorrelationID() string
- func NewPersistentTokenStore(serverName, serverURL string, storage *storage.BoltDB) client.TokenStore
- func NormalizeForRedaction(v interface{}) interface{}
- func ParsePinnedRedirectURI(rawURI string) (int, error)
- func ParsePinnedRedirectURIBinding(rawURI string) (bindHost string, port int, path string, err error)
- func RedactEnvValues(env map[string]string) map[string]string
- func RedactEnvValuesWith(env map[string]string, mask func(string) string) map[string]string
- func RedactHeaders(headers http.Header) map[string]string
- func RedactSensitiveData(data string) string
- func RedactServerConfigSecrets(sc *config.ServerConfig, r Redaction) *config.ServerConfig
- func RedactServerSecretFields(server *contracts.Server)
- func RedactStringHeaders(headers map[string]string) map[string]string
- func RedactStringHeadersWith(headers map[string]string, mask func(string) string) map[string]string
- func RedactURL(urlStr string) string
- func RedactURLQueryParams(rawURL string) string
- func RedactURLQueryParamsWith(rawURL string, mask func(string) string) string
- func RedactUpstreamStats(stats map[string]interface{}, reveal bool) map[string]interface{}
- func RedactUpstreamStatsEntry(entry map[string]interface{})
- func RedactedConfig(cfg *config.Config) *config.Config
- func RedactedConfigView(key string, v interface{}) map[string]interface{}
- func RedactedConfigViews[T any](key string, items []*T) []map[string]interface{}
- func RedactedServerConfigView(sc *config.ServerConfig, r Redaction) map[string]interface{}
- func RedactedServerConfigViews(servers []*config.ServerConfig, r Redaction) []map[string]interface{}
- func ScrubUpstreamText(s string) string
- func ShouldUseOAuth(serverConfig *config.ServerConfig) bool
- func StateFingerprint(state string) string
- func UnmaskEnvValues(incoming, stored map[string]string) map[string]string
- func UnmaskHeaders(incoming, stored map[string]string) map[string]string
- func UnmaskLiveConfigDocument(incoming map[string]interface{}, stored *config.Config) (*config.Config, error)
- func UnmaskLiveConfigTree(incoming, stored interface{}) (interface{}, error)
- func UnmaskLiveEnvValues(incoming, stored map[string]string) map[string]string
- func UnmaskLiveField(key, incoming, stored string) string
- func UnmaskLiveHeaders(incoming, stored map[string]string) map[string]string
- func UnmaskLiveOAuth(incoming, stored *config.OAuthConfig) error
- func UnmaskLiveURL(incoming, stored string) (string, error)
- func UnmaskLiveURLParams(incoming, stored string) string
- func UnmaskURL(incoming, stored string) string
- func WithCorrelationID(ctx context.Context, id string) context.Context
- func WithFlowContext(ctx context.Context, flowCtx *OAuthFlowContext) context.Context
- func WrapDiscoveryFailed(err error) error
- func WrapRefresh403(err error) error
- func WrapRefreshExpired(err error) error
- type CallbackBinding
- type CallbackServer
- type CallbackServerManager
- func (m *CallbackServerManager) GetCallbackServer(serverName string) (*CallbackServer, bool)
- func (m *CallbackServerManager) SetLogger(logger *zap.Logger)
- func (m *CallbackServerManager) StartCallbackServer(serverName string, preferredPort int) (*CallbackServer, error)
- func (m *CallbackServerManager) StartCallbackServerOnHost(serverName string, binding CallbackBinding) (*CallbackServer, error)
- func (m *CallbackServerManager) StopCallbackServer(serverName string) error
- func (m *CallbackServerManager) StopCallbackServerWithLogger(serverName string, logger *zap.Logger) error
- type CompletionEvent
- type DatabaseOAuthNotifier
- type MaskDecision
- type OAuthFlowContext
- type OAuthFlowCoordinator
- func (c *OAuthFlowCoordinator) CleanupStaleFlows() int
- func (c *OAuthFlowCoordinator) EndFlow(serverName string, success bool, err error)
- func (c *OAuthFlowCoordinator) GetActiveFlow(serverName string) *OAuthFlowContext
- func (c *OAuthFlowCoordinator) IsFlowActive(serverName string) bool
- func (c *OAuthFlowCoordinator) StartFlow(serverName string) (*OAuthFlowContext, error)
- func (c *OAuthFlowCoordinator) UpdateFlowState(serverName string, state OAuthFlowState)
- func (c *OAuthFlowCoordinator) WaitForFlow(ctx context.Context, serverName string, timeout time.Duration) error
- type OAuthFlowState
- type OAuthMetadataError
- type OAuthMetadataValidationResult
- type OAuthServerMetadata
- type OAuthStatus
- type OAuthTransportWrapper
- type PersistentTokenStore
- type ProtectedResourceMetadata
- type Redaction
- func (r Redaction) Argv(argv []string) []string
- func (r Redaction) CapString(s string) string
- func (r Redaction) EnvValue(name, value string) string
- func (r Redaction) ExtraParamValue(key, value string) string
- func (r Redaction) HeaderValue(name, value string) string
- func (r Redaction) Leaf(key, s string) string
- func (r Redaction) RedactNested(key string, dst interface{}) bool
- func (r Redaction) SpawnArgv(argv []string) []string
- func (r Redaction) SpawnCommandString(s string) string
- func (r Redaction) URLValue(s string) string
- func (r Redaction) URLValueDeep(rawURL string) string
- func (r Redaction) Value(key string, v interface{}) interface{}
- func (r Redaction) WithLimit(n int) Redaction
- type RefreshEventEmitter
- type RefreshManager
- func (m *RefreshManager) GetRefreshState(serverName string) *RefreshStateInfo
- func (m *RefreshManager) GetSchedule(serverName string) *RefreshSchedule
- func (m *RefreshManager) GetScheduleCount() int
- func (m *RefreshManager) OnTokenCleared(serverName string)
- func (m *RefreshManager) OnTokenSaved(serverName string, expiresAt time.Time)
- func (m *RefreshManager) SetEventEmitter(emitter RefreshEventEmitter)
- func (m *RefreshManager) SetMetricsRecorder(recorder RefreshMetricsRecorder)
- func (m *RefreshManager) SetRuntime(runtime RefreshRuntimeOperations)
- func (m *RefreshManager) Start(ctx context.Context) error
- func (m *RefreshManager) Stop()
- type RefreshManagerConfig
- type RefreshMetricsRecorder
- type RefreshRuntimeOperations
- type RefreshSchedule
- type RefreshState
- type RefreshStateInfo
- type RefreshTokenConfig
- type RefreshTokenStore
- type TokenMetadata
- type TokenRefreshResult
- type TokenStoreManager
- func (m *TokenStoreManager) GetOrCreateTokenStore(serverName string) client.TokenStore
- func (m *TokenStoreManager) HasRecentOAuthCompletion(serverName string) bool
- func (m *TokenStoreManager) HasTokenStore(serverName string) bool
- func (m *TokenStoreManager) HasValidToken(ctx context.Context, serverName string, storage *storage.BoltDB) bool
- func (m *TokenStoreManager) MarkOAuthCompleted(serverName string)
- func (m *TokenStoreManager) MarkOAuthCompletedWithDB(serverName string, storage DatabaseOAuthNotifier) error
- func (m *TokenStoreManager) NotifyTokenSaved(serverName string, expiresAt time.Time)
- func (m *TokenStoreManager) RecordOAuthFailure(serverName string, err error)
- func (m *TokenStoreManager) SetOAuthCompletionCallback(callback func(serverName string))
- func (m *TokenStoreManager) SetOAuthFailureCallback(callback func(serverName string, err error))
- func (m *TokenStoreManager) SetTokenSavedCallback(callback func(serverName string, expiresAt time.Time))
Constants ¶
const ( // Default OAuth redirect URI base - port will be dynamically assigned DefaultRedirectURIBase = "http://" + config.LoopbackIPv4Host // DefaultRedirectPath aliases the canonical callback path. The constant is // defined in internal/config because `oauth.redirect_uri` has to be // validated where the operator types it, and internal/config cannot import // this package. DefaultRedirectPath = config.OAuthCallbackPath )
const ( // DefaultFlowTimeout is the maximum time to wait for an OAuth flow to complete. DefaultFlowTimeout = 5 * time.Minute // StaleFlowTimeout is the time after which a flow is considered stale and can be cleared. StaleFlowTimeout = 10 * time.Minute )
Default timeouts for OAuth flow coordination.
const ( // DefaultRefreshThreshold is the percentage of token lifetime at which proactive refresh triggers. // Used in hybrid calculation: refresh at the EARLIER of (threshold * lifetime) or (expiry - MinRefreshBuffer). // 0.75 means refresh at 75% of lifetime for long-lived tokens. DefaultRefreshThreshold = 0.75 // DefaultMaxRetries is the maximum number of consecutive refresh attempts before giving up. // Acts as a circuit breaker to prevent infinite retry loops (issue #310). // With exponential backoff (10s base, 5min cap), 50 retries spans ~2+ hours. DefaultMaxRetries = 50 // MinRefreshInterval prevents too-frequent refresh attempts. MinRefreshInterval = 5 * time.Second // MinRefreshBuffer is the minimum time before expiration to schedule a refresh. // This ensures adequate time for retries even with short-lived tokens. // Industry best practice: Google and Microsoft recommend 5 minutes. MinRefreshBuffer = 5 * time.Minute // RetryBackoffBase is the base duration for exponential backoff on retry. // Per FR-008: minimum 10 seconds between refresh attempts per server. RetryBackoffBase = 10 * time.Second // MaxRetryBackoff is the maximum backoff duration (5 minutes per FR-009). MaxRetryBackoff = 5 * time.Minute // MaxExpiredTokenAge is how long after token expiration we continue retrying // before giving up completely. After this duration, we assume the refresh token // is no longer valid even if it wasn't explicitly rejected. MaxExpiredTokenAge = 24 * time.Hour )
Default refresh configuration
const ( // TokenRefreshGracePeriod defines how long before expiration we should trigger a refresh. // This prevents race conditions where a token expires during an API call. // Setting this to 5 minutes allows proactive token refresh before expiration. TokenRefreshGracePeriod = 5 * time.Minute )
Variables ¶
var ( // ErrServerNotOAuth indicates server doesn't use OAuth authentication. // This is returned when attempting OAuth operations on a non-OAuth server. ErrServerNotOAuth = errors.New("server does not use OAuth") // ErrTokenExpired indicates OAuth token has expired. // This triggers token refresh or re-authentication flow. ErrTokenExpired = errors.New("OAuth token has expired") // ErrRefreshFailed indicates token refresh failed after all retry attempts. // This typically requires manual re-authentication via browser. ErrRefreshFailed = errors.New("OAuth token refresh failed") // ErrNoRefreshToken indicates refresh token is not available. // Some OAuth providers don't issue refresh tokens. ErrNoRefreshToken = errors.New("no refresh token available") )
OAuth-specific sentinel errors for consistent error handling across the codebase. Note: ErrFlowInProgress and ErrFlowTimeout are defined in coordinator.go
var AuditRedaction = Redaction{Mask: AuditMaskValue, DetectContracted: true}
AuditRedaction is the policy for anything PERSISTED or EXPORTED: the fixed `••••` marker, carrying neither the secret's length nor its trailing bytes.
var ErrFlowInProgress = errors.New("OAuth flow already in progress")
ErrFlowInProgress indicates an OAuth flow is already in progress for the server.
var ErrFlowTimeout = errors.New("timeout waiting for OAuth flow to complete")
ErrFlowTimeout indicates that waiting for an OAuth flow timed out.
var LiveRedaction = Redaction{Mask: MaskValue, DetectContracted: false}
LiveRedaction is the policy for the LIVE read surfaces (the MCP `upstream_servers list` / `quarantine_security list_quarantined` payloads and `GET /api/v1/servers`). It keeps MaskValue's `••••<last2> (<N> chars)` rendering, which the write-path unmaskers recognise.
var MaskMarkers = deriveMaskMarkers()
MaskMarkers are the substrings every masked rendering carries. They are DERIVED from maskRenderings above plus security.MaskMarkers(), so the net can never fall behind a rendering.
They back up the byte-for-byte echo checks so a mask is still recognised when the stored value has since changed and the exact comparison no longer matches. TestArgvMaskMarkers_MatchTheRenderings and TestMaskMarkers_CoverEveryRendering pin them to the functions that produce them.
var ServerFieldMaskDecisions = map[string]MaskDecision{}/* 105 elements not displayed */
ServerFieldMaskDecisions records the decision for every field of a server as it appears on the wire, keyed by its DOTTED WIRE PATH. Both config.ServerConfig (the MCP door + the config file) and contracts.Server (the REST/SSE door) are covered; the two share most names.
The keys are paths, not top-level field names, because round 7 finding 4 found the guard itself failing open: it reflected over the TOP LEVEL only, and all three of that round's leaks — `isolation.extra_args` published in the clear on two doors and its mask accepted on a third — lived one level down, under a single `isolation` row that claimed in prose to cover them.
TestServerFieldMaskDecisions_CoverEveryNestedLeaf walks BOTH structs recursively (into nested structs, slices and maps) and fails when any leaf that can carry TEXT — and therefore a credential — appears without a decision. Whether a leaf can carry text is derived from its Go type, not asserted here: a bool, an int or a time.Time structurally cannot hold a token, so it needs no row. Everything else does, which is what stops a new nested field inheriting "leaked by default" or "corrupted by default".
Functions ¶
func ArgvFlagKey ¶ added in v0.64.0
ArgvFlagKey turns `--api-key` into the key name the env/header redactors match on.
func AuditMaskValue ¶ added in v0.64.0
AuditMaskValue is the mask for surfaces that PERSIST and EXPORT what they redact — the activity store, its SSE payloads and `mcpproxy activity list` (issue #1146, review round 3).
Unlike MaskValue it carries no length and no trailing bytes. On an interactive surface those help an operator recognise which token is configured and are re-read within seconds; written into an audit row they become a durable fingerprint of the credential — a correlation handle across records and a materially smaller search space for a low-entropy secret. The audit surfaces have no need for the affordance, so they do not pay for it.
${keyring:…} / ${env:…} references still pass through unchanged: they are labels pointing at the secret store, and masking them would erase exactly the information the audit row exists to carry.
func BeginManualFlow ¶ added in v0.62.0
BeginManualFlow records that a user-initiated OAuth sign-in is in flight for serverName and returns a release function. Pass window <= 0 to use the default. The returned release only clears the claim it created, so a superseded flow releasing late cannot unsuppress a newer one.
func BuildRFC8414MetadataURLs ¶ added in v0.15.0
BuildRFC8414MetadataURLs constructs OAuth Authorization Server Metadata URLs per RFC 8414.
RFC 8414 Section 3.1 specifies that when the issuer URL contains a path component, the well-known path should be inserted between the host and the path:
https://example.com/path → https://example.com/.well-known/oauth-authorization-server/path
However, some servers (like the current codebase's test servers) expect the path appended:
https://example.com/path → https://example.com/path/.well-known/oauth-authorization-server
This function returns both variants to try, with RFC 8414 compliant path first.
For URLs without a path:
https://example.com → https://example.com/.well-known/oauth-authorization-server
func CheckArgvMaskEcho ¶ added in v0.64.0
CheckArgvMaskEcho reports an error when an incoming argv vector still carries a mask this proxy rendered — either the exact masking of a stored token, or any token bearing a mask marker. `field` names the request parameter to quote back to the caller (`args_json` on the MCP surface, `args` on REST).
Issue #1148, round 3: argv masks are NEVER reverted, they are REFUSED. An argv token has NO KEY — env values bind to the variable name, headers to the header name, a URL secret to its scheme+host, but an argv slot has only its index and its neighbours, and the caller supplies the WHOLE vector *and* `command` in the same request. So every candidate binding is caller-controlled and any revert can be steered into relocating the live credential into an attacker-chosen command line.
Refusing rather than silently keeping the stored vector is deliberate: the argv field REPLACES the vector on both surfaces, so silently ignoring it would make the write look applied when it was not.
Returns nil for a vector that carries no mask, which is every legitimate write: a caller that changed nothing sends the real values it already has, a caller that rotated a credential sends the new one.
func CheckServerWriteMasks ¶ added in v0.64.0
CheckServerWriteMasks is the fail-closed net on EVERY server write door.
After the key-bound reverts above have restored what they can bind, anything still carrying a mask this proxy rendered is refused. That is what makes the scheme total rather than a list of fields somebody remembered: a field with no revert (args, oauth.scopes, isolation.extra_args), a mask relocated to a field it was never read from, and — the case five review rounds kept producing — a field ADDED to config.ServerConfig later, all fail CLOSED instead of persisting the mask over a live credential.
`what` names the thing being written, for the operator-facing message.
func ContainsMaskMarker ¶ added in v0.64.0
ContainsMaskMarker reports whether a string carries a mask this proxy rendered.
func CorrelationLogger ¶
CorrelationLogger returns a logger with the correlation_id field added if present in context. If no correlation ID is found, returns the original logger unchanged.
func CorrelationLoggerWithFlow ¶
CorrelationLoggerWithFlow returns a logger with both correlation_id and flow state fields.
func CreateOAuthConfig ¶
func CreateOAuthConfig(serverConfig *config.ServerConfig, storage *storage.BoltDB) *client.OAuthConfig
CreateOAuthConfig creates an OAuth configuration for dynamic client registration This implements proper callback server coordination required for Cloudflare OAuth
Note: For zero-config OAuth with auto-detected resource parameter, use CreateOAuthConfigWithExtraParams() instead, which returns both config and extraParams.
func CreateOAuthConfigWithExtraParams ¶
func CreateOAuthConfigWithExtraParams(ctx context.Context, serverConfig *config.ServerConfig, storage *storage.BoltDB) (*client.OAuthConfig, map[string]string)
CreateOAuthConfigWithExtraParams creates an OAuth configuration and returns auto-detected extra parameters. This function implements RFC 8707 resource auto-detection for zero-config OAuth.
The function returns:
- *client.OAuthConfig: The OAuth configuration for mcp-go client
- map[string]string: Extra parameters (including auto-detected resource) to inject into authorization URL
Resource auto-detection logic (in priority order):
- Manual extra_params.resource from config (highest priority - preserves backward compatibility)
- Auto-detected resource from RFC 9728 Protected Resource Metadata
- Fallback to server URL if metadata is unavailable or lacks resource field
func CreateOAuthConfigWithExtraParamsAndLogger ¶ added in v0.62.0
func CreateOAuthConfigWithExtraParamsAndLogger(ctx context.Context, serverConfig *config.ServerConfig, storage *storage.BoltDB, logger *zap.Logger) (*client.OAuthConfig, map[string]string, error)
CreateOAuthConfigWithExtraParamsAndLogger is CreateOAuthConfigWithExtraParams with the caller's logger and the reason it failed.
Both additions exist because this package used to log through zap.L(), and zap.ReplaceGlobals is never called in this binary — so zap.L() is the NO-OP logger and every diagnostic here was silently discarded, including the one that names a malformed `oauth.redirect_uri`. Callers now pass a real logger and surface the returned error instead of reporting the generic "server may not support OAuth".
func CreateOAuthConfigWithLogger ¶ added in v0.62.0
func CreateOAuthConfigWithLogger(serverConfig *config.ServerConfig, storage *storage.BoltDB, logger *zap.Logger) (*client.OAuthConfig, error)
CreateOAuthConfigWithLogger is CreateOAuthConfig with the caller's logger and the reason it failed. See CreateOAuthConfigWithExtraParamsAndLogger.
func DetectOAuthAvailability ¶
DetectOAuthAvailability checks if a server supports OAuth by probing the well-known endpoint Returns true if OAuth metadata is discoverable, false otherwise
func DiscoverAuthServerURL ¶ added in v0.15.0
DiscoverAuthServerURL attempts to discover the OAuth authorization server URL by fetching the Protected Resource Metadata (RFC 9728) from the MCP server. Returns the first authorization server URL, or empty string if discovery fails.
This is important for servers like Smithery that use separate domains:
- MCP Server: server.smithery.ai/googledrive
- Auth Server: auth.smithery.ai/googledrive
func DiscoverScopesFromAuthorizationServer ¶
DiscoverScopesFromAuthorizationServer attempts to discover scopes from OAuth Server Metadata (RFC 8414)
func DiscoverScopesFromProtectedResource ¶
func DiscoverScopesFromProtectedResource(metadataURL string, timeout time.Duration) ([]string, error)
DiscoverScopesFromProtectedResource attempts to discover scopes from Protected Resource Metadata (RFC 9728) This is a convenience wrapper around DiscoverProtectedResourceMetadata for backward compatibility.
func ExtractResourceMetadataURL ¶
ExtractResourceMetadataURL parses WWW-Authenticate header to extract resource_metadata URL Format: Bearer error="invalid_request", resource_metadata="https://..."
func FindMaskMarker ¶ added in v0.64.0
FindMaskMarker walks a generic JSON value and returns the dotted path of the first string leaf still carrying a mask this proxy rendered.
Walking the whole value rather than checking a hand-written field list is the point: it is what makes a field ADDED to the struct later fail closed instead of quietly round-tripping its own mask into the config.
func FindWorkingMetadataURL ¶ added in v0.15.0
FindWorkingMetadataURL tries each URL from BuildRFC8414MetadataURLs and returns the first one that successfully returns valid OAuth metadata. This is used to pre-validate which URL format works for a given server before passing it to the OAuth handler.
Returns the working URL and nil error on success, or empty string and error if none work.
func GenerateServerKey ¶
GenerateServerKey creates a unique key for a server by combining name and URL Exported for use by connection.go when persisting DCR credentials
func GetCorrelationID ¶
GetCorrelationID retrieves the correlation ID from the context. Returns an empty string if no correlation ID is present.
func GetPersistedRefreshToken ¶
GetPersistedRefreshToken retrieves the refresh token from persistent storage if available. Returns empty string if no token exists or token has no refresh_token.
func HasPersistedToken ¶
func HasPersistedToken(serverName, serverURL string, boltStorage *storage.BoltDB) (hasToken bool, hasRefreshToken bool, isExpired bool)
HasPersistedToken checks if a token exists in persistent storage (BBolt) for the server. This is the preferred method to check for existing tokens as it reflects actual token availability.
A zero ExpiresAt (time.Time{}) is treated as "no expiration" — some authorization servers (e.g. Atlassian's MCP endpoint) issue access tokens without an `expires_in` field, which the oauth2 library deserializes as the Go zero time. Returning isExpired=true for those records would make the upstream connection loop forever asking for re-auth even though a valid token is on disk. This mirrors HasValidToken (see below), which already treats IsZero() as "never expires".
func IsArgvFieldName ¶ added in v0.64.0
IsArgvFieldName reports whether a slice is a command-line argument vector. Covers the `args` config field and the `args_json` tool parameter.
`isolation.extra_args` is deliberately NOT argv here: `Redaction.Argv` pairs `--flag value` and keeps unrecognised tokens verbatim, which is right for a vector whose command it belongs to is also on the wire. An extra_args vector is docker-run flags, and its elements go through Leaf like any other free text — which is what masks `-e API_KEY=<token>`.
func IsArgvFlag ¶ added in v0.64.0
IsArgvFlag reports whether a token is an option rather than a positional argument. A bare "-" or "--" is a convention, not a flag.
func IsConfigReference ¶ added in v0.64.0
IsConfigReference is the exported form of isConfigReference, for callers outside this package that must decide whether a value is a secret-store LABEL rather than a secret (issue #1146: the activity redactor runs a value-shaped detector over everything the name rules pass through, and a reference must not be mangled by it).
func IsEnvFieldName ¶ added in v0.64.0
IsEnvFieldName reports whether a map should be masked with environment-variable semantics. Covers both the `env` config field and the `env_json` tool parameter (the suffix is trimmed before the walk).
func IsHeadersFieldName ¶ added in v0.64.0
IsHeadersFieldName reports whether a map/leaf should be masked with HTTP header semantics. Covers both the `headers` config field and the `headers_json` tool parameter (the suffix is trimmed before the walk).
func IsManualFlowActive ¶ added in v0.62.0
IsManualFlowActive reports whether a user-initiated OAuth sign-in is currently in flight for serverName. Expired claims are dropped on read.
func IsOAuthCapable ¶
func IsOAuthCapable(serverConfig *config.ServerConfig) bool
IsOAuthCapable determines if a server can use OAuth authentication Returns true if:
- OAuth is explicitly configured in config, OR
- Server uses HTTP-based protocol (OAuth auto-detection available)
func IsOAuthConfigured ¶
func IsOAuthConfigured(serverConfig *config.ServerConfig) bool
IsOAuthConfigured checks if server has OAuth configuration in config file This is mainly for informational purposes - we don't require pre-configuration
func IsOAuthError ¶
IsOAuthError checks if an error message indicates an OAuth-related problem. This is the exported version for use by other packages.
func IsSensitiveHeaderName ¶ added in v0.64.0
IsSensitiveHeaderName reports whether an HTTP header NAME looks like it carries a credential. Exported for callers that must decide masking from a name they hold apart from the value (the activity/audit redactor, issue #1146) so the rule stays defined in exactly one place.
func IsSensitiveKeyName ¶ added in v0.64.0
IsSensitiveKeyName reports whether a NAME looks like it holds a secret, using the same case-insensitive marker match RedactEnvValues applies to env-var keys. Exported for callers that have to decide masking from a name they hold separately from the value — e.g. a command-line flag naming the argv token that follows it (issue #1146), where there is no map to hand to RedactEnvValues.
func LogActualTokenRefreshAttempt ¶ added in v0.16.0
LogActualTokenRefreshAttempt logs an actual proactive token refresh attempt. This is called by RefreshManager when it initiates a token refresh operation.
func LogActualTokenRefreshResult ¶ added in v0.16.0
func LogActualTokenRefreshResult(logger *zap.Logger, serverName string, success bool, duration time.Duration, err error)
LogActualTokenRefreshResult logs the result of an actual token refresh operation. This is called by RefreshManager after a refresh attempt completes.
func LogClientConnectionAttempt ¶ added in v0.16.0
LogClientConnectionAttempt logs a client connection attempt (not an actual token refresh). Note: This is called when retrying client.Start(), which may trigger automatic token refresh internally by mcp-go, but we cannot observe whether refresh actually occurred.
func LogClientConnectionFailure ¶ added in v0.16.0
LogClientConnectionFailure logs a failed client connection attempt.
func LogClientConnectionSuccess ¶ added in v0.16.0
LogClientConnectionSuccess logs a successful client connection. Note: This does NOT mean a token refresh occurred - it means the client connected. The mcp-go library may have used a cached token or performed automatic refresh internally.
func LogOAuthFlowEnd ¶
func LogOAuthFlowEnd(logger *zap.Logger, serverName string, correlationID string, success bool, duration time.Duration)
LogOAuthFlowEnd logs the end of an OAuth flow.
func LogOAuthFlowStart ¶
LogOAuthFlowStart logs the start of an OAuth flow.
func LogOAuthRequest ¶
LogOAuthRequest logs an OAuth HTTP request with redacted sensitive data. Use at debug level for comprehensive request tracing.
func LogOAuthResponse ¶
func LogOAuthResponse(logger *zap.Logger, statusCode int, headers http.Header, duration time.Duration)
LogOAuthResponse logs an OAuth HTTP response with redacted sensitive data. Use at debug level for comprehensive response tracing.
func LogOAuthResponseError ¶
func LogOAuthResponseError(logger *zap.Logger, statusCode int, errorMsg string, duration time.Duration)
LogOAuthResponseError logs an OAuth HTTP response error.
func LogSafeCallbackQuery ¶ added in v0.64.0
LogSafeCallbackQuery renders a whole OAuth callback query string for a log field, parameter by parameter.
The raw `r.URL.RawQuery` of the callback request was logged at INFO on TWO handlers, which put the authorization code on disk a second and third time even after the dedicated `code` field was masked. Rendering per parameter rather than dropping the field keeps the diagnostic the line exists for: WHICH parameters the provider sent back.
func LogSafeErrorText ¶ added in v0.64.0
LogSafeErrorText renders an error's text for a log field or a structured error leaf, with any credential it quotes removed. Exported for internal/upstream/core, which builds the same OAuth failure payloads.
func LogSafeURL ¶ added in v0.64.0
LogSafeURL is logSafeURL for callers OUTSIDE this package (issue #1158, review round 2 finding B6).
internal/upstream/core.Client.logSafeURL, managed.Client.logSafeURL, transport.HTTPTransportConfig.logSafeURL, the CLI client and the registry routes each rendered their URL log fields with RedactURLQueryParams — the NAME rule only. This package's own new renderer deliberately does not, and says why in so many words: a credential under an unrecognised or opaque parameter name (`?opaque=ghp_…`, `?resource=<url-encoded url with a token>`) is invisible to the name rule and still reached the log. Two renderers for the same class of field is how the gap re-opens, so there is one.
func LogTokenMetadata ¶
func LogTokenMetadata(logger *zap.Logger, metadata TokenMetadata)
LogTokenMetadata logs token metadata without exposing actual token values. Safe to use at info level as no sensitive data is included.
func LogTokenRefreshAttempt
deprecated
func LogTokenRefreshFailure
deprecated
func LogTokenRefreshSuccess
deprecated
func MaskDetectedSecrets ¶ added in v0.64.0
MaskDetectedSecrets masks any credential the value-shaped detector recognises inside s, leaving text it does not recognise untouched.
func MaskValue ¶ added in v0.31.0
MaskValue renders a string secret as `••••<last2> (<N> chars)` for human display. Returns "(empty)" for empty input, a 4-bullet preview for values up to 4 characters (where revealing the last two would leak too much), and `${keyring:NAME}` / `${env:VAR}` reference strings pass through unchanged because they are labels, not secrets — the UI renders them as keyring chips and a masked reference would defeat that detection. The format mirrors what the Web UI / macOS tray apply client-side for env vars and other non-redacted-by-backend literals, so a single rendering path produces a uniform look.
func NewCorrelationID ¶
func NewCorrelationID() string
NewCorrelationID generates a new unique correlation ID using UUID v4.
func NewPersistentTokenStore ¶
func NewPersistentTokenStore(serverName, serverURL string, storage *storage.BoltDB) client.TokenStore
NewPersistentTokenStore creates a new persistent token store for a server
func NormalizeForRedaction ¶ added in v0.64.0
func NormalizeForRedaction(v interface{}) interface{}
NormalizeForRedaction turns an arbitrary typed config value into generic JSON (maps / slices / json.Number / string / bool) so the walkers above and the redaction walker in internal/server can inspect it key by key. json.Number keeps integers exact instead of degrading them to float64 and rendering as 1.048576e+06. On failure the value is returned unchanged; the walkers' default branch then passes it through.
func ParsePinnedRedirectURI ¶ added in v0.62.0
ParsePinnedRedirectURI validates an operator-pinned OAuth redirect URI (the per-server `oauth.redirect_uri` config field) and returns the loopback port it pins.
The rules live in internal/config (ParseLoopbackRedirectURI) so that the REST config API, the MCP `upstream_servers` tool and this flow all reject exactly the same values. See that function for the rationale.
func ParsePinnedRedirectURIBinding ¶ added in v0.62.0
func ParsePinnedRedirectURIBinding(rawURI string) (bindHost string, port int, path string, err error)
ParsePinnedRedirectURIBinding is ParsePinnedRedirectURI plus the loopback host the callback listener must bind and the callback path it must serve. A pinned `http://[::1]:PORT/oauth/callback` is only honored if something actually listens on ::1 — binding 127.0.0.1 for it produced an authorize URL nobody could call back to. The path defaults to "/" (not DefaultRedirectPath) when the pinned URI has none - what an HTTP client actually requests for a path-less URL (issue #1304: some providers publish a shared OAuth application whose registered redirect path an operator cannot change).
func RedactEnvValues ¶ added in v0.52.0
RedactEnvValues is the env-var analogue of RedactStringHeaders, for the per-server config `env` map surfaced by the upstream_servers MCP tool, the /api/v1/servers REST response, and the SSE event stream. Returns a new map; the input is not mutated. Returns nil for nil input so JSON callers keep emitting `null` rather than `{}` (same back-compat contract as RedactStringHeaders).
Values under a sensitive-looking key (see isSensitiveEnvKey) are replaced with MaskValue — which passes ${env:...}/${keyring:...} references through unchanged and renders literals as `••••<last2> (<N> chars)`. Non-sensitive keys stay readable so operators can still see LOG_LEVEL, NODE_ENV, etc., with a RedactSensitiveData pass over the value as a defence-in-depth fallback for embedded secrets (it leaves ordinary values like `debug` untouched).
func RedactEnvValuesWith ¶ added in v0.64.0
RedactEnvValuesWith is RedactEnvValues with a caller-chosen mask. See RedactStringHeadersWith for why the audit surfaces need a different one.
func RedactHeaders ¶
RedactHeaders creates a copy of headers with sensitive values redacted. Returns a map suitable for logging.
func RedactSensitiveData ¶
RedactSensitiveData redacts sensitive information from a string. It replaces tokens, secrets, and other sensitive data with redacted placeholders.
func RedactServerConfigSecrets ¶ added in v0.64.0
func RedactServerConfigSecrets(sc *config.ServerConfig, r Redaction) *config.ServerConfig
RedactServerConfigSecrets returns a masked COPY of sc under the given policy, for a door that must hand back a *config.ServerConfig rather than a map (the server edition's ServerResponse embeds one).
The policy is a PARAMETER because the choice is the caller's and it is not obvious. Pass LiveRedaction on a surface whose reader owns the credential and may edit it — MaskValue's `••••<last2> (<N> chars)` says which token is configured and the write-path unmaskers recognise it. Pass AuditRedaction wherever the reader is NOT the owner: for a server edition shared server the affordance buys that reader nothing (shared servers are read-only to users) while publishing the admin credential's exact length and trailing bytes to every tenant of the deployment — a durable fingerprint and a correlation handle, which is the case AuditMaskValue was written for.
The input is never mutated and the result shares no map, slice or pointer with it: the masked view is decoded into a FRESH struct. That matters because the caller's config is typically the LIVE one — `h.sharedServers` is the admin's running configuration, and writing a mask through it would be the #1142/#1146 corruption with a whole deployment's upstreams as the blast radius.
It FAILS CLOSED. If the masked view cannot be decoded back into a ServerConfig, the result carries the server's name and nothing else: a caller that loses fields is a bug report, a caller that publishes an unredacted credential is this issue.
Returns nil for a nil config.
func RedactServerSecretFields ¶ added in v0.64.0
RedactServerSecretFields masks the secret-bearing fields of one contracts.Server in place, using the LIVE policy — the SAME oauth.Redaction rule set the MCP `upstream_servers list` / `quarantine_security list_quarantined` payloads are built from.
Issue #1148, round 4 finding 3 put the FIELD LIST here. Round 6 finding 2 put the RULES here too: this function used to apply name-rule-only redaction (RedactEnvValues / RedactStringHeaders / RedactURLQueryParams) while the MCP door applied the name rule PLUS the value-shaped detector, so a credential under a benign env/header name — or under an unrecognised URL query parameter — was masked on one door and published in the clear on the other. Sharing a field list but not the rules is the same half-done shape this issue keeps producing; both now come from LiveRedaction.
There are THREE doors onto this struct — `GET /api/v1/servers` and its single-server children, the `/events` SSE `servers.changed` payload, and the tray/Web UI reading either. Parity between them is load-bearing beyond the leak: the Web UI's mergeServers treats each payload as authoritative, so a masked-vs-plaintext mismatch between the list response and the SSE delivery would flicker on every event.
Callers apply the `reveal_secret_headers` opt-out themselves; by the time a server reaches here it is being redacted.
The write-path answer for every field is recorded ONCE, in ServerFieldMaskDecisions below, and enforced by the write doors through UnmaskLiveEnvValues / UnmaskLiveHeaders / UnmaskLiveURL / UnmaskLiveOAuth plus the CheckServerWriteMasks residual net.
func RedactStringHeaders ¶ added in v0.27.0
RedactStringHeaders is the map[string]string analogue of RedactHeaders, for the per-server config form (cfg.Headers) used in the upstream_servers MCP tool and the /api/v1/servers REST response. Returns a new map; the input is not mutated. Returns nil for nil input so JSON callers can keep emitting `null` rather than `{}` if they were doing so before.
Sensitive header values are replaced with a length-preserving mask of the form `••••<last2> (<N> chars)` — the same format the Web UI and macOS tray apply to display literals. This gives all callers a single uniform representation: clients render whatever string the API hands back, no `***REDACTED***`-vs-`••••XX`-vs-plaintext branching.
Carrying the length and last two characters is intentional. They are already exposed indirectly (length via response size analysis, tail via prior history, etc.), they materially help operators identify which token is in use without revealing the secret, and they make the "Convert to secret" affordance work on the UI side because the user can confirm a recognisable suffix before approving.
func RedactStringHeadersWith ¶ added in v0.64.0
RedactStringHeadersWith is RedactStringHeaders with a caller-chosen mask.
Issue #1146 (review round 3): MaskValue's `••••<last2> (<N> chars)` rendering is a deliberate trade for the INTERACTIVE surfaces — it lets an operator recognise which token is configured, and the write path (UnmaskHeaders) depends on being able to recognise it when a client echoes it back. On the AUDIT surfaces that trade is wrong: those rows are persisted, streamed and exported, so the length and trailing bytes become a durable fingerprint of every credential. Those callers pass AuditMaskValue instead. Splitting the mask out — rather than forking the "which name is sensitive" rules — keeps one definition of sensitivity behind both renderings.
func RedactURL ¶
RedactURL redacts sensitive query parameters from a URL string.
Issue #1148, round 4: this is not only a standalone helper — it is the fallback RedactURLQueryParams takes when url.Parse FAILS, and a URL that fails to parse is precisely the URL a connection error is being logged about. It masked the query params but had no `user:pass@` rule, so the basic-auth password survived every logSafeURL() site in internal/upstream/core, internal/upstream/managed and internal/transport whenever the configured URL was malformed. Reuse RedactSensitiveData's urlUserinfoPattern so the two scrubbers cannot drift apart.
func RedactURLQueryParams ¶ added in v0.52.0
RedactURLQueryParams masks the values of sensitive query parameters in a URL while leaving the rest of the URL — path, non-sensitive params, and any ${env:...}/${keyring:...} reference values — verbatim. Unlike RedactURL (regex, log-oriented, emits `***REDACTED***`) it parses with net/url and masks with MaskValue, giving the same client-facing representation as the header/env redactors. References are passed through unchanged because they are labels, not secrets. A URL with no query, or no sensitive params, is returned unchanged. On parse failure it falls back to the regex RedactURL.
func RedactURLQueryParamsWith ¶ added in v0.64.0
RedactURLQueryParamsWith is RedactURLQueryParams with a caller-chosen mask. See RedactStringHeadersWith for why the audit surfaces need a different one.
func RedactUpstreamStats ¶ added in v0.64.0
RedactUpstreamStats masks the secret-bearing leaves of an `upstream_stats` map IN PLACE and returns it.
`upstream_stats` is served verbatim on GET /api/v1/status, embedded in the /api/v1/servers response and pushed on every SSE `status` event, so its per-server entries sit behind the same trust boundary as the server list on those same payloads.
Issue #1148, rounds 4 and 8. The map is built by TWO implementations — upstream.Manager.GetStats (the fallback) and server.Server.GetUpstreamStats (the StateView path that actually runs) — and they disagreed: round 4 masked the first with name-only rules and never touched the second at all, so the path that serves nearly every request published `url` and `last_error` verbatim. One rule, applied at the wire boundary both implementations pass through, is the only shape that cannot drift again.
Returns the map unchanged when `reveal` is true, honouring the same reveal_secret_headers opt-out every sibling read door honours.
func RedactUpstreamStatsEntry ¶ added in v0.64.0
func RedactUpstreamStatsEntry(entry map[string]interface{})
RedactUpstreamStatsEntry masks one per-server `upstream_stats` entry in place.
`url` takes the shared LIVE URL rule (the name rule PLUS the value-shaped detector) and `last_error` the shared free-form rule, which are the same two rules the server list in the SAME response applies to the same two strings. Every other leaf of the entry — state, counters, the upstream's self-reported name and version — is proxy-computed and carries no operator value.
func RedactedConfig ¶ added in v0.64.0
RedactedConfig returns a masked deep copy of a whole config, using the same generic LIVE walk every other door masks a nested server block with.
Walking rather than enumerating is the durable half, for exactly the reason round 7 gave: a field added to config.Config later is masked because the walk reaches it, instead of being published in the clear until somebody remembers.
Returns nil when the walk cannot round-trip. A caller must treat that as a failure and serve an error: publishing the unmasked config instead is the fail-open shape this whole issue is made of.
func RedactedConfigView ¶ added in v0.64.0
RedactedConfigView renders one config.ServerConfig — or any other config struct that carries server-derived strings — as a generic JSON map with every secret-bearing leaf masked under the LIVE policy.
Issue #1148, round 8. internal/server has had this shape since round 1 (`redactedServerView`), but it lived up there, so the doors BELOW it in the import graph could not reach it: the server edition's `/admin/servers` fallback wrote `h.config.Servers` — the raw []*config.ServerConfig, every env value, header and oauth.client_secret in it — straight to JSON, and its shared-toggle handler echoed back a raw *config.ServerConfig. The view moves here so EVERY door can build a payload from a redacted view rather than from the struct.
`key` is the enclosing wire field name; pass "" for a whole server config. Returns nil for nil. A value that cannot round-trip through generic JSON fails CLOSED: nil is returned rather than the raw struct.
func RedactedConfigViews ¶ added in v0.64.0
RedactedConfigViews is RedactedConfigView over a slice, skipping nils. Returns an empty (non-nil) slice for an empty input so JSON callers keep emitting `[]`.
func RedactedServerConfigView ¶ added in v0.64.0
func RedactedServerConfigView(sc *config.ServerConfig, r Redaction) map[string]interface{}
RedactedServerConfigView renders one server config as a generic JSON map with every secret-bearing leaf masked under the given policy.
Pass LiveRedaction for an interactive read surface (it keeps MaskValue's `••••<last2> (<N> chars)` rendering, which the write-path unmaskers recognise) and AuditRedaction for anything persisted. Returns nil for a nil config.
The view must stay a MAP for a JSON-rendering caller: config.ServerConfig declares MarshalJSON/UnmarshalJSON and Go promotes those to any struct that embeds it, so an embedding wrapper silently drops its own fields on encode (see the warning on config.ServerConfig.UnmarshalJSON).
func RedactedServerConfigViews ¶ added in v0.64.0
func RedactedServerConfigViews(servers []*config.ServerConfig, r Redaction) []map[string]interface{}
RedactedServerConfigViews renders a slice of server configs, skipping nils.
func ScrubUpstreamText ¶ added in v0.64.0
ScrubUpstreamText is the ONE rule for free-form text that originated OUTSIDE mcpproxy's own structured fields — an upstream connection error, a health detail, a diagnostic cause, a line tailed from a child server's log.
Such a string has no enclosing key to judge it by, so BOTH rules run: the name rule (RedactSensitiveData, which masks `<param>=<value>` shapes, bearer tokens and URL userinfo) and then the value-shaped detector (which masks a vendor-formatted credential wherever it sits — `?opaque=ghp_…`, a token a child process printed).
Issue #1148, round 8 findings 1 and 2: FIVE doors published the same three strings (`last_error`, `health.detail`, `diagnostic.cause`) and disagreed about the rule. `RedactServerSecretFields` (REST + SSE) and the MCP view ran both rules; `upstream.Manager.GetStats` (`upstream_stats` on /api/v1/status and the SSE status event), the per-server diagnostics route, the doctor route and the management diagnostics aggregator ran only the name rule — so the same error string was masked on one door of one response and published in the clear on another. Same strings, one rule, one answer.
func ShouldUseOAuth ¶
func ShouldUseOAuth(serverConfig *config.ServerConfig) bool
ShouldUseOAuth determines if OAuth should be attempted for a given server Headers are tried first if configured, then OAuth as fallback on auth errors
func StateFingerprint ¶ added in v0.64.0
StateFingerprint renders an OAuth `state` for a LOG FIELD or an error message (issue #1158, review round 2 finding B1).
`state` is the CSRF nonce that binds a callback to the flow that minted it. It is not an access credential on its own, but it is the other half of the pair an attacker who has read the log needs: with the authorization code AND the state, a callback can be replayed against the waiting flow. It was written verbatim on five log statements and inside two error messages.
The fingerprint keeps what the log lines actually use it for — correlating "Registered waiter" with "callback received" with "dropped, nobody waiting" across one flow — while carrying no bytes of the nonce itself. A truncated SHA-256 is enough: the values it distinguishes are the handful of flows live in one process.
func UnmaskEnvValues ¶ added in v0.52.0
UnmaskEnvValues is the env-map analogue of UnmaskURL. It guards against a client echoing a masked `env` map back on the write path (Issue #872, Codex round). Returns incoming unchanged for nil.
The whole-value revert is tried FIRST: if incoming exactly equals the masked rendering of the stored value it is reverted to the stored value outright. This covers whole-value masks (sensitive keys, RedactSensitiveData fallback) and — importantly (Codex round 3) — a MALFORMED URL-shaped value that RedactURLQueryParams masked via its RedactURL regex fallback: UnmaskURL cannot re-parse such a value, so without this ordering the mask would be persisted over the stored secret on an unedited echo.
Only when incoming differs (a genuine edit) does a well-formed URL-shaped value under a non-sensitive key fall to component-wise unmasking via UnmaskURL — which restores just the masked userinfo password / sensitive query params and carries the authority safeguard, letting an operator edit a non-secret part of a connection string (db name, an option) without the password mask being persisted as the real password (Codex round 2, finding 2).
func UnmaskHeaders ¶ added in v0.52.0
UnmaskHeaders is the header-map analogue of UnmaskEnvValues. Headers are always whole-value masked by RedactStringHeaders (no component-wise URL masking), so a plain whole-value comparison is sufficient.
func UnmaskLiveConfigDocument ¶ added in v0.64.0
func UnmaskLiveConfigDocument(incoming map[string]interface{}, stored *config.Config) (*config.Config, error)
UnmaskLiveConfigDocument is UnmaskLiveConfigTree for a whole config document a client PUT/POSTed: it resolves the masks against `stored` and decodes the result into a fresh config.Config.
Decoding into a FRESH value rather than over an existing one is the same rule RedactNested follows: encoding/json reuses an existing slice's backing array, so decoding over a value that still aliases the stored config would overwrite live credentials with their own masks.
func UnmaskLiveConfigTree ¶ added in v0.64.0
func UnmaskLiveConfigTree(incoming, stored interface{}) (interface{}, error)
UnmaskLiveConfigTree is the write twin of RedactedConfig: it reverts every mask a live read door rendered that can be BOUND TO A KEY, and refuses whatever is left.
`incoming` is what the client sent — a whole config document on `/config/apply`, a partial one on `PATCH /config` — and `stored` is what the proxy holds. Both are walked as generic JSON, so a PARTIAL tree works: the bindings are per key at each level, not positional.
The bindings are exactly the ones ServerFieldMaskDecisions already records, applied one level up:
- a MAP key (`env`, `headers`, `oauth.extra_params`) and a named struct field (`url`, `command`, `api_key`, `oauth.client_secret`) bind, because the caller cannot restate the key without also restating what the secret is for.
- the `mcpServers` array binds BY NAME, never by index: a caller who renames a server has not told the proxy which stored secret they meant.
- an argv / scopes / extra_args slot binds to NOTHING — an index is not a binding — so its mask survives the walk and CheckServerWriteMasks refuses the write, which is the `refuse` decision the table has recorded since round 6.
- and one binding wider than all of them: a SUBTREE echoed back byte for byte as the read door rendered it is proof the caller changed nothing in it, so the stored subtree is restored wholesale. That is the same binding UnmaskLiveURL has used since round 4 for a whole URL, one level up — and it is what keeps the raw-JSON editor and the onboarding wizard working: they GET the document, change one top-level field and POST it back, so every server block is byte-identical and none of them has to bind leaf by leaf. Change anything inside a block and the equality fails, the walk narrows to per-key bindings, and an argv mask under an edited server is refused exactly as it should be.
Anything the walk did not revert and still carries a mask this proxy rendered fails the write CLOSED, including a field added to config.Config later.
func UnmaskLiveEnvValues ¶ added in v0.64.0
UnmaskLiveEnvValues reverts env values a client echoed back exactly as a LIVE read door rendered them.
It exists alongside UnmaskEnvValues because the live rendering runs the value-shaped detector over leaves the NAME rule left alone (`env: {BENIGN: ghp_…}`) — a rendering UnmaskEnvValues cannot recognise, since it compares against maskedEnvValue. Without this mirror, masking that leaf would trade a disclosure for the read-modify-write corruption of #1142/#1146.
Binding is by KEY, exactly as UnmaskEnvValues binds, so a value can only ever be restored to the variable it was read from.
func UnmaskLiveField ¶ added in v0.64.0
UnmaskLiveField reverts one scalar field echoed back exactly as a live read door rendered it, bound to the field NAME the rendering was keyed on.
func UnmaskLiveHeaders ¶ added in v0.64.0
UnmaskLiveHeaders is UnmaskLiveEnvValues for header maps.
func UnmaskLiveOAuth ¶ added in v0.64.0
func UnmaskLiveOAuth(incoming, stored *config.OAuthConfig) error
UnmaskLiveOAuth reverts masked oauth fields echoed back by a client, and REFUSES the write when a mask it cannot bind survives.
The oauth block is REPLACED wholesale by a write, and the live view masks every leaf of it that looks like a credential — not just client_secret. Round 2 finding 6 fixed client_secret; round 4 finding 1 caught the rest: `extra_params` routinely holds an RFC 8707 resource indicator with a signed URL, which the URL rule masks, and any leaf can be masked by the value-shaped detector. A read-modify-write therefore persisted the MASK STRING over those values.
- client_secret, client_id, redirect_uri — reverted, each bound to its own field name, using the same rendering the read path produced.
- extra_params — reverted per PARAMETER NAME, exactly as env vars and headers are reverted per key.
- scopes, and any field added to config.OAuthConfig in future — REFUSED. A scope's only context is its position in a caller-supplied slice, which is the same non-binding an argv token has (see CheckArgvMaskEcho), and a future field has no revert at all. The residual check walks the whole block, so a new field fails CLOSED instead of silently corrupting.
func UnmaskLiveURL ¶ added in v0.64.0
UnmaskLiveURL reverts a masked URL on the write path, and REFUSES the write when a mask it cannot bind survives.
Three steps, widest binding first:
- The whole URL echoed back byte for byte — revert to the stored URL.
- A genuine edit — UnmaskURL restores the userinfo password and the SENSITIVE query params under its own authority safeguard, then UnmaskLiveURLParams restores, PER PARAMETER, anything the value-shaped detector masked under a parameter name no matcher recognises.
- Whatever still carries a mask marker is refused.
Round 4 finding 2 is why (2) needs the per-parameter pass and (3) exists at all: for `https://host/old?opaque=ghp_…` the LIVE detector masks the value, but changing `/old` to `/new` defeats the whole-URL comparison in (1) and UnmaskURL ignores the unrecognised `opaque` parameter — so the mask was written through as the credential. The per-parameter revert is bound to the parameter name and the authority and to nothing else, so it survives an unrelated edit; the refusal covers everything that binding cannot reach (a URL moved to another host, a mask in the path or the fragment, a parameter whose stored counterpart is gone).
func UnmaskLiveURLParams ¶ added in v0.64.0
UnmaskLiveURLParams reverts, PER QUERY PARAMETER, a value that is exactly the value-shaped detector's masking of the stored value for the same parameter name.
Issue #1148, round 4 finding 2. UnmaskURL only knows the SENSITIVE query params — the ones it masked itself — so a credential the live surface masked through the DETECTOR, under a parameter name no matcher recognises (`?opaque=ghp_…`), had no revert at all. The whole-URL echo check covered the unedited case, but editing any other byte of the URL (the path, a neighbouring param) defeated it and the mask was written through as the credential.
The revert is bound to the PARAMETER NAME and to the authority, and to nothing else — not to the path, not to the other parameters — which is what makes it survive an unrelated edit. As in UnmaskURL, a stored secret is restored ONLY when incoming keeps the stored scheme and host:port, so a URL redirected at another host never receives it; duplicate keys are restored positionally and only when the occurrence counts match.
Anything it cannot bind is left masked on purpose: the caller is then refused by the surface's residual-marker check rather than having a mask persisted over a credential.
func UnmaskURL ¶ added in v0.52.0
UnmaskURL protects the write path from a client that echoes a masked URL back (Issue #872, Codex round). The read path (RedactURLQueryParams) renders sensitive query-param values and the userinfo password with MaskValue; a client editing only a non-secret part of a URL — the tray sends `url` as a single string, not a field-level diff — would otherwise persist the mask over the real credential.
For each sensitive query param (and the userinfo password) in incoming, if its value is exactly MaskValue(<stored value>), the stored real value is substituted so the secret survives. Genuinely edited values (anything that is not the mask of the stored value) are kept verbatim. If stored is empty or either URL fails to parse, incoming is returned unchanged.
Authority safeguard (Codex round 2, finding 1): a stored secret is restored ONLY when incoming keeps the stored scheme and host:port — and, for the userinfo password, the same username. If the authority changed (e.g. the URL was redirected to an attacker host), nothing is restored and the mask is left literal; the write then fails downstream validation rather than silently leaking the real credential to a new host.
func WithCorrelationID ¶
WithCorrelationID returns a new context with the given correlation ID attached.
func WithFlowContext ¶
func WithFlowContext(ctx context.Context, flowCtx *OAuthFlowContext) context.Context
WithFlowContext returns a new context with the OAuth flow context attached.
func WrapDiscoveryFailed ¶ added in v0.25.0
WrapDiscoveryFailed attaches MCPX_OAUTH_DISCOVERY_FAILED for failures to fetch the OAuth authorization-server metadata document.
func WrapRefresh403 ¶ added in v0.25.0
WrapRefresh403 attaches MCPX_OAUTH_REFRESH_403 — use for invalid_grant or HTTP 403 responses from the token endpoint.
func WrapRefreshExpired ¶ added in v0.25.0
WrapRefreshExpired attaches the MCPX_OAUTH_REFRESH_EXPIRED diagnostics code to an error reported from the refresh-token path. Producers should call this at the point the refresh token is determined to be gone/expired so the diagnostics classifier returns the right code without resorting to free-text matching. Spec 044.
Types ¶
type CallbackBinding ¶ added in v0.62.0
type CallbackBinding struct {
// Host is the loopback address to listen on ("127.0.0.1" or "::1").
// Empty means 127.0.0.1.
Host string
// Port is the port to try first. 0 means dynamic allocation.
Port int
// Path is the callback path the listener must serve. Empty means
// DefaultRedirectPath. An operator's `oauth.redirect_uri` can pin a
// different path (issue #1304) when the provider's registered callback URL
// uses one mcpproxy does not control.
Path string
// RedirectURI, when set, is the EXACT verbatim string a pin supplies
// (operator-typed, sent to the provider unchanged) and is recorded as-is on
// the resulting CallbackServer instead of being reconstructed from
// Host/Port/Path. Reconstruction round-trips the decoded Path back into a
// URL string, which is only safe for DefaultRedirectPath's fixed ASCII
// value — an operator-pinned path can contain characters (e.g. a decoded
// "?" from a percent-encoded pin) that change meaning when
// naively re-embedded in a fresh URL string, and the host spelling the
// operator typed (e.g. "localhost") is lost once resolved to a bind
// address. Empty means "reconstruct as before" (the unpinned/dynamic case,
// where Path is always the fixed DefaultRedirectPath).
RedirectURI string
// Pinned reports whether Port came from an operator's `oauth.redirect_uri`
// rather than from the Spec 022 stored-port record.
//
// It is carried explicitly instead of being inferred from Port > 0 because
// the two cases need opposite handling when a cached server is already
// bound elsewhere: a pin CANNOT be satisfied by another port (the provider
// rejects the mismatched redirect_uri), whereas a stored port is only a
// preference and must never cost a live flow its listener.
Pinned bool
// Logger is the caller's real logger. Without it the callback surface logs
// into the no-op zap global and the whole flow is invisible.
Logger *zap.Logger
}
CallbackBinding describes the loopback endpoint a flow needs its OAuth callback server on.
type CallbackServer ¶
type CallbackServer struct {
Port int
RedirectURI string
Server *http.Server
ServerName string
// BindHost is the loopback address the listener is actually bound to
// ("127.0.0.1" or "::1"). A pinned `http://[::1]:PORT/oauth/callback` is
// only honored when the listener is on the same family, so the binding is
// recorded rather than assumed.
BindHost string
// Path is the callback path this listener's mux actually serves. Defaults
// to DefaultRedirectPath; a pinned `oauth.redirect_uri` can override it.
Path string
// contains filtered or unexported fields
}
CallbackServer represents an active OAuth callback server.
Callback parameters are dispatched by the `state` parameter (issue #975): every flow registers the state it minted before opening the browser and gets its own single-use channel. A callback whose state nobody registered is rejected with an explicit failure page instead of being handed to whichever flow happened to be listening.
func GetCallbackServer ¶
func GetCallbackServer(serverName string) (*CallbackServer, bool)
GetCallbackServer is a global helper to access callback servers
func (*CallbackServer) HasState ¶ added in v0.62.0
func (c *CallbackServer) HasState(state string) bool
HasState reports whether a flow is currently waiting for this state.
func (*CallbackServer) RegisterState ¶ added in v0.62.0
func (c *CallbackServer) RegisterState(state string) <-chan map[string]string
RegisterState registers the OAuth `state` a flow just minted and returns the channel its callback parameters will be delivered on. Call it BEFORE opening the browser so a fast user cannot beat the registration, and pair it with UnregisterState so a finished or cancelled flow's state cannot be reused.
Registering the same state twice returns the same channel, which lets the flow that mints the state register early and the goroutine that waits for it obtain the same channel later without a second buffer.
func (*CallbackServer) UnregisterState ¶ added in v0.62.0
func (c *CallbackServer) UnregisterState(state string)
UnregisterState drops the waiter for a state. Safe to call more than once and safe to call after delivery (delivery already removes the waiter).
type CallbackServerManager ¶
type CallbackServerManager struct {
// contains filtered or unexported fields
}
CallbackServerManager manages OAuth callback servers for dynamic port allocation
func GetGlobalCallbackManager ¶
func GetGlobalCallbackManager() *CallbackServerManager
GetGlobalCallbackManager returns the global callback manager instance
func (*CallbackServerManager) GetCallbackServer ¶
func (m *CallbackServerManager) GetCallbackServer(serverName string) (*CallbackServer, bool)
GetCallbackServer retrieves the callback server for a given server name
func (*CallbackServerManager) SetLogger ¶ added in v0.62.0
func (m *CallbackServerManager) SetLogger(logger *zap.Logger)
SetLogger installs a real logger on the manager. Safe to call repeatedly; a nil logger is ignored so a caller without one cannot blind the manager again.
func (*CallbackServerManager) StartCallbackServer ¶
func (m *CallbackServerManager) StartCallbackServer(serverName string, preferredPort int) (*CallbackServer, error)
StartCallbackServer starts a new OAuth callback server for the given server name. If preferredPort > 0, it attempts to bind to that port first for redirect URI persistence (Spec 022). Falls back to dynamic allocation if the preferred port is unavailable.
Deprecated in favour of StartCallbackServerOnHost, which can bind IPv6 loopback and carries the caller's logger. Kept for callers that have neither; a server started here records the zap global as its logger (its records are not routed into any per-server log — never into another server's, Spec 105 FR-007).
func (*CallbackServerManager) StartCallbackServerOnHost ¶ added in v0.62.0
func (m *CallbackServerManager) StartCallbackServerOnHost(serverName string, binding CallbackBinding) (*CallbackServer, error)
StartCallbackServerOnHost starts (or reuses) the OAuth callback server for a server name on the requested loopback binding.
Reuse rules, in order:
- A cached server that already satisfies the binding is reused. Reuse must preserve parked waiters: callbacks are dispatched by `state` (issue #975), so several flows can safely share one listener.
- A cached server bound elsewhere is REPLACED only when that cannot strand a live flow — i.e. when nothing is parked on it — or when the caller pinned the port, in which case reusing the wrong port would hand the provider a redirect_uri it rejects and the flow could never complete anyway.
- Otherwise the cached server is reused despite the mismatch, and the mismatch is logged. This is the case that matters for a static client_id whose stored port is occupied by another process: attempt 1 falls back to a dynamic port and parks a waiter, attempt 2 still prefers the stored port, and tearing down attempt 1's listener would make that server impossible to log into for as long as the stored port stays occupied.
func (*CallbackServerManager) StopCallbackServer ¶
func (m *CallbackServerManager) StopCallbackServer(serverName string) error
StopCallbackServer stops and removes the callback server for a given server name
func (*CallbackServerManager) StopCallbackServerWithLogger ¶ added in v0.62.0
func (m *CallbackServerManager) StopCallbackServerWithLogger(serverName string, logger *zap.Logger) error
StopCallbackServerWithLogger is StopCallbackServer with the caller's logger. The signature is kept for its callers; the tear-down records are written through the stopped server's OWN recorded logger (Spec 105 FR-007, subject-bound routing), and the caller's logger is only the fallback for a server that recorded none. Stopping never adopts a logger as the manager logger: the manager serves every server, and the last-installed logger is a tee into whichever server's log file ran a flow last — pre-105 that is where another server's name, bind host, port and dropped-waiter count landed.
type CompletionEvent ¶
type CompletionEvent = storage.OAuthCompletionEvent
OAuthCompletionEvent represents an OAuth completion event (re-exported from storage)
type DatabaseOAuthNotifier ¶
type DatabaseOAuthNotifier interface {
SaveOAuthCompletionEvent(event *CompletionEvent) error
}
DatabaseOAuthNotifier interface for database-based OAuth completion notifications
type MaskDecision ¶ added in v0.64.0
type MaskDecision string
MaskDecision is what a write door does when a client echoes back the mask a read door rendered for a field.
Issue #1148 spent five review rounds on one shape: a rule applied at one door and not its sibling. The cure is that the answer for a field is written down ONCE, here, and every door reads it from the same place — so a field cannot be masked on read with no matching answer on write (which corrupts the stored credential), nor left in the clear on one door because the other one already handles it.
const ( // MaskDecisionRevertByKey — the read mask is reverted on write, bound to a // KEY the caller cannot restate without also restating what the secret is // for: a map key, a query-parameter name plus the stored scheme+host, a // named struct field. Anything the binding cannot reach is refused. MaskDecisionRevertByKey MaskDecision = "revert-by-key" // MaskDecisionRefuse — the read mask is NEVER reverted; a write carrying it // is rejected and the caller resends the real value. This is the answer for // every field whose secret has no key to bind to (an argv slot has only its // index and its neighbours, and the caller supplies the whole vector *and* // `command` in the same request) and, by default, for every field nobody // has yet given a binding — which is what makes a new field fail CLOSED. MaskDecisionRefuse MaskDecision = "refuse" // MaskDecisionNotSecret — the field carries no credential, is never masked // on any read door, and so can never be echoed back as a mask. The residual // net still refuses one if it appears. MaskDecisionNotSecret MaskDecision = "not-secret" )
type OAuthFlowContext ¶
type OAuthFlowContext struct {
// CorrelationID is a UUID that uniquely identifies this OAuth flow.
CorrelationID string
// ServerName is the name of the MCP server being authenticated.
ServerName string
// StartTime is when the OAuth flow was initiated.
StartTime time.Time
// State is the current state of the OAuth flow.
State OAuthFlowState
}
OAuthFlowContext represents the context for a single OAuth authentication flow. It contains a unique correlation ID that links all log entries for this flow.
func GetFlowContext ¶
func GetFlowContext(ctx context.Context) *OAuthFlowContext
GetFlowContext retrieves the OAuth flow context from the context. Returns nil if no flow context is present.
func NewOAuthFlowContext ¶
func NewOAuthFlowContext(serverName string) *OAuthFlowContext
NewOAuthFlowContext creates a new OAuth flow context with a unique correlation ID.
func (*OAuthFlowContext) Duration ¶
func (c *OAuthFlowContext) Duration() time.Duration
Duration returns the time elapsed since the flow started.
func (*OAuthFlowContext) SetState ¶
func (c *OAuthFlowContext) SetState(state OAuthFlowState)
SetState updates the state of the OAuth flow.
type OAuthFlowCoordinator ¶
type OAuthFlowCoordinator struct {
// contains filtered or unexported fields
}
OAuthFlowCoordinator coordinates OAuth flows to ensure only one flow runs per server. This prevents race conditions where multiple reconnection attempts trigger concurrent OAuth flows.
func GetGlobalCoordinator ¶
func GetGlobalCoordinator() *OAuthFlowCoordinator
GetGlobalCoordinator returns the global OAuth flow coordinator instance.
func NewOAuthFlowCoordinator ¶
func NewOAuthFlowCoordinator() *OAuthFlowCoordinator
NewOAuthFlowCoordinator creates a new OAuth flow coordinator.
func (*OAuthFlowCoordinator) CleanupStaleFlows ¶
func (c *OAuthFlowCoordinator) CleanupStaleFlows() int
CleanupStaleFlows removes any OAuth flows that have been running longer than StaleFlowTimeout. This should be called periodically to prevent memory leaks from abandoned flows.
func (*OAuthFlowCoordinator) EndFlow ¶
func (c *OAuthFlowCoordinator) EndFlow(serverName string, success bool, err error)
EndFlow marks an OAuth flow as completed (success or failure). This notifies any waiting goroutines and cleans up the flow state.
func (*OAuthFlowCoordinator) GetActiveFlow ¶
func (c *OAuthFlowCoordinator) GetActiveFlow(serverName string) *OAuthFlowContext
GetActiveFlow returns the active OAuth flow context for the given server, if any.
func (*OAuthFlowCoordinator) IsFlowActive ¶
func (c *OAuthFlowCoordinator) IsFlowActive(serverName string) bool
IsFlowActive checks if an OAuth flow is currently active for the given server.
func (*OAuthFlowCoordinator) StartFlow ¶
func (c *OAuthFlowCoordinator) StartFlow(serverName string) (*OAuthFlowContext, error)
StartFlow starts a new OAuth flow for the given server. If a flow is already in progress, returns the existing flow context and ErrFlowInProgress. The caller should use WaitForFlow() instead if they want to wait for the existing flow.
func (*OAuthFlowCoordinator) UpdateFlowState ¶
func (c *OAuthFlowCoordinator) UpdateFlowState(serverName string, state OAuthFlowState)
UpdateFlowState updates the state of an active OAuth flow.
func (*OAuthFlowCoordinator) WaitForFlow ¶
func (c *OAuthFlowCoordinator) WaitForFlow(ctx context.Context, serverName string, timeout time.Duration) error
WaitForFlow waits for an active OAuth flow to complete. Returns nil if no flow is active (caller should start one). Returns ErrFlowTimeout if the wait times out. Returns the flow's error if it failed.
type OAuthFlowState ¶
type OAuthFlowState int
OAuthFlowState represents the current state of an OAuth authentication flow.
const ( // FlowInitiated indicates the OAuth flow has started. FlowInitiated OAuthFlowState = iota // FlowAuthenticating indicates the browser is open and waiting for user authentication. FlowAuthenticating // FlowTokenExchange indicates the authorization code is being exchanged for tokens. FlowTokenExchange // FlowCompleted indicates the OAuth flow completed successfully. FlowCompleted // FlowFailed indicates the OAuth flow failed with an error. FlowFailed )
func (OAuthFlowState) String ¶
func (s OAuthFlowState) String() string
String returns a human-readable representation of the OAuth flow state.
type OAuthMetadataError ¶
type OAuthMetadataError struct {
ErrorType string
ErrorCode string
ServerName string
Message string
Details *metadataErrorDetails
Suggestion string
}
OAuthMetadataError represents a metadata validation error (internal type) This is converted to contracts.OAuthFlowError by the caller
func (*OAuthMetadataError) Error ¶
func (e *OAuthMetadataError) Error() string
type OAuthMetadataValidationResult ¶
type OAuthMetadataValidationResult struct {
Valid bool
ProtectedResourceMetadata *ProtectedResourceMetadata
AuthorizationServerMetadata *OAuthServerMetadata
ProtectedResourceMetadataURL string
AuthorizationServerMetadataURL string
AuthorizationServerMetadataURLsTried []string // All URLs tried (RFC 8414 fallback)
ProtectedResourceError error
AuthorizationServerError error
}
OAuthMetadataValidationResult contains the result of OAuth metadata validation
func ValidateOAuthMetadata ¶
func ValidateOAuthMetadata(serverURL, serverName string, timeout time.Duration) (*OAuthMetadataValidationResult, error)
ValidateOAuthMetadata performs pre-flight validation of OAuth metadata. It fetches and validates both protected resource metadata (RFC 9728) and authorization server metadata (RFC 8414) before starting the OAuth flow. This enables early failure with clear, actionable error messages.
Parameters:
- serverURL: The MCP server URL to validate OAuth for
- serverName: The server name for error messages
- timeout: Timeout for HTTP requests
Returns:
- *OAuthMetadataValidationResult: Validation result with metadata if successful
- error: Structured OAuthFlowError if validation fails
type OAuthServerMetadata ¶
type OAuthServerMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
ResponseTypesSupported []string `json:"response_types_supported"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
}
OAuthServerMetadata represents RFC 8414 OAuth Authorization Server Metadata
type OAuthStatus ¶
type OAuthStatus string
OAuthStatus represents the current authentication state of an OAuth server.
const ( // OAuthStatusNone indicates the server does not use OAuth. OAuthStatusNone OAuthStatus = "none" // OAuthStatusAuthenticated indicates valid OAuth token is available. OAuthStatusAuthenticated OAuthStatus = "authenticated" // OAuthStatusExpired indicates OAuth token has expired. OAuthStatusExpired OAuthStatus = "expired" // OAuthStatusError indicates OAuth authentication error. OAuthStatusError OAuthStatus = "error" )
func CalculateOAuthStatus ¶
func CalculateOAuthStatus(token *storage.OAuthTokenRecord, lastError string) OAuthStatus
CalculateOAuthStatus determines the OAuth status for a server based on token state. Returns OAuthStatusNone if token is nil (server doesn't use OAuth). Returns OAuthStatusError if lastError contains OAuth-related errors. Returns OAuthStatusExpired if token has expired. Returns OAuthStatusAuthenticated if token is valid.
func (OAuthStatus) IsValid ¶
func (s OAuthStatus) IsValid() bool
IsValid returns true if the status represents a valid OAuth state.
func (OAuthStatus) String ¶
func (s OAuthStatus) String() string
String returns the string representation of the OAuthStatus.
type OAuthTransportWrapper ¶
type OAuthTransportWrapper struct {
// contains filtered or unexported fields
}
OAuthTransportWrapper wraps an HTTP RoundTripper to inject extra OAuth parameters into authorization and token requests without modifying the mcp-go library.
This wrapper intercepts HTTP requests and adds custom parameters to: - Authorization requests (query parameters) - Token exchange requests (form body parameters) - Token refresh requests (form body parameters)
The wrapper is stateless and thread-safe for concurrent use.
func NewOAuthTransportWrapper ¶
func NewOAuthTransportWrapper(transport http.RoundTripper, extraParams map[string]string, logger *zap.Logger) *OAuthTransportWrapper
NewOAuthTransportWrapper creates a new transport wrapper that injects extra params.
Parameters:
- transport: The base HTTP RoundTripper to wrap (use http.DefaultTransport if nil)
- extraParams: Map of extra parameters to inject into OAuth requests
- logger: Logger for debug output (uses zap.L() if nil)
Returns a wrapper that can be used as http.Client.Transport.
func (*OAuthTransportWrapper) RoundTrip ¶
RoundTrip implements http.RoundTripper by intercepting requests and injecting extra params.
This method: 1. Detects OAuth authorization and token requests by URL path 2. Clones the request to avoid modifying the original 3. Injects extra parameters into query string (authorization) or body (token) 4. Delegates to the wrapped transport for actual HTTP execution 5. Normalizes HTTP 201 responses to 200 for token requests (some providers like Supabase return 201) 6. Logs parameter injection at DEBUG level for observability
type PersistentTokenStore ¶
type PersistentTokenStore struct {
// contains filtered or unexported fields
}
PersistentTokenStore implements client.TokenStore using BBolt storage
func (*PersistentTokenStore) ClearToken ¶
func (p *PersistentTokenStore) ClearToken() error
ClearToken removes the OAuth token from persistent storage
type ProtectedResourceMetadata ¶
type ProtectedResourceMetadata struct {
Resource string `json:"resource"`
ResourceName string `json:"resource_name,omitempty"`
AuthorizationServers []string `json:"authorization_servers"`
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
}
ProtectedResourceMetadata represents RFC 9728 Protected Resource Metadata
func DiscoverProtectedResourceMetadata ¶
func DiscoverProtectedResourceMetadata(metadataURL string, timeout time.Duration) (*ProtectedResourceMetadata, error)
DiscoverProtectedResourceMetadata fetches RFC 9728 Protected Resource Metadata and returns the full metadata structure including the resource parameter. This is the primary function for RFC 8707 resource auto-detection.
type Redaction ¶ added in v0.64.0
type Redaction struct {
// Mask renders one masked secret. Defaults to MaskValue when nil.
Mask func(string) string
// DetectContracted collapses a URL-shaped rendering: the value-shaped
// detector runs over the WHOLE string rather than component by component.
//
// Only the AUDIT policy sets it. Audit rows are never written back and are
// never edited by an operator, so nothing constrains their rendering and
// maximal masking wins.
//
// A LIVE surface cannot collapse the rendering: #872 deliberately renders a
// connection string component-wise (`postgres://u:••••(N chars)@host/db`)
// so an operator can edit the database name without the password mask being
// persisted as the password, and UnmaskURL recognises exactly that
// rendering on the write path.
//
// It does NOT follow that a live surface skips the detector. Round 6
// finding 1: the old guard skipped it for the ENTIRE string as soon as the
// name rule rewrote any one component, so a URL holding two credentials
// published the second in the clear. The detector now runs per component
// (see maskDetectedPreservingURL), which closes that without collapsing
// anything the write path depends on.
DetectContracted bool
// Limit caps each string leaf the generic walker produces, or 0 for no cap.
//
// It is a property of the DESTINATION, not of the rules: the activity store
// caps every leaf so one mutation carrying a large env map cannot bloat
// BBolt, while a LIVE read surface must not cap — a truncated URL or arg is
// no longer equal to mask(stored), so the write-path unmasker would write
// the truncation through.
Limit int
}
Redaction is the shared rule set for masking one server's secret-bearing leaves. The RULES — which key names are sensitive, which values look like credentials, how argv pairs up, how a URL is rendered component-wise — are shared by EVERY door: the MCP `upstream_servers list` / `quarantine_security list_quarantined` payloads, `GET /api/v1/servers`, the `/events` SSE `servers.changed` payload and the activity store. Only the mask RENDERING differs, and that difference is the one thing this struct carries.
func (Redaction) Argv ¶ added in v0.64.0
Argv masks a command-line argument vector. Returns nil for nil.
Two rules, because argv secrets announce themselves in two ways:
- The FLAG names the credential — `--api-key VALUE` and `--api-key=VALUE`. Delegated to Leaf with the de-dashed flag as the key, so the same single source of truth the env map uses decides, and the flag itself stays readable (it is the audit signal: WHICH credential moved).
- The VALUE is recognisably a credential on its own — an AWS key, a GitHub token, a PEM block, a high-entropy blob — wherever it sits.
BOTH rules run on BOTH spellings: Leaf ends in the detector for every leaf, which keeps `--endpoint=ghp_…` and `--endpoint ghp_…` in step by construction rather than by two call sites remembering to agree.
Everything else round-trips verbatim: package names, subcommands, paths and ports are what make the payload useful.
func (Redaction) CapString ¶ added in v0.64.0
CapString applies the policy's per-leaf length cap, if any, cutting on a rune boundary and marking the cut.
func (Redaction) EnvValue ¶ added in v0.64.0
EnvValue masks one environment-variable leaf, reproducing maskedEnvValue's NAME rule exactly so UnmaskEnvValues can recognise the rendering if a client echoes it back on the write path, then running the value-shaped detector over whatever the name rule left of the original value.
func (Redaction) ExtraParamValue ¶ added in v0.64.0
ExtraParamValue renders one OAuth extra-parameter VALUE for a LOG field.
Issue #1158: the authorize-URL builders log every extra parameter as `zap.String("value", value)` while the sibling summary lines mask the same map through maskExtraParams - the map was masked and the individual values were not. The `resource` parameter is the sharpest case: it carries the configured upstream URL verbatim, credentials included.
func (Redaction) HeaderValue ¶ added in v0.64.0
HeaderValue masks one HTTP header leaf, judged by the header NAME first and then by the value's own shape. Both rules are needed and neither is sufficient: the name matcher cannot enumerate every custom credential header, and the detector cannot recognise an opaque value with no credential shape.
func (Redaction) Leaf ¶ added in v0.64.0
Leaf masks one string leaf, judged by the field NAME that encloses it and then by the value's own shape.
The name rule decides first — it is what keeps the payload readable and says WHICH credential is configured — and whatever survives it is offered to the value-shaped detector. A key name is never the only rule: `--endpoint=ghp_…`, a credential under a header name no matcher recognises, or a token pasted into a field nobody thought of is invisible to name matching and obvious to the detector.
`key` is the enclosing field name; pass "" for a leaf with no key (a positional argv token).
func (Redaction) RedactNested ¶ added in v0.64.0
RedactNested masks every secret-bearing leaf of an arbitrary nested value in place, returning a value of the SAME Go type.
It is how the typed doors (RedactServerSecretFields) redact a nested block without enumerating its fields: the value is normalised to generic JSON, walked by the shared rules, and decoded back over `dst`. A field added to the nested struct is therefore masked by default.
On any encode/decode failure `dst` is left UNTOUCHED and false is returned, so the caller can fail closed rather than publish a half-redacted block.
The masked value is decoded into a FRESH zero value and only then assigned over `dst`. Decoding straight into `dst` would be the #1142 corruption in a new place: encoding/json REUSES an existing slice's backing array, so a projection whose []string still aliases the stored config (a caller that assigned the slice instead of copying it) would have its live credentials overwritten with their own masks by the act of rendering a read response.
func (Redaction) SpawnArgv ¶ added in v0.64.0
SpawnArgv masks a child process's argument vector for a LOG sink.
The flag names, subcommands, image names, paths and ports survive — an operator debugging a spawn still needs to see WHICH flag and WHICH image — and only the values are replaced.
Elements that carry embedded whitespace are treated as command STRINGS (the `-c` argument of a login-shell wrap) and get the same two rules applied token-by-token inside the string, because that is the shape most stdio upstreams actually spawn as.
Returns nil for nil.
func (Redaction) SpawnCommandString ¶ added in v0.64.0
SpawnCommandString masks a whole child command LINE for a LOG sink — the single `-c "docker run …"` / `-c "npx some-mcp --api-key …"` element a login-shell wrap produces, which no []string-only redactor can reach.
func (Redaction) URLValue ¶ added in v0.64.0
URLValue masks one URL leaf: the name rule first (sensitive query parameters and the userinfo password, rendered component-wise per #872), then the value-shaped detector over every component the name rule left alone.
func (Redaction) URLValueDeep ¶ added in v0.64.0
URLValueDeep renders a URL for a LOG sink, masking credentials in its own query string AND inside any query-parameter value that is itself a URL.
Issue #1158: the OAuth authorization URL carries the configured upstream URL verbatim as the RFC 8707 `resource` parameter — autoDetectResource returns serverConfig.URL on every fallback branch — and it is logged at Info level and printed to stdout on every login attempt. The nested URL arrives percent-encoded (`resource=https%3A%2F%2Fhost%2Fmcp%3Ftoken%3DSECRET`), where neither the sensitive-query-parameter name rule (which sees one opaque value under the name `resource`) nor secretPattern (which needs a literal `=` after `token`) can see the credential. Decoding one level is what closes it.
type RefreshEventEmitter ¶
type RefreshEventEmitter interface {
EmitOAuthTokenRefreshed(serverName string, expiresAt time.Time)
EmitOAuthRefreshFailed(serverName string, errorMsg string)
}
RefreshEventEmitter defines event emission methods for OAuth refresh events.
type RefreshManager ¶
type RefreshManager struct {
// contains filtered or unexported fields
}
RefreshManager coordinates proactive OAuth token refresh across all servers.
func NewRefreshManager ¶
func NewRefreshManager( tokenStore RefreshTokenStore, coordinator *OAuthFlowCoordinator, config *RefreshManagerConfig, logger *zap.Logger, ) *RefreshManager
NewRefreshManager creates a new RefreshManager instance.
func (*RefreshManager) GetRefreshState ¶ added in v0.16.0
func (m *RefreshManager) GetRefreshState(serverName string) *RefreshStateInfo
GetRefreshState returns the current refresh state for a server. This is used by the health calculator to determine health status. Returns nil if no schedule exists for the server.
func (*RefreshManager) GetSchedule ¶
func (m *RefreshManager) GetSchedule(serverName string) *RefreshSchedule
GetSchedule returns the refresh schedule for a server (for testing/debugging).
func (*RefreshManager) GetScheduleCount ¶
func (m *RefreshManager) GetScheduleCount() int
GetScheduleCount returns the number of active schedules (for testing/debugging).
func (*RefreshManager) OnTokenCleared ¶
func (m *RefreshManager) OnTokenCleared(serverName string)
OnTokenCleared is called when a token is cleared (e.g., logout). It cancels any scheduled refresh for that server.
func (*RefreshManager) OnTokenSaved ¶
func (m *RefreshManager) OnTokenSaved(serverName string, expiresAt time.Time)
OnTokenSaved is called when a token is saved to storage. It reschedules the proactive refresh for the new token expiration.
func (*RefreshManager) SetEventEmitter ¶
func (m *RefreshManager) SetEventEmitter(emitter RefreshEventEmitter)
SetEventEmitter sets the event emitter for SSE notifications.
func (*RefreshManager) SetMetricsRecorder ¶ added in v0.16.0
func (m *RefreshManager) SetMetricsRecorder(recorder RefreshMetricsRecorder)
SetMetricsRecorder sets the metrics recorder for Prometheus metrics. This enables FR-011: OAuth refresh metrics emission.
func (*RefreshManager) SetRuntime ¶
func (m *RefreshManager) SetRuntime(runtime RefreshRuntimeOperations)
SetRuntime sets the runtime operations interface. This must be called before Start() to enable token refresh.
func (*RefreshManager) Start ¶
func (m *RefreshManager) Start(ctx context.Context) error
Start initializes the refresh manager and loads existing tokens. For non-expired tokens, it schedules proactive refresh using hybrid strategy. For expired tokens with valid refresh tokens, it attempts immediate refresh.
func (*RefreshManager) Stop ¶
func (m *RefreshManager) Stop()
Stop cancels all scheduled refreshes and cleans up resources.
type RefreshManagerConfig ¶
type RefreshManagerConfig struct {
Threshold float64 // Percentage of lifetime at which to refresh (default: 0.8)
MaxRetries int // Maximum retry attempts (default: 3)
}
RefreshManagerConfig holds configuration for the RefreshManager.
type RefreshMetricsRecorder ¶ added in v0.16.0
type RefreshMetricsRecorder interface {
// RecordOAuthRefresh records an OAuth token refresh attempt.
// Result should be one of: "success", "failed_network", "failed_invalid_grant", "failed_other".
RecordOAuthRefresh(server, result string)
// RecordOAuthRefreshDuration records the duration of an OAuth token refresh attempt.
RecordOAuthRefreshDuration(server, result string, duration time.Duration)
}
RefreshMetricsRecorder defines metrics recording methods for OAuth refresh operations. This interface decouples RefreshManager from the concrete MetricsManager.
type RefreshRuntimeOperations ¶
RefreshRuntimeOperations defines runtime methods needed by RefreshManager.
type RefreshSchedule ¶
type RefreshSchedule struct {
ServerName string // Unique server identifier
ExpiresAt time.Time // When the current token expires
ScheduledRefresh time.Time // When proactive refresh is scheduled (hybrid strategy)
RetryCount int // Number of refresh retry attempts
LastError string // Last refresh error message
Timer *time.Timer // Background timer for scheduled refresh
RetryBackoff time.Duration // Current backoff duration for retries
MaxBackoff time.Duration // Maximum backoff duration (5 minutes)
LastAttempt time.Time // Time of last refresh attempt
RefreshState RefreshState // Current state for health reporting
}
RefreshSchedule tracks the proactive refresh state for a single server.
type RefreshState ¶ added in v0.16.0
type RefreshState int
RefreshState represents the current state of token refresh for health reporting.
const ( // RefreshStateIdle means no refresh is pending or in progress. RefreshStateIdle RefreshState = iota // RefreshStateScheduled means a proactive refresh is scheduled (hybrid: 75% lifetime or 5min buffer). RefreshStateScheduled // RefreshStateRetrying means refresh failed and is retrying with exponential backoff. RefreshStateRetrying // RefreshStateFailed means refresh permanently failed (e.g., invalid_grant). RefreshStateFailed )
func (RefreshState) String ¶ added in v0.16.0
func (s RefreshState) String() string
String returns the string representation of RefreshState.
type RefreshStateInfo ¶ added in v0.16.0
type RefreshStateInfo struct {
State RefreshState // Current refresh state
RetryCount int // Number of retry attempts
LastError string // Last error message
NextAttempt *time.Time // When next refresh attempt is scheduled
ExpiresAt time.Time // When the token expires
}
RefreshStateInfo contains refresh state information for health status reporting.
type RefreshTokenConfig ¶
type RefreshTokenConfig struct {
MaxAttempts int
InitialBackoff time.Duration
MaxBackoff time.Duration
}
RefreshTokenConfig contains configuration for token refresh operations.
func DefaultRefreshConfig ¶
func DefaultRefreshConfig() RefreshTokenConfig
DefaultRefreshConfig returns the default token refresh configuration.
type RefreshTokenStore ¶
type RefreshTokenStore interface {
ListOAuthTokens() ([]*storage.OAuthTokenRecord, error)
GetOAuthToken(serverName string) (*storage.OAuthTokenRecord, error)
}
RefreshTokenStore defines storage operations needed by RefreshManager.
type TokenMetadata ¶
type TokenMetadata struct {
TokenType string
ExpiresAt time.Time
ExpiresIn time.Duration
Scope string
HasRefreshToken bool
}
TokenMetadata contains non-sensitive token information for logging.
type TokenRefreshResult ¶
type TokenRefreshResult struct {
Success bool
NewToken *storage.OAuthTokenRecord
Error error
Attempt int
MaxAttempts int
}
TokenRefreshResult contains the result of a token refresh attempt.
type TokenStoreManager ¶
type TokenStoreManager struct {
// contains filtered or unexported fields
}
Global token store manager to persist tokens across client instances
func GetTokenStoreManager ¶
func GetTokenStoreManager() *TokenStoreManager
GetTokenStoreManager returns the global token store manager for debugging
func (*TokenStoreManager) GetOrCreateTokenStore ¶
func (m *TokenStoreManager) GetOrCreateTokenStore(serverName string) client.TokenStore
GetOrCreateTokenStore returns a shared token store for the given server
func (*TokenStoreManager) HasRecentOAuthCompletion ¶
func (m *TokenStoreManager) HasRecentOAuthCompletion(serverName string) bool
HasRecentOAuthCompletion checks if OAuth was recently completed for a server
func (*TokenStoreManager) HasTokenStore ¶
func (m *TokenStoreManager) HasTokenStore(serverName string) bool
HasTokenStore checks if a token store exists for the server in memory (for debugging) Note: This only checks the in-memory store, not persisted tokens in BBolt. Use HasPersistedToken() to check for tokens in persistent storage.
func (*TokenStoreManager) HasValidToken ¶
func (m *TokenStoreManager) HasValidToken(ctx context.Context, serverName string, storage *storage.BoltDB) bool
HasValidToken checks if a server has a valid, non-expired OAuth token Returns true if token exists and hasn't expired (with grace period)
func (*TokenStoreManager) MarkOAuthCompleted ¶
func (m *TokenStoreManager) MarkOAuthCompleted(serverName string)
MarkOAuthCompleted records that OAuth was successfully completed for a server This method is used by CLI processes to notify server processes about OAuth completion
func (*TokenStoreManager) MarkOAuthCompletedWithDB ¶
func (m *TokenStoreManager) MarkOAuthCompletedWithDB(serverName string, storage DatabaseOAuthNotifier) error
MarkOAuthCompletedWithDB records OAuth completion in the database for cross-process notification This is the new preferred method that works across different processes
func (*TokenStoreManager) NotifyTokenSaved ¶
func (m *TokenStoreManager) NotifyTokenSaved(serverName string, expiresAt time.Time)
NotifyTokenSaved triggers the token saved callback if set. Called by PersistentTokenStore.SaveToken() to notify the RefreshManager.
func (*TokenStoreManager) RecordOAuthFailure ¶ added in v0.62.0
func (m *TokenStoreManager) RecordOAuthFailure(serverName string, err error)
RecordOAuthFailure reports an OAuth failure that nobody is waiting on.
func (*TokenStoreManager) SetOAuthCompletionCallback ¶
func (m *TokenStoreManager) SetOAuthCompletionCallback(callback func(serverName string))
SetOAuthCompletionCallback sets a callback function to be called when OAuth completes
func (*TokenStoreManager) SetOAuthFailureCallback ¶ added in v0.62.0
func (m *TokenStoreManager) SetOAuthFailureCallback(callback func(serverName string, err error))
SetOAuthFailureCallback sets a callback invoked when an OAuth flow fails in a place that has no caller to return the error to — a callback that could not be delivered, a state mismatch, or a background token exchange that failed. The upstream manager wires this to the server's connection status so the failure is visible to the operator rather than only in the log (issue #975). Pass nil to clear it.
func (*TokenStoreManager) SetTokenSavedCallback ¶
func (m *TokenStoreManager) SetTokenSavedCallback(callback func(serverName string, expiresAt time.Time))
SetTokenSavedCallback sets a callback function to be called when a token is saved. Used by RefreshManager to reschedule proactive refresh when tokens are updated.