oauth

package
v0.73.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 40 Imported by: 0

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

View Source
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
)
View Source
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.

View Source
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

View Source
const (
	// AuthorizeProbeTimeout bounds the whole probe request.
	AuthorizeProbeTimeout = 5 * time.Second
)
View Source
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

View Source
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

View Source
var (
	// ErrTokenRefreshTransient is returned by a refresher-bound token store when
	// a refresh failed transiently (or is cooling down after such a failure).
	// It is returned instead of the expired token so mcp-go never starts its
	// own, unserialized refresh (Spec 113 FR-005).
	ErrTokenRefreshTransient = errors.New("oauth: token refresh failed transiently")

	// ErrNoClientCredentials means neither the live handler nor the stored
	// record has a client id to refresh with (e.g. the DCR registration was
	// cleared after invalid_client). A refresh is never sent with an empty
	// client_id; the user has to sign in again.
	ErrNoClientCredentials = errors.New("oauth: no client credentials available for token refresh; sign in again")
)
View Source
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.

View Source
var ErrCredentialBindingStale = errors.New("server was removed, replaced or reconfigured; OAuth result discarded")

ErrCredentialBindingStale reports that an OAuth write of an upstream instance was refused because a config commit removed, replaced or re-bound (OAuth config change) the server since the instance was built. Nothing was written; the instance that serves the server now runs its own flow.

View Source
var ErrFlowInProgress = errors.New("OAuth flow already in progress")

ErrFlowInProgress indicates an OAuth flow is already in progress for the server.

View Source
var ErrFlowTimeout = errors.New("timeout waiting for OAuth flow to complete")

ErrFlowTimeout indicates that waiting for an OAuth flow timed out.

View Source
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.

View Source
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.

View Source
var ServerFieldMaskDecisions = map[string]MaskDecision{}/* 114 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

func ArgvFlagKey(flag string) string

ArgvFlagKey turns `--api-key` into the key name the env/header redactors match on.

func AuditMaskValue added in v0.64.0

func AuditMaskValue(v string) string

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 BeforeClearHook added in v0.71.0

func BeforeClearHook(server string, b commitview.CredentialBinding, op string)

BeforeClearHook runs the before-clear seam, for core's own bound clears.

func BeforePersistHook added in v0.71.0

func BeforePersistHook(server string, b commitview.CredentialBinding)

BeforePersistHook runs the before-persist seam, for core's own bound writes (DCR persistence, the stored-credential refresh).

func BeforeRefreshDoHook added in v0.71.0

func BeforeRefreshDoHook(server string, b commitview.CredentialBinding)

BeforeRefreshDoHook runs the before-Do seam, for core's direct refresh.

func BeginManualFlow added in v0.62.0

func BeginManualFlow(serverName string, window time.Duration) (release func())

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 BindRefresher added in v0.71.0

func BindRefresher(store client.TokenStore, b RefreshBinding) bool

BindRefresher binds b to store if the store supports reactive refresh (PersistentTokenStore, or the CLI in-memory store). Binding again replaces the previous binding (reconnects create a new handler). It reports whether the store was bound.

func BuildRFC8414MetadataURLs added in v0.15.0

func BuildRFC8414MetadataURLs(authServerURL string) []string

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

func CheckArgvMaskEcho(field string, incoming, stored []string) error

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

func CheckServerWriteMasks(what string, v interface{}) error

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 ClassifyAuthorizeClientRejection added in v0.71.0

func ClassifyAuthorizeClientRejection(status int, body []byte) (rejected bool, oauthErr, description string)

ClassifyAuthorizeClientRejection decides whether an authorization-endpoint response says the client_id itself is unknown or invalid. It returns the parsed OAuth error code and description alongside the verdict.

Matches (status 400 or 401, OAuth JSON error body):

  • error=invalid_client (never unauthorized_client: that is a policy refusal for a client that exists);
  • error=invalid_request whose error_description names the client(_id) as invalid, unknown, not found, not registered or nonexistent (Cloudflare: "Invalid client_id"), case-insensitively — unless the description is about the redirect_uri or the scope.

func ClearClientIfBound added in v0.71.0

func ClearClientIfBound(db *storage.BoltDB, serverKey, server string, b commitview.CredentialBinding, rec *storage.OAuthTokenRecord) (bool, error)

ClearClientIfBound is clearClientIfBound for core's refresh and login paths.

func ContainsMaskMarker added in v0.64.0

func ContainsMaskMarker(s string) bool

ContainsMaskMarker reports whether a string carries a mask this proxy rendered.

func CorrelationLogger

func CorrelationLogger(ctx context.Context, logger *zap.Logger) *zap.Logger

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

func CorrelationLoggerWithFlow(ctx context.Context, logger *zap.Logger) *zap.Logger

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 CreateOAuthConfigWithEnv added in v0.71.0

func CreateOAuthConfigWithEnv(env Env, serverConfig *config.ServerConfig, storage *storage.BoltDB, logger *zap.Logger) (*client.OAuthConfig, map[string]string, error)

CreateOAuthConfigWithEnv is CreateOAuthConfigWithExtraParamsAndLogger in an upstream instance's environment (Spec 116 PR4, FR-024, FR-024a): the resource auto-detection, the scope and metadata preflights, the discovery cache fetches and the OAuth HTTP client mcp-go uses for registration, code exchange and refresh all run on env.Transport, so a retired instance sends nothing through any of them.

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

  1. Manual extra_params.resource from config (highest priority - preserves backward compatibility)
  2. Auto-detected resource from RFC 9728 Protected Resource Metadata
  3. 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

func DetectOAuthAvailability(baseURL string, timeout time.Duration) bool

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

func DiscoverAuthServerURL(serverURL string, timeout time.Duration) string

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

func DiscoverScopesFromAuthorizationServer(baseURL string, timeout time.Duration) ([]string, error)

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

func ExtractResourceMetadataURL(wwwAuthHeader string) string

ExtractResourceMetadataURL parses WWW-Authenticate header to extract resource_metadata URL Format: Bearer error="invalid_request", resource_metadata="https://..."

Parameters are scanned per RFC 7235 section 2.1: names are case-insensitive, whitespace may surround "=", and quoted values of other parameters are skipped rather than searched, so only a real resource_metadata parameter with a quoted-string value is returned.

func FindMaskMarker added in v0.64.0

func FindMaskMarker(path string, v interface{}) (string, bool)

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

func FindWorkingMetadataURL(serverURL string, timeout time.Duration) (string, error)

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 FlightGeneration added in v0.71.0

func FlightGeneration(ctx context.Context) (string, bool)

FlightGeneration returns the generation of the refresh flight ctx belongs to. A token persisted under such a ctx MUST only be written while the stored record still has that generation (FR-006a).

func GenerateServerKey

func GenerateServerKey(serverName, serverURL string) string

GenerateServerKey creates a unique key for a server by combining name and URL Exported for use by connection.go when persisting DCR credentials

func GenerationMatches added in v0.71.0

func GenerationMatches(rec *storage.OAuthTokenRecord, gen string) bool

GenerationMatches reports whether rec still has the generation gen.

func GetCorrelationID

func GetCorrelationID(ctx context.Context) string

GetCorrelationID retrieves the correlation ID from the context. Returns an empty string if no correlation ID is present.

func GetPersistedRefreshToken

func GetPersistedRefreshToken(serverName, serverURL string, boltStorage *storage.BoltDB) string

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 HasPersistedTokenBound added in v0.71.0

func HasPersistedTokenBound(serverName, serverURL string, boltStorage *storage.BoltDB, b commitview.CredentialBinding) (hasToken bool, hasRefreshToken bool, isExpired bool)

HasPersistedTokenBound is HasPersistedToken for an upstream instance bound to b (Spec 116 PR2b): a record written under another binding is absent.

func InvalidateDiscovery added in v0.71.0

func InvalidateDiscovery(serverURL string)

InvalidateDiscovery drops every cached discovery result for serverURL.

func IsArgvFieldName added in v0.64.0

func IsArgvFieldName(key string) bool

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

func IsArgvFlag(token string) bool

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

func IsConfigReference(v string) bool

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

func IsEnvFieldName(key string) bool

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

func IsHeadersFieldName(key string) bool

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

func IsManualFlowActive(serverName string) bool

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:

  1. OAuth is explicitly configured in config, OR
  2. 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

func IsOAuthError(err string) bool

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

func IsSensitiveHeaderName(name string) bool

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

func IsSensitiveKeyName(name string) bool

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

func LogActualTokenRefreshAttempt(logger *zap.Logger, serverName string, tokenAge time.Duration)

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

func LogClientConnectionAttempt(logger *zap.Logger, attempt int, maxAttempts int)

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

func LogClientConnectionFailure(logger *zap.Logger, attempt int, err error)

LogClientConnectionFailure logs a failed client connection attempt.

func LogClientConnectionSuccess added in v0.16.0

func LogClientConnectionSuccess(logger *zap.Logger, duration time.Duration)

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

func LogOAuthFlowStart(logger *zap.Logger, serverName string, correlationID string)

LogOAuthFlowStart logs the start of an OAuth flow.

func LogOAuthRequest

func LogOAuthRequest(logger *zap.Logger, method, url string, headers http.Header)

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

func LogSafeCallbackQuery(rawQuery string) string

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

func LogSafeErrorText(err error) string

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 LogSafeQueryString added in v0.69.0

func LogSafeQueryString(rawQuery string, knownSecrets ...string) string

LogSafeQueryString is LogSafeURL for a BARE query string — `r.URL.RawQuery`, with no scheme, host or path in front of it.

SEC-01: internal/httpapi's access logger writes `zap.String("query", r.URL.RawQuery)` for every request the router sees, and `?apikey=` is an accepted credential source, so the root admin key was landing at rest in http.log.

It runs the shared name rule (redactRawQueryParams) and then the same value-shaped detector AuditRedaction applies to a whole URL, so a credential under an unrecognised parameter name is still caught. What it deliberately does NOT do is go through url.Parse (codex round 2): a request's query is not required to be parseable as part of a URL — an HTAB is legal inside an HTTP header value, and url.ParseRequestURI leaves a literal '#' in RawQuery — and every parse-dependent path falls back to a regex with no `apikey` rule, which is how the credential got published in the first place.

knownSecrets, when given, are redacted by EXACT VALUE before the name and value-shaped rules run — see redactKnownSecrets. Omit it (or pass "") for the internal recursive uses in this file, which run on a string a caller above has already put through this pass once.

func LogSafeRequestPath added in v0.69.0

func LogSafeRequestPath(path string, knownSecrets ...string) string

LogSafeRequestPath renders a request PATH for a log field.

SEC-01, codex round 6 finding 2. internal/httpapi logs `r.URL.Path` on the access line and on every authentication decision, and a path is as client-controlled as the query beside it, so it had the same shape of exposure LogSafeRequestURL now closes for the Referer.

Capped at entry (SEC-01 second-lens review, PR #1350): logSafeURLComponent splits on '/' and runs the full value-shaped detector per segment, so an uncapped path let a client turn one request into an unbounded number of detector passes. See maxLogSafeRequestBytes.

knownSecrets, when given, are redacted by EXACT VALUE before the path is split into segments — see redactKnownSecrets. This is the fix for the admin key surviving as a bare PATH SEGMENT: it has no `name=` wrapper for the per-segment name rule to key on and, being plain hex, tops out at 4.0 bits/char of Shannon entropy — under the value-shaped detector's 4.5 threshold — so no shape-based rule below this call can ever catch it. internal/httpapi.Server.currentAdminAPIKey is the one caller that passes it, reading the live key fresh on every request.

func LogSafeRequestURL added in v0.69.0

func LogSafeRequestURL(rawURL string, knownSecrets ...string) string

LogSafeRequestURL renders a URL that arrived from an UNTRUSTED client for a log field - a Referer header, most of all. Unlike LogSafeURL it assumes nothing: not that the URL parses, and not that the credential is in the query.

SEC-01, codex rounds 1-4. Every assumption LogSafeURL makes was a way for the admin key to reach http.log verbatim, because a client controls its Referer completely and a 64-character hex key has no vendor shape for the value detector to catch on its own:

  • url.Parse rejects the URL (`http://host/%zz?apikey=<KEY>`, or an HTAB, which is legal inside a header value) and the redactor drops to the regex RedactURL, which has no `apikey` rule at all;
  • the credential sits in the FRAGMENT (`http://host/ui/#?apikey=<KEY>`, or hash routing `#/servers?apikey=<KEY>`), which no URL renderer applies the name rule to;
  • the credential sits in the PATH (`http://host/ui/apikey=<KEY>`), likewise;
  • the parameter NAME is percent-encoded (`api%6bey=<KEY>`), which the free-form scrubber cannot see because it never decodes.

So the URL is taken apart by hand and every piece is redacted in its own right, with no parse anywhere on the path: userinfo first, against the WHOLE raw string, because in a malformed URL either delimiter can fall between the password and its '@' (`https://user:<KEY>?x@`, `https://user:<KEY>#x@`) and leave nothing for the userinfo rule to match; then the fragment, the query, and what is left.

The one thing this does NOT do, which LogSafeURL does, is decode a query parameter whose VALUE is itself a URL (the RFC 8707 `resource` parameter). That is a shape mcpproxy's own authorize URLs have and a browser Referer does not, and buying it back would mean parsing - the one thing an untrusted URL cannot be relied on to survive.

knownSecrets, when given, are redacted by EXACT VALUE against the WHOLE raw string before it is taken apart — see redactKnownSecrets. This is what catches the admin key sitting in the path or fragment of a Referer with no `apikey=` wrapper at all, which none of the piecewise rules above can.

func LogSafeURL added in v0.64.0

func LogSafeURL(rawURL string) string

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 LogTokenRefreshAttempt(logger *zap.Logger, attempt int, maxAttempts int)

Deprecated: Use LogClientConnectionAttempt instead. LogTokenRefreshAttempt is kept for backward compatibility but is misleading.

func LogTokenRefreshFailure deprecated

func LogTokenRefreshFailure(logger *zap.Logger, attempt int, err error)

Deprecated: Use LogClientConnectionFailure instead. LogTokenRefreshFailure is kept for backward compatibility but is misleading.

func LogTokenRefreshSuccess deprecated

func LogTokenRefreshSuccess(logger *zap.Logger, duration time.Duration)

Deprecated: Use LogClientConnectionSuccess instead. LogTokenRefreshSuccess is kept for backward compatibility but is misleading. This is called when client.Start() succeeds, not when a token refresh occurs.

func MaskDetectedSecrets added in v0.64.0

func MaskDetectedSecrets(s string) string

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

func MaskValue(v string) string

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 NewBoundPersistentTokenStore added in v0.71.0

func NewBoundPersistentTokenStore(serverName, serverURL string, storage *storage.BoltDB, b commitview.CredentialBinding) client.TokenStore

NewBoundPersistentTokenStore is the token store of an upstream instance built for the committed credential binding b (Spec 116 PR2b): it serves only records written under b, and its saves and clears land only while the server's row still carries b. A store whose instance a commit removed, replaced or re-bound therefore cannot re-create, reuse or erase the credentials of whatever serves the name now.

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. The store is unbound (see NewBoundPersistentTokenStore); the daemon uses unbound stores only to read.

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 NoteFlightSavedRevision added in v0.71.0

func NoteFlightSavedRevision(ctx context.Context, rev uint64)

NoteFlightSavedRevision is noteFlightSavedRevision for a refresh function that persists outside PersistentTokenStore.SaveToken (core's stored-DCR sub-path, Sol r4 on #1621): every flight persist reports the revision it wrote, so the flight serves that record and never a later rewrite's.

func ParsePinnedRedirectURI added in v0.62.0

func ParsePinnedRedirectURI(rawURI string) (int, error)

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

func RedactEnvValues(env map[string]string) map[string]string

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

func RedactEnvValuesWith(env map[string]string, mask func(string) string) map[string]string

RedactEnvValuesWith is RedactEnvValues with a caller-chosen mask. See RedactStringHeadersWith for why the audit surfaces need a different one.

func RedactHeaders

func RedactHeaders(headers http.Header) map[string]string

RedactHeaders creates a copy of headers with sensitive values redacted. Returns a map suitable for logging.

func RedactSensitiveData

func RedactSensitiveData(data string) string

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

func RedactServerSecretFields(server *contracts.Server)

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

func RedactStringHeaders(headers map[string]string) map[string]string

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

func RedactStringHeadersWith(headers map[string]string, mask func(string) string) map[string]string

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

func RedactURL(urlStr string) string

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

func RedactURLQueryParams(rawURL string) string

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

func RedactURLQueryParamsWith(rawURL string, mask func(string) string) string

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

func RedactUpstreamStats(stats map[string]interface{}, reveal bool) map[string]interface{}

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

func RedactedConfig(cfg *config.Config) *config.Config

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

func RedactedConfigView(key string, v interface{}) map[string]interface{}

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

func RedactedConfigViews[T any](key string, items []*T) []map[string]interface{}

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 ScrubRefreshError added in v0.71.0

func ScrubRefreshError(err error, sent ...string) error

ScrubRefreshError wraps an error from a token-endpoint request so that its message never carries provider-authored text verbatim: mcp-go embeds the RFC 6749 error_description, or the whole non-JSON response body, in the error string, and providers echo request parameters (refresh_token, client_secret) back there. The message is scrubbed with ScrubUpstreamText and capped; the wrapped chain is kept for ClassifyRefreshError. sent lists the credential values the request carried (refresh token, client secret): they are removed verbatim first, since an opaque value echoed without a recognisable key/value shape is invisible to the pattern scrubber.

func ScrubUpstreamText added in v0.64.0

func ScrubUpstreamText(s string) string

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 SentValueSpellings added in v0.71.0

func SentValueSpellings(v string) []string

SentValueSpellings returns the spellings of a credential value that a token endpoint may echo back: raw, JSON-string-escaped and URL-query-escaped. An empty value has none.

func SetBindingTestHooks added in v0.71.0

func SetBindingTestHooks(h BindingTestHooks) (restore func())

SetBindingTestHooks installs h and returns a restore func. Test-only: the hooks are plain variables, so set them before the code under test runs.

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

func StateFingerprint(state string) string

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

func UnmaskEnvValues(incoming, stored map[string]string) map[string]string

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

func UnmaskHeaders(incoming, stored map[string]string) map[string]string

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

func UnmaskLiveEnvValues(incoming, stored map[string]string) map[string]string

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

func UnmaskLiveField(key, incoming, stored string) string

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

func UnmaskLiveHeaders(incoming, stored map[string]string) map[string]string

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 and the Spec 113-b endpoint overrides — 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

func UnmaskLiveURL(incoming, stored string) (string, error)

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:

  1. The whole URL echoed back byte for byte — revert to the stored URL.
  2. 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.
  3. 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

func UnmaskLiveURLParams(incoming, stored string) string

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

func UnmaskURL(incoming, stored string) string

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

func WithCorrelationID(ctx context.Context, id string) context.Context

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 WithLoginClient added in v0.71.0

func WithLoginClient(ctx context.Context, lc LoginClient) context.Context

WithLoginClient marks ctx as a login's code exchange that used lc: a token SaveToken persists under it is stored together with lc in one transaction. An empty lc.ClientID carries no registration and leaves the stored one.

func WrapDiscoveryFailed added in v0.25.0

func WrapDiscoveryFailed(err error) error

WrapDiscoveryFailed attaches MCPX_OAUTH_DISCOVERY_FAILED for failures to fetch the OAuth authorization-server metadata document.

func WrapRefresh403 added in v0.25.0

func WrapRefresh403(err error) error

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

func WrapRefreshExpired(err error) error

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 AuthorizeProbeResult added in v0.71.0

type AuthorizeProbeResult struct {
	// ClientRejected reports that the authorization server identified the
	// client_id itself as unknown or invalid.
	ClientRejected bool
	// StatusCode is the HTTP status of the probe response (0 when Err is set).
	StatusCode int
	// OAuthError and ErrorDescription are the parsed OAuth error fields, when
	// the body was an OAuth JSON error object.
	OAuthError       string
	ErrorDescription string
	// Err is the transport-level failure, if any.
	Err error
}

AuthorizeProbeResult is the outcome of ProbeAuthorizationClient. Only ClientRejected=true is actionable; every other outcome (Err set, 2xx, 3xx, 5xx, an unrelated 4xx, an unparsable body) means "proceed as before".

func ProbeAuthorizationClient added in v0.71.0

func ProbeAuthorizationClient(ctx context.Context, httpClient *http.Client, authURL string) AuthorizeProbeResult

ProbeAuthorizationClient issues one GET to authURL without following redirects (a valid client gets a login/consent page or a redirect; only an invalid client gets a direct 400/401) and classifies the answer with ClassifyAuthorizeClientRejection. httpClient may be nil; its CheckRedirect is always overridden, and AuthorizeProbeTimeout applies unless the client sets a shorter Timeout. No cookies are sent, so no session is touched.

func (AuthorizeProbeResult) Summary added in v0.71.0

func (r AuthorizeProbeResult) Summary() string

Summary renders the server's answer for logs and error messages, e.g. `HTTP 400 invalid_request: Invalid client_id`.

type BindingTestHooks added in v0.71.0

type BindingTestHooks struct {
	BeforePersist   func(server string, b commitview.CredentialBinding)
	BeforeClear     func(server string, b commitview.CredentialBinding, op string)
	BeforeRefreshDo func(server string, b commitview.CredentialBinding)
}

BindingTestHooks are the PR2b test seams, settable from other packages' tests.

type BoundOAuthNotifier added in v0.71.0

type BoundOAuthNotifier interface {
	SaveOAuthCompletionEventIfBound(event *CompletionEvent, binding commitview.CredentialBinding) (bool, error)
}

BoundOAuthNotifier records a completion event bound to the credential binding of the instance that completed the login (Spec 116 PR2b, T055c).

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) EffectiveRedirectURI added in v0.71.0

func (c *CallbackServer) EffectiveRedirectURI() string

EffectiveRedirectURI is the exact URI registered with the provider, which can differ from the private loopback listener behind a reverse proxy.

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) InvalidateState added in v0.72.0

func (c *CallbackServer) InvalidateState(state, reason string)

InvalidateState drops the waiter for a state whose flow cannot finish any more (GH #1722: the instance that owns it was retired while the person was still signing in) and remembers reason, so the browser callback that lands afterwards renders a failure page that says so instead of the generic "unknown or expired state". A state nobody is waiting for is left alone.

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) RemoteCallbackHandler added in v0.71.0

func (m *CallbackServerManager) RemoteCallbackHandler(w http.ResponseWriter, r *http.Request)

RemoteCallbackHandler is mounted outside API-key middleware: an OAuth provider has no API key. The unpredictable, single-use state authenticates the callback, and only explicitly configured remote flows can receive it.

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 Env added in v0.71.0

type Env struct {
	Ctx       context.Context
	Transport http.RoundTripper
	Binding   commitview.CredentialBinding
}

Env is the environment an upstream instance runs its OAuth work in (Spec 116 PR4, FR-024, FR-024a). Transport is the instance's gated transport: every OAuth preflight, resource auto-detection, metadata discovery, cache fetch, dynamic client registration, code exchange and refresh the instance starts goes through it, so none of them reaches the network once the instance is retired. Ctx bounds the resource auto-detection's rate-limit waits, as the caller's context did before.

The zero Env is the process default (http.DefaultTransport, a background context): the exported helpers that run outside an upstream instance (the doctor, the REST diagnostics, the CLI) keep using it.

Binding (Spec 116 PR2b, #1607) is the instance's committed credential binding: the token store, the DCR client lookup and every OAuth clear the config build makes are bound to it, so an instance that a commit removed, replaced or re-bound (OAuth config change) cannot write, reuse or clear the credentials of whatever serves the name now. The zero binding is unbound (the doctor, the REST diagnostics, the standalone CLI).

type LoginClient added in v0.71.0

type LoginClient struct {
	ClientID     string
	ClientSecret string
	CallbackPort int
	RedirectURI  string
}

LoginClient is the client registration a login's code exchange used. A zero CallbackPort or empty RedirectURI keeps the stored value.

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

func ValidateOAuthMetadataWithEnv added in v0.71.0

func ValidateOAuthMetadataWithEnv(env Env, serverURL, serverName string, timeout time.Duration) (*OAuthMetadataValidationResult, error)

ValidateOAuthMetadataWithEnv is ValidateOAuthMetadata on an upstream instance's transport (Spec 116 PR4, FR-024a).

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"`
	// contains filtered or unexported fields
}

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

func (w *OAuthTransportWrapper) RoundTrip(req *http.Request) (*http.Response, error)

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

func (*OAuthTransportWrapper) SetEndpoints added in v0.71.0

func (w *OAuthTransportWrapper) SetEndpoints(ep wrapperEndpoints)

SetEndpoints configures discovery overrides for this wrapper. Call before the wrapper is used by a client.

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. It deletes only the exact record this store last served (its revision) and only while the server's row still carries the store's binding (Spec 116 PR2b, review R6.2, R7.3): the 5xx recovery of an instance a commit superseded, or of an instance whose replacement rewrote the record meanwhile, erases nothing.

func (*PersistentTokenStore) CredentialBinding added in v0.71.0

func (p *PersistentTokenStore) CredentialBinding() commitview.CredentialBinding

CredentialBinding returns the binding the store is bound to (zero when unbound).

func (*PersistentTokenStore) GetToken

func (p *PersistentTokenStore) GetToken(ctx context.Context) (*client.Token, error)

GetToken retrieves the OAuth token from persistent storage

func (*PersistentTokenStore) SaveToken

func (p *PersistentTokenStore) SaveToken(ctx context.Context, token *client.Token) error

SaveToken stores the OAuth token to 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

func (r Redaction) Argv(argv []string) []string

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

func (r Redaction) CapString(s string) string

CapString applies the policy's per-leaf length cap, if any, cutting on a rune boundary and marking the cut.

func (Redaction) CommandString added in v0.70.0

func (r Redaction) CommandString(s string) string

CommandString masks credentials in a human-readable command string for configuration read surfaces. It applies flag-name and value-shape rules without the log-only structural Docker env rule or spawn-specific flag relaxations.

func (Redaction) EnvValue added in v0.64.0

func (r Redaction) EnvValue(name, value string) string

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

func (r Redaction) ExtraParamValue(key, value string) string

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

func (r Redaction) HeaderValue(name, value string) string

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

func (r Redaction) Leaf(key, s string) string

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

func (r Redaction) RedactNested(key string, dst interface{}) bool

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

func (r Redaction) SpawnArgv(argv []string) []string

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

func (r Redaction) SpawnCommandString(s string) string

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

func (r Redaction) URLValue(s string) string

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

func (r Redaction) URLValueDeep(rawURL string) string

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.

func (Redaction) Value added in v0.64.0

func (r Redaction) Value(key string, v interface{}) interface{}

Value walks a generic JSON value (as produced by NormalizeForRedaction), masking every string leaf according to the key that encloses it. `key` is the enclosing field name — pass "" at the root, and for a slice the name of the slice itself.

func (Redaction) WithLimit added in v0.64.0

func (r Redaction) WithLimit(n int) Redaction

WithLimit returns a copy of the policy that caps each string leaf at n bytes.

type RefreshBinding added in v0.71.0

type RefreshBinding struct {
	// Refresh performs the network refresh (handler or stored-DCR sub-path).
	Refresh RefreshFunc
	// StaticClient is true when the client id comes from oauth.client_id.
	StaticClient bool
}

RefreshBinding is what a token store needs to refresh through the RefreshCoordinator on its own (Spec 113 FR-002). It is bound by core once the live mcp-go OAuth handler exists.

type RefreshBindingResolver added in v0.71.0

type RefreshBindingResolver interface {
	CurrentCredentialBinding(serverName string) (commitview.CredentialBinding, bool)
}

RefreshBindingResolver is optionally implemented by the runtime (Spec 116 PR2b): it reports the credential binding of the instance that serves the server now. A reactive flight's terminal outcome is applied to the schedule only when it ran under that binding, so the failure of a flight of an instance a commit removed, replaced or re-bound never marks its replacement as needing sign-in.

type RefreshCoordinator added in v0.71.0

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

RefreshCoordinator serializes refresh flights per server key across the reactive (token store) and proactive (RefreshManager) triggers (Spec 113 FR-001). It is process-wide; see DefaultRefreshCoordinator.

func DefaultRefreshCoordinator added in v0.71.0

func DefaultRefreshCoordinator() *RefreshCoordinator

DefaultRefreshCoordinator returns the process-wide coordinator used by the token stores and core.Client.RefreshOAuthTokenDirect.

func NewRefreshCoordinator added in v0.71.0

func NewRefreshCoordinator() *RefreshCoordinator

NewRefreshCoordinator returns an empty coordinator.

func (*RefreshCoordinator) AnnotateCodeExchangeError added in v0.71.0

func (c *RefreshCoordinator) AnnotateCodeExchangeError(key string, staticClient bool, exchangeClientID string, err error) error

AnnotateCodeExchangeError applies the FR-009 "exactly one re-registration" rule to the login flow's authorization-code exchange: an invalid_client after the registration was cleared, before any successful token response, is reported with an actionable terminal message. exchangeClientID is the client id the exchange used.

func (*RefreshCoordinator) AnnotateCodeExchangeErrorFor added in v0.71.0

func (c *RefreshCoordinator) AnnotateCodeExchangeErrorFor(key string, b commitview.CredentialBinding, staticClient bool, exchangeClientID string, err error) error

AnnotateCodeExchangeErrorFor is AnnotateCodeExchangeError for a login bound to the credential binding b (Spec 116 PR2b).

func (*RefreshCoordinator) Do added in v0.71.0

Do runs at most one refresh flight per key. A caller arriving while a flight is running waits for it and gets the same token or the same error. skipped reports that the flight made no network request (another flight had already rotated the token, or the latch/cooldown answered). A caller whose own ctx ends returns ctx.Err(); the flight continues for the others.

func (*RefreshCoordinator) DoServed added in v0.71.0

DoServed is Do that also returns the revision of the stored record whose token it handed out, as the flight read it (Sol r3 on #1621). A token store guards its later 5xx-recovery clear with that revision: a record a same-binding replacement rewrote after the flight's read, even with the same access token, carries a newer revision and is not erased.

func (*RefreshCoordinator) Forget added in v0.71.0

func (c *RefreshCoordinator) Forget(serverKey string, b commitview.CredentialBinding)

Forget drops the coordinator state of one credential binding of serverKey (Spec 116 PR2b): the removal purge, the OAuth-config clear and a logout call it for the binding they made obsolete, so the map stays bounded by the live bindings plus in-flight stale ones. A flight still running keeps its own state value and finishes for its joiners; its result is recorded on that orphaned value only.

func (*RefreshCoordinator) ForgetServer added in v0.71.0

func (c *RefreshCoordinator) ForgetServer(serverKey string)

ForgetServer drops the coordinator state of every binding of serverKey (a logout, which clears the credential whatever binding wrote it).

func (*RefreshCoordinator) NoteTokenSaved added in v0.71.0

func (c *RefreshCoordinator) NoteTokenSaved(key string)

NoteTokenSaved records a successful token response for key (a login or a refresh): the latch, cooldown and re-registration state are reset.

func (*RefreshCoordinator) NoteTokenSavedFor added in v0.71.0

func (c *RefreshCoordinator) NoteTokenSavedFor(key string, b commitview.CredentialBinding)

NoteTokenSavedFor is NoteTokenSaved for a token saved under the credential binding b (Spec 116 PR2b): only that binding's state is reset.

func (*RefreshCoordinator) SetCompletionHook added in v0.71.0

func (c *RefreshCoordinator) SetCompletionHook(hook func(RefreshOutcome))

SetCompletionHook installs the function called once per flight for a terminal outcome that still applies to the stored record. nil removes it.

type RefreshErrorClass added in v0.71.0

type RefreshErrorClass string

RefreshErrorClass is the structured class of an OAuth refresh failure (Spec 113 FR-007/FR-008). It drives both retry handling and the Prometheus result label.

const (
	// RefreshClassSuccess is the class of a nil error.
	RefreshClassSuccess RefreshErrorClass = "success"
	// RefreshClassInvalidGrant: RFC 6749 §5.2 invalid_grant. Terminal; the user must log in again.
	RefreshClassInvalidGrant RefreshErrorClass = "invalid_grant"
	// RefreshClassInvalidClient: RFC 6749 §5.2 invalid_client. Terminal; see FR-009 for DCR handling.
	RefreshClassInvalidClient RefreshErrorClass = "invalid_client"
	// RefreshClassTerminalOther: unauthorized_client, unsupported_grant_type,
	// invalid_scope, or no usable client credentials. Terminal.
	RefreshClassTerminalOther RefreshErrorClass = "terminal_other"
	// RefreshClassServerError: OAuth server_error/temporarily_unavailable, HTTP 5xx or 429. Transient.
	RefreshClassServerError RefreshErrorClass = "server_error"
	// RefreshClassNetwork: connection/timeout failures. Transient.
	RefreshClassNetwork RefreshErrorClass = "network"
	// RefreshClassServerGone: the server was removed or no longer uses OAuth. Terminal.
	RefreshClassServerGone RefreshErrorClass = "server_gone"
	// RefreshClassOther: anything else. Existing backoff, then the existing give-up.
	RefreshClassOther RefreshErrorClass = "other"
)

func ClassifyRefreshError added in v0.71.0

func ClassifyRefreshError(err error) (RefreshErrorClass, int)

ClassifyRefreshError classifies a refresh error structurally (Spec 113 FR-007): the RFC 6749 §5.2 error code of a transport.OAuthError anywhere in the chain, the HTTP status of a RefreshHTTPError or of mcp-go's fixed non-JSON failure text, then network error types. Substring matching is only the last fallback for non-compliant bodies. The returned status is 0 when it is not recoverable (mcp-go JSON error bodies drop it).

func (RefreshErrorClass) IsTerminal added in v0.71.0

func (c RefreshErrorClass) IsTerminal() bool

IsTerminal reports whether retrying the refresh cannot succeed without user action.

func (RefreshErrorClass) MetricLabel added in v0.71.0

func (c RefreshErrorClass) MetricLabel() string

MetricLabel maps the class onto the oauth refresh metric result label. The pre-Spec-113 values are kept; failed_invalid_client and failed_server_error are new.

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 RefreshFailure added in v0.71.0

type RefreshFailure struct {
	Class   RefreshErrorClass
	Message string
	Err     error
}

RefreshFailure is a refresh error after coordinator handling: it carries the final class (which may differ from the raw error's, e.g. FR-009 messages) and an actionable message for the user.

func (*RefreshFailure) Error added in v0.71.0

func (e *RefreshFailure) Error() string

func (*RefreshFailure) Unwrap added in v0.71.0

func (e *RefreshFailure) Unwrap() error

type RefreshFunc added in v0.71.0

type RefreshFunc func(ctx context.Context, current *storage.OAuthTokenRecord) (*client.Token, error)

RefreshFunc performs one network refresh for the given record and persists the result. It MUST persist through a compare-and-swap against the generation of the record it was given (see FlightGeneration), so a login that superseded the flight is never overwritten (FR-006a).

type RefreshHTTPError added in v0.71.0

type RefreshHTTPError struct {
	Status    int
	OAuthCode string
	Detail    string
}

RefreshHTTPError is the typed error of mcpproxy's own refresh request (the stored-DCR-credentials path). Detail is already scrubbed and capped by the producer; the raw body is never kept.

func (*RefreshHTTPError) Error added in v0.71.0

func (e *RefreshHTTPError) Error() string

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) OnTokenSavedFor added in v0.71.0

func (m *RefreshManager) OnTokenSavedFor(serverName string, expiresAt time.Time, binding commitview.CredentialBinding)

OnTokenSavedFor is OnTokenSaved for a token saved under binding (Spec 116 PR2b): the new schedule carries the binding, so a terminal outcome of another binding's flight never fails it (Sol r1 on #1621).

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 is one of: "success", "failed_network", "failed_invalid_grant", "failed_invalid_client", "failed_server_error", "failed_server_gone", "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 RefreshOutcome added in v0.71.0

type RefreshOutcome struct {
	ServerName string
	Key        string
	// Binding is the flight's credential binding (Spec 116 PR2b): the
	// RefreshManager applies the outcome only while it is the binding of
	// the instance that serves the server now.
	Binding commitview.CredentialBinding
	Trigger RefreshTrigger
	Class   RefreshErrorClass
	Err     error
	// ExpiresAt is the access-token expiry of the record the flight failed
	// on. The RefreshManager only applies the outcome to a schedule built
	// for that token, so a login that replaced the schedule after the
	// flight's last generation check is not failed by it (FR-006a).
	ExpiresAt time.Time
}

RefreshOutcome is passed to the completion hook for a terminal flight outcome whose generation still matches the stored record.

type RefreshRequest added in v0.71.0

type RefreshRequest struct {
	// Key is the server key (GenerateServerKey).
	Key string
	// Binding is the caller's committed credential binding (Spec 116 PR2b,
	// review R7.1). Flights, the terminal latch, the transient cooldown and
	// lastSavedAt are keyed by (Key, Binding): an instance a commit removed,
	// replaced or re-bound never joins its replacement's flight (and gets
	// its token), and the replacement never inherits the old instance's
	// failure, latch or cooldown. Load must be the caller's bound loader.
	Binding commitview.CredentialBinding
	// ServerName is the display name (logs, flow-active checks, hook).
	ServerName string
	// ObservedRefreshToken is the refresh token the caller read. It is only
	// compared, never logged.
	ObservedRefreshToken string
	Trigger              RefreshTrigger
	// Load re-reads the persisted record.
	Load func() (*storage.OAuthTokenRecord, error)
	// Refresh performs the network refresh (one of the two sub-paths).
	Refresh RefreshFunc
	// StaticClient is true when the client id comes from oauth.client_id.
	StaticClient bool
	// ClearClient compare-and-clears the stored DCR registration (FR-009)
	// while the stored client id and refresh token are still the ones the
	// failed request used (FR-006a).
	// nil means there is nothing to clear (e.g. no storage).
	ClearClient func(expectedClientID, expectedRefreshToken string) (bool, error)
	// ClearClientAt, when set, replaces ClearClient (Spec 116 PR2b, review
	// R7.3): it clears the DCR registration of exactly the record the flight
	// read (its revision), bound to Binding.
	ClearClientAt func(rec *storage.OAuthTokenRecord) (bool, error)
}

RefreshRequest describes one caller's request to refresh a server's token.

type RefreshRuntimeOperations

type RefreshRuntimeOperations interface {
	RefreshOAuthToken(serverName string) error
}

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
	// Binding is the credential binding of the instance whose token save
	// built this schedule (Spec 116 PR2b, Sol r1 on #1621); zero when unknown
	// (schedules loaded from storage at startup, unbound stores). A reactive
	// flight's terminal outcome applies only to a schedule of its binding.
	Binding commitview.CredentialBinding
}

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 RefreshTrigger added in v0.71.0

type RefreshTrigger string

RefreshTrigger names what started a refresh flight (Spec 113 FR-011).

const (
	// RefreshTriggerReactive: mcp-go asked the token store for a token that is
	// inside its refresh margin.
	RefreshTriggerReactive RefreshTrigger = "reactive"
	// RefreshTriggerProactive: the RefreshManager's schedule fired.
	RefreshTriggerProactive RefreshTrigger = "proactive"
)

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) HasRecentOAuthCompletionBound added in v0.71.0

func (m *TokenStoreManager) HasRecentOAuthCompletionBound(serverName string, binding commitview.CredentialBinding) bool

HasRecentOAuthCompletionBound is HasRecentOAuthCompletion for an upstream instance bound to binding: a completion recorded for another binding (an old incarnation, or an OAuth epoch a commit superseded) is not recent for it. An unbound reader, or an unbound record (the CLI process), keeps the name-only semantics.

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) MarkOAuthCompletedBound added in v0.71.0

func (m *TokenStoreManager) MarkOAuthCompletedBound(serverName string, binding commitview.CredentialBinding)

MarkOAuthCompletedBound is MarkOAuthCompleted for an upstream instance bound to binding: the recorded completion reads as recent only for readers with the same binding (or unbound readers), never for a same-name replacement.

Review r9: a bound completion of an instance a commit superseded (the resolver reports another binding, or no instance, for the name) records nothing and invokes no completion callback, so it can neither retry nor disconnect a same-name replacement.

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) MarkOAuthCompletedWithDBBound added in v0.71.0

func (m *TokenStoreManager) MarkOAuthCompletedWithDBBound(serverName string, storage BoundOAuthNotifier, binding commitview.CredentialBinding) error

MarkOAuthCompletedWithDBBound is MarkOAuthCompletedWithDB for an upstream instance bound to binding: the event is written only while the server's row still carries the binding, and carries it, so the consumer never retries a replacement for a login an instance the commit superseded completed. A refused write is not an error, and records nothing in memory either: the in-memory recent-completion flag is set (bound to binding) only once the bound DB write landed (review r8), so a superseded instance's login cannot make a replacement skip its automatic OAuth deferral.

func (*TokenStoreManager) NotifyTokenSaved

func (m *TokenStoreManager) NotifyTokenSaved(serverName string, expiresAt time.Time)

NotifyTokenSaved triggers the token saved callback if set, for a token saved without a credential binding.

func (*TokenStoreManager) NotifyTokenSavedFor added in v0.71.0

func (m *TokenStoreManager) NotifyTokenSavedFor(serverName string, expiresAt time.Time, binding commitview.CredentialBinding)

NotifyTokenSavedFor triggers the token saved callback for a token saved under binding. Called by PersistentTokenStore.SaveToken() and the stored-DCR refresh 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) SetCompletionBindingResolver added in v0.71.0

func (m *TokenStoreManager) SetCompletionBindingResolver(resolve func(serverName string) (commitview.CredentialBinding, bool))

SetCompletionBindingResolver sets the resolver of the credential binding of the instance that serves a name now (Spec 116 PR2b review r9). nil keeps the pre-PR2b behaviour: every bound completion is recorded and called back.

func (*TokenStoreManager) SetOAuthCompletionBoundCallback added in v0.71.0

func (m *TokenStoreManager) SetOAuthCompletionBoundCallback(callback func(serverName string, binding commitview.CredentialBinding))

SetOAuthCompletionBoundCallback sets the binding-aware completion callback (Spec 116 PR2b review r9). When set it is called instead of the name-only callback, with the binding of the instance that completed the login (zero for an unbound completion, e.g. the CLI process).

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) SetTokenSavedBoundCallback added in v0.71.0

func (m *TokenStoreManager) SetTokenSavedBoundCallback(callback func(serverName string, expiresAt time.Time, binding commitview.CredentialBinding))

SetTokenSavedBoundCallback sets the binding-aware token saved callback (Spec 116 PR2b). When set it is called instead of the plain callback, with the credential binding the token was saved under (zero when unbound).

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.

Jump to

Keyboard shortcuts

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