diff --git a/core/mcp/clientmanager.go b/core/mcp/clientmanager.go index 1a83693a0b0..05b08610122 100644 --- a/core/mcp/clientmanager.go +++ b/core/mcp/clientmanager.go @@ -600,8 +600,6 @@ func (m *MCPManager) UpdateClient(id string, updatedConfig *schemas.MCPClientCon return fmt.Errorf("auth_type cannot be updated for client %s", id) } - oldName := client.ExecutionConfig.Name - oauthConfigID := client.ExecutionConfig.OauthConfigID if updatedConfig.OauthConfigID != nil { oauthConfigID = updatedConfig.OauthConfigID @@ -638,38 +636,27 @@ func (m *MCPManager) UpdateClient(id string, updatedConfig *schemas.MCPClientCon // Atomically replace the config pointer client.ExecutionConfig = newConfig - // If the client name has changed, update all tool name prefixes in the ToolMap - if oldName != updatedConfig.Name { - oldPrefix := oldName + "-" - newPrefix := updatedConfig.Name + "-" - - // Create a new ToolMap with updated tool names - newToolMap := make(map[string]schemas.ChatTool, len(client.ToolMap)) - for oldToolName, tool := range client.ToolMap { - var newToolName string - if strings.HasPrefix(oldToolName, oldPrefix) { - // Update the tool name by replacing the old prefix with the new prefix - newToolName = newPrefix + strings.TrimPrefix(oldToolName, oldPrefix) - } else { - newToolName = oldToolName - } - - // Update the tool's function name if it's a function tool - if tool.Function != nil { - updatedTool := tool - updatedTool.Function.Name = newToolName - newToolMap[newToolName] = updatedTool - } else { - newToolMap[newToolName] = tool - } + // Rebind ToolMap keys (and inner Function.Name) to the current client name. + newPrefix := updatedConfig.Name + "-" + newToolMap := make(map[string]schemas.ChatTool, len(client.ToolMap)) + for oldToolName, tool := range client.ToolMap { + newToolName := oldToolName + if _, suffix, ok := strings.Cut(oldToolName, "-"); ok { + newToolName = newPrefix + suffix + } + if tool.Function != nil { + fn := *tool.Function + fn.Name = newToolName + tool.Function = &fn } + newToolMap[newToolName] = tool + } - // Replace the old ToolMap with the new one - client.ToolMap = newToolMap + // Replace the old ToolMap with the new one + client.ToolMap = newToolMap - // Also update the client Name field - client.Name = updatedConfig.Name - } + // Also update the client Name field + client.Name = updatedConfig.Name return nil } diff --git a/core/mcp/codemode/starlark/listfiles.go b/core/mcp/codemode/starlark/listfiles.go index 4d6aa73addc..484b0803fdc 100644 --- a/core/mcp/codemode/starlark/listfiles.go +++ b/core/mcp/codemode/starlark/listfiles.go @@ -27,7 +27,9 @@ func (s *StarlarkCodeMode) createListToolFilesTool() schemas.ChatTool { "In code, access tools via: server_name.tool_name(param=value). " + "The server names used in code correspond to the human-readable names shown in this listing. " + "This tool is generic and works with any set of servers connected at runtime. " + - "Always check this tool whenever you are unsure about what tools you have available or if you want to verify available servers and their tools." + "CALL THIS TOOL FIRST whenever the user references a server, tool, capability, or action that is not visible in your current tool list — connected MCP servers and their tools are NOT included in your top-level tool schema, so the only way to discover them is by calling listToolFiles. " + + "Examples that should trigger this tool: user names a server you don't recognize (e.g. 'localserver', 'mydb'), asks 'who am I on X', 'what can X do', 'does X have a tool for Y', or asks you to perform an action and you are unsure whether a matching tool exists. " + + "Do NOT tell the user a server or capability is unavailable until you have called listToolFiles and confirmed it is absent." } else { description = "Returns a tree structure listing all virtual .pyi stub files available for connected MCP servers, organized by individual tool. " + "Each tool has a corresponding file (e.g., servers//.pyi) that contains compact Python signatures for that specific tool. " + @@ -38,7 +40,9 @@ func (s *StarlarkCodeMode) createListToolFilesTool() schemas.ChatTool { "In code, access tools via: server_name.tool_name(param=value). " + "The server names used in code correspond to the human-readable names shown in this listing. " + "This tool is generic and works with any set of servers connected at runtime. " + - "Always check this tool whenever you are unsure about what tools you have available or if you want to verify available servers and their tools." + "CALL THIS TOOL FIRST whenever the user references a server, tool, capability, or action that is not visible in your current tool list — connected MCP servers and their tools are NOT included in your top-level tool schema, so the only way to discover them is by calling listToolFiles. " + + "Examples that should trigger this tool: user names a server you don't recognize (e.g. 'localserver', 'mydb'), asks 'who am I on X', 'what can X do', 'does X have a tool for Y', or asks you to perform an action and you are unsure whether a matching tool exists. " + + "Do NOT tell the user a server or capability is unavailable until you have called listToolFiles and confirmed it is absent." } return schemas.ChatTool{ diff --git a/core/mcp/utils/utils.go b/core/mcp/utils/utils.go index 494838bc1c2..66362965556 100644 --- a/core/mcp/utils/utils.go +++ b/core/mcp/utils/utils.go @@ -10,21 +10,28 @@ import ( // ResolvePerUserOAuthToken looks up the per-user OAuth access token for the given client. // If no token exists yet, it initiates an OAuth flow and returns an MCPUserOAuthRequiredError. +// +// Mode-strict: derives AuthMode from context state +// and looks up exactly one identity column. No fallback chain. func ResolvePerUserOAuthToken(ctx *schemas.BifrostContext, client *schemas.MCPClientState, oauth2Provider schemas.OAuth2Provider) (string, error) { if oauth2Provider == nil { return "", fmt.Errorf("per-user OAuth requires an OAuth2Provider but none is configured") } - virtualKeyID, _ := ctx.Value(schemas.BifrostContextKeyGovernanceVirtualKeyID).(string) - userID, _ := ctx.Value(schemas.BifrostContextKeyUserID).(string) - sessionToken, _ := ctx.Value(schemas.BifrostContextKeyMCPUserSession).(string) + mode := ctx.MCPAuthMode() + identity := identityForMCPAuthMode(ctx, mode) - // Optional X-Bf-User-Id header overrides user identity; if absent, falls back to virtual key - if mcpUserID, _ := ctx.Value(schemas.BifrostContextKeyMCPUserID).(string); mcpUserID != "" { - userID = mcpUserID + if identity == "" { + // No identity column populated for the derived mode. We can neither + // look up an existing token nor mint a flow whose result would be + // findable on subsequent calls, so refuse early with actionable copy. + return "", fmt.Errorf( + "per-user OAuth for %s requires an identity: send a Virtual Key (x-bf-vk), authenticate as a user, or set x-bf-mcp-session-id to any opaque string you'll re-send on subsequent calls", + client.ExecutionConfig.Name, + ) } - accessToken, err := oauth2Provider.GetUserAccessTokenByIdentity(ctx, virtualKeyID, userID, sessionToken, client.ExecutionConfig.ID) + accessToken, err := oauth2Provider.GetUserAccessTokenByMode(ctx, mode, identity, client.ExecutionConfig.ID) // Both sentinels mean "this user must re-authenticate": // - ErrOAuth2TokenNotFound: row missing (never authed, or purged after permanent refresh failure) // - ErrOAuth2TokenExpired: row present but tokens unusable (access expired + no refresh available) @@ -33,15 +40,6 @@ func ResolvePerUserOAuthToken(ctx *schemas.BifrostContext, client *schemas.MCPCl return "", fmt.Errorf("failed to get user access token for MCP server %s: %w", client.ExecutionConfig.Name, err) } if err != nil { - // In LLM gateway mode with no identity, an OAuth flow would produce an orphaned token. - isMCPGateway, _ := ctx.Value(schemas.BifrostContextKeyIsMCPGateway).(bool) - if !isMCPGateway && userID == "" && virtualKeyID == "" { - return "", fmt.Errorf( - "per-user OAuth for %s requires a user identity: include X-Bf-User-Id or a Virtual Key in your request so the token can be linked to you", - client.ExecutionConfig.Name, - ) - } - if client.ExecutionConfig.OauthConfigID == nil || *client.ExecutionConfig.OauthConfigID == "" { return "", fmt.Errorf("per-user OAuth requires an OAuth config but MCP client %s has none", client.ExecutionConfig.Name) } @@ -49,7 +47,7 @@ func ResolvePerUserOAuthToken(ctx *schemas.BifrostContext, client *schemas.MCPCl if redirectURI == "" { return "", fmt.Errorf("per-user OAuth requires a redirect URI but none is available in context") } - flowInitiation, sessionID, flowErr := oauth2Provider.InitiateUserOAuthFlow(ctx, *client.ExecutionConfig.OauthConfigID, client.ExecutionConfig.ID, redirectURI) + flowInitiation, sessionID, flowErr := oauth2Provider.InitiateUserOAuthFlow(ctx, *client.ExecutionConfig.OauthConfigID, client.ExecutionConfig.ID, redirectURI, mode) if flowErr != nil { return "", fmt.Errorf("failed to initiate per-user OAuth flow for %s: %w", client.ExecutionConfig.Name, flowErr) } @@ -58,13 +56,40 @@ func ResolvePerUserOAuthToken(ctx *schemas.BifrostContext, client *schemas.MCPCl MCPClientName: client.ExecutionConfig.Name, AuthorizeURL: flowInitiation.AuthorizeURL, SessionID: sessionID, - Message: fmt.Sprintf("Authentication required for %s. Please visit the authorize URL to connect your account.", client.ExecutionConfig.Name), + // Include the URL in the message itself — plain-text clients + // (curl, basic SDK wrappers) won't parse extra_fields, and a + // "please visit the authorize URL" hint with no URL is + // useless to them. The URL is already exposed on the same + // response via extra_fields.mcp_auth_required.authorize_url, + // so embedding it here doesn't widen the surface. + Message: fmt.Sprintf("Authentication required for %s. Visit %s to connect your account.", client.ExecutionConfig.Name, flowInitiation.AuthorizeURL), } } return accessToken, nil } +// identityForMode returns the identity string to look up by, given the derived +// mode. Mirrors the priority used by ctx.AuthMode(): UserID for user mode, +// resolved VK ID for vk mode, session ID for session mode. +func identityForMCPAuthMode(ctx *schemas.BifrostContext, mode schemas.MCPAuthMode) string { + switch mode { + case schemas.MCPAuthModeUser: + if v, _ := ctx.Value(schemas.BifrostContextKeyUserID).(string); v != "" { + return v + } + case schemas.MCPAuthModeVK: + if v, _ := ctx.Value(schemas.BifrostContextKeyGovernanceVirtualKeyID).(string); v != "" { + return v + } + case schemas.MCPAuthModeSession: + if v, _ := ctx.Value(schemas.BifrostContextKeyMCPSessionID).(string); v != "" { + return v + } + } + return "" +} + // BuildPerUserOAuthHeaders clones the provided headers and adds the Bearer token, // preserving any request-scoped extra headers already present. func BuildPerUserOAuthHeaders(headers http.Header, accessToken string) http.Header { diff --git a/core/schemas/bifrost.go b/core/schemas/bifrost.go index 016800df8c6..06299e3d5be 100644 --- a/core/schemas/bifrost.go +++ b/core/schemas/bifrost.go @@ -164,6 +164,28 @@ const ( // BifrostContextKey is a type for context keys used in Bifrost. type BifrostContextKey string +// MCPAuthMode describes which identity dimension a per-user OAuth row is keyed by. +// It is a derived view of context state at the point of token lookup, never +// stored as a context key. Derived via BifrostContext.MCPAuthMode(). +type MCPAuthMode string + +const ( + // MCPAuthModeUser: identity is a user id populated by an upstream auth + // middleware or plugin. Token rows keyed by user_id. + MCPAuthModeUser MCPAuthMode = "user" + // MCPAuthModeVK: identity is a virtual key. Token rows keyed by vk_id. + MCPAuthModeVK MCPAuthMode = "vk" + // MCPAuthModeSession: identity is a client-issued opaque session ID, asserted + // via the x-bf-mcp-session-id header. Token rows keyed by session_id. + // Used when there's no VK or user; the caller owns the session ID and must + // present it on every subsequent request to use the bound OAuth token. + MCPAuthModeSession MCPAuthMode = "session" + // MCPAuthModeNone: no identity dimension is present on the request (no + // user, no VK, no session header). Lets callers branch on the mode + // without mistaking an unauthenticated request for a session-mode caller. + MCPAuthModeNone MCPAuthMode = "none" +) + // BifrostContextKeyRequestType is a context key for the request type. const ( BifrostContextKeySessionToken BifrostContextKey = "bifrost-session-token" // string (session token for authentication - set by auth middleware) @@ -221,8 +243,7 @@ const ( BifrostContextKeyDeferTraceCompletion BifrostContextKey = "bifrost-defer-trace-completion" // bool (signals trace completion should be deferred for streaming - set by streaming handlers) BifrostContextKeyTraceCompleter BifrostContextKey = "bifrost-trace-completer" // func([]PluginLogEntry) (callback to complete trace after streaming, receives transport plugin logs - set by tracing middleware) BifrostContextKeyAccumulatorID BifrostContextKey = "bifrost-accumulator-id" // string (ID for streaming accumulator lookup - set by tracer for accumulator operations) - BifrostContextKeyMCPUserSession BifrostContextKey = "bifrost-mcp-user-session" // string (per-user OAuth session token, automatically generated by bifrost) - BifrostContextKeyMCPUserID BifrostContextKey = "bifrost-mcp-user-id" // string (per-user OAuth user identifier from X-Bf-User-Id header) + BifrostContextKeyMCPSessionID BifrostContextKey = "bifrost-mcp-session-id" // string (session-mode identity: any opaque value asserted by the caller via x-bf-mcp-session-id; binds the OAuth token row to subsequent /mcp calls when no VK or user is present) BifrostContextKeyOAuthRedirectURI BifrostContextKey = "bifrost-oauth-redirect-uri" // string (OAuth callback URL, e.g. https://host/api/oauth/callback - set by HTTP middleware) BifrostContextKeyIsMCPGateway BifrostContextKey = "bifrost-is-mcp-gateway" // bool (true when request is being handled via the MCP gateway path) BifrostContextKeyHasEmittedMessageDelta BifrostContextKey = "bifrost-has-emitted-message-delta" // bool (tracks whether message_delta was already emitted during streaming - avoids duplicates) diff --git a/core/schemas/context.go b/core/schemas/context.go index 14bcd186430..d69bbd4c801 100644 --- a/core/schemas/context.go +++ b/core/schemas/context.go @@ -299,6 +299,31 @@ func (bc *BifrostContext) Value(key any) any { return bc.parent.Value(key) } +// AuthMode derives the per-user OAuth lookup mode from current context state. +// Priority: UserID > VirtualKey > session. Call this at token-lookup time, not +// in middleware — the governance plugin can inject UserID (via VK→owner +// resolution) after middleware runs, and the mode must reflect that. +// +// Returns MCPAuthModeNone when no identity column is populated (no user, no +// VK, no session header), so callers that branch on the returned mode alone +// cannot mistake an unauthenticated request for a session-mode caller. +// +// VK check uses BifrostContextKeyGovernanceVirtualKeyID (the resolved VK row +// ID) rather than BifrostContextKeyVirtualKey (the raw header value) because +// vk-mode token rows are keyed by the resolved VK ID. +func (bc *BifrostContext) MCPAuthMode() MCPAuthMode { + if userID, ok := bc.Value(BifrostContextKeyUserID).(string); ok && userID != "" { + return MCPAuthModeUser + } + if vkID, ok := bc.Value(BifrostContextKeyGovernanceVirtualKeyID).(string); ok && vkID != "" { + return MCPAuthModeVK + } + if sid, ok := bc.Value(BifrostContextKeyMCPSessionID).(string); ok && sid != "" { + return MCPAuthModeSession + } + return MCPAuthModeNone +} + // SetValue sets a value in the internal userValues map. // For scoped contexts, delegates to the root context via valueDelegate. // This is thread-safe and can be called concurrently. diff --git a/core/schemas/mcp.go b/core/schemas/mcp.go index 2533ee58111..16cdbf1bb74 100644 --- a/core/schemas/mcp.go +++ b/core/schemas/mcp.go @@ -28,7 +28,8 @@ var ( ErrOAuth2RefreshFailed = errors.New("oauth2 token refresh failed") ErrOAuth2NotPerUserSession = errors.New("state does not match a per-user oauth session") ErrOAuth2TokenNotFound = errors.New("per-user oauth token not found for this identity and mcp server") - ErrPerUserOAuthPendingFlowExpired = errors.New("per-user oauth pending flow has expired") + ErrOAuth2FlowNotPending = errors.New("oauth flow is not in pending state") + ErrOAuth2FlowExpired = errors.New("oauth flow has expired") // ErrMCPReconnectNotApplicable signals that the reconnect operation is not // meaningful for this client type — e.g. per-user OAuth clients, where // each user manages their own auth and there is no shared upstream diff --git a/core/schemas/oauth.go b/core/schemas/oauth.go index 7ff3bb93628..c0fa9d0ecdd 100644 --- a/core/schemas/oauth.go +++ b/core/schemas/oauth.go @@ -21,28 +21,32 @@ type OAuth2Provider interface { // Per-user OAuth methods - // GetUserAccessToken retrieves the access token for a per-user OAuth session. - // If the token is expired, it automatically attempts a refresh. - GetUserAccessToken(ctx context.Context, sessionToken string) (string, error) - - // GetUserAccessTokenByIdentity retrieves the upstream access token for a user - // identified by virtualKeyID, userID, or sessionToken (fallback), for a specific - // MCP client. Tokens looked up by identity persist across sessions. - GetUserAccessTokenByIdentity(ctx context.Context, virtualKeyID, userID, sessionToken, mcpClientID string) (string, error) - - // InitiateUserOAuthFlow creates a per-user OAuth session and returns the authorization URL. - // Returns (flow initiation details, session ID for polling, error). - InitiateUserOAuthFlow(ctx context.Context, oauthConfigID string, mcpClientID string, redirectURI string) (*OAuth2FlowInitiation, string, error) + // GetUserAccessTokenByMode retrieves the upstream access token for a single + // identity dimension determined by mode. No fallback chain — exactly one + // identity column is queried. Filters status='active' so orphaned rows never + // satisfy a lookup. identity is the user ID for MCPAuthModeUser, the VK row + // ID for MCPAuthModeVK, and the raw session ID for MCPAuthModeSession. + GetUserAccessTokenByMode(ctx context.Context, mode MCPAuthMode, identity, mcpClientID string) (string, error) + + // InitiateUserOAuthFlow creates or refreshes the per-user OAuth flow row + // for a (mode, identity, mcp_client) binding and returns the auth landing + // URL. flowMode tags the row's flow_mode and decides which identity column + // gets populated from context (UserID for MCPAuthModeUser, the resolved VK + // row ID for MCPAuthModeVK, the session ID for MCPAuthModeSession). For + // MCPAuthModeUser flows where no UserID is available in context yet + // (external MCP client OAuth init), the column is left NULL and stamped + // at completion. Returns (flow initiation details, flow row ID, error). + InitiateUserOAuthFlow(ctx context.Context, oauthConfigID string, mcpClientID string, redirectURI string, flowMode MCPAuthMode) (*OAuth2FlowInitiation, string, error) // CompleteUserOAuthFlow handles the OAuth callback for a per-user flow. - // Returns the session token that the user should send on subsequent requests. + // Returns the SessionID stored on the flow row (populated for session-mode, + // empty otherwise). CompleteUserOAuthFlow(ctx context.Context, state string, code string) (string, error) - // RefreshUserAccessToken refreshes a per-user OAuth access token. - RefreshUserAccessToken(ctx context.Context, sessionToken string) error + // RefreshUserAccessToken refreshes a per-user OAuth access token, looked up + // by the token row's primary-key ID. + RefreshUserAccessToken(ctx context.Context, tokenID string) error - // RevokeUserToken revokes a per-user OAuth token and marks the session as revoked. - RevokeUserToken(ctx context.Context, sessionToken string) error } // OauthConfig represents OAuth client configuration diff --git a/framework/configstore/clientconfig.go b/framework/configstore/clientconfig.go index b2985bee0ca..0f71c910224 100644 --- a/framework/configstore/clientconfig.go +++ b/framework/configstore/clientconfig.go @@ -94,7 +94,6 @@ type ClientConfig struct { WhitelistedRoutes []string `json:"whitelisted_routes,omitempty"` // Routes that bypass auth middleware HideDeletedVirtualKeysInFilters bool `json:"hide_deleted_virtual_keys_in_filters"` // Hide deleted virtual keys from logs/MCP filter data RoutingChainMaxDepth int `json:"routing_chain_max_depth"` // Maximum depth for routing rule chain evaluation (default: 10) - MCPExternalServerURL *schemas.EnvVar `json:"mcp_external_server_url,omitempty"` // Public base URL advertised in OAuth server metadata (.well-known, WWW-Authenticate). Supports env var syntax ("env.MY_VAR") MCPExternalClientURL *schemas.EnvVar `json:"mcp_external_client_url,omitempty"` // Public base URL used as redirect_uri when Bifrost acts as an OAuth client to upstream MCP servers. Supports env var syntax ("env.MY_VAR") ConfigHash string `json:"-"` // Config hash for reconciliation (not serialized) } @@ -346,14 +345,6 @@ func (c *ClientConfig) GenerateClientConfigHash() (string, error) { } } - if c.MCPExternalServerURL.IsSet() { - if c.MCPExternalServerURL.IsFromEnv() { - hash.Write([]byte("externalServerURL:env:" + c.MCPExternalServerURL.EnvVar)) - } else { - hash.Write([]byte("externalServerURL:val:" + c.MCPExternalServerURL.GetValue())) - } - } - if c.MCPExternalClientURL.IsSet() { if c.MCPExternalClientURL.IsFromEnv() { hash.Write([]byte("externalClientURL:env:" + c.MCPExternalClientURL.EnvVar)) @@ -389,9 +380,6 @@ func (c *ClientConfig) GenerateClientConfigHashWithToolManager(tm *schemas.MCPTo // Redacted returns a copy of ClientConfig with any env-backed EnvVar fields masked. func (c *ClientConfig) Redacted() ClientConfig { out := *c - if c.MCPExternalServerURL != nil && c.MCPExternalServerURL.IsFromEnv() { - out.MCPExternalServerURL = c.MCPExternalServerURL.Redacted() - } if c.MCPExternalClientURL != nil && c.MCPExternalClientURL.IsFromEnv() { out.MCPExternalClientURL = c.MCPExternalClientURL.Redacted() } diff --git a/framework/configstore/migrations.go b/framework/configstore/migrations.go index e2efa8acc40..ee025d230f1 100644 --- a/framework/configstore/migrations.go +++ b/framework/configstore/migrations.go @@ -743,6 +743,21 @@ func triggerMigrations(ctx context.Context, db *gorm.DB) error { if err := migrationDropAllowDirectKeysColumnDDL(ctx, db); err != nil { return err } + if err := migrationAddOAuthAuthModeColumns(ctx, db); err != nil { + return err + } + if err := migrationReplaceOauthSessionTokenWithSessionID(ctx, db); err != nil { + return err + } + if err := migrationDropLegacyOAuthServerTables(ctx, db); err != nil { + return err + } + if err := migrationDropNonVKOauthUserRows(ctx, db); err != nil { + return err + } + if err := migrationDropMCPExternalServerURL(ctx, db); err != nil { + return err + } if err := migrationAddTeamCalendarAlignedColumn(ctx, db); err != nil { return err } @@ -764,6 +779,16 @@ func triggerMigrations(ctx context.Context, db *gorm.DB) error { if err := migrationAddClientConfigMetadataColumn(ctx, db); err != nil { return err } + // Runs LAST in this batch — the refresh does tx.Find(&clientConfigs) + // which GORM projects to every column in TableClientConfig, so it has + // to come after every config_client column-add above (otherwise the + // SELECT trips on a yet-to-be-added column on upgraded DBs). The refresh + // no longer gates on the legacy mcp_external_server_url column still + // existing — idempotency is handled by migrator_meta, so ordering + // relative to migrationDropMCPExternalServerURL is unconstrained. + if err := migrationRefreshConfigHashAfterMCPExternalServerURLRemoval(ctx, db); err != nil { + return err + } return nil } @@ -6816,21 +6841,6 @@ func migrationAddPerUserOAuthTables(ctx context.Context, db *gorm.DB) error { Migrate: func(tx *gorm.DB) error { tx = tx.WithContext(ctx) mg := tx.Migrator() - if !mg.HasTable(&tables.TablePerUserOAuthClient{}) { - if err := mg.CreateTable(&tables.TablePerUserOAuthClient{}); err != nil { - return fmt.Errorf("failed to create oauth_per_user_clients table: %w", err) - } - } - if !mg.HasTable(&tables.TablePerUserOAuthSession{}) { - if err := mg.CreateTable(&tables.TablePerUserOAuthSession{}); err != nil { - return fmt.Errorf("failed to create oauth_per_user_sessions table: %w", err) - } - } - if !mg.HasTable(&tables.TablePerUserOAuthCode{}) { - if err := mg.CreateTable(&tables.TablePerUserOAuthCode{}); err != nil { - return fmt.Errorf("failed to create oauth_per_user_codes table: %w", err) - } - } if !mg.HasTable(&tables.TableOauthUserToken{}) { if err := mg.CreateTable(&tables.TableOauthUserToken{}); err != nil { return fmt.Errorf("failed to create oauth_user_tokens table: %w", err) @@ -6841,11 +6851,6 @@ func migrationAddPerUserOAuthTables(ctx context.Context, db *gorm.DB) error { return fmt.Errorf("failed to create oauth_user_sessions table: %w", err) } } - if !mg.HasTable(&tables.TablePerUserOAuthPendingFlow{}) { - if err := mg.CreateTable(&tables.TablePerUserOAuthPendingFlow{}); err != nil { - return fmt.Errorf("failed to create oauth_per_user_pending_flows table: %w", err) - } - } return nil }, @@ -6853,10 +6858,6 @@ func migrationAddPerUserOAuthTables(ctx context.Context, db *gorm.DB) error { tx = tx.WithContext(ctx) mg := tx.Migrator() for _, table := range []any{ - &tables.TablePerUserOAuthPendingFlow{}, - &tables.TablePerUserOAuthCode{}, - &tables.TablePerUserOAuthSession{}, - &tables.TablePerUserOAuthClient{}, &tables.TableOauthUserToken{}, &tables.TableOauthUserSession{}, } { @@ -7532,8 +7533,14 @@ func migrationSplitMCPExternalBaseURL(ctx context.Context, db *gorm.DB) error { Migrate: func(tx *gorm.DB) error { tx = tx.WithContext(ctx) mg := tx.Migrator() + // Use raw SQL — MCPExternalServerURL was removed from + // TableClientConfig in a later refactor, so mg.AddColumn (which + // looks up the column type from the struct tag) can no longer + // find the field on a fresh upgrade. Existing deployments that + // already ran this migration take the fast no-op path via + // HasColumn. if !mg.HasColumn(&tables.TableClientConfig{}, "mcp_external_server_url") { - if err := mg.AddColumn(&tables.TableClientConfig{}, "MCPExternalServerURL"); err != nil { + if err := tx.Exec("ALTER TABLE config_client ADD COLUMN mcp_external_server_url VARCHAR(512)").Error; err != nil { return fmt.Errorf("failed to add mcp_external_server_url column: %w", err) } } @@ -7681,6 +7688,619 @@ func migrationUniqueTeamNames(ctx context.Context, db *gorm.DB) error { }) } +// migrationAddOAuthAuthModeColumns adds the AuthMode/Status/FlowMode discriminator +// columns to the per-user OAuth tables, backfills them from existing identity +// column population, drops the legacy non-unique composite indexes on +// oauth_user_tokens, and creates partial unique indexes (one per identity +// dimension). +func migrationAddOAuthAuthModeColumns(ctx context.Context, db *gorm.DB) error { + return RunSingleMigration(ctx, db, &migrator.Migration{ + ID: "add_oauth_auth_mode_columns", + Migrate: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + mg := tx.Migrator() + + // 1) oauth_user_tokens: add status + auth_mode + if mg.HasTable(&tables.TableOauthUserToken{}) { + if !mg.HasColumn(&tables.TableOauthUserToken{}, "status") { + if err := mg.AddColumn(&tables.TableOauthUserToken{}, "Status"); err != nil { + return fmt.Errorf("add status to oauth_user_tokens: %w", err) + } + } + if !mg.HasColumn(&tables.TableOauthUserToken{}, "auth_mode") { + // Add as nullable first — mg.AddColumn would derive + // NOT NULL from the struct tag and fail on tables with + // existing rows. The backfill below populates every + // row, then we tighten to NOT NULL on Postgres. + if err := tx.Exec(`ALTER TABLE oauth_user_tokens ADD COLUMN auth_mode VARCHAR(20)`).Error; err != nil { + return fmt.Errorf("add auth_mode to oauth_user_tokens: %w", err) + } + } + // Backfill auth_mode from whichever identity column is populated. + // Priority: user_id > virtual_key_id > session column. The session + // column was renamed in a later migration (session_token_hash → + // session_id), so the SQL has to adapt: a fresh DB starts on the + // new schema and never had session_token_hash; an existing DB + // hasn't been through the rename yet and still has it. + sessionCol := "" + switch { + case mg.HasColumn(&tables.TableOauthUserToken{}, "session_token_hash"): + sessionCol = "session_token_hash" + case mg.HasColumn(&tables.TableOauthUserToken{}, "session_id"): + sessionCol = "session_id" + } + var backfillSQL string + // Priority is vk → user → session. vk wins over user so that a + // legacy row carrying both identity columns survives as a + // vk-mode binding through migrationDropNonVKOauthUserRows, + // which is the binding type this refactor is meant to keep. + if sessionCol != "" { + backfillSQL = ` + UPDATE oauth_user_tokens + SET auth_mode = CASE + WHEN virtual_key_id IS NOT NULL AND virtual_key_id != '' THEN 'vk' + WHEN user_id IS NOT NULL AND user_id != '' THEN 'user' + WHEN ` + sessionCol + ` IS NOT NULL AND ` + sessionCol + ` != '' THEN 'session' + ELSE NULL + END + ` + } else { + backfillSQL = ` + UPDATE oauth_user_tokens + SET auth_mode = CASE + WHEN virtual_key_id IS NOT NULL AND virtual_key_id != '' THEN 'vk' + WHEN user_id IS NOT NULL AND user_id != '' THEN 'user' + ELSE NULL + END + ` + } + if err := tx.Exec(backfillSQL).Error; err != nil { + return fmt.Errorf("backfill oauth_user_tokens.auth_mode: %w", err) + } + // Identity-less rows can't satisfy any (mode, identity, mcp_client) + // lookup, so they're dead data. Drop them now — leaving them as + // 'vk' would let them sneak past migrationDropNonVKOauthUserRows + // later in the chain and pollute the sessions UI. + if err := tx.Exec(`DELETE FROM oauth_user_tokens WHERE auth_mode IS NULL`).Error; err != nil { + return fmt.Errorf("delete identity-less oauth_user_tokens rows: %w", err) + } + // Tighten the constraint on Postgres now that every row has + // a value. SQLite doesn't support ALTER COLUMN SET NOT NULL; + // app-level validation (BeforeSave) enforces non-empty + // AuthMode there instead. + if tx.Dialector.Name() == "postgres" { + if err := tx.Exec(`ALTER TABLE oauth_user_tokens ALTER COLUMN auth_mode SET NOT NULL`).Error; err != nil { + return fmt.Errorf("set oauth_user_tokens.auth_mode NOT NULL: %w", err) + } + } + // Ensure status is populated for legacy rows. + if err := tx.Exec(`UPDATE oauth_user_tokens SET status = 'active' WHERE status IS NULL OR status = ''`).Error; err != nil { + return fmt.Errorf("backfill oauth_user_tokens.status: %w", err) + } + + // Drop legacy non-unique composite indexes. Replaced by partial unique indexes below. + if mg.HasIndex(&tables.TableOauthUserToken{}, "idx_vk_mcp") { + if err := mg.DropIndex(&tables.TableOauthUserToken{}, "idx_vk_mcp"); err != nil { + return fmt.Errorf("drop idx_vk_mcp: %w", err) + } + } + if mg.HasIndex(&tables.TableOauthUserToken{}, "idx_user_mcp") { + if err := mg.DropIndex(&tables.TableOauthUserToken{}, "idx_user_mcp"); err != nil { + return fmt.Errorf("drop idx_user_mcp: %w", err) + } + } + + // Dedupe legacy bindings before flipping the indexes to UNIQUE. + // idx_user_mcp / idx_vk_mcp were non-unique up to this migration, + // and the OAuth-server consent flow we ripped out could write + // multiple rows for the same (identity, mcp_client_id). Without + // this pass the CREATE UNIQUE INDEX below would abort on the + // first duplicate. Keep the newest row per group (highest + // updated_at, breaking ties on id) so the live credential + // survives and stale duplicates are deleted. + dedupeStmts := []string{ + `DELETE FROM oauth_user_tokens + WHERE id IN ( + SELECT id FROM ( + SELECT id, + ROW_NUMBER() OVER ( + PARTITION BY user_id, mcp_client_id + ORDER BY updated_at DESC, id DESC + ) AS rn + FROM oauth_user_tokens + WHERE auth_mode = 'user' AND user_id IS NOT NULL AND user_id != '' + ) ranked + WHERE rn > 1 + )`, + `DELETE FROM oauth_user_tokens + WHERE id IN ( + SELECT id FROM ( + SELECT id, + ROW_NUMBER() OVER ( + PARTITION BY virtual_key_id, mcp_client_id + ORDER BY updated_at DESC, id DESC + ) AS rn + FROM oauth_user_tokens + WHERE auth_mode = 'vk' AND virtual_key_id IS NOT NULL AND virtual_key_id != '' + ) ranked + WHERE rn > 1 + )`, + } + if sessionCol != "" { + dedupeStmts = append(dedupeStmts, + `DELETE FROM oauth_user_tokens + WHERE id IN ( + SELECT id FROM ( + SELECT id, + ROW_NUMBER() OVER ( + PARTITION BY `+sessionCol+`, mcp_client_id + ORDER BY updated_at DESC, id DESC + ) AS rn + FROM oauth_user_tokens + WHERE auth_mode = 'session' AND `+sessionCol+` IS NOT NULL AND `+sessionCol+` != '' + ) ranked + WHERE rn > 1 + )`, + ) + } + for _, stmt := range dedupeStmts { + if err := tx.Exec(stmt).Error; err != nil { + return fmt.Errorf("dedupe legacy oauth_user_tokens bindings: %w", err) + } + } + + // Partial unique indexes (one per identity dimension), each + // scoped by auth_mode to match the dedupe pass above. Without + // the auth_mode predicate, a legacy row that carries both + // (e.g.) user_id and virtual_key_id would participate in two + // uniqueness domains and could collide with rows that own a + // different mode. Both Postgres and SQLite (3.8+) support + // WHERE on indexes. Use whichever session column exists + // (legacy session_token_hash vs renamed session_id); + // migrationReplaceOauthSessionTokenWithSessionID later drops + + // recreates the session index on session_id anyway. + partialUniques := []string{ + `CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_user_tokens_user_mcp + ON oauth_user_tokens (user_id, mcp_client_id) + WHERE auth_mode = 'user' AND user_id IS NOT NULL AND user_id != ''`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_user_tokens_vk_mcp + ON oauth_user_tokens (virtual_key_id, mcp_client_id) + WHERE auth_mode = 'vk' AND virtual_key_id IS NOT NULL AND virtual_key_id != ''`, + } + if sessionCol != "" { + partialUniques = append(partialUniques, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_user_tokens_session_mcp + ON oauth_user_tokens (`+sessionCol+`, mcp_client_id) + WHERE auth_mode = 'session' AND `+sessionCol+` IS NOT NULL AND `+sessionCol+` != ''`, + ) + } + for _, stmt := range partialUniques { + if err := tx.Exec(stmt).Error; err != nil { + return fmt.Errorf("create partial unique index on oauth_user_tokens: %w", err) + } + } + + // Partial index on orphaned rows to keep the sessions-tab "orphaned" query cheap. + if err := tx.Exec(` + CREATE INDEX IF NOT EXISTS idx_oauth_user_tokens_orphaned + ON oauth_user_tokens (status) + WHERE status = 'orphaned' + `).Error; err != nil { + return fmt.Errorf("create orphaned-status index: %w", err) + } + } + + // 2) oauth_user_sessions: add flow_mode + if mg.HasTable(&tables.TableOauthUserSession{}) { + if !mg.HasColumn(&tables.TableOauthUserSession{}, "flow_mode") { + if err := mg.AddColumn(&tables.TableOauthUserSession{}, "FlowMode"); err != nil { + return fmt.Errorf("add flow_mode to oauth_user_sessions: %w", err) + } + } + // Same vk → user precedence as the token backfill above so + // migrationDropNonVKOauthUserRows preserves dual-identity rows. + if err := tx.Exec(` + UPDATE oauth_user_sessions + SET flow_mode = CASE + WHEN virtual_key_id IS NOT NULL AND virtual_key_id != '' THEN 'vk' + WHEN user_id IS NOT NULL AND user_id != '' THEN 'user' + ELSE 'none' + END + `).Error; err != nil { + return fmt.Errorf("backfill oauth_user_sessions.flow_mode: %w", err) + } + } + + return nil + }, + Rollback: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + mg := tx.Migrator() + + // Drop partial unique + orphan indexes. + for _, name := range []string{ + "idx_oauth_user_tokens_user_mcp", + "idx_oauth_user_tokens_vk_mcp", + "idx_oauth_user_tokens_session_mcp", + "idx_oauth_user_tokens_orphaned", + } { + if err := tx.Exec("DROP INDEX IF EXISTS " + name).Error; err != nil { + return fmt.Errorf("drop %s: %w", name, err) + } + } + + // Restore legacy composite non-unique indexes. + if mg.HasTable(&tables.TableOauthUserToken{}) { + if err := tx.Exec(`CREATE INDEX IF NOT EXISTS idx_vk_mcp ON oauth_user_tokens (virtual_key_id, mcp_client_id)`).Error; err != nil { + return fmt.Errorf("restore idx_vk_mcp: %w", err) + } + if err := tx.Exec(`CREATE INDEX IF NOT EXISTS idx_user_mcp ON oauth_user_tokens (user_id, mcp_client_id)`).Error; err != nil { + return fmt.Errorf("restore idx_user_mcp: %w", err) + } + if mg.HasColumn(&tables.TableOauthUserToken{}, "status") { + _ = mg.DropColumn(&tables.TableOauthUserToken{}, "Status") + } + if mg.HasColumn(&tables.TableOauthUserToken{}, "auth_mode") { + _ = mg.DropColumn(&tables.TableOauthUserToken{}, "AuthMode") + } + } + if mg.HasTable(&tables.TableOauthUserSession{}) && mg.HasColumn(&tables.TableOauthUserSession{}, "flow_mode") { + _ = mg.DropColumn(&tables.TableOauthUserSession{}, "FlowMode") + } + + return nil + }, + }) +} + +// migrationReplaceOauthSessionTokenWithSessionID switches both +// oauth_user_sessions and oauth_user_tokens from the legacy SessionToken + +// SessionTokenHash pair (server-issued bearer credential, SHA-256 hashed for +// the lookup column) to a single plaintext SessionID column. +// +// Why the change: session-mode identity is now caller-asserted via the +// x-bf-mcp-session-id header (same trust model as a VK value). It's no longer +// a Bifrost-issued bearer token, so hashing buys nothing and the unique index +// on session_token_hash was conflating "uniqueness of token value" with +// "uniqueness of binding" — the latter is now enforced at the application +// layer by the (mode, identity, mcp_client_id) lookup in +// InitiateUserOAuthFlow and CreateOauthUserToken. +// +// Order: add SessionID first, then drop the legacy columns + their indexes. +// No data backfill: existing rows are dev-only test data; production hasn't +// landed yet. +func migrationReplaceOauthSessionTokenWithSessionID(ctx context.Context, db *gorm.DB) error { + return RunSingleMigration(ctx, db, &migrator.Migration{ + ID: "replace_oauth_session_token_with_session_id", + Migrate: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + mg := tx.Migrator() + + // 1) oauth_user_sessions: add session_id, drop legacy columns + index. + if mg.HasTable(&tables.TableOauthUserSession{}) { + if !mg.HasColumn(&tables.TableOauthUserSession{}, "session_id") { + if err := mg.AddColumn(&tables.TableOauthUserSession{}, "SessionID"); err != nil { + return fmt.Errorf("add session_id to oauth_user_sessions: %w", err) + } + } + // The legacy session_token_hash column had a uniqueIndex declared + // via gorm tag; GORM names it something like + // "idx_oauth_user_sessions_session_token_hash". DROP COLUMN drops + // the dependent index on Postgres/SQLite, but be explicit on + // Postgres for safety. + if err := tx.Exec("DROP INDEX IF EXISTS idx_oauth_user_sessions_session_token_hash").Error; err != nil { + return fmt.Errorf("drop legacy session_token_hash index on oauth_user_sessions: %w", err) + } + if mg.HasColumn(&tables.TableOauthUserSession{}, "session_token_hash") { + if err := mg.DropColumn(&tables.TableOauthUserSession{}, "session_token_hash"); err != nil { + return fmt.Errorf("drop session_token_hash from oauth_user_sessions: %w", err) + } + } + if mg.HasColumn(&tables.TableOauthUserSession{}, "session_token") { + if err := mg.DropColumn(&tables.TableOauthUserSession{}, "session_token"); err != nil { + return fmt.Errorf("drop session_token from oauth_user_sessions: %w", err) + } + } + } + + // 2) oauth_user_tokens: same dance plus drop the partial unique index + // idx_oauth_user_tokens_session_mcp created by the prior migration — + // its key column (session_token_hash) is being removed. + if mg.HasTable(&tables.TableOauthUserToken{}) { + if !mg.HasColumn(&tables.TableOauthUserToken{}, "session_id") { + if err := mg.AddColumn(&tables.TableOauthUserToken{}, "SessionID"); err != nil { + return fmt.Errorf("add session_id to oauth_user_tokens: %w", err) + } + } + if err := tx.Exec("DROP INDEX IF EXISTS idx_oauth_user_tokens_session_mcp").Error; err != nil { + return fmt.Errorf("drop legacy idx_oauth_user_tokens_session_mcp: %w", err) + } + if err := tx.Exec("DROP INDEX IF EXISTS idx_oauth_user_tokens_session_token_hash").Error; err != nil { + return fmt.Errorf("drop legacy session_token_hash index on oauth_user_tokens: %w", err) + } + if mg.HasColumn(&tables.TableOauthUserToken{}, "session_token_hash") { + if err := mg.DropColumn(&tables.TableOauthUserToken{}, "session_token_hash"); err != nil { + return fmt.Errorf("drop session_token_hash from oauth_user_tokens: %w", err) + } + } + if mg.HasColumn(&tables.TableOauthUserToken{}, "session_token") { + if err := mg.DropColumn(&tables.TableOauthUserToken{}, "session_token"); err != nil { + return fmt.Errorf("drop session_token from oauth_user_tokens: %w", err) + } + } + + // Replace the partial unique index with one keyed on the new + // column. Scope by auth_mode = 'session' to match the + // mode-scoped uniqueness set up for user / vk in + // migrationAddOAuthAuthModeColumns; without it, a row that + // carries both session_id and another identity column could + // participate in two uniqueness domains. + if err := tx.Exec(` + CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_user_tokens_session_mcp + ON oauth_user_tokens (session_id, mcp_client_id) + WHERE auth_mode = 'session' AND session_id IS NOT NULL AND session_id != '' + `).Error; err != nil { + return fmt.Errorf("create idx_oauth_user_tokens_session_mcp on session_id: %w", err) + } + } + + return nil + }, + Rollback: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + mg := tx.Migrator() + + // Drop the new partial unique index keyed on session_id. + if err := tx.Exec("DROP INDEX IF EXISTS idx_oauth_user_tokens_session_mcp").Error; err != nil { + return fmt.Errorf("drop idx_oauth_user_tokens_session_mcp: %w", err) + } + + // Re-add legacy columns via raw DDL. The typed struct fields no + // longer exist, so we can't use mg.AddColumn. Best-effort + // schema-only rollback; original session tokens are gone, so + // callers depending on this data would need their own recovery. + for _, tableName := range []string{"oauth_user_sessions", "oauth_user_tokens"} { + if err := tx.Exec(fmt.Sprintf("ALTER TABLE %s ADD COLUMN session_token VARCHAR(255)", tableName)).Error; err != nil { + // Ignore "column already exists" / dialect quirks. + _ = err + } + if err := tx.Exec(fmt.Sprintf("ALTER TABLE %s ADD COLUMN session_token_hash VARCHAR(64)", tableName)).Error; err != nil { + _ = err + } + } + for _, model := range []interface{}{&tables.TableOauthUserSession{}, &tables.TableOauthUserToken{}} { + if mg.HasTable(model) && mg.HasColumn(model, "session_id") { + _ = mg.DropColumn(model, "SessionID") + } + } + + return nil + }, + }) +} + +// migrationDropLegacyOAuthServerTables drops the four tables that backed the +// MCP-gateway-OAuth-server flow (Bifrost acting as an OAuth Authorization +// Server to upstream MCP clients), plus the gateway_session_id column on +// oauth_user_sessions that linked them. Bifrost is now strictly an OAuth +// *client* to upstream providers; the server-side flow was replaced by the +// x-bf-mcp-session-id header model (see migrationReplaceOauthSessionTokenWithSessionID). +// +// Tables removed: +// - oauth_per_user_clients (dynamic client registration) +// - oauth_per_user_sessions (Bifrost-issued bearer tokens for MCP clients) +// - oauth_per_user_codes (authorization codes) +// - oauth_per_user_pending_flows (in-flight consent state) +// +// No data preservation needed: the flow that wrote these rows no longer exists +// in the code, so any rows present are orphans referring to a removed code path. +// Rollback recreates the tables empty (best-effort schema-only; original data +// is gone). +func migrationDropLegacyOAuthServerTables(ctx context.Context, db *gorm.DB) error { + return RunSingleMigration(ctx, db, &migrator.Migration{ + ID: "drop_legacy_oauth_server_tables", + Migrate: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + + // Drop the gateway_session_id column on oauth_user_sessions first, + // since the table dropped below (oauth_per_user_sessions) was its + // logical pairing. DROP COLUMN with IF EXISTS is supported by + // Postgres but not SQLite — fall back to checking via Migrator. + mg := tx.Migrator() + if mg.HasTable("oauth_user_sessions") && mg.HasColumn("oauth_user_sessions", "gateway_session_id") { + if err := tx.Exec("ALTER TABLE oauth_user_sessions DROP COLUMN gateway_session_id").Error; err != nil { + return fmt.Errorf("drop gateway_session_id from oauth_user_sessions: %w", err) + } + } + + for _, table := range []string{ + "oauth_per_user_codes", + "oauth_per_user_pending_flows", + "oauth_per_user_sessions", + "oauth_per_user_clients", + } { + if err := tx.Exec("DROP TABLE IF EXISTS " + table).Error; err != nil { + return fmt.Errorf("drop %s: %w", table, err) + } + } + return nil + }, + Rollback: func(tx *gorm.DB) error { + // Irreversible. The four oauth_per_user_* tables backed the + // Bifrost-as-OAuth-server flow; their original schemas (dynamic + // client metadata, hashed bearer tokens, authorization codes, + // PKCE state) cannot be reconstructed from the live oauth_user_* + // tables. A "best-effort" stub Rollback that re-creates empty + // tables with just an id column would let downgrades report + // success against a schema the pre-refactor code path cannot use, + // and the application would then fail on first access. Fail loud + // instead so the operator knows a true rollback requires a backup + // restore. + return fmt.Errorf("drop_legacy_oauth_server_tables is irreversible: restore from backup to recover the pre-refactor schema") + }, + }) +} + +// migrationDropNonVKOauthUserRows hard-deletes user-mode and session-mode rows +// from oauth_user_tokens and oauth_user_sessions. Only vk-mode rows survive the +// refactor: their (virtual_key, mcp_client) binding is stable across the change. +// User-mode and session-mode semantics changed when Bifrost stopped acting as +// an OAuth server (see migrationDropLegacyOAuthServerTables); the prior rows +// are stale credentials that wouldn't satisfy a lookup under the new flow. +// Affected users / clients re-authenticate fresh — the alternative is carrying +// forward dead state that surfaces in the sessions UI but can never refresh. +func migrationDropNonVKOauthUserRows(ctx context.Context, db *gorm.DB) error { + return RunSingleMigration(ctx, db, &migrator.Migration{ + ID: "drop_non_vk_oauth_user_rows", + Migrate: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + mg := tx.Migrator() + // `!= 'vk'` alone doesn't match NULL in SQL three-valued logic. + // Rolling-upgrade writes from older replicas, or any row that + // somehow slipped past the auth_mode/flow_mode backfill, could + // still carry a NULL discriminator — explicitly include those so + // stale user/session state can't survive the cleanup. + if mg.HasTable("oauth_user_tokens") { + if err := tx.Exec("DELETE FROM oauth_user_tokens WHERE auth_mode IS NULL OR auth_mode != 'vk'").Error; err != nil { + return fmt.Errorf("delete non-vk oauth_user_tokens: %w", err) + } + } + if mg.HasTable("oauth_user_sessions") { + if err := tx.Exec("DELETE FROM oauth_user_sessions WHERE flow_mode IS NULL OR flow_mode != 'vk'").Error; err != nil { + return fmt.Errorf("delete non-vk oauth_user_sessions: %w", err) + } + } + return nil + }, + Rollback: func(tx *gorm.DB) error { + // No-op: the dropped rows are unrecoverable. Users on user/session + // modes re-authenticate after rollback the same way they would + // after the forward migration. + return nil + }, + }) +} + +// migrationDropMCPExternalServerURL drops the mcp_external_server_url column +// from config_client. This URL was used to advertise Bifrost as an OAuth +// authorization server (.well-known endpoints, WWW-Authenticate header on +// /mcp). Bifrost no longer acts as an OAuth server (see +// migrationDropLegacyOAuthServerTables), so the column is dead. +// +// Hash recompute is handled separately by +// migrationRefreshConfigHashAfterMCPExternalServerURLRemoval so this migration +// holds the AccessExclusiveLock only for the brief catalog update. +// +// The companion mcp_external_client_url column is retained — it's still used +// as the redirect_uri base when Bifrost acts as an OAuth *client* to upstream +// MCP servers. +func migrationDropMCPExternalServerURL(ctx context.Context, db *gorm.DB) error { + return RunSingleMigration(ctx, db, &migrator.Migration{ + ID: "drop_mcp_external_server_url_column", + Migrate: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + mg := tx.Migrator() + if mg.HasTable("config_client") && mg.HasColumn("config_client", "mcp_external_server_url") { + if err := tx.Exec("ALTER TABLE config_client DROP COLUMN mcp_external_server_url").Error; err != nil { + return fmt.Errorf("drop mcp_external_server_url from config_client: %w", err) + } + } + return nil + }, + Rollback: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + // Best-effort: re-add the column (empty values; no data to restore). + _ = tx.Exec("ALTER TABLE config_client ADD COLUMN mcp_external_server_url VARCHAR(512)").Error + return nil + }, + }) +} + +// migrationRefreshConfigHashAfterMCPExternalServerURLRemoval recomputes +// config_hash for every config_client row after MCPExternalServerURL was +// removed from GenerateClientConfigHash. Without this refresh, every stored +// hash that was computed while the field was still mixed in would mismatch +// on first startup and trigger spurious config-reload cycles. +// +// The actual DROP COLUMN is handled by migrationDropMCPExternalServerURL so +// that the DDL (AccessExclusiveLock) never shares a transaction with the +// SELECT + UPDATE on the same table — that combination was observed to lock +// config_client indefinitely on contended Postgres instances. See the same +// split for migrationDropAllowDirectKeysColumn. +func migrationRefreshConfigHashAfterMCPExternalServerURLRemoval(ctx context.Context, db *gorm.DB) error { + return RunSingleMigration(ctx, db, &migrator.Migration{ + ID: "refresh_config_hash_after_mcp_external_server_url_removal", + Migrate: func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + mg := tx.Migrator() + if !mg.HasTable("config_client") { + return nil + } + // Unconditional recompute — don't gate on the legacy column still + // existing. The migrator framework's migrator_meta tracking + // ensures this runs exactly once per DB, so re-stamping the same + // hash on a fresh DB (where there's nothing to fix) is harmless. + // Gating on the legacy column would make ordering brittle: any + // reordering that drops the column before this runs would silently + // turn the refresh into a no-op and leave stale hashes behind. + var clientConfigs []tables.TableClientConfig + if err := tx.Find(&clientConfigs).Error; err != nil { + return fmt.Errorf("fetch client configs for hash recompute: %w", err) + } + for _, cc := range clientConfigs { + if cc.ConfigHash == "" { + continue + } + clientConfig := ClientConfig{ + DropExcessRequests: cc.DropExcessRequests, + InitialPoolSize: cc.InitialPoolSize, + PrometheusLabels: cc.PrometheusLabels, + EnableLogging: cc.EnableLogging, + DisableContentLogging: cc.DisableContentLogging, + AllowPerRequestContentStorageOverride: cc.AllowPerRequestContentStorageOverride, + AllowPerRequestRawOverride: cc.AllowPerRequestRawOverride, + DisableDBPingsInHealth: cc.DisableDBPingsInHealth, + LogRetentionDays: cc.LogRetentionDays, + EnforceAuthOnInference: cc.EnforceAuthOnInference, + AllowedOrigins: cc.AllowedOrigins, + AllowedHeaders: cc.AllowedHeaders, + MaxRequestBodySizeMB: cc.MaxRequestBodySizeMB, + MCPAgentDepth: cc.MCPAgentDepth, + MCPToolExecutionTimeout: cc.MCPToolExecutionTimeout, + MCPCodeModeBindingLevel: cc.MCPCodeModeBindingLevel, + MCPToolSyncInterval: cc.MCPToolSyncInterval, + MCPDisableAutoToolInject: cc.MCPDisableAutoToolInject, + MCPExternalClientURL: schemas.NewEnvVar(cc.MCPExternalClientURL), + HeaderFilterConfig: cc.HeaderFilterConfig, + AsyncJobResultTTL: cc.AsyncJobResultTTL, + RequiredHeaders: cc.RequiredHeaders, + LoggingHeaders: cc.LoggingHeaders, + WhitelistedRoutes: cc.WhitelistedRoutes, + HideDeletedVirtualKeysInFilters: cc.HideDeletedVirtualKeysInFilters, + RoutingChainMaxDepth: cc.RoutingChainMaxDepth, + Compat: CompatConfig{ + ConvertTextToChat: cc.CompatConvertTextToChat, + ConvertChatToResponses: cc.CompatConvertChatToResponses, + ShouldDropParams: cc.CompatShouldDropParams, + ShouldConvertParams: cc.CompatShouldConvertParams, + }, + } + newHash, err := clientConfig.GenerateClientConfigHash() + if err != nil { + return fmt.Errorf("regenerate config hash for client config %d: %w", cc.ID, err) + } + if err := tx.Model(&cc).Update("config_hash", newHash).Error; err != nil { + return fmt.Errorf("update config_hash for client config %d: %w", cc.ID, err) + } + } + return nil + }, + Rollback: func(tx *gorm.DB) error { + return nil + }, + }) +} + // migrationDropLegacyCalendarAlignedColumns drops the legacy calendar_aligned // columns from governance_budgets and governance_rate_limits. Calendar // alignment is now a VK-only setting (governance_virtual_keys.calendar_aligned); diff --git a/framework/configstore/rdb.go b/framework/configstore/rdb.go index ee6425c1b03..3779826cb1f 100644 --- a/framework/configstore/rdb.go +++ b/framework/configstore/rdb.go @@ -252,7 +252,6 @@ func (s *RDBConfigStore) UpdateClientConfig(ctx context.Context, config *ClientC WhitelistedRoutes: config.WhitelistedRoutes, HideDeletedVirtualKeysInFilters: config.HideDeletedVirtualKeysInFilters, RoutingChainMaxDepth: config.RoutingChainMaxDepth, - MCPExternalServerURL: mcpExternalURLToString(config.MCPExternalServerURL), MCPExternalClientURL: mcpExternalURLToString(config.MCPExternalClientURL), HeaderFilterConfig: config.HeaderFilterConfig, AllowPerRequestContentStorageOverride: config.AllowPerRequestContentStorageOverride, @@ -515,7 +514,6 @@ func (s *RDBConfigStore) GetClientConfig(ctx context.Context) (*ClientConfig, er WhitelistedRoutes: dbConfig.WhitelistedRoutes, HideDeletedVirtualKeysInFilters: dbConfig.HideDeletedVirtualKeysInFilters, RoutingChainMaxDepth: dbConfig.RoutingChainMaxDepth, - MCPExternalServerURL: schemas.NewEnvVar(dbConfig.MCPExternalServerURL), MCPExternalClientURL: schemas.NewEnvVar(dbConfig.MCPExternalClientURL), HeaderFilterConfig: dbConfig.HeaderFilterConfig, AllowPerRequestContentStorageOverride: dbConfig.AllowPerRequestContentStorageOverride, @@ -1883,6 +1881,17 @@ func (s *RDBConfigStore) DeleteMCPClientConfig(ctx context.Context, id string) e } } + // Delete per-user OAuth token + flow rows for this MCP client. Token + // rows reference mcp_client_id by the string client_id; nothing + // auto-cascades, so we do it explicitly inside the same transaction + // to keep cleanup atomic. + if err := tx.WithContext(ctx).Where("mcp_client_id = ?", existingClient.ClientID).Delete(&tables.TableOauthUserToken{}).Error; err != nil { + return err + } + if err := tx.WithContext(ctx).Where("mcp_client_id = ?", existingClient.ClientID).Delete(&tables.TableOauthUserSession{}).Error; err != nil { + return err + } + // Delete the client (this will also handle foreign key cascades) return tx.WithContext(ctx).Delete(&existingClient).Error }) @@ -2706,14 +2715,6 @@ func (s *RDBConfigStore) DeleteVirtualKey(ctx context.Context, id string, tx ... if err := txDB.WithContext(ctx).Delete(&tables.TableVirtualKeyMCPConfig{}, "virtual_key_id = ?", id).Error; err != nil { return err } - // Delete per-user OAuth pending flows tied to this VK - if err := txDB.WithContext(ctx).Where("virtual_key_id = ?", id).Delete(&tables.TablePerUserOAuthPendingFlow{}).Error; err != nil { - return err - } - // Delete per-user OAuth sessions tied to this VK - if err := txDB.WithContext(ctx).Where("virtual_key_id = ?", id).Delete(&tables.TablePerUserOAuthSession{}).Error; err != nil { - return err - } // Delete upstream OAuth user sessions tied to this VK if err := txDB.WithContext(ctx).Where("virtual_key_id = ?", id).Delete(&tables.TableOauthUserSession{}).Error; err != nil { return err @@ -4762,7 +4763,10 @@ func (s *RDBConfigStore) GetOauthConfigByTokenID(ctx context.Context, tokenID st // GetOauthUserSessionByID retrieves a per-user OAuth session by its ID func (s *RDBConfigStore) GetOauthUserSessionByID(ctx context.Context, id string) (*tables.TableOauthUserSession, error) { var session tables.TableOauthUserSession - result := s.DB().WithContext(ctx).Where("id = ?", id).First(&session) + result := s.ScopedDB(ctx). + Preload("MCPClient", func(db *gorm.DB) *gorm.DB { return db.Select("client_id, name") }). + Preload("VirtualKey", func(db *gorm.DB) *gorm.DB { return db.Select("id, name") }). + Where("id = ?", id).First(&session) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, nil @@ -4772,19 +4776,6 @@ func (s *RDBConfigStore) GetOauthUserSessionByID(ctx context.Context, id string) return &session, nil } -// GetOauthUserSessionByState retrieves a per-user OAuth session by its state token -func (s *RDBConfigStore) GetOauthUserSessionByState(ctx context.Context, state string) (*tables.TableOauthUserSession, error) { - var session tables.TableOauthUserSession - result := s.DB().WithContext(ctx).Where("state = ?", state).First(&session) - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { - return nil, nil - } - return nil, fmt.Errorf("failed to get oauth user session by state: %w", result.Error) - } - return &session, nil -} - // ClaimOauthUserSessionByState atomically claims a pending per-user OAuth session by its state token. // Returns nil if the session doesn't exist or has already been claimed by another request. func (s *RDBConfigStore) ClaimOauthUserSessionByState(ctx context.Context, state string) (*tables.TableOauthUserSession, error) { @@ -4810,16 +4801,34 @@ func (s *RDBConfigStore) ClaimOauthUserSessionByState(ctx context.Context, state return &session, nil } -// GetOauthUserSessionBySessionToken retrieves a per-user OAuth session by its Bifrost session token (hashed lookup) -func (s *RDBConfigStore) GetOauthUserSessionBySessionToken(ctx context.Context, sessionToken string) (*tables.TableOauthUserSession, error) { +// GetOauthUserSessionByModeIdentityAndMCPClient returns the single flow row +// bound to (mode, identity, mcp_client_id). This is the canonical lookup at +// flow-init time: there's exactly one flow row per binding, and reauth always +// updates it in place rather than inserting a new one. +// +// identity per mode: AuthModeUser=user_id, AuthModeVK=virtual_key_id, +// AuthModeSession=raw session token (hashed for the lookup column). +func (s *RDBConfigStore) GetOauthUserSessionByModeIdentityAndMCPClient(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) (*tables.TableOauthUserSession, error) { + if strings.TrimSpace(identity) == "" || strings.TrimSpace(mcpClientID) == "" { + return nil, nil + } + q := s.DB().WithContext(ctx).Where("mcp_client_id = ?", mcpClientID) + switch mode { + case schemas.MCPAuthModeUser: + q = q.Where("user_id = ?", identity) + case schemas.MCPAuthModeVK: + q = q.Where("virtual_key_id = ?", identity) + case schemas.MCPAuthModeSession: + q = q.Where("session_id = ?", identity) + default: + return nil, fmt.Errorf("unknown auth mode: %s", mode) + } var session tables.TableOauthUserSession - tokenHash := encrypt.HashSHA256(sessionToken) - result := s.DB().WithContext(ctx).Where("session_token_hash = ?", tokenHash).First(&session) - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { + if err := q.First(&session).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil } - return nil, fmt.Errorf("failed to get oauth user session by session token: %w", result.Error) + return nil, fmt.Errorf("failed to get oauth user session (mode=%s): %w", mode, err) } return &session, nil } @@ -4844,72 +4853,48 @@ func (s *RDBConfigStore) UpdateOauthUserSession(ctx context.Context, session *ta // ---------- Per-User OAuth Token CRUD ---------- -// GetOauthUserTokenBySessionToken retrieves a per-user OAuth token by its Bifrost session token -// GetOauthUserTokenByIdentity looks up an upstream OAuth token by user identity and MCP client. -// Priority: userID > virtualKeyID > sessionToken (fallback for anonymous users). -func (s *RDBConfigStore) GetOauthUserTokenByIdentity(ctx context.Context, virtualKeyID, userID, sessionToken, mcpClientID string) (*tables.TableOauthUserToken, error) { - var token tables.TableOauthUserToken - var result *gorm.DB - - if userID != "" { - result = s.DB().WithContext(ctx).Where("user_id = ? AND mcp_client_id = ?", userID, mcpClientID).First(&token) - } else if virtualKeyID != "" { - result = s.DB().WithContext(ctx).Where("virtual_key_id = ? AND mcp_client_id = ?", virtualKeyID, mcpClientID).First(&token) - } else if sessionToken != "" { - result = s.DB().WithContext(ctx).Where("session_token = ? AND mcp_client_id = ?", sessionToken, mcpClientID).First(&token) - } else { - return nil, nil - } - - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { - return nil, nil - } - return nil, fmt.Errorf("failed to get oauth user token by identity: %w", result.Error) - } - return &token, nil -} - -func (s *RDBConfigStore) GetOauthUserTokenBySessionToken(ctx context.Context, sessionToken string) (*tables.TableOauthUserToken, error) { - var token tables.TableOauthUserToken - tokenHash := encrypt.HashSHA256(sessionToken) - result := s.DB().WithContext(ctx).Where("session_token_hash = ?", tokenHash).First(&token) - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { - return nil, nil - } - return nil, fmt.Errorf("failed to get oauth user token by session token: %w", result.Error) - } - return &token, nil -} - -// CreateOauthUserToken creates or replaces a per-user OAuth token. -// When an identity (VirtualKeyID or UserID) is set, any existing token for the -// same identity + MCPClientID pair is replaced to keep resolution deterministic. +// CreateOauthUserToken creates or replaces a per-user OAuth token. Looks up +// any existing row matching the populated identity column + MCP client and +// reuses its ID, ensuring the partial-unique index never trips. SessionToken's +// hash is set in BeforeSave; the upsert lookup uses the hash column to match +// the unique index. Wrapped in a transaction so SELECT + CREATE/UPDATE is +// atomic under concurrent same-identity races. func (s *RDBConfigStore) CreateOauthUserToken(ctx context.Context, token *tables.TableOauthUserToken) error { - // Wrap in a transaction so the SELECT + CREATE/UPDATE is atomic, preventing - // duplicate tokens when concurrent requests race on the same identity+client pair. return s.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error { - if token.UserID != nil && *token.UserID != "" { - var existing tables.TableOauthUserToken - err := dbForUpdate(tx).Where("user_id = ? AND mcp_client_id = ?", *token.UserID, token.MCPClientID).First(&existing).Error - if err == nil { - token.ID = existing.ID // reuse the row - return tx.Save(token).Error - } - if !errors.Is(err, gorm.ErrRecordNotFound) { - return fmt.Errorf("failed to query oauth user token: %w", err) - } - } else if token.VirtualKeyID != nil && *token.VirtualKeyID != "" { - var existing tables.TableOauthUserToken - err := dbForUpdate(tx).Where("virtual_key_id = ? AND mcp_client_id = ?", *token.VirtualKeyID, token.MCPClientID).First(&existing).Error - if err == nil { - token.ID = existing.ID // reuse the row - return tx.Save(token).Error - } - if !errors.Is(err, gorm.ErrRecordNotFound) { - return fmt.Errorf("failed to query oauth user token: %w", err) - } + var existing tables.TableOauthUserToken + var lookupErr error + switch { + case token.UserID != nil && *token.UserID != "": + lookupErr = dbForUpdate(tx). + Where("user_id = ? AND mcp_client_id = ?", *token.UserID, token.MCPClientID). + First(&existing).Error + case token.VirtualKeyID != nil && *token.VirtualKeyID != "": + lookupErr = dbForUpdate(tx). + Where("virtual_key_id = ? AND mcp_client_id = ?", *token.VirtualKeyID, token.MCPClientID). + First(&existing).Error + case token.SessionID != "": + lookupErr = dbForUpdate(tx). + Where("session_id = ? AND mcp_client_id = ?", token.SessionID, token.MCPClientID). + First(&existing).Error + default: + lookupErr = gorm.ErrRecordNotFound + } + + if lookupErr == nil { + token.ID = existing.ID // reuse the row so unique index sees an UPDATE, not INSERT + // Preserve the original binding's creation time; the row represents + // the (identity, mcp_client) link, not the individual credential, so + // a re-auth shouldn't move CreatedAt forward. + token.CreatedAt = existing.CreatedAt + // Stamp LastRefreshedAt so the dashboard surfaces "refreshed Xm ago" + // after a successful re-auth (this path is only hit on upsert, which + // always means new credentials replacing old). + now := time.Now() + token.LastRefreshedAt = &now + return tx.Save(token).Error + } + if !errors.Is(lookupErr, gorm.ErrRecordNotFound) { + return fmt.Errorf("failed to query oauth user token: %w", lookupErr) } if err := tx.Create(token).Error; err != nil { @@ -4937,305 +4922,180 @@ func (s *RDBConfigStore) DeleteOauthUserToken(ctx context.Context, id string) er return nil } -// DeleteOauthUserTokensByMCPClient deletes all per-user OAuth tokens for a specific MCP client -func (s *RDBConfigStore) DeleteOauthUserTokensByMCPClient(ctx context.Context, mcpClientID string) error { - result := s.DB().WithContext(ctx).Where("mcp_client_id = ?", mcpClientID).Delete(&tables.TableOauthUserToken{}) - if result.Error != nil { - return fmt.Errorf("failed to delete oauth user tokens for mcp client: %w", result.Error) - } - return nil -} - -// ---------- Per-User OAuth Authorization Server CRUD ---------- - -// GetPerUserOAuthClientByClientID retrieves a dynamically registered OAuth client by its client_id. -func (s *RDBConfigStore) GetPerUserOAuthClientByClientID(ctx context.Context, clientID string) (*tables.TablePerUserOAuthClient, error) { - var client tables.TablePerUserOAuthClient - result := s.DB().WithContext(ctx).Where("client_id = ?", clientID).First(&client) - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { - return nil, nil - } - return nil, fmt.Errorf("failed to get per-user oauth client: %w", result.Error) +// DeleteOauthUserSession hard-deletes a single flow row by primary key. +func (s *RDBConfigStore) DeleteOauthUserSession(ctx context.Context, id string) error { + if id == "" { + return nil } - return &client, nil -} - -// CreatePerUserOAuthClient creates a new dynamically registered OAuth client. -func (s *RDBConfigStore) CreatePerUserOAuthClient(ctx context.Context, client *tables.TablePerUserOAuthClient) error { - result := s.DB().WithContext(ctx).Create(client) - if result.Error != nil { - return fmt.Errorf("failed to create per-user oauth client: %w", result.Error) + if err := s.DB().WithContext(ctx).Where("id = ?", id).Delete(&tables.TableOauthUserSession{}).Error; err != nil { + return fmt.Errorf("failed to delete oauth user session %s: %w", id, err) } return nil } -// GetPerUserOAuthSessionByAccessToken retrieves a Bifrost-issued session by its access token. -func (s *RDBConfigStore) GetPerUserOAuthSessionByAccessToken(ctx context.Context, accessToken string) (*tables.TablePerUserOAuthSession, error) { - var session tables.TablePerUserOAuthSession - tokenHash := encrypt.HashSHA256(accessToken) - result := s.DB().WithContext(ctx).Where("access_token_hash = ?", tokenHash).Preload("VirtualKey", func(db *gorm.DB) *gorm.DB { - return db.Select("id, name, value, encryption_status") - }).First(&session) - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { - return nil, nil - } - return nil, fmt.Errorf("failed to get per-user oauth session: %w", result.Error) +// DeleteOauthUserSessionsByModeIdentityAndMCPClient hard-deletes any oauth_user_sessions +// (pending or completed flow) rows matching the given identity column + MCP client. +// Used by revoke so a subsequent OAuth init for the same identity starts from a clean +// slate instead of upserting the stale row (session mode) or accumulating dead flow +// rows over time (vk/user modes, whose flow rows have random server-generated +// session tokens and therefore never get reused, but linger as 'authorized'). +// +// identity meaning per mode: +// - AuthModeUser: user_id +// - AuthModeVK: virtual_key_id +// - AuthModeSession: raw session token (the store hashes for the lookup column) +func (s *RDBConfigStore) DeleteOauthUserSessionsByModeIdentityAndMCPClient(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) error { + if strings.TrimSpace(identity) == "" || strings.TrimSpace(mcpClientID) == "" { + return nil } - return &session, nil -} - -// GetPerUserOAuthSessionByID retrieves a Bifrost-issued session by its ID. -func (s *RDBConfigStore) GetPerUserOAuthSessionByID(ctx context.Context, id string) (*tables.TablePerUserOAuthSession, error) { - var session tables.TablePerUserOAuthSession - result := s.DB().WithContext(ctx).Where("id = ?", id).First(&session) - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { - return nil, nil - } - return nil, fmt.Errorf("failed to get per-user oauth session by id: %w", result.Error) + q := s.DB().WithContext(ctx).Where("mcp_client_id = ?", mcpClientID) + switch mode { + case schemas.MCPAuthModeUser: + q = q.Where("user_id = ?", identity) + case schemas.MCPAuthModeVK: + q = q.Where("virtual_key_id = ?", identity) + case schemas.MCPAuthModeSession: + q = q.Where("session_id = ?", identity) + default: + return fmt.Errorf("unknown auth mode: %s", mode) } - return &session, nil -} - -// CreatePerUserOAuthSession creates a new Bifrost-issued OAuth session. -func (s *RDBConfigStore) CreatePerUserOAuthSession(ctx context.Context, session *tables.TablePerUserOAuthSession) error { - result := s.DB().WithContext(ctx).Create(session) - if result.Error != nil { - return fmt.Errorf("failed to create per-user oauth session: %w", result.Error) + if err := q.Delete(&tables.TableOauthUserSession{}).Error; err != nil { + return fmt.Errorf("failed to delete oauth user sessions (mode=%s): %w", mode, err) } return nil } -// UpdatePerUserOAuthSession updates a Bifrost-issued OAuth session (e.g., to attach user identity). -func (s *RDBConfigStore) UpdatePerUserOAuthSession(ctx context.Context, session *tables.TablePerUserOAuthSession) error { - result := s.DB().WithContext(ctx).Save(session) - if result.Error != nil { - return fmt.Errorf("failed to update per-user oauth session: %w", result.Error) +// GetOauthUserTokenByMode looks up an active per-user OAuth token by a single +// identity dimension. Filters status='active' so orphaned rows never satisfy +// a lookup. Also constrains on auth_mode so a row whose identity column was +// accidentally populated by a different mode's write path cannot leak into a +// mode it doesn't belong to. +func (s *RDBConfigStore) GetOauthUserTokenByMode(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) (*tables.TableOauthUserToken, error) { + if identity == "" || mcpClientID == "" { + return nil, nil } - return nil -} - -// DeletePerUserOAuthSession deletes a Bifrost-issued OAuth session by ID. -func (s *RDBConfigStore) DeletePerUserOAuthSession(ctx context.Context, id string) error { - result := s.DB().WithContext(ctx).Where("id = ?", id).Delete(&tables.TablePerUserOAuthSession{}) - if result.Error != nil { - return fmt.Errorf("failed to delete per-user oauth session: %w", result.Error) + var token tables.TableOauthUserToken + var result *gorm.DB + switch mode { + case schemas.MCPAuthModeUser: + result = s.DB().WithContext(ctx). + Where("auth_mode = ? AND user_id = ? AND mcp_client_id = ? AND status = ?", string(schemas.MCPAuthModeUser), identity, mcpClientID, "active"). + First(&token) + case schemas.MCPAuthModeVK: + result = s.DB().WithContext(ctx). + Where("auth_mode = ? AND virtual_key_id = ? AND mcp_client_id = ? AND status = ?", string(schemas.MCPAuthModeVK), identity, mcpClientID, "active"). + First(&token) + case schemas.MCPAuthModeSession: + result = s.DB().WithContext(ctx). + Where("auth_mode = ? AND session_id = ? AND mcp_client_id = ? AND status = ?", string(schemas.MCPAuthModeSession), identity, mcpClientID, "active"). + First(&token) + default: + return nil, fmt.Errorf("unknown auth mode: %s", mode) } - return nil -} - -// GetPerUserOAuthCodeByCode retrieves an authorization code record. -func (s *RDBConfigStore) GetPerUserOAuthCodeByCode(ctx context.Context, code string) (*tables.TablePerUserOAuthCode, error) { - var codeRecord tables.TablePerUserOAuthCode - codeHash := encrypt.HashSHA256(code) - result := s.DB().WithContext(ctx).Where("code_hash = ?", codeHash).First(&codeRecord) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, nil } - return nil, fmt.Errorf("failed to get per-user oauth code: %w", result.Error) - } - return &codeRecord, nil -} - -// CreatePerUserOAuthCode creates a new authorization code record. -func (s *RDBConfigStore) CreatePerUserOAuthCode(ctx context.Context, code *tables.TablePerUserOAuthCode) error { - result := s.DB().WithContext(ctx).Create(code) - if result.Error != nil { - return fmt.Errorf("failed to create per-user oauth code: %w", result.Error) + return nil, fmt.Errorf("failed to get oauth user token by mode %s: %w", mode, result.Error) } - return nil + return &token, nil } -// ClaimPerUserOAuthCode atomically marks an authorization code as used. -// Returns the code record if successfully claimed, nil if already used or not found. -func (s *RDBConfigStore) ClaimPerUserOAuthCode(ctx context.Context, code string) (*tables.TablePerUserOAuthCode, error) { - codeHash := encrypt.HashSHA256(code) - var codeRecord tables.TablePerUserOAuthCode - result := s.DB().WithContext(ctx).Where("code_hash = ? AND used = ?", codeHash, false).First(&codeRecord) - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { - return nil, nil - } - return nil, fmt.Errorf("failed to find per-user oauth code: %w", result.Error) - } - // Atomically mark as used - updateResult := s.DB().WithContext(ctx).Model(&tables.TablePerUserOAuthCode{}). - Where("id = ? AND used = ?", codeRecord.ID, false). - Update("used", true) - if updateResult.Error != nil { - return nil, fmt.Errorf("failed to claim per-user oauth code: %w", updateResult.Error) - } - if updateResult.RowsAffected == 0 { - return nil, nil // Another request already claimed it +// MarkOauthUserTokenNeedsReauthByID flips status to 'needs_reauth' on a single +// token row. Called by the refresh-failure path when the upstream credential +// is permanently rejected: the row stays (preserves audit + binding for +// re-auth), but is filtered from active lookups so the next inference +// triggers a fresh OAuth flow. +func (s *RDBConfigStore) MarkOauthUserTokenNeedsReauthByID(ctx context.Context, tokenID string) error { + if tokenID == "" { + return nil } - codeRecord.Used = true - return &codeRecord, nil -} - -// UpdatePerUserOAuthCode updates an authorization code record (e.g., marking as used). -func (s *RDBConfigStore) UpdatePerUserOAuthCode(ctx context.Context, code *tables.TablePerUserOAuthCode) error { - result := s.DB().WithContext(ctx).Save(code) + result := s.DB().WithContext(ctx). + Model(&tables.TableOauthUserToken{}). + Where("id = ?", tokenID). + Update("status", "needs_reauth") if result.Error != nil { - return fmt.Errorf("failed to update per-user oauth code: %w", result.Error) + return fmt.Errorf("failed to mark oauth user token %s needs_reauth: %w", tokenID, result.Error) } return nil } -// ---------- Per-User OAuth Pending Flow CRUD ---------- - -// GetPerUserOAuthPendingFlow retrieves a pending consent flow by its ID. -func (s *RDBConfigStore) GetPerUserOAuthPendingFlow(ctx context.Context, id string) (*tables.TablePerUserOAuthPendingFlow, error) { - var flow tables.TablePerUserOAuthPendingFlow - result := s.DB().WithContext(ctx).Where("id = ?", id).First(&flow) - if result.Error != nil { - if errors.Is(result.Error, gorm.ErrRecordNotFound) { +// GetOauthUserTokenByID looks up a single token row by primary key. Returns +// nil, nil when not found. +func (s *RDBConfigStore) GetOauthUserTokenByID(ctx context.Context, id string) (*tables.TableOauthUserToken, error) { + if id == "" { + return nil, nil + } + var token tables.TableOauthUserToken + if err := s.ScopedDB(ctx).Where("id = ?", id).First(&token).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil } - return nil, fmt.Errorf("failed to get per-user oauth pending flow: %w", result.Error) - } - return &flow, nil -} - -// CreatePerUserOAuthPendingFlow persists a new pending consent flow. -func (s *RDBConfigStore) CreatePerUserOAuthPendingFlow(ctx context.Context, flow *tables.TablePerUserOAuthPendingFlow) error { - result := s.DB().WithContext(ctx).Create(flow) - if result.Error != nil { - return fmt.Errorf("failed to create per-user oauth pending flow: %w", result.Error) + return nil, fmt.Errorf("failed to get oauth user token by id %s: %w", id, err) } - return nil -} - -// UpdatePerUserOAuthPendingFlow updates an existing pending consent flow (e.g., after VK step). -func (s *RDBConfigStore) UpdatePerUserOAuthPendingFlow(ctx context.Context, flow *tables.TablePerUserOAuthPendingFlow) error { - result := s.DB().WithContext(ctx).Save(flow) - if result.Error != nil { - return fmt.Errorf("failed to update per-user oauth pending flow: %w", result.Error) - } - return nil + return &token, nil } -// DeletePerUserOAuthPendingFlow deletes a pending consent flow after it has been submitted. -func (s *RDBConfigStore) DeletePerUserOAuthPendingFlow(ctx context.Context, id string) error { - result := s.DB().WithContext(ctx).Where("id = ?", id).Delete(&tables.TablePerUserOAuthPendingFlow{}) - if result.Error != nil { - return fmt.Errorf("failed to delete per-user oauth pending flow: %w", result.Error) +// ListAllOauthUserTokens returns every token row regardless of status. Used by +// the sessions tab UI, which renders distinct affordances per state; filtering +// here would only hide rows the user needs to see (especially needs_reauth). +// Runtime lookups apply their own status='active' filter and don't use this. +func (s *RDBConfigStore) ListAllOauthUserTokens(ctx context.Context) ([]tables.TableOauthUserToken, error) { + var tokens []tables.TableOauthUserToken + if err := s.ScopedDB(ctx). + Preload("MCPClient", func(db *gorm.DB) *gorm.DB { return db.Select("client_id, name") }). + Preload("VirtualKey", func(db *gorm.DB) *gorm.DB { return db.Select("id, name") }). + Order("created_at DESC"). + Find(&tokens).Error; err != nil { + return nil, fmt.Errorf("failed to list all oauth user tokens: %w", err) } - return nil + return tokens, nil } -func (s *RDBConfigStore) ConsumePerUserOAuthPendingFlow(ctx context.Context, id string) (int64, error) { - now := time.Now().UTC() - result := s.DB().WithContext(ctx).Where("id = ? AND expires_at > ?", id, now).Delete(&tables.TablePerUserOAuthPendingFlow{}) +// ListAllPendingOauthUserSessions returns all pending OAuth flow rows whose +// expiry is in the future. Companion to ListAllOauthUserTokens. +func (s *RDBConfigStore) ListAllPendingOauthUserSessions(ctx context.Context) ([]tables.TableOauthUserSession, error) { + var sessions []tables.TableOauthUserSession + if err := s.ScopedDB(ctx). + Preload("MCPClient", func(db *gorm.DB) *gorm.DB { return db.Select("client_id, name") }). + Preload("VirtualKey", func(db *gorm.DB) *gorm.DB { return db.Select("id, name") }). + Where("status = ? AND expires_at > ?", "pending", time.Now()). + Order("created_at DESC"). + Find(&sessions).Error; err != nil { + return nil, fmt.Errorf("failed to list all pending oauth user sessions: %w", err) + } + return sessions, nil +} + +// DeleteExpiredOauthUserSessions hard-deletes pending and claiming OAuth flow +// rows whose ExpiresAt has passed. Including 'claiming' covers callbacks that +// died after ClaimOauthUserSessionByState flipped the status — otherwise that +// row outlives its expiry and any new flow init for the same (mode, identity, +// mcp_client) binding keeps seeing the dead row. +func (s *RDBConfigStore) DeleteExpiredOauthUserSessions(ctx context.Context) (int64, error) { + result := s.DB().WithContext(ctx). + Where("expires_at < ? AND status IN ?", time.Now(), []string{"pending", "claiming"}). + Delete(&tables.TableOauthUserSession{}) if result.Error != nil { - return 0, fmt.Errorf("failed to consume per-user oauth pending flow: %w", result.Error) - } - if result.RowsAffected == 0 { - // Distinguish between already-consumed (record gone) and expired (record exists but TTL elapsed). - var count int64 - if err := s.DB().WithContext(ctx).Model(&tables.TablePerUserOAuthPendingFlow{}).Where("id = ?", id).Count(&count).Error; err != nil { - return 0, fmt.Errorf("failed to inspect per-user oauth pending flow: %w", err) - } - if count > 0 { - return 0, schemas.ErrPerUserOAuthPendingFlowExpired - } + return 0, fmt.Errorf("failed to delete expired oauth user sessions: %w", result.Error) } return result.RowsAffected, nil } -// FinalizePerUserOAuthConsent atomically consumes a pending flow, creates the session, -// and creates the authorization code in a single transaction. -func (s *RDBConfigStore) FinalizePerUserOAuthConsent(ctx context.Context, flowID string, session *tables.TablePerUserOAuthSession, code *tables.TablePerUserOAuthCode) (int64, error) { - var rowsAffected int64 - err := s.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error { - // 1. Consume the pending flow (atomic idempotency guard). - // Also enforce the TTL so an expired flow cannot be finalized even if callers miss the check. - now := time.Now().UTC() - result := tx.Where("id = ? AND expires_at > ?", flowID, now).Delete(&tables.TablePerUserOAuthPendingFlow{}) - if result.Error != nil { - return fmt.Errorf("failed to consume per-user oauth pending flow: %w", result.Error) - } - rowsAffected = result.RowsAffected - if rowsAffected == 0 { - // Distinguish between already-consumed (record gone) and expired (record exists but TTL elapsed). - var count int64 - if err := tx.Model(&tables.TablePerUserOAuthPendingFlow{}).Where("id = ?", flowID).Count(&count).Error; err != nil { - return fmt.Errorf("failed to inspect per-user oauth pending flow: %w", err) - } - if count > 0 { - return schemas.ErrPerUserOAuthPendingFlowExpired - } - // Record gone — consumed by a concurrent request; caller treats as conflict. - return nil - } - - // 2. Create the Bifrost session. - if err := tx.Create(session).Error; err != nil { - return fmt.Errorf("failed to create per-user oauth session: %w", err) - } - - // 3. Create the authorization code. - if err := tx.Create(code).Error; err != nil { - return fmt.Errorf("failed to create per-user oauth code: %w", err) - } - - return nil - }) - if err != nil { - return 0, err +// DeleteOrphanedOauthUserTokens hard-deletes token rows that have been in +// 'orphaned' state longer than olderThan. Skipped silently when olderThan +// is zero or negative. +func (s *RDBConfigStore) DeleteOrphanedOauthUserTokens(ctx context.Context, olderThan time.Duration) (int64, error) { + if olderThan <= 0 { + return 0, nil } - return rowsAffected, nil -} - -// GetOauthUserTokensByGatewaySessionID returns all upstream tokens linked to a gateway session ID. -func (s *RDBConfigStore) GetOauthUserTokensByGatewaySessionID(ctx context.Context, gatewaySessionID string) ([]tables.TableOauthUserToken, error) { - if strings.TrimSpace(gatewaySessionID) == "" { - return nil, fmt.Errorf("gateway session id is required") - } - // Find all tokens whose session_token_hash matches any upstream session - // linked to this gateway session ID. This supports per-service proxy tokens - // (e.g. "flow::") where each MCP service gets its own hash. - var tokens []tables.TableOauthUserToken - subquery := s.DB().Model(&tables.TableOauthUserSession{}).Select("session_token_hash").Where("gateway_session_id = ?", gatewaySessionID) - result := s.DB().WithContext(ctx).Where("session_token_hash IN (?)", subquery).Find(&tokens) + cutoff := time.Now().Add(-olderThan) + result := s.DB().WithContext(ctx). + Where("status = ? AND updated_at < ?", "orphaned", cutoff). + Delete(&tables.TableOauthUserToken{}) if result.Error != nil { - return nil, fmt.Errorf("failed to get oauth user tokens by gateway session id: %w", result.Error) + return 0, fmt.Errorf("failed to delete orphaned oauth user tokens: %w", result.Error) } - return tokens, nil + return result.RowsAffected, nil } -// TransferOauthUserTokensFromGatewaySession migrates upstream tokens from all flow proxy sessions -// (identified by gateway_session_id) to the real Bifrost session token, and sets VirtualKeyID/UserID. -func (s *RDBConfigStore) TransferOauthUserTokensFromGatewaySession(ctx context.Context, gatewaySessionID, realSessionToken, virtualKeyID, userID string) error { - if strings.TrimSpace(gatewaySessionID) == "" { - return fmt.Errorf("gateway session id is required") - } - if strings.TrimSpace(realSessionToken) == "" { - return fmt.Errorf("real session token is required") - } - realTokenHash := encrypt.HashSHA256(realSessionToken) - - // Always overwrite both identity columns from the finalized values so stale - // identities from a prior flow phase cannot persist and cause GetOauthUserTokenByIdentity - // to resolve this token under the wrong identity. - updates := map[string]interface{}{ - "session_token": realSessionToken, - "session_token_hash": realTokenHash, - "virtual_key_id": virtualKeyID, - "user_id": userID, - } - - // Update all tokens whose session_token_hash matches any upstream session - // linked to this gateway session ID. - subquery := s.DB().Model(&tables.TableOauthUserSession{}).Select("session_token_hash").Where("gateway_session_id = ?", gatewaySessionID) - result := s.DB().WithContext(ctx).Model(&tables.TableOauthUserToken{}). - Where("session_token_hash IN (?)", subquery). - Updates(updates) - if result.Error != nil { - return fmt.Errorf("failed to transfer oauth user tokens from gateway session: %w", result.Error) - } - s.logger.Debug("[rdb] TransferOauthUserTokensFromGatewaySession done: rows_affected=%d", result.RowsAffected) - return nil -} diff --git a/framework/configstore/rdb_test.go b/framework/configstore/rdb_test.go index 5967f8f64be..268ef1ba2b5 100644 --- a/framework/configstore/rdb_test.go +++ b/framework/configstore/rdb_test.go @@ -42,8 +42,6 @@ func setupRDBTestStore(t *testing.T) *RDBConfigStore { &tables.TablePromptVersionMessage{}, &tables.TablePromptSession{}, &tables.TablePromptSessionMessage{}, - &tables.TablePerUserOAuthPendingFlow{}, - &tables.TablePerUserOAuthSession{}, &tables.TableOauthUserSession{}, &tables.TableOauthUserToken{}, ) diff --git a/framework/configstore/store.go b/framework/configstore/store.go index dbd1ccf57d4..021b3eb8827 100644 --- a/framework/configstore/store.go +++ b/framework/configstore/store.go @@ -324,52 +324,59 @@ type ConfigStore interface { // Per-user OAuth session CRUD GetOauthUserSessionByID(ctx context.Context, id string) (*tables.TableOauthUserSession, error) - GetOauthUserSessionByState(ctx context.Context, state string) (*tables.TableOauthUserSession, error) ClaimOauthUserSessionByState(ctx context.Context, state string) (*tables.TableOauthUserSession, error) - GetOauthUserSessionBySessionToken(ctx context.Context, sessionToken string) (*tables.TableOauthUserSession, error) + // GetOauthUserSessionByModeIdentityAndMCPClient returns the canonical flow + // row for an (identity, mcp_client) binding. Used at flow-init time as the + // single source of truth: reauth updates this row in place rather than + // inserting a new one. Returns (nil, nil) when no row exists. + GetOauthUserSessionByModeIdentityAndMCPClient(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) (*tables.TableOauthUserSession, error) CreateOauthUserSession(ctx context.Context, session *tables.TableOauthUserSession) error UpdateOauthUserSession(ctx context.Context, session *tables.TableOauthUserSession) error // Per-user OAuth token CRUD - GetOauthUserTokenByIdentity(ctx context.Context, virtualKeyID, userID, sessionToken, mcpClientID string) (*tables.TableOauthUserToken, error) - GetOauthUserTokenBySessionToken(ctx context.Context, sessionToken string) (*tables.TableOauthUserToken, error) + // GetOauthUserTokenByMode looks up the active token row keyed by a single + // identity dimension. Filters status='active'. identity is the user ID for + // AuthModeUser, the VK row ID for AuthModeVK, and the session ID for + // AuthModeSession. + GetOauthUserTokenByMode(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) (*tables.TableOauthUserToken, error) CreateOauthUserToken(ctx context.Context, token *tables.TableOauthUserToken) error UpdateOauthUserToken(ctx context.Context, token *tables.TableOauthUserToken) error DeleteOauthUserToken(ctx context.Context, id string) error - DeleteOauthUserTokensByMCPClient(ctx context.Context, mcpClientID string) error - - // Per-user OAuth Authorization Server CRUD (Bifrost as OAuth server) - GetPerUserOAuthClientByClientID(ctx context.Context, clientID string) (*tables.TablePerUserOAuthClient, error) - CreatePerUserOAuthClient(ctx context.Context, client *tables.TablePerUserOAuthClient) error - GetPerUserOAuthSessionByAccessToken(ctx context.Context, accessToken string) (*tables.TablePerUserOAuthSession, error) - GetPerUserOAuthSessionByID(ctx context.Context, id string) (*tables.TablePerUserOAuthSession, error) - CreatePerUserOAuthSession(ctx context.Context, session *tables.TablePerUserOAuthSession) error - UpdatePerUserOAuthSession(ctx context.Context, session *tables.TablePerUserOAuthSession) error - DeletePerUserOAuthSession(ctx context.Context, id string) error - GetPerUserOAuthCodeByCode(ctx context.Context, code string) (*tables.TablePerUserOAuthCode, error) - ClaimPerUserOAuthCode(ctx context.Context, code string) (*tables.TablePerUserOAuthCode, error) - CreatePerUserOAuthCode(ctx context.Context, code *tables.TablePerUserOAuthCode) error - UpdatePerUserOAuthCode(ctx context.Context, code *tables.TablePerUserOAuthCode) error - - // Per-user OAuth consent flow (pending flows before code issuance) - GetPerUserOAuthPendingFlow(ctx context.Context, id string) (*tables.TablePerUserOAuthPendingFlow, error) - CreatePerUserOAuthPendingFlow(ctx context.Context, flow *tables.TablePerUserOAuthPendingFlow) error - UpdatePerUserOAuthPendingFlow(ctx context.Context, flow *tables.TablePerUserOAuthPendingFlow) error - DeletePerUserOAuthPendingFlow(ctx context.Context, id string) error - // ConsumePerUserOAuthPendingFlow atomically deletes a pending flow and returns the number of - // rows affected. Returns 0 if the flow was already consumed by a concurrent request. - ConsumePerUserOAuthPendingFlow(ctx context.Context, id string) (int64, error) - // FinalizePerUserOAuthConsent atomically consumes a pending flow, creates the session, - // and creates the authorization code in a single transaction. Returns (0, nil) if the - // flow was already consumed by a concurrent request. - FinalizePerUserOAuthConsent(ctx context.Context, flowID string, session *tables.TablePerUserOAuthSession, code *tables.TablePerUserOAuthCode) (int64, error) - // GetOauthUserTokensByGatewaySessionID returns all upstream tokens linked to a gateway session ID. - // Used during consent submit to discover which MCPs the user authenticated with. - // Queries tokens via upstream sessions matching the given gateway session ID. - GetOauthUserTokensByGatewaySessionID(ctx context.Context, gatewaySessionID string) ([]tables.TableOauthUserToken, error) - // TransferOauthUserTokensFromGatewaySession migrates upstream tokens from all flow proxy sessions - // (identified by gateway_session_id) to the real Bifrost session token, and sets VirtualKeyID/UserID on each record. - TransferOauthUserTokensFromGatewaySession(ctx context.Context, gatewaySessionID, realSessionToken, virtualKeyID, userID string) error + // DeleteOauthUserSession hard-deletes a single flow row by primary key. + // Used by CompleteUserOAuthFlow on terminal transitions so completed, + // failed, and expired-at-completion flows don't accumulate. The UI + // treats 404 on flow-detail as "expired or completed". + DeleteOauthUserSession(ctx context.Context, id string) error + // DeleteOauthUserSessionsByModeIdentityAndMCPClient hard-deletes any flow + // rows matching the given identity column + MCP client. Used by revoke + // across all auth modes so subsequent OAuth init starts from a clean slate. + DeleteOauthUserSessionsByModeIdentityAndMCPClient(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) error + // MarkOauthUserTokenNeedsReauthByID flips status to 'needs_reauth' + // on a single token row. Called by the refresh-failure path when + // the upstream credential is permanently rejected: the row stays + // (preserves audit + binding for re-auth), but is filtered from + // active lookups so the next inference triggers a fresh OAuth + // flow that upserts the row back to 'active'. + MarkOauthUserTokenNeedsReauthByID(ctx context.Context, tokenID string) error + // GetOauthUserTokenByID looks up a single token row by primary key. + // Returns nil, nil when not found. + GetOauthUserTokenByID(ctx context.Context, id string) (*tables.TableOauthUserToken, error) + // ListAllOauthUserTokens returns every token row regardless of status. + // The sessions UI renders all three states (active / orphaned / + // needs_reauth) with distinct affordances, so hiding any of them only + // breaks the user's ability to act on rows that need their attention. + // Runtime token lookups apply their own status='active' filter and don't + // go through this method. + ListAllOauthUserTokens(ctx context.Context) ([]tables.TableOauthUserToken, error) + // ListAllPendingOauthUserSessions returns all pending OAuth flow rows. + // Companion to ListAllOauthUserTokens for the admin view. + ListAllPendingOauthUserSessions(ctx context.Context) ([]tables.TableOauthUserSession, error) + // DeleteExpiredOauthUserSessions hard-deletes pending OAuth flow rows + // whose ExpiresAt has passed. Returns the number of rows removed. + DeleteExpiredOauthUserSessions(ctx context.Context) (int64, error) + // DeleteOrphanedOauthUserTokens hard-deletes token rows where status='orphaned' + // and updated_at is older than olderThan. Returns the number of rows removed. + DeleteOrphanedOauthUserTokens(ctx context.Context, olderThan time.Duration) (int64, error) // Not found retry wrapper RetryOnNotFound(ctx context.Context, fn func(ctx context.Context) (any, error), maxRetries int, retryDelay time.Duration) (any, error) diff --git a/framework/configstore/tables/clientconfig.go b/framework/configstore/tables/clientconfig.go index 7fca0bb08e5..68ee284f75a 100644 --- a/framework/configstore/tables/clientconfig.go +++ b/framework/configstore/tables/clientconfig.go @@ -35,7 +35,6 @@ type TableClientConfig struct { LoggingHeadersJSON string `gorm:"type:text" json:"-"` // JSON serialized []string HideDeletedVirtualKeysInFilters bool `gorm:"default:false" json:"hide_deleted_virtual_keys_in_filters"` // Hide deleted virtual keys in logs filter dropdowns RoutingChainMaxDepth int `gorm:"default:10" json:"routing_chain_max_depth"` // Maximum depth for routing rule chain evaluation (default: 10) - MCPExternalServerURL string `gorm:"type:varchar(512)" json:"mcp_external_server_url,omitempty"` // Public base URL advertised in OAuth server metadata (.well-known, WWW-Authenticate) MCPExternalClientURL string `gorm:"type:varchar(512)" json:"mcp_external_client_url,omitempty"` // Public base URL used as redirect_uri when Bifrost acts as an OAuth client to upstream MCP servers WhitelistedRoutesJSON string `gorm:"type:text" json:"-"` // JSON serialized []string AllowPerRequestContentStorageOverride bool `gorm:"default:false" json:"allow_per_request_content_storage_override"` // Allow per-request override for content storage (e.g. long-term vs ephemeral) diff --git a/framework/configstore/tables/oauth.go b/framework/configstore/tables/oauth.go index 88c86c04e1f..144c20a5869 100644 --- a/framework/configstore/tables/oauth.go +++ b/framework/configstore/tables/oauth.go @@ -163,16 +163,33 @@ type TableOauthUserSession struct { State string `gorm:"type:varchar(255);uniqueIndex;not null" json:"-"` // CSRF state token sent to OAuth provider RedirectURI string `gorm:"type:text" json:"-"` // Per-request redirect URI used in authorize step CodeVerifier string `gorm:"type:text" json:"-"` // PKCE code verifier (kept secret) - SessionToken string `gorm:"type:varchar(255)" json:"-"` // Bifrost session ID (links to oauth_per_user_sessions) - SessionTokenHash string `gorm:"type:varchar(64);uniqueIndex" json:"-"` // SHA-256 hash of SessionToken for secure lookups - GatewaySessionID string `gorm:"type:varchar(255);index" json:"-"` // Bifrost MCP gateway session ID (separate from SessionToken) + SessionID string `gorm:"type:varchar(255);index" json:"session_id,omitempty"` // Session-mode identity: client-asserted x-bf-mcp-session-id. Empty for vk/user mode rows. Stored plaintext (not a bearer credential; same trust model as a VK value). VirtualKeyID *string `gorm:"type:varchar(255);index" json:"virtual_key_id"` // VK identity (propagated to oauth_user_tokens) - UserID *string `gorm:"type:varchar(255);index" json:"user_id"` // Enterprise user identity (propagated to oauth_user_tokens) + UserID *string `gorm:"type:varchar(255);index" json:"user_id"` // Enterprise user identity (propagated to oauth_user_tokens); nullable for deferred-fill user-mode flows + FlowMode string `gorm:"type:varchar(20);not null;default:'vk'" json:"flow_mode"` // 'user' | 'vk' | 'session' — mirrors the token row's AuthMode; immutable after creation Status string `gorm:"type:varchar(50);not null;index" json:"status"` // "pending", "authorized", "failed", "expired" EncryptionStatus string `gorm:"type:varchar(20);default:'plain_text'" json:"-"` ExpiresAt time.Time `gorm:"index;not null" json:"expires_at"` // Flow expiration (15 min) CreatedAt time.Time `gorm:"index;not null" json:"created_at"` UpdatedAt time.Time `gorm:"index;not null" json:"updated_at"` + + // Display-only relations (no DB-level FK constraint; preloaded for sessions UI). + MCPClient *TableMCPClient `gorm:"foreignKey:MCPClientID;references:ClientID" json:"-"` + VirtualKey *TableVirtualKey `gorm:"foreignKey:VirtualKeyID;references:ID" json:"-"` + + // User is a non-DB, enterprise-only annotation populated after fetch on + // user-keyed flow rows so the sessions UI can render name/email instead + // of a raw user_id. OSS has no users table; OSS leaves it nil. + User *OauthUserSummary `gorm:"-" json:"-"` +} + +// OauthUserSummary is the minimal user view embedded on user-keyed oauth rows +// for display purposes. Populated post-fetch by the enterprise configstore +// wrapper (it carries the SCIM user table data into OSS without OSS knowing +// the enterprise type). +type OauthUserSummary struct { + ID string + Name string } func (TableOauthUserSession) TableName() string { @@ -183,9 +200,6 @@ func (s *TableOauthUserSession) BeforeSave(tx *gorm.DB) error { if s.Status == "" { s.Status = "pending" } - if s.SessionToken != "" { - s.SessionTokenHash = encrypt.HashSHA256(s.SessionToken) - } if encrypt.IsEnabled() { if s.CodeVerifier != "" { if err := encryptString(&s.CodeVerifier); err != nil { @@ -207,25 +221,34 @@ func (s *TableOauthUserSession) AfterFind(tx *gorm.DB) error { } // TableOauthUserToken stores per-user OAuth credentials. -// Each record holds the access/refresh tokens for a specific user session + MCP client pair. -// Lookup is by SessionToken. +// Each record holds the access/refresh tokens for a specific identity × MCP client pair. +// Exactly one identity column (UserID, VirtualKeyID, or SessionID) is populated +// per row; AuthMode records which one. type TableOauthUserToken struct { - ID string `gorm:"type:varchar(255);primaryKey" json:"id"` // Token UUID - SessionToken string `gorm:"type:varchar(255)" json:"-"` // Maps to Bifrost session (fallback for anonymous users) - SessionTokenHash string `gorm:"type:varchar(64);index" json:"-"` // SHA-256 hash of SessionToken for secure lookups - VirtualKeyID *string `gorm:"type:varchar(255);index:idx_vk_mcp" json:"virtual_key_id"` // VK identity (persistent across sessions) - UserID *string `gorm:"type:varchar(255);index:idx_user_mcp" json:"user_id"` // Enterprise user identity (persistent across sessions) - MCPClientID string `gorm:"type:varchar(255);not null;index:idx_vk_mcp;index:idx_user_mcp" json:"mcp_client_id"` // Which MCP server - OauthConfigID string `gorm:"type:varchar(255);not null;index" json:"oauth_config_id"` // Template OAuth config - AccessToken string `gorm:"type:text;not null" json:"-"` // Encrypted user's OAuth access token - RefreshToken string `gorm:"type:text" json:"-"` // Encrypted user's OAuth refresh token - TokenType string `gorm:"type:varchar(50);not null" json:"token_type"` // "Bearer" - ExpiresAt *time.Time `gorm:"index" json:"expires_at,omitempty"` // Token expiry (nil means unknown/non-expiring) - Scopes string `gorm:"type:text" json:"scopes"` // JSON array of granted scopes - LastRefreshedAt *time.Time `gorm:"index" json:"last_refreshed_at,omitempty"` // Last refresh time + ID string `gorm:"type:varchar(255);primaryKey" json:"id"` // Token UUID + SessionID string `gorm:"type:varchar(255);index" json:"session_id,omitempty"` // Session-mode identity: client-asserted x-bf-mcp-session-id. Empty for vk/user mode rows. + VirtualKeyID *string `gorm:"type:varchar(255);index" json:"virtual_key_id"` // VK identity (vk-mode rows) + UserID *string `gorm:"type:varchar(255);index" json:"user_id"` // User identity (user-mode rows; populated by enterprise middleware/governance) + MCPClientID string `gorm:"type:varchar(255);not null;index" json:"mcp_client_id"` // Which MCP server + AuthMode string `gorm:"type:varchar(20);not null" json:"auth_mode"` // 'user' | 'vk' | 'session' — which identity column keys this row + Status string `gorm:"type:varchar(20);not null;default:'active'" json:"status"` // 'active' | 'orphaned' | 'needs_reauth' — only 'active' satisfies a runtime lookup; the others are surfaced in the UI with distinct copy + OauthConfigID string `gorm:"type:varchar(255);not null;index" json:"oauth_config_id"` // Template OAuth config + AccessToken string `gorm:"type:text;not null" json:"-"` // Encrypted user's OAuth access token + RefreshToken string `gorm:"type:text" json:"-"` // Encrypted user's OAuth refresh token + TokenType string `gorm:"type:varchar(50);not null" json:"token_type"` // "Bearer" + ExpiresAt *time.Time `gorm:"index" json:"expires_at,omitempty"` // Token expiry (nil means unknown/non-expiring) + Scopes string `gorm:"type:text" json:"scopes"` // JSON array of granted scopes + LastRefreshedAt *time.Time `gorm:"index" json:"last_refreshed_at,omitempty"` // Last refresh time EncryptionStatus string `gorm:"type:varchar(20);default:'plain_text'" json:"-"` CreatedAt time.Time `gorm:"index;not null" json:"created_at"` UpdatedAt time.Time `gorm:"index;not null" json:"updated_at"` + + // Display-only relations (no DB-level FK constraint; preloaded for sessions UI). + MCPClient *TableMCPClient `gorm:"foreignKey:MCPClientID;references:ClientID" json:"-"` + VirtualKey *TableVirtualKey `gorm:"foreignKey:VirtualKeyID;references:ID" json:"-"` + + // User mirrors TableOauthUserSession.User — see OauthUserSummary above. + User *OauthUserSummary `gorm:"-" json:"-"` } func (TableOauthUserToken) TableName() string { @@ -236,9 +259,6 @@ func (t *TableOauthUserToken) BeforeSave(tx *gorm.DB) error { if t.TokenType == "" { t.TokenType = "Bearer" } - if t.SessionToken != "" { - t.SessionTokenHash = encrypt.HashSHA256(t.SessionToken) - } if encrypt.IsEnabled() { if err := encryptString(&t.AccessToken); err != nil { return fmt.Errorf("failed to encrypt oauth user access token: %w", err) @@ -262,136 +282,3 @@ func (t *TableOauthUserToken) AfterFind(tx *gorm.DB) error { } return nil } - -// ---------- Per-User OAuth Authorization Server Tables ---------- - -// TablePerUserOAuthClient stores dynamically registered OAuth clients (RFC 7591). -// MCP clients (like Claude Code) register themselves with Bifrost's OAuth -// authorization server to obtain a client_id for the authorization code flow. -type TablePerUserOAuthClient struct { - ID string `gorm:"type:varchar(255);primaryKey" json:"id"` - ClientID string `gorm:"type:varchar(255);uniqueIndex;not null" json:"client_id"` - ClientName string `gorm:"type:varchar(255)" json:"client_name"` - RedirectURIs string `gorm:"type:text;not null" json:"redirect_uris"` // JSON array of allowed redirect URIs - GrantTypes string `gorm:"type:text" json:"grant_types"` // JSON array of grant types - CreatedAt time.Time `gorm:"index;not null" json:"created_at"` - UpdatedAt time.Time `gorm:"index;not null" json:"updated_at"` -} - -// TableName returns the table name for per-user OAuth clients. -func (TablePerUserOAuthClient) TableName() string { - return "oauth_per_user_clients" -} - -// TablePerUserOAuthSession stores Bifrost-issued access tokens for authenticated -// MCP connections. When a user authenticates via Bifrost's OAuth flow, a session -// is created. The access token is included in all subsequent MCP requests. -// Upstream provider tokens are linked via the oauth_user_tokens table. -type TablePerUserOAuthSession struct { - ID string `gorm:"type:varchar(255);primaryKey" json:"id"` - AccessToken string `gorm:"type:text;not null" json:"-"` // Bifrost-issued access token (encrypted) - AccessTokenHash string `gorm:"type:varchar(64);uniqueIndex" json:"-"` // SHA-256 hash for secure lookups - RefreshToken string `gorm:"type:text" json:"-"` // Bifrost-issued refresh token (encrypted, optional) - RefreshTokenHash string `gorm:"type:varchar(64);index" json:"-"` // SHA-256 hash for secure lookups (not unique — refresh tokens are optional) - ClientID string `gorm:"type:varchar(255);not null;index" json:"client_id"` // Which OAuth client registered this session - VirtualKeyID *string `gorm:"type:varchar(255);index" json:"virtual_key_id"` // Linked VK identity (set when VK is present during auth) - VirtualKey *TableVirtualKey `gorm:"foreignKey:VirtualKeyID" json:"-"` // Linked VK identity (server-only, not serialized) - UserID *string `gorm:"type:varchar(255);index" json:"user_id"` // Linked enterprise user identity (set when user ID is present) - ExpiresAt time.Time `gorm:"index;not null" json:"expires_at"` - EncryptionStatus string `gorm:"type:varchar(20);default:'plain_text'" json:"-"` - CreatedAt time.Time `gorm:"index;not null" json:"created_at"` - UpdatedAt time.Time `gorm:"index;not null" json:"updated_at"` -} - -// TableName returns the table name for per-user OAuth sessions. -func (TablePerUserOAuthSession) TableName() string { - return "oauth_per_user_sessions" -} - -// BeforeSave encrypts sensitive fields. -func (s *TablePerUserOAuthSession) BeforeSave(tx *gorm.DB) error { - if s.AccessToken != "" { - s.AccessTokenHash = encrypt.HashSHA256(s.AccessToken) - } - if s.RefreshToken != "" { - s.RefreshTokenHash = encrypt.HashSHA256(s.RefreshToken) - } - if encrypt.IsEnabled() { - if err := encryptString(&s.AccessToken); err != nil { - return fmt.Errorf("failed to encrypt per-user oauth access token: %w", err) - } - if s.RefreshToken != "" { - if err := encryptString(&s.RefreshToken); err != nil { - return fmt.Errorf("failed to encrypt per-user oauth refresh token: %w", err) - } - } - s.EncryptionStatus = EncryptionStatusEncrypted - } - return nil -} - -// AfterFind decrypts sensitive fields. -func (s *TablePerUserOAuthSession) AfterFind(tx *gorm.DB) error { - if s.EncryptionStatus == EncryptionStatusEncrypted { - if err := decryptString(&s.AccessToken); err != nil { - return fmt.Errorf("failed to decrypt per-user oauth access token: %w", err) - } - if s.RefreshToken != "" { - if err := decryptString(&s.RefreshToken); err != nil { - return fmt.Errorf("failed to decrypt per-user oauth refresh token: %w", err) - } - } - } - return nil -} - -// TablePerUserOAuthCode stores authorization codes during the OAuth flow. -// Codes are short-lived (5 minutes) and single-use. -type TablePerUserOAuthCode struct { - ID string `gorm:"type:varchar(255);primaryKey" json:"id"` - Code string `gorm:"type:text;not null" json:"-"` // Authorization code - CodeHash string `gorm:"type:varchar(64);uniqueIndex" json:"-"` // SHA-256 hash for secure lookups - ClientID string `gorm:"type:varchar(255);not null;index" json:"client_id"` - RedirectURI string `gorm:"type:text;not null" json:"redirect_uri"` - CodeChallenge string `gorm:"type:varchar(255);not null" json:"-"` // PKCE S256 challenge - Scopes string `gorm:"type:text" json:"scopes"` // JSON array of requested scopes - SessionID string `gorm:"type:varchar(255);index" json:"-"` // Links to the TablePerUserOAuthSession created during consent submit - ExpiresAt time.Time `gorm:"index;not null" json:"expires_at"` // 5 min TTL - Used bool `gorm:"default:false;not null" json:"used"` // Single-use flag - CreatedAt time.Time `gorm:"index;not null" json:"created_at"` -} - -// BeforeSave hashes the code for secure lookups. -func (c *TablePerUserOAuthCode) BeforeSave(tx *gorm.DB) error { - if c.Code != "" { - c.CodeHash = encrypt.HashSHA256(c.Code) - } - return nil -} - -// TableName returns the table name for per-user OAuth authorization codes. -func (TablePerUserOAuthCode) TableName() string { - return "oauth_per_user_codes" -} - -// TablePerUserOAuthPendingFlow stores OAuth parameters between the authorize step -// and the final code issuance. It carries state through the multi-step consent -// screen (VK entry + per-MCP upstream auth) before a real authorization code is issued. -type TablePerUserOAuthPendingFlow struct { - ID string `gorm:"type:varchar(255);primaryKey" json:"id"` - ClientID string `gorm:"type:varchar(255);not null;index" json:"client_id"` // Registered OAuth client (from authorize request) - RedirectURI string `gorm:"type:text;not null" json:"redirect_uri"` // Client's callback URL - CodeChallenge string `gorm:"type:varchar(255);not null" json:"-"` // PKCE S256 challenge (echoed into the final code) - State string `gorm:"type:text;not null" json:"-"` // Original OAuth state (echoed back on final redirect) - VirtualKeyID *string `gorm:"type:varchar(255);index" json:"virtual_key_id"` // Set if user chose VK identity - UserID *string `gorm:"type:varchar(255);index" json:"user_id"` // Set if user chose User ID identity - BrowserSecretHash string `gorm:"type:varchar(255)" json:"-"` // SHA-256 hash of browser-binding cookie secret - ExpiresAt time.Time `gorm:"index;not null" json:"expires_at"` // 15-min TTL - CreatedAt time.Time `gorm:"index;not null" json:"created_at"` - UpdatedAt time.Time `gorm:"index;not null" json:"updated_at"` -} - -// TableName returns the table name for per-user OAuth pending flows. -func (TablePerUserOAuthPendingFlow) TableName() string { - return "oauth_per_user_pending_flows" -} diff --git a/framework/oauth2/main.go b/framework/oauth2/main.go index f8e5a69631d..de545b1bd1e 100644 --- a/framework/oauth2/main.go +++ b/framework/oauth2/main.go @@ -3,6 +3,7 @@ package oauth2 import ( "context" "crypto/rand" + "crypto/sha256" "encoding/base64" "encoding/json" "errors" @@ -591,34 +592,94 @@ func (p *OAuth2Provider) CompleteOAuthFlow(ctx context.Context, state, code stri return nil } -// buildAuthorizeURLWithPKCE constructs the OAuth authorization URL with PKCE parameters -func (p *OAuth2Provider) buildAuthorizeURLWithPKCE(authorizeURL, clientID, redirectURI, state, codeChallenge string, scopes []string) string { - params := url.Values{} - params.Set("response_type", "code") - params.Set("client_id", clientID) - params.Set("redirect_uri", redirectURI) - params.Set("state", state) - params.Set("code_challenge", codeChallenge) - params.Set("code_challenge_method", "S256") // SHA-256 hashing - if len(scopes) > 0 { - params.Set("scope", strings.Join(scopes, " ")) +// BuildUpstreamAuthorizeURL reconstructs the upstream provider authorization +// URL for a pending per-user OAuth flow. Called by the frontend sessions tab +// when the user clicks "Authenticate" — at which point the flow row already +// exists (from a prior InitiateUserOAuthFlow), the CSRF state + PKCE verifier +// are stored on it, and we just need to hand the user the upstream redirect. +// +// The code_challenge is recomputed deterministically from the stored verifier +// so we don't have to persist it separately. +func (p *OAuth2Provider) BuildUpstreamAuthorizeURL(ctx context.Context, flowID string) (string, error) { + flow, err := p.configStore.GetOauthUserSessionByID(ctx, flowID) + if err != nil { + return "", fmt.Errorf("failed to load pending oauth flow: %w", err) + } + if flow == nil { + return "", schemas.ErrOAuth2NotPerUserSession } + if flow.Status != "pending" { + return "", fmt.Errorf("oauth flow %s is %s: %w", flowID, flow.Status, schemas.ErrOAuth2FlowNotPending) + } + if time.Now().After(flow.ExpiresAt) { + return "", fmt.Errorf("oauth flow %s: %w", flowID, schemas.ErrOAuth2FlowExpired) + } + templateConfig, err := p.configStore.GetOauthConfigByID(ctx, flow.OauthConfigID) + if err != nil { + return "", fmt.Errorf("failed to load template oauth config: %w", err) + } + if templateConfig == nil { + return "", schemas.ErrOAuth2ConfigNotFound + } + // Recompute the PKCE challenge from the stored verifier (deterministic). + hash := sha256.Sum256([]byte(flow.CodeVerifier)) + codeChallenge := base64.RawURLEncoding.EncodeToString(hash[:]) - return authorizeURL + "?" + params.Encode() + var scopes []string + if templateConfig.Scopes != "" { + if err := json.Unmarshal([]byte(templateConfig.Scopes), &scopes); err != nil { + return "", fmt.Errorf("failed to parse oauth scopes for flow %s: %w", flowID, err) + } + } + redirectURI := flow.RedirectURI + if redirectURI == "" { + redirectURI = templateConfig.RedirectURI + } + return p.buildAuthorizeURLWithPKCE( + templateConfig.AuthorizeURL, + templateConfig.GetResolvedClientID(), + redirectURI, + flow.State, + codeChallenge, + scopes, + ), nil } -// exchangeCodeForTokens exchanges authorization code for access/refresh tokens -func (p *OAuth2Provider) exchangeCodeForTokens(ctx context.Context, tokenURL, code, clientID, clientSecret, redirectURI string) (*schemas.OAuth2TokenExchangeResponse, error) { - data := url.Values{} - data.Set("grant_type", "authorization_code") - data.Set("code", code) - data.Set("redirect_uri", redirectURI) - data.Set("client_id", clientID) - if clientSecret != "" { - data.Set("client_secret", clientSecret) +// buildAuthorizeURLWithPKCE constructs the OAuth authorization URL with PKCE +// parameters, preserving any query params already present on the stored +// authorizeURL. Naive "authorizeURL + ?" + params.Encode() concatenation +// would produce malformed URLs like "...?existing=1?response_type=code" when +// the provider's stored URL is already parameterized. +func (p *OAuth2Provider) buildAuthorizeURLWithPKCE(authorizeURL, clientID, redirectURI, state, codeChallenge string, scopes []string) string { + parsed, err := url.Parse(authorizeURL) + if err != nil { + // Fall back to the naive form rather than dropping the auth URL — + // callers expect a non-empty return. The OAuth provider will reject + // a malformed URL, which is the same end state as not redirecting. + params := url.Values{} + params.Set("response_type", "code") + params.Set("client_id", clientID) + params.Set("redirect_uri", redirectURI) + params.Set("state", state) + params.Set("code_challenge", codeChallenge) + params.Set("code_challenge_method", "S256") + if len(scopes) > 0 { + params.Set("scope", strings.Join(scopes, " ")) + } + return authorizeURL + "?" + params.Encode() + } + q := parsed.Query() + q.Set("response_type", "code") + q.Set("client_id", clientID) + q.Set("redirect_uri", redirectURI) + q.Set("state", state) + q.Set("code_challenge", codeChallenge) + q.Set("code_challenge_method", "S256") // SHA-256 hashing + if len(scopes) > 0 { + q.Set("scope", strings.Join(scopes, " ")) } - - return p.callTokenEndpoint(ctx, tokenURL, data) + parsed.RawQuery = q.Encode() + return parsed.String() } // exchangeCodeForTokensWithPKCE exchanges authorization code for access/refresh tokens with PKCE verifier @@ -783,21 +844,21 @@ func generateSecureRandomString(length int) (string, error) { return base64.URLEncoding.EncodeToString(bytes)[:length], nil } -// generateSessionToken generates a cryptographically secure opaque session token (hex-encoded) -func generateSessionToken() (string, error) { - bytes := make([]byte, 32) - if _, err := rand.Read(bytes); err != nil { - return "", fmt.Errorf("failed to generate session token: %w", err) - } - return fmt.Sprintf("%x", bytes), nil -} - // ---------- Per-User OAuth Methods ---------- -// InitiateUserOAuthFlow creates a per-user OAuth session and returns the authorization URL. -// It reuses the template OAuth config (which holds client_id, token_url, etc.) to build the flow. -func (p *OAuth2Provider) InitiateUserOAuthFlow(ctx context.Context, oauthConfigID string, mcpClientID string, redirectURI string) (*schemas.OAuth2FlowInitiation, string, error) { - // Load the template OAuth config +// InitiateUserOAuthFlow creates or refreshes the per-user OAuth flow row for a +// given (mode, identity, mcp_client) binding and returns the auth landing URL. +// +// Determinism: there is exactly one flow row per binding. If one already exists +// (from a prior auth attempt), it's updated in place — fresh CSRF state, fresh +// PKCE verifier, status reset to 'pending'. Otherwise a new row is inserted. +// Reauth never duplicates rows; revoke deletes them. +// +// The function errors out cleanly on any misconfig (missing identity, unknown +// mode, missing template config) — no fallbacks, no generated identities. +func (p *OAuth2Provider) InitiateUserOAuthFlow(ctx context.Context, oauthConfigID string, mcpClientID string, redirectURI string, flowMode schemas.MCPAuthMode) (*schemas.OAuth2FlowInitiation, string, error) { + + // 1. Load template OAuth config. templateConfig, err := p.configStore.GetOauthConfigByID(ctx, oauthConfigID) if err != nil { return nil, "", fmt.Errorf("failed to load template oauth config: %w", err) @@ -806,112 +867,128 @@ func (p *OAuth2Provider) InitiateUserOAuthFlow(ctx context.Context, oauthConfigI return nil, "", schemas.ErrOAuth2ConfigNotFound } - // Generate state token for CSRF protection + // 2. Resolve identity from context for the given mode. Required (no + // fallbacks). Each mode populates exactly one of (vkId, uid, sessionID). + var ( + vkId, uid *string + sessionID, lookupID string + ) + switch flowMode { + case schemas.MCPAuthModeUser: + v, _ := ctx.Value(schemas.BifrostContextKeyUserID).(string) + if v == "" { + // Deferred-fill: external MCP client OAuth init where the user + // identity is stamped at completion time. No identity → no + // existing-row lookup; we always insert a fresh row. + uid = nil + } else { + uid = &v + lookupID = v + } + case schemas.MCPAuthModeVK: + v, _ := ctx.Value(schemas.BifrostContextKeyGovernanceVirtualKeyID).(string) + if v == "" { + return nil, "", fmt.Errorf("vk-mode flow requires a resolved virtual key in context") + } + vkId = &v + lookupID = v + case schemas.MCPAuthModeSession: + v, _ := ctx.Value(schemas.BifrostContextKeyMCPSessionID).(string) + if v == "" { + return nil, "", fmt.Errorf("session-mode flow requires x-bf-mcp-session-id in context") + } + sessionID = v + lookupID = v + default: + return nil, "", fmt.Errorf("unknown auth mode for flow: %s", flowMode) + } + + // 3. Generate fresh CSRF state + PKCE verifier for this attempt. state, err := generateSecureRandomString(32) if err != nil { return nil, "", fmt.Errorf("failed to generate state token: %w", err) } - - // Generate PKCE challenge - codeVerifier, codeChallenge, err := GeneratePKCEChallenge() + codeVerifier, _, err := GeneratePKCEChallenge() if err != nil { return nil, "", fmt.Errorf("failed to generate PKCE challenge: %w", err) } - - // Parse scopes from template config - var scopes []string - if templateConfig.Scopes != "" { - json.Unmarshal([]byte(templateConfig.Scopes), &scopes) - } - - // Create per-user OAuth session - sessionID := uuid.New().String() expiresAt := time.Now().Add(15 * time.Minute) - // Propagate identity from context so the callback can link the token to the user - virtualKeyID, _ := ctx.Value(schemas.BifrostContextKeyGovernanceVirtualKeyID).(string) - userID, _ := ctx.Value(schemas.BifrostContextKeyUserID).(string) - // For OSS: prefer X-Bf-User-Id header as user identity - if mcpUserID, _ := ctx.Value(schemas.BifrostContextKeyMCPUserID).(string); mcpUserID != "" { - userID = mcpUserID - } - - // If a Bifrost MCP session token is present in context, reuse it as the session token - // so the MCP server token is stored under the same key used for subsequent lookups. - // Otherwise generate a fresh token. - sessionToken, _ := ctx.Value(schemas.BifrostContextKeyMCPUserSession).(string) - if sessionToken == "" { - sessionToken, err = generateSessionToken() - if err != nil { - return nil, "", fmt.Errorf("failed to generate session token: %w", err) + // 4. Single canonical lookup: one flow row per (mode, identity, mcp_client). + // Deferred-fill user-mode (lookupID empty) always inserts a fresh row. + // + // Only treat a 'pending' hit as reusable. A 'claiming' row means an + // upstream callback is mid-flight for this binding — rotating its + // state/PKCE here would invalidate that callback's state token and + // leave the user with an "OAuth flow not found" error. Falling through + // to insert a fresh row lets both flows complete independently. + var existing *tables.TableOauthUserSession + if lookupID != "" { + found, lookupErr := p.configStore.GetOauthUserSessionByModeIdentityAndMCPClient(ctx, flowMode, lookupID, mcpClientID) + if lookupErr != nil { + return nil, "", fmt.Errorf("failed to look up existing flow row: %w", lookupErr) + } + if found != nil && found.Status == "pending" { + existing = found } } - var vkId *string - if virtualKeyID != "" { - vkId = &virtualKeyID - } - var uid *string - if userID != "" { - uid = &userID - } - // session_token_hash has a unique index, so if the user is re-authenticating - // with a session token that already has a row (e.g. after a previous - // authorized flow whose tokens later got purged), we must update the - // existing row rather than insert a fresh one — otherwise INSERT trips the - // unique constraint. The CSRF state, PKCE verifier, and flow expiry are - // always rotated; identity fields refresh from the current context. - existing, err := p.configStore.GetOauthUserSessionBySessionToken(ctx, sessionToken) - if err != nil { - return nil, "", fmt.Errorf("failed to lookup per-user oauth session for re-auth: %w", err) - } + + var rowID string if existing != nil { - existing.MCPClientID = mcpClientID + // Reauth path: update the same row in place. Identity columns already + // match (we looked them up); only rotate the OAuth-dance fields. existing.OauthConfigID = oauthConfigID existing.State = state existing.RedirectURI = redirectURI existing.CodeVerifier = codeVerifier - existing.VirtualKeyID = vkId - existing.UserID = uid existing.Status = "pending" existing.ExpiresAt = expiresAt if err := p.configStore.UpdateOauthUserSession(ctx, existing); err != nil { - return nil, "", fmt.Errorf("failed to update per-user oauth session for re-auth: %w", err) + return nil, "", fmt.Errorf("failed to update flow row for reauth: %w", err) } - sessionID = existing.ID + rowID = existing.ID } else { - session := &tables.TableOauthUserSession{ - ID: sessionID, + // First-time auth (or deferred-fill user): insert a new row. SessionID + // is populated only for session-mode (the caller's x-bf-mcp-session-id); + // vk/user-mode rows have an empty SessionID — their identity lives in + // virtual_key_id / user_id. + row := &tables.TableOauthUserSession{ + ID: uuid.New().String(), MCPClientID: mcpClientID, OauthConfigID: oauthConfigID, State: state, RedirectURI: redirectURI, CodeVerifier: codeVerifier, - SessionToken: sessionToken, + SessionID: sessionID, VirtualKeyID: vkId, UserID: uid, + FlowMode: string(flowMode), Status: "pending", ExpiresAt: expiresAt, } - if err := p.configStore.CreateOauthUserSession(ctx, session); err != nil { - return nil, "", fmt.Errorf("failed to create per-user oauth session: %w", err) + if err := p.configStore.CreateOauthUserSession(ctx, row); err != nil { + return nil, "", fmt.Errorf("failed to create flow row: %w", err) } + rowID = row.ID } + sessionID = rowID - // Build authorize URL with PKCE - authURL := p.buildAuthorizeURLWithPKCE( - templateConfig.AuthorizeURL, - templateConfig.GetResolvedClientID(), - redirectURI, - state, - codeChallenge, - scopes, - ) + // Frontend URL the user (or their teammate) opens in a browser. The + // upstream provider URL is reconstructed on demand by the /flows/:id/start + // endpoint using the stored CSRF state + PKCE verifier — we don't pin it + // here so the row stays the single source of truth for those fields. + // + // Derive the Bifrost base URL from the OAuth callback redirect URI passed + // in by the caller — it always has the shape "{base}/api/oauth/callback". + // Flow ID rides as a query param to match the flat-route convention used + // elsewhere in the dashboard UI. + frontendURL := strings.TrimSuffix(redirectURI, "/api/oauth/callback") + "/workspace/mcp-sessions/auth?flow=" + sessionID logger.Debug("Per-user OAuth flow initiated: session_id=%s, mcp_client_id=%s", sessionID, mcpClientID) return &schemas.OAuth2FlowInitiation{ OauthConfigID: oauthConfigID, - AuthorizeURL: authURL, + AuthorizeURL: frontendURL, State: state, ExpiresAt: expiresAt, }, sessionID, nil @@ -930,20 +1007,28 @@ func (p *OAuth2Provider) CompleteUserOAuthFlow(ctx context.Context, state string return "", schemas.ErrOAuth2NotPerUserSession } - // Check expiry + // Check expiry. Flow rows are deleted on every terminal transition + // (authorized / failed / expired) so the table doesn't accumulate + // dead rows. The UI sees 404 on flow-detail and renders "expired + // or already completed" — no audit trail to preserve here. if time.Now().After(session.ExpiresAt) { - session.Status = "expired" - p.configStore.UpdateOauthUserSession(ctx, session) + _ = p.configStore.DeleteOauthUserSession(ctx, session.ID) return "", fmt.Errorf("per-user oauth flow expired") } - // Load template OAuth config for token_url, client_id, etc. + // Load template OAuth config for token_url, client_id, etc. Split the + // nil-config case from a real lookup failure — otherwise wrapping a nil + // error with %w produces a useless "%!w()" string and the real cause + // (config row missing) is hidden. templateConfig, err := p.configStore.GetOauthConfigByID(ctx, session.OauthConfigID) - if err != nil || templateConfig == nil { - session.Status = "failed" - p.configStore.UpdateOauthUserSession(ctx, session) + if err != nil { + _ = p.configStore.DeleteOauthUserSession(ctx, session.ID) return "", fmt.Errorf("failed to load template oauth config: %w", err) } + if templateConfig == nil { + _ = p.configStore.DeleteOauthUserSession(ctx, session.ID) + return "", schemas.ErrOAuth2ConfigNotFound + } // Exchange code for tokens with PKCE verifier // Use the redirect URI stored in the session (same one used in authorize step) // to satisfy OAuth spec requirement that redirect_uri must match @@ -961,22 +1046,14 @@ func (p *OAuth2Provider) CompleteUserOAuthFlow(ctx context.Context, state string session.CodeVerifier, ) if err != nil { - session.Status = "failed" - p.configStore.UpdateOauthUserSession(ctx, session) + _ = p.configStore.DeleteOauthUserSession(ctx, session.ID) return "", fmt.Errorf("per-user token exchange failed: %w", err) } - // Use existing session token if set (e.g., Bifrost session ID from MCP spec OAuth flow), - // otherwise generate a new one (for standalone per-user OAuth). - sessionToken := session.SessionToken - if sessionToken == "" { - sessionToken, err = generateSessionToken() - if err != nil { - session.Status = "failed" - p.configStore.UpdateOauthUserSession(ctx, session) - return "", err - } - } + // SessionID is carried from the flow row as-is: populated for session-mode + // flows (the caller's x-bf-mcp-session-id) and empty for vk/user-mode. + // No fallback generation — identity for vk/user lives in their own columns. + sessionID := session.SessionID // Parse scopes var scopes []string @@ -985,7 +1062,47 @@ func (p *OAuth2Provider) CompleteUserOAuthFlow(ctx context.Context, state string } scopesJSON, _ := json.Marshal(scopes) - // Create per-user OAuth token record, propagating identity from session + // Resolve identity columns from the flow row, honoring its flow_mode. Only + // the column that matches the mode is populated on the token row; the others + // stay nil to maintain the single-identity invariant. For user-mode flows + // where the row's UserID was deferred at init time, stamp from completer + // context here. + flowMode := schemas.MCPAuthMode(session.FlowMode) + var ( + tokenVKID *string + tokenUserID *string + ) + switch flowMode { + case schemas.MCPAuthModeUser: + tokenUserID = session.UserID + if tokenUserID == nil || *tokenUserID == "" { + // Deferred fill: pull from completer context. + if v, _ := ctx.Value(schemas.BifrostContextKeyUserID).(string); v != "" { + tokenUserID = &v + } + } + if tokenUserID == nil || *tokenUserID == "" { + _ = p.configStore.DeleteOauthUserSession(ctx, session.ID) + return "", fmt.Errorf("user-mode oauth flow has no user_id at completion (neither flow nor completer context)") + } + // Stamp the resolved user_id back on the flow for audit. + session.UserID = tokenUserID + case schemas.MCPAuthModeVK: + tokenVKID = session.VirtualKeyID + if tokenVKID == nil || *tokenVKID == "" { + _ = p.configStore.DeleteOauthUserSession(ctx, session.ID) + return "", fmt.Errorf("vk-mode oauth flow has no virtual_key_id at completion") + } + case schemas.MCPAuthModeSession: + // Both identity columns left nil; row is keyed by session_id. + default: + // Bogus flow_mode on the row — drop it so a fresh flow can start + // instead of leaving the row stuck in 'claiming' forever. + _ = p.configStore.DeleteOauthUserSession(ctx, session.ID) + return "", fmt.Errorf("invalid flow mode on session: %s", session.ID) + } + + // Create per-user OAuth token record var expiresAt *time.Time if tokenResponse.ExpiresIn > 0 { exp := time.Now().Add(time.Duration(tokenResponse.ExpiresIn) * time.Second) @@ -993,9 +1110,9 @@ func (p *OAuth2Provider) CompleteUserOAuthFlow(ctx context.Context, state string } tokenRecord := &tables.TableOauthUserToken{ ID: uuid.New().String(), - SessionToken: sessionToken, - VirtualKeyID: session.VirtualKeyID, - UserID: session.UserID, + SessionID: sessionID, + VirtualKeyID: tokenVKID, + UserID: tokenUserID, MCPClientID: session.MCPClientID, OauthConfigID: session.OauthConfigID, AccessToken: strings.TrimSpace(tokenResponse.AccessToken), @@ -1003,41 +1120,52 @@ func (p *OAuth2Provider) CompleteUserOAuthFlow(ctx context.Context, state string TokenType: tokenResponse.TokenType, ExpiresAt: expiresAt, Scopes: string(scopesJSON), + AuthMode: string(flowMode), + Status: "active", } if err := p.configStore.CreateOauthUserToken(ctx, tokenRecord); err != nil { + // The flow row has already been claimed and the auth code has been + // exchanged; leaving the row in 'claiming' state would block the + // next initiation for this binding indefinitely. Drop it so the + // caller can restart cleanly. + _ = p.configStore.DeleteOauthUserSession(ctx, session.ID) return "", fmt.Errorf("failed to create per-user oauth token: %w", err) } - // Update session with session token and mark as authorized - session.SessionToken = sessionToken - session.Status = "authorized" - if err := p.configStore.UpdateOauthUserSession(ctx, session); err != nil { - return "", fmt.Errorf("failed to update per-user oauth session: %w", err) + // Token row is written; the flow row's purpose ends here. Delete it + // instead of marking 'authorized' — the token row is the durable + // record of the binding; the flow row is just the transient PKCE/ + // state carrier. The UI shows "expired or already completed" on the + // resulting 404, which is the truthful read. + if err := p.configStore.DeleteOauthUserSession(ctx, session.ID); err != nil { + // Non-fatal: log but proceed. The token row is already created + // and usable; a lingering flow row is hygienic, not correctness. + logger.Warn("per-user OAuth flow row cleanup failed (token already created): session_id=%s err=%v", session.ID, err) } logger.Debug("Per-user OAuth flow completed: session_id=%s, mcp_client_id=%s", session.ID, session.MCPClientID) - return sessionToken, nil + return sessionID, nil } -// GetUserAccessToken retrieves the access token for a per-user OAuth session. -// If the token is expired, it automatically attempts a refresh. -func (p *OAuth2Provider) GetUserAccessToken(ctx context.Context, sessionToken string) (string, error) { - token, err := p.configStore.GetOauthUserTokenBySessionToken(ctx, sessionToken) +// GetUserAccessTokenByMode retrieves the upstream access token using exactly +// one identity column determined by mode. No fallback chain. Filters +// status='active' so orphaned rows never satisfy a lookup. +func (p *OAuth2Provider) GetUserAccessTokenByMode(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) (string, error) { + token, err := p.configStore.GetOauthUserTokenByMode(ctx, mode, identity, mcpClientID) if err != nil { - return "", fmt.Errorf("failed to load per-user oauth token: %w", err) + return "", fmt.Errorf("failed to load per-user oauth token (mode=%s): %w", mode, err) } if token == nil { - return "", fmt.Errorf("per-user oauth token not found for session") + return "", schemas.ErrOAuth2TokenNotFound } // Refresh only when known-expired and refresh token exists. if token.ExpiresAt != nil && time.Now().After(*token.ExpiresAt) && strings.TrimSpace(token.RefreshToken) != "" { - if err := p.RefreshUserAccessToken(ctx, sessionToken); err != nil { + if err := p.RefreshUserAccessToken(ctx, token.ID); err != nil { return "", fmt.Errorf("per-user token expired and refresh failed: %w", err) } - // Reload token after refresh - token, err = p.configStore.GetOauthUserTokenBySessionToken(ctx, sessionToken) + token, err = p.configStore.GetOauthUserTokenByMode(ctx, mode, identity, mcpClientID) if err != nil || token == nil { return "", fmt.Errorf("failed to reload per-user token after refresh") } @@ -1053,64 +1181,31 @@ func (p *OAuth2Provider) GetUserAccessToken(ctx context.Context, sessionToken st return accessToken, nil } -// GetUserAccessTokenByIdentity retrieves the upstream access token for a user -// identified by virtualKeyID, userID, or sessionToken (fallback), for a specific -// MCP client. Identity-based lookups persist tokens across sessions so users don't -// need to re-authenticate with upstream providers on reconnect. -func (p *OAuth2Provider) GetUserAccessTokenByIdentity(ctx context.Context, virtualKeyID, userID, sessionToken, mcpClientID string) (string, error) { - token, err := p.configStore.GetOauthUserTokenByIdentity(ctx, virtualKeyID, userID, sessionToken, mcpClientID) - if err != nil { - return "", fmt.Errorf("failed to load per-user oauth token by identity: %w", err) - } - if token == nil { - return "", schemas.ErrOAuth2TokenNotFound - } - - // Refresh only when known-expired and refresh token exists. - if token.ExpiresAt != nil && time.Now().After(*token.ExpiresAt) && strings.TrimSpace(token.RefreshToken) != "" { - if token.SessionToken != "" { - if err := p.RefreshUserAccessToken(ctx, token.SessionToken); err != nil { - return "", fmt.Errorf("per-user token expired and refresh failed: %w", err) - } - // Reload after refresh - token, err = p.configStore.GetOauthUserTokenByIdentity(ctx, virtualKeyID, userID, sessionToken, mcpClientID) - if err != nil || token == nil { - return "", fmt.Errorf("failed to reload per-user token after refresh") - } - } else { - return "", fmt.Errorf("per-user token expired and no session token available for refresh") - } - } - if token.ExpiresAt != nil && time.Now().After(*token.ExpiresAt) { - return "", fmt.Errorf("per-user token expired and no refresh token is available; re-authorization required: %w", schemas.ErrOAuth2TokenExpired) - } - - accessToken := strings.TrimSpace(token.AccessToken) - if accessToken == "" { - return "", fmt.Errorf("per-user access token is empty after sanitization") - } - return accessToken, nil -} - -// RefreshUserAccessToken refreshes a per-user OAuth access token. -func (p *OAuth2Provider) RefreshUserAccessToken(ctx context.Context, sessionToken string) error { +// RefreshUserAccessToken refreshes a per-user OAuth access token, looked up +// by the token row's primary-key ID. +func (p *OAuth2Provider) RefreshUserAccessToken(ctx context.Context, tokenID string) error { p.mu.Lock() defer p.mu.Unlock() - token, err := p.configStore.GetOauthUserTokenBySessionToken(ctx, sessionToken) + token, err := p.configStore.GetOauthUserTokenByID(ctx, tokenID) if err != nil || token == nil { return fmt.Errorf("per-user oauth token not found: %w", err) } if token.RefreshToken == "" { - return fmt.Errorf("no refresh token available for per-user oauth session") + return fmt.Errorf("no refresh token available for per-user oauth token") } - // Load template OAuth config for token_url, client_id, etc. + // Load template OAuth config for token_url, client_id, etc. Split nil + // from a real lookup failure so a missing config doesn't surface as a + // useless "%!w()" wrapped error. templateConfig, err := p.configStore.GetOauthConfigByID(ctx, token.OauthConfigID) - if err != nil || templateConfig == nil { + if err != nil { return fmt.Errorf("failed to load template oauth config for refresh: %w", err) } + if templateConfig == nil { + return schemas.ErrOAuth2ConfigNotFound + } // Exchange refresh token newTokenResponse, err := p.exchangeRefreshToken( @@ -1124,34 +1219,26 @@ func (p *OAuth2Provider) RefreshUserAccessToken(ctx context.Context, sessionToke // Permanent rejection (HTTP 401, or 400 with invalid_grant / // unauthorized_client per RFC 6749 §5.2) means the refresh token is // dead — revoked, expired, or bound to a grant the AS no longer - // honors. Purge the row and signal re-authentication via the - // ErrOAuth2TokenExpired sentinel, which ResolvePerUserOAuthToken + // honors. Flip the row to 'needs_reauth' and signal re-authentication + // via the ErrOAuth2TokenExpired sentinel, which ResolvePerUserOAuthToken // converts into an inline MCPUserOAuthRequiredError with auth URL. + // Keeping the row (rather than deleting) preserves binding identity + + // audit history; the OAuth callback at re-auth completion upserts + // the same row back to 'active' with fresh access/refresh tokens. var permErr *PermanentOAuthError if errors.As(err, &permErr) { - // The delete is load-bearing: without it, the dead refresh token - // row survives and the caller's subsequent reauth can collide - // with it (or replay the rejected refresh). If purge fails, - // surface the error rather than misleadingly returning the - // "re-authentication required" sentinel. - if delErr := p.configStore.DeleteOauthUserToken(ctx, token.ID); delErr != nil { - return fmt.Errorf("per-user oauth refresh permanently rejected but token cleanup failed (mcp_client=%s upstream_status=%d): %w", - token.MCPClientID, permErr.StatusCode, delErr) + // Use context.Background for the terminal status flip — the + // caller's ctx may already be canceled (request abort, upstream + // timeout) by the time we get the 'invalid_grant' / 401, and if + // the UPDATE fails because of that, the row stays 'active' and + // every subsequent inference call keeps retrying a dead refresh + // token instead of surfacing the re-auth requirement. + if markErr := p.configStore.MarkOauthUserTokenNeedsReauthByID(context.Background(), token.ID); markErr != nil { + return fmt.Errorf("per-user oauth refresh permanently rejected but status update failed (mcp_client=%s upstream_status=%d): %w", + token.MCPClientID, permErr.StatusCode, markErr) } - logger.Debug("Per-user OAuth refresh permanently rejected; token purged — re-authentication required: mcp_client=%s upstream_status=%d", + logger.Debug("Per-user OAuth refresh permanently rejected; row marked needs_reauth: mcp_client=%s upstream_status=%d", token.MCPClientID, permErr.StatusCode) - // Surface the state on the session row so dashboards / - // observability can show "this user needs to reconnect". The token - // delete above is the load-bearing action; this update never gates - // the OAuth flow, so a failure here is logged and ignored. - if token.SessionToken != "" { - if sess, sessErr := p.configStore.GetOauthUserSessionBySessionToken(ctx, token.SessionToken); sessErr == nil && sess != nil { - sess.Status = "needs_reauth" - if updErr := p.configStore.UpdateOauthUserSession(ctx, sess); updErr != nil { - logger.Warn("Failed to mark session needs_reauth after permanent refresh failure: session_id=%s err=%v", sess.ID, updErr) - } - } - } return fmt.Errorf("refresh token rejected by upstream OAuth server, re-authentication required: %w", schemas.ErrOAuth2TokenExpired) } // Transient failure (5xx, network blip, non-permanent 400) — keep the @@ -1176,32 +1263,6 @@ func (p *OAuth2Provider) RefreshUserAccessToken(ctx context.Context, sessionToke return fmt.Errorf("failed to update per-user token after refresh: %w", err) } - logger.Debug("Per-user OAuth token refreshed: session_token=...%s", sessionToken[len(sessionToken)-4:]) - return nil -} - -// RevokeUserToken revokes a per-user OAuth token and marks the session as revoked. -func (p *OAuth2Provider) RevokeUserToken(ctx context.Context, sessionToken string) error { - p.mu.Lock() - defer p.mu.Unlock() - - token, err := p.configStore.GetOauthUserTokenBySessionToken(ctx, sessionToken) - if err != nil || token == nil { - return fmt.Errorf("per-user oauth token not found: %w", err) - } - - // Delete the token - if err := p.configStore.DeleteOauthUserToken(ctx, token.ID); err != nil { - return fmt.Errorf("failed to delete per-user oauth token: %w", err) - } - - // Update session status - session, err := p.configStore.GetOauthUserSessionBySessionToken(ctx, sessionToken) - if err == nil && session != nil { - session.Status = "revoked" - p.configStore.UpdateOauthUserSession(ctx, session) - } - - logger.Debug("Per-user OAuth token revoked: session_token=...%s", sessionToken[len(sessionToken)-4:]) + logger.Debug("Per-user OAuth token refreshed: token_id=%s", token.ID) return nil } diff --git a/framework/oauth2/sync.go b/framework/oauth2/sync.go index 120b450c8ef..a46ae6e4f86 100644 --- a/framework/oauth2/sync.go +++ b/framework/oauth2/sync.go @@ -2,6 +2,7 @@ package oauth2 import ( "context" + "sync" "time" "github.com/maximhq/bifrost/core/schemas" @@ -13,6 +14,7 @@ type TokenRefreshWorker struct { refreshInterval time.Duration lookAheadWindow time.Duration // How far ahead to look for expiring tokens stopCh chan struct{} + stopOnce sync.Once logger schemas.Logger } @@ -39,12 +41,16 @@ func (w *TokenRefreshWorker) Start(ctx context.Context) { } } -// Stop gracefully stops the token refresh worker +// Stop gracefully stops the token refresh worker. Safe to call multiple times +// — guarded by sync.Once so a redundant call from a secondary shutdown path +// can't panic by re-closing the channel. func (w *TokenRefreshWorker) Stop() { - close(w.stopCh) - if w.logger != nil { - w.logger.Info("Token refresh worker stopped") - } + w.stopOnce.Do(func() { + close(w.stopCh) + if w.logger != nil { + w.logger.Info("Token refresh worker stopped") + } + }) } // run is the main worker loop @@ -133,3 +139,131 @@ func (w *TokenRefreshWorker) SetRefreshInterval(interval time.Duration) { func (w *TokenRefreshWorker) SetLookAheadWindow(window time.Duration) { w.lookAheadWindow = window } + +// PerUserOAuthSweepWorker periodically purges stale per-user OAuth state: +// - expired pending flow rows (oauth_user_sessions where ExpiresAt < now and status='pending') +// - orphaned token rows older than OrphanRetention (oauth_user_tokens where status='orphaned') +// +// Pending-flow expiry is short (driven by the row's own ExpiresAt, default +// 15min) so the flow tick is fast. Orphan retention is operator-tunable +// (default 30 days) and the orphan tick is slow. +type PerUserOAuthSweepWorker struct { + provider *OAuth2Provider + flowSweepEvery time.Duration + orphanSweepEvery time.Duration + orphanRetention time.Duration + stopCh chan struct{} + stopOnce sync.Once + logger schemas.Logger +} + +// NewPerUserOAuthSweepWorker creates a sweep worker with sensible defaults. +// orphanRetention <= 0 disables the orphan-token sweep. +func NewPerUserOAuthSweepWorker(provider *OAuth2Provider, orphanRetention time.Duration, logger schemas.Logger) *PerUserOAuthSweepWorker { + if provider == nil || provider.configStore == nil { + if logger != nil { + logger.Warn("per-user OAuth sweep worker not started: provider or config store is nil") + } + return nil + } + return &PerUserOAuthSweepWorker{ + provider: provider, + flowSweepEvery: 1 * time.Minute, + orphanSweepEvery: 24 * time.Hour, + orphanRetention: orphanRetention, + stopCh: make(chan struct{}), + logger: logger, + } +} + +// Start begins the sweep worker in a background goroutine. +func (w *PerUserOAuthSweepWorker) Start(ctx context.Context) { + go w.run(ctx) + if w.logger != nil { + w.logger.Info("Per-user OAuth sweep worker started (flow=%s, orphan=%s, retention=%s)", + w.flowSweepEvery, w.orphanSweepEvery, w.orphanRetention) + } +} + +// Stop gracefully stops the sweep worker. sync.Once guards against double-close +// panics when called from multiple shutdown paths. +func (w *PerUserOAuthSweepWorker) Stop() { + w.stopOnce.Do(func() { + close(w.stopCh) + if w.logger != nil { + w.logger.Info("Per-user OAuth sweep worker stopped") + } + }) +} + +func (w *PerUserOAuthSweepWorker) run(ctx context.Context) { + flowTicker := time.NewTicker(w.flowSweepEvery) + defer flowTicker.Stop() + orphanTicker := time.NewTicker(w.orphanSweepEvery) + defer orphanTicker.Stop() + + // Run once on start so a deploy doesn't have to wait a full interval. + w.sweepExpiredFlows(ctx) + w.sweepOrphanedTokens(ctx) + + for { + select { + case <-flowTicker.C: + w.sweepExpiredFlows(ctx) + case <-orphanTicker.C: + w.sweepOrphanedTokens(ctx) + case <-w.stopCh: + return + case <-ctx.Done(): + return + } + } +} + +func (w *PerUserOAuthSweepWorker) sweepExpiredFlows(ctx context.Context) { + n, err := w.provider.configStore.DeleteExpiredOauthUserSessions(ctx) + if err != nil { + if w.logger != nil { + w.logger.Error("per-user OAuth flow sweep failed: %v", err) + } + return + } + if n > 0 && w.logger != nil { + w.logger.Debug("per-user OAuth flow sweep removed %d expired pending flows", n) + } +} + +func (w *PerUserOAuthSweepWorker) sweepOrphanedTokens(ctx context.Context) { + if w.orphanRetention <= 0 { + return + } + n, err := w.provider.configStore.DeleteOrphanedOauthUserTokens(ctx, w.orphanRetention) + if err != nil { + if w.logger != nil { + w.logger.Error("per-user OAuth orphan-token sweep failed: %v", err) + } + return + } + if n > 0 && w.logger != nil { + w.logger.Info("per-user OAuth orphan-token sweep removed %d rows older than %s", n, w.orphanRetention) + } +} + +// SetFlowSweepInterval updates the pending-flow sweep cadence (for testing). +// Non-positive durations are ignored — run() feeds the field straight into +// time.NewTicker, which panics on d <= 0. +func (w *PerUserOAuthSweepWorker) SetFlowSweepInterval(d time.Duration) { + if d <= 0 { + return + } + w.flowSweepEvery = d +} + +// SetOrphanSweepInterval updates the orphan-token sweep cadence (for testing). +// Same non-positive guard as SetFlowSweepInterval. +func (w *PerUserOAuthSweepWorker) SetOrphanSweepInterval(d time.Duration) { + if d <= 0 { + return + } + w.orphanSweepEvery = d +} diff --git a/transports/bifrost-http/handlers/config.go b/transports/bifrost-http/handlers/config.go index f822f5ba495..adaf2249f77 100644 --- a/transports/bifrost-http/handlers/config.go +++ b/transports/bifrost-http/handlers/config.go @@ -257,10 +257,6 @@ func (h *ConfigHandler) updateConfig(ctx *fasthttp.RequestCtx) { // applies live mutations (drop-excess flag, MCP tool-manager reload, compat // plugin reload, in-memory MCP config) before persisting, so a late // rejection would leave the process in a partially-updated state. - if err := lib.ValidateBaseURL(payload.ClientConfig.MCPExternalServerURL.GetValue()); err != nil { - SendError(ctx, fasthttp.StatusBadRequest, fmt.Sprintf("mcp_external_server_url %v", err)) - return - } if err := lib.ValidateBaseURL(payload.ClientConfig.MCPExternalClientURL.GetValue()); err != nil { SendError(ctx, fasthttp.StatusBadRequest, fmt.Sprintf("mcp_external_client_url %v", err)) return @@ -496,7 +492,6 @@ func (h *ConfigHandler) updateConfig(ctx *fasthttp.RequestCtx) { // Update external base URLs for OAuth server metadata and client redirect_uri (nil clears each override). // Validation is performed up front in this handler so a failure here cannot leave the process in a partial state. - updatedConfig.MCPExternalServerURL = payload.ClientConfig.MCPExternalServerURL updatedConfig.MCPExternalClientURL = payload.ClientConfig.MCPExternalClientURL // Handle HeaderFilterConfig changes diff --git a/transports/bifrost-http/handlers/governance.go b/transports/bifrost-http/handlers/governance.go index d9a4c82ef29..a80c2a2cd97 100644 --- a/transports/bifrost-http/handlers/governance.go +++ b/transports/bifrost-http/handlers/governance.go @@ -1628,12 +1628,6 @@ func (h *GovernanceHandler) deleteVirtualKey(ctx *fasthttp.RequestCtx) { SendError(ctx, 500, "Failed to retrieve virtual key") return } - // Removing key from in-memory store - err = h.governanceManager.RemoveVirtualKey(ctx, vk.ID) - if err != nil { - // But we ignore this error because its not - logger.Error("failed to remove virtual key: %v", err) - } // Deleting key from database if err := h.configStore.DeleteVirtualKey(ctx, vkID); err != nil { if errors.Is(err, configstore.ErrNotFound) { @@ -1644,6 +1638,12 @@ func (h *GovernanceHandler) deleteVirtualKey(ctx *fasthttp.RequestCtx) { SendError(ctx, 500, "Failed to delete virtual key") return } + // Removing key from in-memory store + err = h.governanceManager.RemoveVirtualKey(ctx, vk.ID) + if err != nil { + // But we ignore this error because its not + logger.Error("failed to remove virtual key: %v", err) + } SendJSON(ctx, map[string]interface{}{ "message": "Virtual key deleted successfully", }) diff --git a/transports/bifrost-http/handlers/mcp.go b/transports/bifrost-http/handlers/mcp.go index 892eaacf4b8..f4e683c685b 100644 --- a/transports/bifrost-http/handlers/mcp.go +++ b/transports/bifrost-http/handlers/mcp.go @@ -934,6 +934,26 @@ func (h *MCPHandler) updateMCPClient(ctx *fasthttp.RequestCtx) { req.TableMCPClient.ToolsToExecute = resolvedToolsToExecute req.TableMCPClient.ToolsToAutoExecute = resolvedToolsToAutoExecute dbUpdateRecord := req.TableMCPClient + // Rebind persisted discovered tool keys (and inner Function.Name) to the current + // client name so a restart restores them under the right prefix. + if oldDBConfig != nil && len(oldDBConfig.DiscoveredTools) > 0 { + newPrefix := req.TableMCPClient.Name + "-" + migrated := make(map[string]schemas.ChatTool, len(oldDBConfig.DiscoveredTools)) + for oldKey, tool := range oldDBConfig.DiscoveredTools { + newKey := oldKey + if _, suffix, ok := strings.Cut(oldKey, "-"); ok { + newKey = newPrefix + suffix + } + if tool.Function != nil { + fn := *tool.Function + fn.Name = newKey + tool.Function = &fn + } + migrated[newKey] = tool + } + dbUpdateRecord.DiscoveredTools = migrated + dbUpdateRecord.DiscoveredToolNameMapping = oldDBConfig.DiscoveredToolNameMapping + } if h.store.ConfigStore != nil { if err := h.store.ConfigStore.UpdateMCPClientConfig(ctx, id, &dbUpdateRecord); err != nil { SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("failed to update mcp client config in store: %v", err)) @@ -988,6 +1008,25 @@ func (h *MCPHandler) updateMCPClient(ctx *fasthttp.RequestCtx) { return } + // Reload every VK currently referencing this MCP client so the governance + // cache's preloaded MCPClient relation picks up the rename / tool / header + // changes. The VK-assignment-change block below does its own targeted + // reload, but only fires when req.VKConfigs != nil — a name-only update + // otherwise leaves every cached VK pointing at the old MCPClient.Name and + // the per-VK allowlist check rejects tool calls under the new prefix. + if h.store.ConfigStore != nil && h.governanceManager != nil { + assignedVKs, listErr := h.store.ConfigStore.GetVirtualKeyMCPConfigsByMCPClientID(ctx, oldDBConfig.ID) + if listErr != nil { + logger.Error(fmt.Sprintf("failed to fetch VK assignments for MCP client %s after update: %v", id, listErr)) + } else { + for _, av := range assignedVKs { + if _, err := h.governanceManager.ReloadVirtualKey(ctx, av.VirtualKeyID); err != nil { + logger.Error(fmt.Sprintf("failed to reload virtual key %s after MCP client update: %v", av.VirtualKeyID, err)) + } + } + } + } + // Manage VK assignments if vk_configs was provided if req.VKConfigs != nil && h.store.ConfigStore != nil { current, err := h.store.ConfigStore.GetVirtualKeyMCPConfigsByMCPClientID(ctx, oldDBConfig.ID) diff --git a/transports/bifrost-http/handlers/mcp_sessions.go b/transports/bifrost-http/handlers/mcp_sessions.go new file mode 100644 index 00000000000..df12e3fb383 --- /dev/null +++ b/transports/bifrost-http/handlers/mcp_sessions.go @@ -0,0 +1,562 @@ +// Package handlers — MCP Auth Sessions tab API. +// +// Surfaces the per-user OAuth token rows and pending flow rows visible to the +// caller's identity. Mode-strict: the handler derives AuthMode at request time +// via ctx.AuthMode() and only returns rows whose identity column matches. +// Orphaned tokens are included in the listing so the UI can surface "needs +// re-auth"; they never satisfy a runtime token lookup (filtered at the +// resolver layer). +package handlers + +import ( + "errors" + + "github.com/fasthttp/router" + "github.com/maximhq/bifrost/core/schemas" + "github.com/maximhq/bifrost/framework/configstore/tables" + "github.com/maximhq/bifrost/transports/bifrost-http/lib" + "github.com/valyala/fasthttp" +) + +// MCPSessionsHandler serves the sessions tab API. +type MCPSessionsHandler struct { + store *lib.Config +} + +// NewMCPSessionsHandler creates the handler. +func NewMCPSessionsHandler(store *lib.Config) *MCPSessionsHandler { + return &MCPSessionsHandler{store: store} +} + +// RegisterRoutes registers the sessions tab routes. +func (h *MCPSessionsHandler) RegisterRoutes(r *router.Router, middlewares ...schemas.BifrostHTTPMiddleware) { + r.GET("/api/mcp/sessions", lib.ChainMiddlewares(h.list, middlewares...)) + r.POST("/api/mcp/sessions/{id}/reauth", lib.ChainMiddlewares(h.reauth, middlewares...)) + r.DELETE("/api/mcp/sessions/{id}", lib.ChainMiddlewares(h.revoke, middlewares...)) + r.GET("/api/oauth/per-user/flows/{id}", lib.ChainMiddlewares(h.flowDetail, middlewares...)) + r.GET("/api/oauth/per-user/flows/{id}/start", lib.ChainMiddlewares(h.flowStart, middlewares...)) +} + +// mcpClientSummary is the minimal MCP client view embedded in session rows. +type mcpClientSummary struct { + ClientID string `json:"client_id"` + Name string `json:"name"` +} + +// virtualKeySummary is the minimal VK view embedded in session rows. +type virtualKeySummary struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// userSummary is the minimal user view embedded in user-keyed session rows. +// Populated server-side from the enterprise SCIM user table; OSS leaves it +// nil so the UI falls back to rendering the raw user_id. +type userSummary struct { + ID string `json:"id"` + Name string `json:"name,omitempty"` +} + +// mcpSessionRow is the wire shape for both authenticated tokens and pending flows. +type mcpSessionRow struct { + ID string `json:"id"` + Kind string `json:"kind"` // "token" | "flow" + AuthMode string `json:"auth_mode"` + UserID *string `json:"user_id,omitempty"` + User *userSummary `json:"user,omitempty"` // Preloaded by enterprise on user-keyed rows; nil in OSS so UI falls back to user_id + VirtualKey *virtualKeySummary `json:"virtual_key,omitempty"` + MCPClient *mcpClientSummary `json:"mcp_client,omitempty"` + SessionID *string `json:"session_id,omitempty"` // Session-mode identity: caller-issued x-bf-mcp-session-id value + Status string `json:"status"` // 'active' | 'orphaned' | 'pending' | 'needs_reauth' + ExpiresAt *string `json:"expires_at,omitempty"` // RFC3339; nil for non-expiring tokens + CreatedAt string `json:"created_at"` // When the session was first authenticated + LastRefreshedAt *string `json:"last_refreshed_at,omitempty"` // Token rows only; nil if never refreshed + OauthConfigID string `json:"oauth_config_id,omitempty"` +} + +type mcpSessionsListResponse struct { + Sessions []mcpSessionRow `json:"sessions"` +} + +// list returns sessions visible to the caller. Each row's identity column +// matches the caller's derived AuthMode + identity. +func (h *MCPSessionsHandler) list(ctx *fasthttp.RequestCtx) { + // Always call the unfiltered list methods. Row visibility is handled + // by DAC scope at the enterprise configstore layer (own-data narrows + // to the caller's identity + owned VKs; team-data widens to members; + // all-data / OSS-only sees everything). Matches the canonical pattern + // used by getVirtualKeys, getPrompts, getTeams, etc. + tokens, err := h.store.ConfigStore.ListAllOauthUserTokens(ctx) + var flows []tables.TableOauthUserSession + if err == nil { + flows, err = h.store.ConfigStore.ListAllPendingOauthUserSessions(ctx) + } + if err != nil { + logger.Error("[mcp/sessions] list failed: %v", err) + SendError(ctx, fasthttp.StatusInternalServerError, "Failed to list MCP sessions") + return + } + + // A reauth in flight produces a token row (the live credential) and a + // pending flow row (the in-flight OAuth attempt) for the same binding. + // They're conceptually the same identity — surface the token row only and + // suppress the flow row to avoid confusing duplicates in the UI. The flow + // row is still in the DB; once the callback completes it moves to status + // 'authorized' and stops being returned by the pending-flow query anyway. + tokenBindings := make(map[sessionBindingKey]struct{}, len(tokens)) + for _, t := range tokens { + tokenBindings[bindingKeyFromToken(t)] = struct{}{} + } + + rows := make([]mcpSessionRow, 0, len(tokens)+len(flows)) + for _, t := range tokens { + rows = append(rows, tokenRow(t)) + } + for _, f := range flows { + if _, hasToken := tokenBindings[bindingKeyFromFlow(f)]; hasToken { + continue + } + // Skip deferred-fill user-mode flow rows (user_id not yet stamped). + // They have no concrete binding to render, and surfacing them in + // the table forces an ambiguous label. + if f.FlowMode == string(schemas.MCPAuthModeUser) && (f.UserID == nil || *f.UserID == "") { + continue + } + rows = append(rows, flowRow(f)) + } + SendJSON(ctx, mcpSessionsListResponse{Sessions: rows}) +} + +type sessionBindingKey struct { + Mode string + Identity string + MCPClientID string +} + +func bindingKeyFromToken(t tables.TableOauthUserToken) sessionBindingKey { + k := sessionBindingKey{Mode: t.AuthMode, MCPClientID: t.MCPClientID} + switch schemas.MCPAuthMode(t.AuthMode) { + case schemas.MCPAuthModeUser: + if t.UserID != nil { + k.Identity = *t.UserID + } + case schemas.MCPAuthModeVK: + if t.VirtualKeyID != nil { + k.Identity = *t.VirtualKeyID + } + case schemas.MCPAuthModeSession: + k.Identity = t.SessionID + } + return k +} + +func bindingKeyFromFlow(f tables.TableOauthUserSession) sessionBindingKey { + k := sessionBindingKey{Mode: f.FlowMode, MCPClientID: f.MCPClientID} + switch schemas.MCPAuthMode(f.FlowMode) { + case schemas.MCPAuthModeUser: + if f.UserID != nil { + k.Identity = *f.UserID + } + case schemas.MCPAuthModeVK: + if f.VirtualKeyID != nil { + k.Identity = *f.VirtualKeyID + } + case schemas.MCPAuthModeSession: + k.Identity = f.SessionID + } + return k +} + +// reauth starts a fresh OAuth flow for the MCP client backing the given token +// row. Returns the authorize URL the user must visit. +func (h *MCPSessionsHandler) reauth(ctx *fasthttp.RequestCtx) { + rowID, ok := ctx.UserValue("id").(string) + if !ok || rowID == "" { + SendError(ctx, fasthttp.StatusBadRequest, "Invalid session id") + return + } + bfCtx, cancel := lib.ConvertToBifrostContext(ctx, h.store) + defer cancel() + + tok, err := h.loadRowAuthorizedForCaller(ctx, rowID) + if err != nil { + // loadRowAuthorizedForCaller already wrote the error response. + _ = err + return + } + + // Re-auth on an 'orphaned' row would be a no-op for the user: the + // credential isn't dead, they've lost grant-level access. The OAuth + // callback would mint a row keyed to a user who can't use it, and + // the next AP sync would just orphan it again. Refuse with a + // distinct status so the UI can show the right copy. + if tok.Status == "orphaned" { + SendError(ctx, fasthttp.StatusForbidden, "Access to this MCP has been revoked. Re-authenticating will not restore access - contact your administrator.") + return + } + + // The new flow must reuse the existing row's identity so the callback's + // upsert lands on the same (identity, mcp_client) row. Inject the row's + // values into context; InitiateUserOAuthFlow reads them per-mode. + rowMode := schemas.MCPAuthMode(tok.AuthMode) + switch rowMode { + case schemas.MCPAuthModeSession: + if tok.SessionID != "" { + bfCtx.SetValue(schemas.BifrostContextKeyMCPSessionID, tok.SessionID) + } + case schemas.MCPAuthModeVK: + if tok.VirtualKeyID != nil && *tok.VirtualKeyID != "" { + bfCtx.SetValue(schemas.BifrostContextKeyGovernanceVirtualKeyID, *tok.VirtualKeyID) + } + case schemas.MCPAuthModeUser: + if tok.UserID != nil && *tok.UserID != "" { + bfCtx.SetValue(schemas.BifrostContextKeyUserID, *tok.UserID) + } + } + + provider := h.store.OAuthProvider + if provider == nil { + SendError(ctx, fasthttp.StatusServiceUnavailable, "OAuth provider not configured") + return + } + redirectURI := lib.BuildBaseURL(ctx, h.store.GetMCPExternalClientURL()) + "/api/oauth/callback" + flow, sessionID, err := provider.InitiateUserOAuthFlow(bfCtx, tok.OauthConfigID, tok.MCPClientID, redirectURI, rowMode) + if err != nil { + logger.Error("[mcp/sessions] reauth flow init failed: token=%s err=%v", rowID, err) + SendError(ctx, fasthttp.StatusInternalServerError, "Failed to initiate reauthentication") + return + } + logger.Debug("[mcp/sessions] reauth initiated: token=%s mcp_client=%s mode=%s flow=%s", rowID, tok.MCPClientID, rowMode, sessionID) + SendJSON(ctx, map[string]any{ + "authorize_url": flow.AuthorizeURL, + "session_id": sessionID, + }) +} + +// revoke hard-deletes the local token row and any pending flow rows for the +// same identity + MCP client. Upstream revocation against the OAuth provider +// is NOT performed — the per-user OAuth template config doesn't carry a +// revocation endpoint, and discovery for it is not yet wired up. The provider +// token therefore remains live upstream until natural expiry; a follow-up can +// add explicit upstream revocation once the schema captures the endpoint. +// +// Same authorization model as list/reauth: caller with an identity must match +// the row's identity column; caller without an identity is the dashboard admin +// view and can act on any row. +func (h *MCPSessionsHandler) revoke(ctx *fasthttp.RequestCtx) { + rowID, ok := ctx.UserValue("id").(string) + if !ok || rowID == "" { + SendError(ctx, fasthttp.StatusBadRequest, "Invalid session id") + return + } + tok, err := h.loadRowAuthorizedForCaller(ctx, rowID) + if err != nil { + _ = err + return + } + // Delete pending flow rows BEFORE the token row. If a flow finishes + // upstream and lands on /api/oauth/callback after a successful revoke, + // CompleteUserOAuthFlow would mint a brand-new token for the same + // binding — the revoke would be effectively undone. Dropping flows + // first closes that window; if this step fails we bail without + // touching the token, so the caller retries cleanly. + rowMode, rowIdentity := identityFromTokenRow(tok) + if rowIdentity != "" { + if delErr := h.store.ConfigStore.DeleteOauthUserSessionsByModeIdentityAndMCPClient(ctx, rowMode, rowIdentity, tok.MCPClientID); delErr != nil { + logger.Error("[mcp/sessions] clearing flow rows failed: token=%s err=%v", rowID, delErr) + SendError(ctx, fasthttp.StatusInternalServerError, "Failed to delete MCP session") + return + } + } + if err := h.store.ConfigStore.DeleteOauthUserToken(ctx, tok.ID); err != nil { + logger.Error("[mcp/sessions] delete row failed: token=%s err=%v", rowID, err) + SendError(ctx, fasthttp.StatusInternalServerError, "Failed to delete MCP session") + return + } + logger.Debug("[mcp/sessions] revoked: token=%s mcp_client=%s mode=%s", rowID, tok.MCPClientID, tok.AuthMode) + ctx.SetStatusCode(fasthttp.StatusNoContent) +} + +// mcpFlowDetailResponse is the wire shape for GET /api/oauth/per-user/flows/{id}. +type mcpFlowDetailResponse struct { + ID string `json:"id"` + FlowMode string `json:"flow_mode"` + Status string `json:"status"` + MCPClient *mcpClientSummary `json:"mcp_client,omitempty"` + OauthConfigID string `json:"oauth_config_id"` + UserID *string `json:"user_id,omitempty"` + User *userSummary `json:"user,omitempty"` + VirtualKey *virtualKeySummary `json:"virtual_key,omitempty"` + SessionID *string `json:"session_id,omitempty"` + ExpiresAt string `json:"expires_at"` + CreatedAt string `json:"created_at"` + // HasActiveToken is true when an active token already exists for the + // flow's (mode, identity, mcp_client) binding. A pending flow with this + // set means the user re-initiated OAuth (or a stale caller did) on a + // binding that already has a working token — the auth page should treat + // it as "no auth needed" rather than prompting the user. + HasActiveToken bool `json:"has_active_token"` +} + +// flowDetail returns the pending flow row's metadata so the frontend sessions +// auth page can render a "you're about to authenticate X" view. +// +// Permission model: deferred-fill flows (flow_mode='user' with user_id=nil) +// are visible to any user-mode caller — the first SCIM-authenticated user to +// open the URL will become the row's user_id at completion time. For all +// other modes the caller's identity must match the row's identity column. +func (h *MCPSessionsHandler) flowDetail(ctx *fasthttp.RequestCtx) { + flowID, ok := ctx.UserValue("id").(string) + if !ok || flowID == "" { + SendError(ctx, fasthttp.StatusBadRequest, "Invalid flow id") + return + } + + flow, err := h.loadAuthorizedFlow(ctx, flowID) + if err != nil { + _ = err + return + } + resp := mcpFlowDetailResponse{ + ID: flow.ID, + FlowMode: flow.FlowMode, + Status: flow.Status, + OauthConfigID: flow.OauthConfigID, + UserID: flow.UserID, + ExpiresAt: flow.ExpiresAt.UTC().Format(rfc3339Nano), + CreatedAt: flow.CreatedAt.UTC().Format(rfc3339Nano), + } + if flow.MCPClient != nil { + resp.MCPClient = &mcpClientSummary{ClientID: flow.MCPClient.ClientID, Name: flow.MCPClient.Name} + } else { + resp.MCPClient = &mcpClientSummary{ClientID: flow.MCPClientID} + } + if flow.VirtualKey != nil { + resp.VirtualKey = &virtualKeySummary{ID: flow.VirtualKey.ID, Name: flow.VirtualKey.Name} + } else if flow.VirtualKeyID != nil { + resp.VirtualKey = &virtualKeySummary{ID: *flow.VirtualKeyID} + } + if flow.User != nil { + resp.User = &userSummary{ID: flow.User.ID, Name: flow.User.Name} + } + if flow.FlowMode == string(schemas.MCPAuthModeSession) && flow.SessionID != "" { + sid := flow.SessionID + resp.SessionID = &sid + } + // Check whether an active token already exists for this binding. A pending + // flow on top of a working token means OAuth was re-initiated for some + // reason; the auth page should display this as "already authenticated" + // rather than prompt the user to authenticate again. + if flowMode := schemas.MCPAuthMode(flow.FlowMode); flowMode != "" { + identity := "" + switch flowMode { + case schemas.MCPAuthModeUser: + if flow.UserID != nil && *flow.UserID != "" { + identity = *flow.UserID + } else if v, _ := ctx.UserValue(schemas.BifrostContextKeyUserID).(string); v != "" { + // Deferred-fill: flow.UserID is nil until completion. Fall + // back to the signed-in caller's user_id so HasActiveToken + // reflects whether THIS user already has a credential for + // the MCP client and we don't prompt an unnecessary re-auth. + // + // Use UserValue (not Value) — auth middleware stores via + // SetUserValue, and fasthttp's Value() only handles bare + // string keys, so a typed BifrostContextKey lookup via + // Value() always returns nil. + identity = v + } + case schemas.MCPAuthModeVK: + if flow.VirtualKeyID != nil { + identity = *flow.VirtualKeyID + } + case schemas.MCPAuthModeSession: + identity = flow.SessionID + } + if identity != "" { + if tok, lookupErr := h.store.ConfigStore.GetOauthUserTokenByMode(ctx, flowMode, identity, flow.MCPClientID); lookupErr == nil && tok != nil { + resp.HasActiveToken = true + } + } + } + SendJSON(ctx, resp) +} + +// flowStart reconstructs the upstream provider authorize URL for a pending +// flow and returns it. The frontend redirects the browser to that URL; the +// user completes upstream auth; upstream redirects back to /api/oauth/callback +// which calls CompleteUserOAuthFlow. +func (h *MCPSessionsHandler) flowStart(ctx *fasthttp.RequestCtx) { + flowID, ok := ctx.UserValue("id").(string) + if !ok || flowID == "" { + SendError(ctx, fasthttp.StatusBadRequest, "Invalid flow id") + return + } + if _, err := h.loadAuthorizedFlow(ctx, flowID); err != nil { + _ = err + return + } + if h.store.OAuthProvider == nil { + SendError(ctx, fasthttp.StatusServiceUnavailable, "OAuth provider not configured") + return + } + upstreamURL, err := h.store.OAuthProvider.BuildUpstreamAuthorizeURL(ctx, flowID) + if err != nil { + // Stale flow state is a client-recoverable condition (restart the auth + // flow), not an outage. Map it to a 4xx so the frontend can show + // "expired / restart auth" instead of a generic error. + switch { + case errors.Is(err, schemas.ErrOAuth2FlowExpired), + errors.Is(err, schemas.ErrOAuth2FlowNotPending), + errors.Is(err, schemas.ErrOAuth2NotPerUserSession): + logger.Debug("[mcp/sessions] flow start refused (stale): flow=%s err=%v", flowID, err) + SendError(ctx, fasthttp.StatusGone, "OAuth flow is no longer pending; restart authentication") + return + } + logger.Error("[mcp/sessions] flow start failed: flow=%s err=%v", flowID, err) + SendError(ctx, fasthttp.StatusInternalServerError, "Failed to build upstream authorize URL") + return + } + SendJSON(ctx, map[string]any{"authorize_url": upstreamURL}) +} + +// loadAuthorizedFlow looks up the pending flow row. Visibility is enforced +// at the enterprise configstore layer via DAC scope on +// GetOauthUserSessionByID: if the caller is not allowed to see this row, +// the store returns (nil, nil) and we surface 404. Deferred-fill user-mode +// flows (user_id IS NULL) are visible to any SCIM-authenticated caller by +// the scope builder so they can claim the auth URL. Writes the appropriate +// HTTP error response and returns a sentinel error on failure. +func (h *MCPSessionsHandler) loadAuthorizedFlow(ctx *fasthttp.RequestCtx, flowID string) (*tables.TableOauthUserSession, error) { + flow, err := h.store.ConfigStore.GetOauthUserSessionByID(ctx, flowID) + if err != nil { + logger.Error("[mcp/sessions] load flow failed: flow=%s err=%v", flowID, err) + SendError(ctx, fasthttp.StatusInternalServerError, "Failed to load OAuth flow") + return nil, err + } + if flow == nil { + SendError(ctx, fasthttp.StatusNotFound, "OAuth flow not found") + return nil, errNotFound + } + return flow, nil +} + +// identityFromTokenRow returns the (mode, identity) pair recorded on the row. +// Inverse of the mode/identity routing used when creating the row; the row's +// AuthMode column is the source of truth for which identity column is keyed. +func identityFromTokenRow(tok *tables.TableOauthUserToken) (schemas.MCPAuthMode, string) { + switch schemas.MCPAuthMode(tok.AuthMode) { + case schemas.MCPAuthModeUser: + if tok.UserID != nil { + return schemas.MCPAuthModeUser, *tok.UserID + } + case schemas.MCPAuthModeVK: + if tok.VirtualKeyID != nil { + return schemas.MCPAuthModeVK, *tok.VirtualKeyID + } + case schemas.MCPAuthModeSession: + return schemas.MCPAuthModeSession, tok.SessionID + } + return schemas.MCPAuthMode(tok.AuthMode), "" +} + +// loadRowAuthorizedForCaller loads a token row. Visibility is enforced at +// the enterprise configstore layer via DAC scope on GetOauthUserTokenByID: +// if the caller is not allowed to see this row, the store returns +// (nil, nil) and we surface 404 — the same "if you can see it, you can +// act on it" model used by GetVirtualKey / DeleteVirtualKey. Writes the +// HTTP error response on failure. +func (h *MCPSessionsHandler) loadRowAuthorizedForCaller(ctx *fasthttp.RequestCtx, rowID string) (*tables.TableOauthUserToken, error) { + tok, err := h.store.ConfigStore.GetOauthUserTokenByID(ctx, rowID) + if err != nil { + logger.Error("[mcp/sessions] load row failed: token=%s err=%v", rowID, err) + SendError(ctx, fasthttp.StatusInternalServerError, "Failed to load MCP session") + return nil, err + } + if tok == nil { + SendError(ctx, fasthttp.StatusNotFound, "MCP session not found") + return nil, errNotFound + } + return tok, nil +} + +// errNotFound is a sentinel so handlers can early-return without +// re-writing the HTTP response. +var errNotFound = errSentinel("not found") + +type errSentinel string + +func (e errSentinel) Error() string { return string(e) } + +// tokenRow maps an oauth_user_tokens row to the wire shape. +func tokenRow(t tables.TableOauthUserToken) mcpSessionRow { + row := mcpSessionRow{ + ID: t.ID, + Kind: "token", + AuthMode: t.AuthMode, + UserID: t.UserID, + Status: t.Status, + CreatedAt: t.CreatedAt.UTC().Format(rfc3339Nano), + OauthConfigID: t.OauthConfigID, + } + if t.MCPClient != nil { + row.MCPClient = &mcpClientSummary{ClientID: t.MCPClient.ClientID, Name: t.MCPClient.Name} + } else { + row.MCPClient = &mcpClientSummary{ClientID: t.MCPClientID} + } + if t.VirtualKey != nil { + row.VirtualKey = &virtualKeySummary{ID: t.VirtualKey.ID, Name: t.VirtualKey.Name} + } else if t.VirtualKeyID != nil { + row.VirtualKey = &virtualKeySummary{ID: *t.VirtualKeyID} + } + if t.User != nil { + row.User = &userSummary{ID: t.User.ID, Name: t.User.Name} + } + if t.AuthMode == string(schemas.MCPAuthModeSession) && t.SessionID != "" { + s := t.SessionID + row.SessionID = &s + } + if t.ExpiresAt != nil { + s := t.ExpiresAt.UTC().Format(rfc3339Nano) + row.ExpiresAt = &s + } + if t.LastRefreshedAt != nil { + s := t.LastRefreshedAt.UTC().Format(rfc3339Nano) + row.LastRefreshedAt = &s + } + return row +} + +// flowRow maps an oauth_user_sessions (pending flow) row to the wire shape. +func flowRow(f tables.TableOauthUserSession) mcpSessionRow { + exp := f.ExpiresAt.UTC().Format(rfc3339Nano) + row := mcpSessionRow{ + ID: f.ID, + Kind: "flow", + AuthMode: f.FlowMode, + UserID: f.UserID, + Status: f.Status, + ExpiresAt: &exp, + CreatedAt: f.CreatedAt.UTC().Format(rfc3339Nano), + OauthConfigID: f.OauthConfigID, + } + if f.MCPClient != nil { + row.MCPClient = &mcpClientSummary{ClientID: f.MCPClient.ClientID, Name: f.MCPClient.Name} + } else { + row.MCPClient = &mcpClientSummary{ClientID: f.MCPClientID} + } + if f.VirtualKey != nil { + row.VirtualKey = &virtualKeySummary{ID: f.VirtualKey.ID, Name: f.VirtualKey.Name} + } else if f.VirtualKeyID != nil { + row.VirtualKey = &virtualKeySummary{ID: *f.VirtualKeyID} + } + if f.User != nil { + row.User = &userSummary{ID: f.User.ID, Name: f.User.Name} + } + if f.FlowMode == string(schemas.MCPAuthModeSession) && f.SessionID != "" { + s := f.SessionID + row.SessionID = &s + } + return row +} + +const rfc3339Nano = "2006-01-02T15:04:05.999999999Z07:00" diff --git a/transports/bifrost-http/handlers/mcpserver.go b/transports/bifrost-http/handlers/mcpserver.go index d743a446301..627759fcf8a 100644 --- a/transports/bifrost-http/handlers/mcpserver.go +++ b/transports/bifrost-http/handlers/mcpserver.go @@ -86,33 +86,18 @@ func (h *MCPServerHandler) RegisterRoutes(r *router.Router, middlewares ...schem // MCP server endpoint - supports both POST (JSON-RPC) and GET (SSE) r.POST("/mcp", lib.ChainMiddlewares(h.handleMCPServer, middlewares...)) r.GET("/mcp", lib.ChainMiddlewares(h.handleMCPServerSSE, middlewares...)) -} - -// handleMCPServer handles POST requests for MCP JSON-RPC 2.0 messages -// injectMCPSessionIdentity sets the MCP gateway flag and, if a per-user OAuth -// session exists, injects the session token and identity (VK / User ID) directly -// into the BifrostContext. This avoids header-based identity propagation which -// would be vulnerable to spoofing by upstream callers. -// -// Governance context keys are set here intentionally (bypassing governance plugin) -// because in the MCP gateway path, identity is pre-authenticated via the OAuth session. -func injectMCPSessionIdentity(bifrostCtx *schemas.BifrostContext, session *tables.TablePerUserOAuthSession) { - bifrostCtx.SetValue(schemas.BifrostContextKeyIsMCPGateway, true) - if session != nil { - if session.AccessToken != "" { - bifrostCtx.SetValue(schemas.BifrostContextKeyMCPUserSession, session.AccessToken) - } - if session.VirtualKeyID != nil && *session.VirtualKeyID != "" && session.VirtualKey != nil && session.VirtualKey.Value != "" { - bifrostCtx.SetValue(schemas.BifrostContextKeyVirtualKey, session.VirtualKey.Value) - } - if session.UserID != nil && *session.UserID != "" { - bifrostCtx.SetValue(schemas.BifrostContextKeyUserID, *session.UserID) - } - } + // Bifrost is NOT an OAuth authorization server — auth is via the + // x-bf-vk / x-bf-mcp-session-id headers or upstream SSO. Claude Code's + // MCP client may proactively POST `/register` (RFC 7591 DCR) on + // `claude mcp add` and log "SDK auth failed: ..." when the probe fails, + // even though the underlying `/mcp` connection works fine. That warning + // is a known Claude Code bug — see + // https://github.com/anthropics/claude-code/issues/46640 — and is safe + // to ignore. We intentionally do NOT implement an OAuth stub. } func (h *MCPServerHandler) handleMCPServer(ctx *fasthttp.RequestCtx) { - mcpServer, session, err := h.getMCPServerForRequest(ctx) + mcpServer, err := h.getMCPServerForRequest(ctx) if err != nil { SendError(ctx, fasthttp.StatusUnauthorized, err.Error()) return @@ -120,10 +105,9 @@ func (h *MCPServerHandler) handleMCPServer(ctx *fasthttp.RequestCtx) { // Convert context bifrostCtx, cancel := lib.ConvertToBifrostContext(ctx, h.config) + bifrostCtx.SetValue(schemas.BifrostContextKeyIsMCPGateway, true) defer cancel() - injectMCPSessionIdentity(bifrostCtx, session) - // Use mcp-go server to handle the request // HandleMessage processes JSON-RPC messages and returns appropriate responses response := mcpServer.HandleMessage(bifrostCtx, ctx.PostBody()) @@ -148,7 +132,7 @@ func (h *MCPServerHandler) handleMCPServer(ctx *fasthttp.RequestCtx) { // handleMCPServerSSE handles GET requests for MCP Server-Sent Events streaming func (h *MCPServerHandler) handleMCPServerSSE(ctx *fasthttp.RequestCtx) { - _, session, err := h.getMCPServerForRequest(ctx) + _, err := h.getMCPServerForRequest(ctx) if err != nil { SendError(ctx, fasthttp.StatusUnauthorized, err.Error()) return @@ -180,8 +164,7 @@ func (h *MCPServerHandler) handleMCPServerSSE(ctx *fasthttp.RequestCtx) { // Convert context bifrostCtx, cancel := lib.ConvertToBifrostContext(ctx, h.config) - - injectMCPSessionIdentity(bifrostCtx, session) + bifrostCtx.SetValue(schemas.BifrostContextKeyIsMCPGateway, true) // Use SSEStreamReader to bypass fasthttp's internal pipe batching reader := lib.NewSSEStreamReader() @@ -544,7 +527,7 @@ func (h *MCPServerHandler) makeIncludeClientsFilter() server.ToolFilterFunc { // Utility methods -func (h *MCPServerHandler) getMCPServerForRequest(ctx *fasthttp.RequestCtx) (*server.MCPServer, *tables.TablePerUserOAuthSession, error) { +func (h *MCPServerHandler) getMCPServerForRequest(ctx *fasthttp.RequestCtx) (*server.MCPServer, error) { h.mu.RLock() defer h.mu.RUnlock() @@ -554,87 +537,21 @@ func (h *MCPServerHandler) getMCPServerForRequest(ctx *fasthttp.RequestCtx) (*se vk := getVKFromRequest(ctx) - // Check for Bifrost per-user OAuth Bearer token (not a VK) - userOauthSession, sessionErr := h.getPerUserOAuthSession(ctx) - if sessionErr != nil { - return nil, nil, fmt.Errorf("failed to look up OAuth session: %w", sessionErr) - } - - // If per_user_oauth MCP clients are configured and no valid auth, return 401 with discovery - if clients := h.config.GetPerUserOAuthMCPClients(); len(clients) > 0 && userOauthSession == nil && vk == "" { - resourceMetadataURL := lib.BuildBaseURL(ctx, h.config.GetMCPExternalServerURL()) + "/.well-known/oauth-protected-resource" - ctx.Response.Header.Set("WWW-Authenticate", - fmt.Sprintf(`Bearer resource_metadata="%s"`, resourceMetadataURL)) - return nil, nil, fmt.Errorf("oauth authentication required for mcp access") - } - - if userOauthSession != nil { - if !enforceVK && (userOauthSession.VirtualKeyID == nil || *userOauthSession.VirtualKeyID == "") { - return h.globalMCPServer, userOauthSession, nil - } - - if userOauthSession.VirtualKeyID == nil || *userOauthSession.VirtualKeyID == "" || userOauthSession.VirtualKey == nil { - return nil, nil, fmt.Errorf("virtual key required in oauth session to access mcp server, please re-authenticate with a virtual key") - } - - vkServer, ok := h.vkMCPServers[userOauthSession.VirtualKey.Value] - if !ok { - return nil, nil, fmt.Errorf("virtual key not found") - } - - return vkServer, userOauthSession, nil - } - - // Return global MCP server if not enforcing virtual key header and no virtual key is provided + // EnforceAuth=false: anonymous access to the global (un-scoped) MCP server + // is allowed in dev mode. EnforceAuth=true: VK header is mandatory. if !enforceVK && vk == "" { - return h.globalMCPServer, nil, nil + return h.globalMCPServer, nil } if vk == "" { - return nil, nil, fmt.Errorf("virtual key header required to access mcp server") + return nil, fmt.Errorf("virtual key required to access mcp server; set one of x-bf-vk, Authorization: Bearer , or x-api-key in your MCP client config") } vkServer, ok := h.vkMCPServers[vk] if !ok { - return nil, nil, fmt.Errorf("virtual key not found") - } - - return vkServer, nil, nil -} - -// getPerUserOAuthSession extracts and validates a Bifrost-issued per-user OAuth -// token from the Authorization header. Returns the session if valid, nil otherwise. -func (h *MCPServerHandler) getPerUserOAuthSession(ctx *fasthttp.RequestCtx) (*tables.TablePerUserOAuthSession, error) { - authHeader := strings.TrimSpace(string(ctx.Request.Header.Peek("Authorization"))) - if authHeader == "" || !strings.HasPrefix(strings.ToLower(authHeader), "bearer ") { - return nil, nil - } - token := strings.TrimSpace(authHeader[7:]) - if token == "" || strings.HasPrefix(strings.ToLower(token), governance.VirtualKeyPrefix) { - return nil, nil // It's a virtual key, not a per-user OAuth token + return nil, fmt.Errorf("virtual key not found") } - - if h.config.ConfigStore == nil { - return nil, nil - } - - session, err := h.config.ConfigStore.GetPerUserOAuthSessionByAccessToken(ctx, token) - if err != nil { - logger.Warn("[mcp/auth] GetPerUserOAuthSessionByAccessToken error: %v", err) - return nil, err - } - if session == nil { - logger.Debug("[mcp/auth] Session not found for token") - return nil, nil - } - - // Check expiry - if session.ExpiresAt.Before(time.Now()) { - logger.Debug("[mcp/auth] Session expired: session_id=%s expires_at=%v", session.ID, session.ExpiresAt) - return nil, nil - } - - return session, nil + return vkServer, nil } func getVKFromRequest(ctx *fasthttp.RequestCtx) string { diff --git a/transports/bifrost-http/handlers/oauth2.go b/transports/bifrost-http/handlers/oauth2.go index c1676863b4b..40c03e2b294 100644 --- a/transports/bifrost-http/handlers/oauth2.go +++ b/transports/bifrost-http/handlers/oauth2.go @@ -4,12 +4,9 @@ package handlers import ( "context" - "encoding/json" "errors" "fmt" - "html" "net/url" - "strings" "github.com/fasthttp/router" bifrost "github.com/maximhq/bifrost/core" @@ -42,7 +39,23 @@ func (h *OAuthHandler) RegisterRoutes(r *router.Router, middlewares ...schemas.B r.DELETE("/api/oauth/config/{id}", lib.ChainMiddlewares(h.revokeOAuthConfig, middlewares...)) } -// handleOAuthCallback handles the OAuth provider callback +// handleOAuthCallback handles the upstream OAuth provider callback. Performs +// the token exchange server-side (needs client_secret) and then redirects the +// browser into the dashboard, which shows the user-facing success/error UX. +// +// Two flow types share this redirect_uri, distinguished by which state table +// the state token belongs to: +// - Per-user runtime flow (Bifrost-as-client to upstream for an MCP server's +// per-user OAuth). On success → /workspace/mcp-sessions. +// - Server-level admin-test flow (mcpClientSheet OAuth2Authorizer popup +// validating an OAuth config template). On success → /workspace/mcp-registry/oauth-callback +// which posts a message to the opener window and closes itself. +// +// Error details from internal completion failures are logged server-side and +// never piped into the redirect URL — the URL ends up in browser history, +// access logs, and the Referer header, so anything that ships there is +// effectively public. +// // GET /api/oauth/callback?state=xxx&code=yyy&error=zzz func (h *OAuthHandler) handleOAuthCallback(ctx *fasthttp.RequestCtx) { state := string(ctx.QueryArgs().Peek("state")) @@ -50,90 +63,78 @@ func (h *OAuthHandler) handleOAuthCallback(ctx *fasthttp.RequestCtx) { errorParam := string(ctx.QueryArgs().Peek("error")) errorDescription := string(ctx.QueryArgs().Peek("error_description")) - // Handle authorization denial if errorParam != "" { h.handleCallbackError(ctx, state, errorParam, errorDescription) return } - // Validate required parameters if state == "" || code == "" { SendError(ctx, fasthttp.StatusBadRequest, "Missing required parameters: state and code") return } - // Try per-user OAuth runtime flow first (state from oauth_user_sessions table). - // This handles the case where an end-user authenticates during inference. - sessionToken, perUserErr := h.oauthProvider.CompleteUserOAuthFlow(context.Background(), state, code) + // Per-user runtime flow (state lives in oauth_user_sessions). + _, perUserErr := h.oauthProvider.CompleteUserOAuthFlow(ctx, state, code) if perUserErr != nil && !errors.Is(perUserErr, schemas.ErrOAuth2NotPerUserSession) { - // Real per-user error (not "state not found") — don't fall through to admin flow - SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("Per-user OAuth flow failed: %v", perUserErr)) + // The OAuth state is the CSRF token — never log it raw; it could + // be replayed by anyone with log access while the flow is alive. + logger.Error("[oauth] per-user callback completion failed: err=%v", perUserErr) + ctx.Redirect("/workspace/mcp-sessions?error="+url.QueryEscape("OAuth authentication failed. Please try again."), fasthttp.StatusFound) return } - if perUserErr == nil && sessionToken != "" { - // Consent flow: session token is a flow proxy ("flow::"). - // Redirect back to the MCPs consent page so the user can continue. - if strings.HasPrefix(sessionToken, "flow:") { - rest := strings.TrimPrefix(sessionToken, "flow:") - flowID := strings.SplitN(rest, ":", 2)[0] - mcpsURL := fmt.Sprintf("/oauth/consent/mcps?flow_id=%s", url.QueryEscape(flowID)) - ctx.Redirect(mcpsURL, fasthttp.StatusFound) - return - } - - // Per-user runtime OAuth flow completed — show success page. - ctx.SetStatusCode(fasthttp.StatusOK) - ctx.SetContentType("text/html") - ctx.SetBodyString(oauthSuccessPage(` - if (window.opener) { - window.opener.postMessage({ type: 'oauth_success' }, window.location.origin); - window.close(); - } - `, "Authorization Successful", "You can close this tab.")) + if perUserErr == nil { + ctx.Redirect("/workspace/mcp-sessions?completed=1", fasthttp.StatusFound) return } - // Fall through to standard OAuth flow (handles both admin test logins for - // per_user_oauth setup and regular server-level OAuth). - if err := h.oauthProvider.CompleteOAuthFlow(context.Background(), state, code); err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("OAuth flow completion failed: %v", err)) + // Fall through: server-level admin-test flow. + if err := h.oauthProvider.CompleteOAuthFlow(ctx, state, code); err != nil { + logger.Error("[oauth] admin-test callback completion failed: err=%v", err) + ctx.Redirect("/workspace/mcp-registry/oauth-callback?status=failed&error="+url.QueryEscape("OAuth authentication failed."), fasthttp.StatusFound) return } - - // Redirect to success page (or close popup) - ctx.SetStatusCode(fasthttp.StatusOK) - ctx.SetContentType("text/html") - ctx.SetBodyString(oauthSuccessPage(` - if (window.opener) { - window.opener.postMessage({ type: 'oauth_success' }, window.location.origin); - window.close(); - } - `, "Authorization Successful", "OAuth authorization successful! You can close this window.")) + ctx.Redirect("/workspace/mcp-registry/oauth-callback?status=success", fasthttp.StatusFound) } -// handleCallbackError handles OAuth callback errors +// handleCallbackError handles ?error= responses from upstream providers. +// Marks the OAuth config row as failed (for admin UI's pending-setup display), +// then redirects to the route that matches the originating flow: +// - admin-test popup flow → /workspace/mcp-registry/oauth-callback (posts a +// message to window.opener and closes itself) +// - per-user runtime flow → /workspace/mcp-sessions (full-page, no opener) +// +// We infer the flow by looking up the state in oauth_configs; if it's there +// it's the admin-test flow, otherwise we assume per-user. The upstream-supplied +// error code/description is logged server-side; only a generic message reaches +// the URL so provider error text doesn't leak into history / Referer. func (h *OAuthHandler) handleCallbackError(ctx *fasthttp.RequestCtx, state, errorParam, errorDescription string) { - // Update OAuth config status to failed if state is provided + isAdminTestFlow := false if state != "" { - oauthConfig, err := h.store.ConfigStore.GetOauthConfigByState(context.Background(), state) - if err == nil && oauthConfig != nil { + oauthConfig, err := h.store.ConfigStore.GetOauthConfigByState(ctx, state) + switch { + case err != nil: + // Lookup failed — we can't reliably classify the flow. Default + // to the per-user (full-page) route since that's the common + // case; the popup-callback page expects window.opener and would + // strand a per-user caller on a "you can close this tab" view. + // Log the underlying cause for diagnostics. + logger.Error("[oauth] failed to look up oauth config by state for callback error: err=%v", err) + case oauthConfig != nil: + isAdminTestFlow = true oauthConfig.Status = "failed" - h.store.ConfigStore.UpdateOauthConfig(context.Background(), oauthConfig) + if updateErr := h.store.ConfigStore.UpdateOauthConfig(ctx, oauthConfig); updateErr != nil { + logger.Warn("[oauth] failed to mark oauth config as failed: id=%s err=%v", oauthConfig.ID, updateErr) + } } } - - // Show error page - ctx.SetStatusCode(fasthttp.StatusBadRequest) - ctx.SetContentType("text/html") - errorMsg := errorParam - if errorDescription != "" { - errorMsg = fmt.Sprintf("%s: %s", errorParam, errorDescription) + // Don't log state (CSRF token, replayable while flow is alive). + logger.Warn("[oauth] upstream callback error: error=%s description=%s", errorParam, errorDescription) + const userMsg = "Authentication was denied or failed. Please try again." + if isAdminTestFlow { + ctx.Redirect("/workspace/mcp-registry/oauth-callback?status=failed&error="+url.QueryEscape(userMsg), fasthttp.StatusFound) + return } - // JSON-encode for safe embedding in JavaScript context (prevents JS injection) - jsEscaped, _ := json.Marshal(errorMsg) - // HTML-escape for safe embedding in HTML body (prevents HTML injection) - htmlEscaped := html.EscapeString(errorMsg) - ctx.SetBodyString(oauthErrorPage(string(jsEscaped), htmlEscaped)) + ctx.Redirect("/workspace/mcp-sessions?error="+url.QueryEscape(userMsg), fasthttp.StatusFound) } // getOAuthConfigStatus returns the current status of an OAuth config @@ -141,7 +142,7 @@ func (h *OAuthHandler) handleCallbackError(ctx *fasthttp.RequestCtx, state, erro func (h *OAuthHandler) getOAuthConfigStatus(ctx *fasthttp.RequestCtx) { configID := ctx.UserValue("id").(string) - oauthConfig, err := h.store.ConfigStore.GetOauthConfigByID(context.Background(), configID) + oauthConfig, err := h.store.ConfigStore.GetOauthConfigByID(ctx, configID) if err != nil { SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("Failed to get OAuth config: %v", err)) return @@ -163,7 +164,7 @@ func (h *OAuthHandler) getOAuthConfigStatus(ctx *fasthttp.RequestCtx) { response["token_id"] = *oauthConfig.TokenID // Get token metadata - token, err := h.store.ConfigStore.GetOauthTokenByID(context.Background(), *oauthConfig.TokenID) + token, err := h.store.ConfigStore.GetOauthTokenByID(ctx, *oauthConfig.TokenID) if err == nil && token != nil { if token.ExpiresAt != nil { response["token_expires_at"] = token.ExpiresAt @@ -180,7 +181,7 @@ func (h *OAuthHandler) getOAuthConfigStatus(ctx *fasthttp.RequestCtx) { func (h *OAuthHandler) revokeOAuthConfig(ctx *fasthttp.RequestCtx) { configID := ctx.UserValue("id").(string) - if err := h.oauthProvider.RevokeToken(context.Background(), configID); err != nil { + if err := h.oauthProvider.RevokeToken(ctx, configID); err != nil { SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("Failed to revoke OAuth token: %v", err)) return } @@ -264,70 +265,6 @@ func (h *OAuthHandler) GetAccessToken(ctx context.Context, oauthConfigID string) return h.oauthProvider.GetAccessToken(ctx, oauthConfigID) } -// oauthSuccessPage renders a Bifrost-themed success HTML page. -// extraScript is injected verbatim into a - - -
-
✓
-

%s

-

%s

-
- -`, html.EscapeString(title), bifrostPageCSS, extraScript, html.EscapeString(title), html.EscapeString(message)) -} - -// oauthErrorPage renders a Bifrost-themed error HTML page. -// jsEscapedError must already be JSON-encoded (with quotes) for safe JS embedding. -// htmlError must already be HTML-escaped for safe body embedding. -func oauthErrorPage(jsEscapedError, htmlError string) string { - return fmt.Sprintf(` - - - - -Authorization Failed - - - - -
-
✗
-

Authorization Failed

-

%s

-

You can close this window.

-
- -`, bifrostPageCSS, jsEscapedError, htmlError) -} - -// jsEscapeString returns a JSON-encoded string (with quotes) safe for embedding in JavaScript. -func jsEscapeString(s string) string { - b, _ := json.Marshal(s) - return string(b) -} - // RevokeToken revokes the OAuth token for a given oauth_config_id. // Used during per-user OAuth setup to discard the admin's temporary token after verification. func (h *OAuthHandler) RevokeToken(ctx context.Context, oauthConfigID string) error { diff --git a/transports/bifrost-http/handlers/oauth2_consent.go b/transports/bifrost-http/handlers/oauth2_consent.go deleted file mode 100644 index 50dd620cc17..00000000000 --- a/transports/bifrost-http/handlers/oauth2_consent.go +++ /dev/null @@ -1,643 +0,0 @@ -// Package handlers provides HTTP request handlers for the Bifrost HTTP transport. -// This file implements the per-user OAuth consent flow — the intermediate screens -// shown between the MCP client's authorize request and the final authorization code -// issuance. The flow is: -// -// 1. GET /oauth/consent?flow_id=xxx → VK input page (HTML) -// 2. POST /api/oauth/per-user/consent/vk → validate VK, update PendingFlow, redirect -// 3. GET /oauth/consent/mcps?flow_id=xxx → MCPs page (HTML, server-rendered) -// 4. POST /api/oauth/per-user/consent/submit → create session + code, redirect to client -package handlers - -import ( - "errors" - "fmt" - "html" - "net/url" - "sort" - "strings" - "time" - - "github.com/fasthttp/router" - "github.com/google/uuid" - "github.com/maximhq/bifrost/core/schemas" - "github.com/maximhq/bifrost/framework/configstore/tables" - "github.com/maximhq/bifrost/transports/bifrost-http/lib" - "github.com/valyala/fasthttp" -) - -// ConsentHandler manages the per-user OAuth consent flow screens. -type ConsentHandler struct { - store *lib.Config -} - -// NewConsentHandler creates a new consent handler instance. -func NewConsentHandler(store *lib.Config) *ConsentHandler { - return &ConsentHandler{store: store} -} - -// RegisterRoutes registers the consent flow routes. -// All routes are public — no auth middleware — since they are part of the OAuth -// flow for unauthenticated users acquiring credentials. -func (h *ConsentHandler) RegisterRoutes(r *router.Router) { - // HTML pages (GET, served by Go) - r.GET("/oauth/consent", h.handleIdentityPage) - r.GET("/oauth/consent/mcps", h.handleMCPsPage) - - // API actions (POST) - // NOTE: All state-mutating endpoints use POST. CSRF protection relies on the - // SameSite=Lax browser-binding cookie (__bifrost_flow_secret) combined with - // the flow_id — SameSite=Lax blocks cross-site POST, and the cookie is - // HttpOnly+Secure. This is sufficient for the threat model here. - r.POST("/api/oauth/per-user/consent/vk", h.handleSubmitVK) - r.POST("/api/oauth/per-user/consent/user-id", h.handleSubmitUserID) - r.POST("/api/oauth/per-user/consent/skip", h.handleSkip) - r.POST("/api/oauth/per-user/consent/submit", h.handleSubmit) -} - -// ---------- HTML pages ---------- - -// handleIdentityPage renders the identity selection page with three options: -// User ID, Virtual Key, or skip (lazy auth when tools are called). -// GET /oauth/consent?flow_id=xxx[&error=xxx] -func (h *ConsentHandler) handleIdentityPage(ctx *fasthttp.RequestCtx) { - flowID := string(ctx.QueryArgs().Peek("flow_id")) - errorMsg := string(ctx.QueryArgs().Peek("error")) - - if flowID == "" { - ctx.SetStatusCode(fasthttp.StatusBadRequest) - ctx.SetBodyString("Missing flow_id") - return - } - - if h.store.ConfigStore == nil { - ctx.SetStatusCode(fasthttp.StatusServiceUnavailable) - ctx.SetBodyString("Config store unavailable") - return - } - - flow, err := h.store.ConfigStore.GetPerUserOAuthPendingFlow(ctx, flowID) - if err != nil { - ctx.SetStatusCode(fasthttp.StatusInternalServerError) - ctx.SetBodyString("Failed to load consent flow.") - return - } - if flow == nil || time.Now().After(flow.ExpiresAt) { - ctx.SetStatusCode(fasthttp.StatusBadRequest) - ctx.SetBodyString("Invalid or expired consent flow. Please restart the authentication process.") - return - } - if !validateFlowBrowserSecret(ctx, flow) { - ctx.SetStatusCode(fasthttp.StatusForbidden) - ctx.SetBodyString("Flow does not belong to this browser session. Please restart the authentication process.") - return - } - - h.store.Mu.RLock() - enforceVK := h.store.ClientConfig.EnforceAuthOnInference - h.store.Mu.RUnlock() - - safeFlowID := html.EscapeString(flowID) - safeError := html.EscapeString(errorMsg) - - errorBanner := "" - if safeError != "" { - errorBanner = fmt.Sprintf(`
%s
`, safeError) - } - - skipOption := "" - if !enforceVK { - skipOption = fmt.Sprintf(` -
- Skip for now - Connect to services when a tool is called -
- - -
-
`, safeFlowID) - } - - ctx.SetStatusCode(fasthttp.StatusOK) - ctx.SetContentType("text/html; charset=utf-8") - ctx.SetBodyString(fmt.Sprintf(` - - - - -Connect to Bifrost - - - -
-

Connect to Bifrost

-

Choose how to identify yourself for this session.

-

This setup page expires in 15 minutes.

- %s -
- User ID - Use a stable identifier — access all available services -
- - - - -
-
-
- Virtual Key - Use a VK — access services within your key's limits -
- - - - -
-
- %s -
- -`, bifrostPageCSS, errorBanner, safeFlowID, safeFlowID, skipOption)) -} - -// handleMCPsPage renders the MCP authentication list page. -// GET /oauth/consent/mcps?flow_id=xxx -func (h *ConsentHandler) handleMCPsPage(ctx *fasthttp.RequestCtx) { - flowID := string(ctx.QueryArgs().Peek("flow_id")) - - if flowID == "" { - ctx.SetStatusCode(fasthttp.StatusBadRequest) - ctx.SetBodyString("Missing flow_id") - return - } - - if h.store.ConfigStore == nil { - ctx.SetStatusCode(fasthttp.StatusServiceUnavailable) - ctx.SetBodyString("Config store unavailable") - return - } - - flow, err := h.store.ConfigStore.GetPerUserOAuthPendingFlow(ctx, flowID) - if err != nil { - ctx.SetStatusCode(fasthttp.StatusInternalServerError) - ctx.SetBodyString("Failed to load consent flow.") - return - } - if flow == nil || time.Now().After(flow.ExpiresAt) { - ctx.SetStatusCode(fasthttp.StatusBadRequest) - ctx.SetBodyString("Invalid or expired consent flow. Please restart the authentication process.") - return - } - if !validateFlowBrowserSecret(ctx, flow) { - ctx.SetStatusCode(fasthttp.StatusForbidden) - ctx.SetBodyString("Flow does not belong to this browser session. Please restart the authentication process.") - return - } - - // Find which MCP clients the user has already authed. - // Check both: tokens stored under the flow proxy (connected during this flow) - // and tokens already stored under the VK/user identity (connected in a prior flow). - completedTokens, err := h.store.ConfigStore.GetOauthUserTokensByGatewaySessionID(ctx, flowID) - if err != nil { - completedTokens = nil // non-fatal; just show no checkmarks - } - completedMCPs := make(map[string]bool, len(completedTokens)) - for _, t := range completedTokens { - completedMCPs[t.MCPClientID] = true - } - - // Per_user_oauth MCP clients visible to this identity — sorted for deterministic rendering. - // When a VK is set on the flow, only show clients that VK is allowed to use. - perUserClients := h.store.GetPerUserOAuthMCPClientsForVirtualKey(ctx, strVal(flow.VirtualKeyID)) - clientIDs := make([]string, 0, len(perUserClients)) - for id := range perUserClients { - clientIDs = append(clientIDs, id) - } - sort.Strings(clientIDs) - - safeFlowID := html.EscapeString(flowID) - - // Determine if user skipped identity selection. - isSkipped := strVal(flow.VirtualKeyID) == "" && strVal(flow.UserID) == "" - - // Build MCP rows — only show connect buttons if user has an identity. - var mcpRows strings.Builder - if isSkipped { - mcpRows.WriteString(`

You skipped identity selection. Services will be connected when you first use their tools. Since no identity is attached, your connections will only persist as long as the service keeps the OAuth token active — they will not be remembered across sessions.

`) - } else { - for _, clientID := range clientIDs { - clientName := perUserClients[clientID] - safeName := html.EscapeString(clientName) - - // Also check if a token already exists under the user's identity (e.g. from a prior LLM gateway auth). - alreadyConnected := completedMCPs[clientID] - if !alreadyConnected && (strVal(flow.VirtualKeyID) != "" || strVal(flow.UserID) != "") { - existing, tokenErr := h.store.ConfigStore.GetOauthUserTokenByIdentity(ctx, strVal(flow.VirtualKeyID), strVal(flow.UserID), "", clientID) - if tokenErr != nil { - logger.Warn("[consent/mcps] failed to check existing token: mcp_client_id=%s err=%v", clientID, tokenErr) - } - alreadyConnected = existing != nil - } - - if alreadyConnected { - mcpRows.WriteString(fmt.Sprintf(` -
-
%s
- ✓ Connected -
`, safeName)) - } else { - connectURL := fmt.Sprintf("/api/oauth/per-user/upstream/authorize?mcp_client_id=%s&flow_id=%s", - url.QueryEscape(clientID), url.QueryEscape(flowID)) - mcpRows.WriteString(fmt.Sprintf(` -
-
%s
- Connect -
`, safeName, html.EscapeString(connectURL))) - } - } - if len(perUserClients) == 0 { - mcpRows.WriteString(`

No MCP services require authentication.

`) - } - } - - ctx.SetStatusCode(fasthttp.StatusOK) - ctx.SetContentType("text/html; charset=utf-8") - ctx.SetBodyString(fmt.Sprintf(` - - - - -Connect Your Apps — Bifrost - - - -
-

Connect Your Apps

-

Authenticate with the services below to enable their tools.

-

This setup page expires in 15 minutes.

-
%s
-
- - -
- -
- -`, bifrostPageCSS, mcpRows.String(), safeFlowID, safeFlowID)) -} - -// ---------- API action handlers ---------- - -// handleSubmitVK validates the submitted Virtual Key, links it to the pending flow, -// and redirects to the MCPs page. -// POST /api/oauth/per-user/consent/vk (form: flow_id, vk) -func (h *ConsentHandler) handleSubmitVK(ctx *fasthttp.RequestCtx) { - if h.store.ConfigStore == nil { - SendError(ctx, fasthttp.StatusServiceUnavailable, "Config store unavailable") - return - } - - flowID := string(ctx.FormValue("flow_id")) - vkValue := strings.TrimSpace(string(ctx.FormValue("vk"))) - - if flowID == "" { - SendError(ctx, fasthttp.StatusBadRequest, "flow_id is required") - return - } - - flow, err := h.store.ConfigStore.GetPerUserOAuthPendingFlow(ctx, flowID) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to load consent flow") - return - } - if flow == nil || time.Now().After(flow.ExpiresAt) { - SendError(ctx, fasthttp.StatusBadRequest, "Invalid or expired consent flow") - return - } - if !validateFlowBrowserSecret(ctx, flow) { - SendError(ctx, fasthttp.StatusForbidden, "Flow does not belong to this browser session") - return - } - - if vkValue == "" { - redirectToIdentityPage(ctx, flowID, "Please enter a Virtual Key.") - return - } - - vk, err := h.store.ConfigStore.GetVirtualKeyByValue(ctx, vkValue) - if err != nil { - redirectToIdentityPage(ctx, flowID, "Failed to validate Virtual Key. Please try again.") - return - } - if vk == nil || !vk.IsActiveValue() { - redirectToIdentityPage(ctx, flowID, "Virtual Key not found or inactive. Please check and try again.") - return - } - - flow.VirtualKeyID = &vk.ID - flow.UserID = nil // Clear other identity to keep selection exclusive - if err := h.store.ConfigStore.UpdatePerUserOAuthPendingFlow(ctx, flow); err != nil { - redirectToIdentityPage(ctx, flowID, "Failed to save Virtual Key. Please try again.") - return - } - - ctx.Redirect(fmt.Sprintf("/oauth/consent/mcps?flow_id=%s", url.QueryEscape(flowID)), fasthttp.StatusFound) -} - -// handleSubmitUserID links a user-supplied User ID to the pending flow and proceeds to MCPs page. -// SECURITY: The User ID is self-declared (typed in a form) with no server-side verification. -// This matches the trust model of X-Bf-User-Id in the LLM gateway path. Deployments requiring -// verified identity should use Virtual Keys or an auth layer in front of Bifrost. -// POST /api/oauth/per-user/consent/user-id (form: flow_id, user_id) -func (h *ConsentHandler) handleSubmitUserID(ctx *fasthttp.RequestCtx) { - if h.store.ConfigStore == nil { - SendError(ctx, fasthttp.StatusServiceUnavailable, "Config store unavailable") - return - } - - flowID := string(ctx.FormValue("flow_id")) - userID := strings.TrimSpace(string(ctx.FormValue("user_id"))) - - if flowID == "" { - SendError(ctx, fasthttp.StatusBadRequest, "flow_id is required") - return - } - - flow, err := h.store.ConfigStore.GetPerUserOAuthPendingFlow(ctx, flowID) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to load consent flow") - return - } - if flow == nil || time.Now().After(flow.ExpiresAt) { - SendError(ctx, fasthttp.StatusBadRequest, "Invalid or expired consent flow") - return - } - if !validateFlowBrowserSecret(ctx, flow) { - SendError(ctx, fasthttp.StatusForbidden, "Flow does not belong to this browser session") - return - } - - if userID == "" { - redirectToIdentityPage(ctx, flowID, "Please enter a User ID.") - return - } - if len(userID) > 255 { - redirectToIdentityPage(ctx, flowID, "User ID is too long (max 255 characters).") - return - } - - if userID != "" { - flow.UserID = &userID - } - flow.VirtualKeyID = nil // Clear other identity to keep selection exclusive - if err := h.store.ConfigStore.UpdatePerUserOAuthPendingFlow(ctx, flow); err != nil { - redirectToIdentityPage(ctx, flowID, "Failed to save User ID. Please try again.") - return - } - - ctx.Redirect(fmt.Sprintf("/oauth/consent/mcps?flow_id=%s", url.QueryEscape(flowID)), fasthttp.StatusFound) -} - -// handleSkip skips identity selection and proceeds directly to the MCPs page. -// Upstream services will be connected lazily when tools are first called. -// POST /api/oauth/per-user/consent/skip (form: flow_id) -func (h *ConsentHandler) handleSkip(ctx *fasthttp.RequestCtx) { - if h.store.ConfigStore == nil { - SendError(ctx, fasthttp.StatusServiceUnavailable, "Config store unavailable") - return - } - - flowID := string(ctx.FormValue("flow_id")) - if flowID == "" { - SendError(ctx, fasthttp.StatusBadRequest, "flow_id is required") - return - } - - flow, err := h.store.ConfigStore.GetPerUserOAuthPendingFlow(ctx, flowID) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to load consent flow") - return - } - if flow == nil || time.Now().After(flow.ExpiresAt) { - SendError(ctx, fasthttp.StatusBadRequest, "Invalid or expired consent flow") - return - } - if !validateFlowBrowserSecret(ctx, flow) { - SendError(ctx, fasthttp.StatusForbidden, "Flow does not belong to this browser session") - return - } - - h.store.Mu.RLock() - enforceVK := h.store.ClientConfig.EnforceAuthOnInference - h.store.Mu.RUnlock() - - if enforceVK { - redirectToIdentityPage(ctx, flowID, "An identity (Virtual Key or User ID) is required. Please choose one to continue.") - return - } - - // Clear any previously selected identity so skip truly resets the flow. - if strVal(flow.VirtualKeyID) != "" || strVal(flow.UserID) != "" { - flow.VirtualKeyID = nil - flow.UserID = nil - if err := h.store.ConfigStore.UpdatePerUserOAuthPendingFlow(ctx, flow); err != nil { - redirectToIdentityPage(ctx, flowID, "Failed to clear identity. Please try again.") - return - } - } - - // Skip goes straight to MCPs page; no identity means only lazy auth is available. - ctx.Redirect(fmt.Sprintf("/oauth/consent/mcps?flow_id=%s", url.QueryEscape(flowID)), fasthttp.StatusFound) -} - -// handleSubmit finalises the consent flow: -// 1. Creates a real Bifrost session (TablePerUserOAuthSession) -// 2. Migrates upstream tokens from the flow proxy to the real session -// 3. Issues a TablePerUserOAuthCode -// 4. Deletes the PendingFlow -// 5. Redirects to the original MCP client callback URL with code + state -// -// POST /api/oauth/per-user/consent/submit (form: flow_id) -func (h *ConsentHandler) handleSubmit(ctx *fasthttp.RequestCtx) { - if h.store.ConfigStore == nil { - SendError(ctx, fasthttp.StatusServiceUnavailable, "Config store unavailable") - return - } - - flowID := string(ctx.FormValue("flow_id")) - if flowID == "" { - SendError(ctx, fasthttp.StatusBadRequest, "flow_id is required") - return - } - flow, err := h.store.ConfigStore.GetPerUserOAuthPendingFlow(ctx, flowID) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to load consent flow") - return - } - if flow == nil { - SendError(ctx, fasthttp.StatusBadRequest, "Invalid consent flow") - return - } - if time.Now().After(flow.ExpiresAt) { - SendError(ctx, fasthttp.StatusBadRequest, "Consent flow has expired. Please restart the authentication process.") - return - } - if !validateFlowBrowserSecret(ctx, flow) { - SendError(ctx, fasthttp.StatusForbidden, "Flow does not belong to this browser session") - return - } - - // Server-side enforcement: reject if identity is required but not provided. - h.store.Mu.RLock() - enforceAuth := h.store.ClientConfig.EnforceAuthOnInference - h.store.Mu.RUnlock() - if enforceAuth && strVal(flow.VirtualKeyID) == "" && strVal(flow.UserID) == "" { - redirectToIdentityPage(ctx, flowID, "An identity (Virtual Key or User ID) is required. Please choose one to continue.") - return - } - - // 1. Generate session credentials. - accessToken, err := generateOpaqueToken(32) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to generate session token") - return - } - refreshToken, err := generateOpaqueToken(32) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to generate refresh token") - return - } - - session := &tables.TablePerUserOAuthSession{ - ID: uuid.New().String(), - AccessToken: accessToken, - RefreshToken: refreshToken, - ClientID: flow.ClientID, - VirtualKeyID: flow.VirtualKeyID, - UserID: flow.UserID, - ExpiresAt: time.Now().Add(24 * time.Hour), - } - - // 2. Generate authorization code. - code, err := generateOpaqueToken(32) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to generate authorization code") - return - } - codeRecord := &tables.TablePerUserOAuthCode{ - ID: uuid.New().String(), - Code: code, - ClientID: flow.ClientID, - RedirectURI: flow.RedirectURI, - CodeChallenge: flow.CodeChallenge, - SessionID: session.ID, // Links token endpoint to this session so it can return the same access token - // Scopes intentionally omitted: the consent flow has no scope selection step. - ExpiresAt: time.Now().Add(5 * time.Minute), - } - - // 3. Atomically consume the pending flow, create session, and create auth code. - // If another concurrent request already consumed the flow, rowsAffected will be 0. - rowsAffected, err := h.store.ConfigStore.FinalizePerUserOAuthConsent(ctx, flowID, session, codeRecord) - if err != nil { - if errors.Is(err, schemas.ErrPerUserOAuthPendingFlowExpired) { - SendError(ctx, fasthttp.StatusGone, "Consent flow has expired. Please restart the authentication process.") - return - } - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to finalize consent flow") - return - } - if rowsAffected == 0 { - SendError(ctx, fasthttp.StatusConflict, "Consent flow has already been submitted") - return - } - logger.Debug("[consent/submit] session created: session_id=%s flow_id=%s", session.ID, flowID) - - // 4. Migrate upstream tokens from flow proxy sessions to real session (non-fatal). - if err := h.store.ConfigStore.TransferOauthUserTokensFromGatewaySession(ctx, flowID, accessToken, strVal(flow.VirtualKeyID), strVal(flow.UserID)); err != nil { - // Non-fatal: tokens can be re-acquired on first tool use. - logger.Warn("[consent/submit] failed to transfer upstream tokens: flow_id=%s err=%v", flowID, err) - } - - // 5. Redirect to MCP client callback with code + original state. - redirectURL, err := url.Parse(flow.RedirectURI) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Invalid redirect URI in pending flow") - return - } - q := redirectURL.Query() - q.Set("code", code) - if flow.State != "" { - q.Set("state", flow.State) - } - redirectURL.RawQuery = q.Encode() - - ctx.Redirect(redirectURL.String(), fasthttp.StatusFound) -} - -// ---------- helpers ---------- - -// bifrostPageCSS is the shared inline CSS for all Go-rendered consent/callback pages. -// It mirrors Bifrost's UI design tokens: teal primary, zinc palette, Geist font stack. -const bifrostPageCSS = ` - *,*::before,*::after{box-sizing:border-box;margin:0;padding:0} - body{font-family:"Geist",system-ui,-apple-system,sans-serif;font-size:0.95rem; - line-height:1.5;background:#f4f4f5;color:oklch(0.141 0.005 285.823); - display:flex;align-items:center;justify-content:center;min-height:100vh; - -webkit-font-smoothing:antialiased} - .card{background:#fff;border:1px solid oklch(0.92 0.004 286.32);border-radius:12px; - padding:40px;width:100%;max-width:480px} - h1{font-size:1.25rem;font-weight:600;color:oklch(0.141 0.005 285.823);margin-bottom:6px} - .subtitle{font-size:0.825rem;color:oklch(0.552 0.016 285.938);line-height:1.5;margin-bottom:24px} - label{display:block;font-size:0.825rem;font-weight:500;color:oklch(0.141 0.005 285.823);margin-bottom:5px} - input[type=text],input[type=password]{width:100%;padding:8px 12px;border:1px solid oklch(0.92 0.004 286.32); - border-radius:0.5rem;font-size:0.875rem;outline:none; - transition:border-color .15s,box-shadow .15s;margin-bottom:10px; - background:#fff;color:oklch(0.141 0.005 285.823)} - input[type=text]:focus,input[type=password]:focus{border-color:oklch(0.5081 0.1049 165.61); - box-shadow:0 0 0 3px oklch(0.5081 0.1049 165.61 / 0.15)} - .btn{display:block;width:100%;padding:9px 16px;border-radius:0.5rem;font-size:0.875rem; - font-weight:500;cursor:pointer;border:none;text-align:center;text-decoration:none; - transition:background .15s;font-family:inherit} - .btn-primary{background:oklch(0.5081 0.1049 165.61);color:oklch(0.985 0 0)} - .btn-primary:hover{background:oklch(0.43 0.1049 165.61)} - .btn-ghost{background:transparent;border:1px solid oklch(0.92 0.004 286.32); - color:oklch(0.552 0.016 285.938);display:inline-block;width:auto;padding:8px 16px} - .btn-ghost:hover{background:#f4f4f5} - .error-banner{background:oklch(0.97 0.02 27);border:1px solid oklch(0.88 0.06 27); - border-radius:0.5rem;padding:12px 14px;margin-bottom:18px; - color:oklch(0.50 0.18 27);font-size:0.825rem} -` - -// redirectToIdentityPage redirects to the identity selection page with an error message. -func redirectToIdentityPage(ctx *fasthttp.RequestCtx, flowID, errorMsg string) { - u := fmt.Sprintf("/oauth/consent?flow_id=%s&error=%s", - url.QueryEscape(flowID), url.QueryEscape(errorMsg)) - ctx.Redirect(u, fasthttp.StatusFound) -} - -// strVal safely dereferences a *string, returning "" for nil. -func strVal(s *string) string { - if s == nil { - return "" - } - return *s -} diff --git a/transports/bifrost-http/handlers/oauth2_metadata.go b/transports/bifrost-http/handlers/oauth2_metadata.go deleted file mode 100644 index 8b49889f86c..00000000000 --- a/transports/bifrost-http/handlers/oauth2_metadata.go +++ /dev/null @@ -1,81 +0,0 @@ -// Package handlers provides HTTP request handlers for the Bifrost HTTP transport. -// This file implements OAuth 2.0 metadata discovery endpoints per RFC 9728 -// (Protected Resource Metadata) and RFC 8414 (Authorization Server Metadata). -// These endpoints enable MCP-spec-compliant clients (like Claude Code) to -// automatically discover Bifrost's OAuth configuration and authenticate. -package handlers - -import ( - "github.com/fasthttp/router" - "github.com/maximhq/bifrost/core/schemas" - "github.com/maximhq/bifrost/transports/bifrost-http/lib" - "github.com/valyala/fasthttp" -) - -// OAuthMetadataHandler serves OAuth 2.0 discovery metadata endpoints. -// It provides the Protected Resource Metadata (RFC 9728) and Authorization -// Server Metadata (RFC 8414) that MCP clients use to discover how to -// authenticate with Bifrost's MCP server endpoint. -type OAuthMetadataHandler struct { - store *lib.Config -} - -// NewOAuthMetadataHandler creates a new OAuth metadata handler instance. -func NewOAuthMetadataHandler(store *lib.Config) *OAuthMetadataHandler { - return &OAuthMetadataHandler{store: store} -} - -// RegisterRoutes registers the well-known metadata discovery routes. -// These routes do NOT go through auth middleware since they must be -// accessible to unauthenticated clients during OAuth discovery. -func (h *OAuthMetadataHandler) RegisterRoutes(r *router.Router, middlewares ...schemas.BifrostHTTPMiddleware) { - // RFC 9728: Protected Resource Metadata - r.GET("/.well-known/oauth-protected-resource", lib.ChainMiddlewares(h.handleProtectedResourceMetadata, middlewares...)) - // RFC 8414: Authorization Server Metadata - r.GET("/.well-known/oauth-authorization-server", lib.ChainMiddlewares(h.handleAuthorizationServerMetadata, middlewares...)) -} - -// handleProtectedResourceMetadata serves the Protected Resource Metadata -// document per RFC 9728. MCP clients fetch this after receiving a 401 response -// to discover which authorization server(s) protect the MCP resource. -// -// GET /.well-known/oauth-protected-resource -func (h *OAuthMetadataHandler) handleProtectedResourceMetadata(ctx *fasthttp.RequestCtx) { - if clients := h.store.GetPerUserOAuthMCPClients(); len(clients) == 0 { - sendStringError(ctx, fasthttp.StatusNotFound, "Not Found") - return - } - baseURL := lib.BuildBaseURL(ctx, h.store.GetMCPExternalServerURL()) - - SendJSON(ctx, map[string]interface{}{ - "resource": baseURL + "/mcp", - "authorization_servers": []string{baseURL}, - "scopes_supported": []string{"mcp:read", "mcp:write"}, - "bearer_methods_supported": []string{"header"}, - }) -} - -// handleAuthorizationServerMetadata serves the Authorization Server Metadata -// document per RFC 8414. MCP clients use this to discover Bifrost's OAuth -// endpoints (authorize, token, register) and supported capabilities. -// -// GET /.well-known/oauth-authorization-server -func (h *OAuthMetadataHandler) handleAuthorizationServerMetadata(ctx *fasthttp.RequestCtx) { - if clients := h.store.GetPerUserOAuthMCPClients(); len(clients) == 0 { - sendStringError(ctx, fasthttp.StatusNotFound, "Not Found") - return - } - baseURL := lib.BuildBaseURL(ctx, h.store.GetMCPExternalServerURL()) - - SendJSON(ctx, map[string]interface{}{ - "issuer": baseURL, - "authorization_endpoint": baseURL + "/api/oauth/per-user/authorize", - "token_endpoint": baseURL + "/api/oauth/per-user/token", - "registration_endpoint": baseURL + "/api/oauth/per-user/register", - "response_types_supported": []string{"code"}, - "grant_types_supported": []string{"authorization_code"}, - "code_challenge_methods_supported": []string{"S256"}, - "token_endpoint_auth_methods_supported": []string{"none"}, - "scopes_supported": []string{"mcp:read", "mcp:write"}, - }) -} diff --git a/transports/bifrost-http/handlers/oauth2_per_user.go b/transports/bifrost-http/handlers/oauth2_per_user.go deleted file mode 100644 index 71da97b64f2..00000000000 --- a/transports/bifrost-http/handlers/oauth2_per_user.go +++ /dev/null @@ -1,577 +0,0 @@ -// Package handlers provides HTTP request handlers for the Bifrost HTTP transport. -// This file implements Bifrost's OAuth 2.1 Authorization Server for per-user MCP -// authentication. It provides Dynamic Client Registration (RFC 7591), Authorization -// Code flow with PKCE, and token issuance. MCP clients (Claude Code, IDEs) use -// these endpoints to authenticate users before accessing Bifrost's /mcp endpoint. -package handlers - -import ( - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "fmt" - "html" - "net/url" - "strings" - "time" - - "github.com/fasthttp/router" - "github.com/google/uuid" - "github.com/maximhq/bifrost/core/schemas" - "github.com/maximhq/bifrost/framework/configstore" - "github.com/maximhq/bifrost/framework/configstore/tables" - "github.com/maximhq/bifrost/transports/bifrost-http/lib" - "github.com/valyala/fasthttp" -) - -// PerUserOAuthHandler implements Bifrost's OAuth 2.1 Authorization Server. -// It handles dynamic client registration, authorization code issuance with PKCE, -// and token exchange for MCP per-user authentication. -type PerUserOAuthHandler struct { - store *lib.Config -} - -// NewPerUserOAuthHandler creates a new per-user OAuth handler instance. -func NewPerUserOAuthHandler(store *lib.Config) *PerUserOAuthHandler { - return &PerUserOAuthHandler{store: store} -} - -// RegisterRoutes registers the per-user OAuth authorization server routes. -// These routes do NOT go through auth middleware since they are part of the -// OAuth flow that unauthenticated clients use to obtain tokens. -func (h *PerUserOAuthHandler) RegisterRoutes(r *router.Router, middlewares ...schemas.BifrostHTTPMiddleware) { - r.POST("/api/oauth/per-user/register", lib.ChainMiddlewares(h.handleDynamicClientRegistration, middlewares...)) - r.GET("/api/oauth/per-user/authorize", lib.ChainMiddlewares(h.handleAuthorize, middlewares...)) - r.POST("/api/oauth/per-user/token", lib.ChainMiddlewares(h.handleToken, middlewares...)) - r.GET("/api/oauth/per-user/upstream/authorize", lib.ChainMiddlewares(h.handleUpstreamAuthorize, middlewares...)) -} - -// handleDynamicClientRegistration handles OAuth 2.0 Dynamic Client Registration -// per RFC 7591. MCP clients register themselves to obtain a client_id. -// -// POST /api/oauth/per-user/register -func (h *PerUserOAuthHandler) handleDynamicClientRegistration(ctx *fasthttp.RequestCtx) { - if h.store.ConfigStore == nil { - SendError(ctx, fasthttp.StatusServiceUnavailable, "OAuth registration unavailable: config store is disabled") - return - } - - if len(h.store.GetPerUserOAuthMCPClients()) == 0 { - sendStringError(ctx, fasthttp.StatusNotFound, "Not found") - return - } - - var req struct { - ClientName string `json:"client_name"` - RedirectURIs []string `json:"redirect_uris"` - GrantTypes []string `json:"grant_types"` - ResponseTypes []string `json:"response_types"` - TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` - Scope string `json:"scope"` - } - - if err := json.Unmarshal(ctx.PostBody(), &req); err != nil { - SendError(ctx, fasthttp.StatusBadRequest, fmt.Sprintf("Invalid registration request: %v", err)) - return - } - - if len(req.RedirectURIs) == 0 { - SendError(ctx, fasthttp.StatusBadRequest, "redirect_uris is required") - return - } - - // Generate client_id - clientID := uuid.New().String() - - // Serialize arrays - redirectURIsJSON, _ := json.Marshal(req.RedirectURIs) - grantTypes := req.GrantTypes - if len(grantTypes) == 0 { - grantTypes = []string{"authorization_code"} - } - grantTypesJSON, _ := json.Marshal(grantTypes) - - client := &tables.TablePerUserOAuthClient{ - ID: uuid.New().String(), - ClientID: clientID, - ClientName: req.ClientName, - RedirectURIs: string(redirectURIsJSON), - GrantTypes: string(grantTypesJSON), - } - - if err := h.store.ConfigStore.CreatePerUserOAuthClient(ctx, client); err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("Failed to register client: %v", err)) - return - } - - // Return RFC 7591 response - ctx.SetStatusCode(fasthttp.StatusCreated) - SendJSON(ctx, map[string]interface{}{ - "client_id": clientID, - "client_name": req.ClientName, - "redirect_uris": req.RedirectURIs, - "grant_types": grantTypes, - "response_types": req.ResponseTypes, - "token_endpoint_auth_method": "none", - }) -} - -// handleAuthorize handles the OAuth 2.1 authorization endpoint. -// Instead of issuing a code immediately, it validates the request parameters, -// creates a PendingFlow record, and redirects the user to the consent screen. -// The code is only issued after the user completes the consent flow (VK + MCP auths). -// -// GET /api/oauth/per-user/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&code_challenge=xxx&code_challenge_method=S256[&state=xxx] -func (h *PerUserOAuthHandler) handleAuthorize(ctx *fasthttp.RequestCtx) { - if h.store.ConfigStore == nil { - SendError(ctx, fasthttp.StatusServiceUnavailable, "OAuth authorization unavailable: config store is disabled") - return - } - - if len(h.store.GetPerUserOAuthMCPClients()) == 0 { - sendStringError(ctx, fasthttp.StatusNotFound, "Not found") - return - } - - // Extract parameters - responseType := string(ctx.QueryArgs().Peek("response_type")) - clientID := string(ctx.QueryArgs().Peek("client_id")) - redirectURI := string(ctx.QueryArgs().Peek("redirect_uri")) - state := string(ctx.QueryArgs().Peek("state")) - codeChallenge := string(ctx.QueryArgs().Peek("code_challenge")) - codeChallengeMethod := string(ctx.QueryArgs().Peek("code_challenge_method")) - - // Validate required parameters - if responseType != "code" { - SendError(ctx, fasthttp.StatusBadRequest, "response_type must be 'code'") - return - } - if clientID == "" || redirectURI == "" { - SendError(ctx, fasthttp.StatusBadRequest, "client_id and redirect_uri are required") - return - } - if codeChallenge == "" || codeChallengeMethod != "S256" { - SendError(ctx, fasthttp.StatusBadRequest, "PKCE is required: code_challenge and code_challenge_method=S256") - return - } - - // Validate client exists and redirect_uri is registered - client, err := h.store.ConfigStore.GetPerUserOAuthClientByClientID(ctx, clientID) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("Failed to validate client: %v", err)) - return - } - if client == nil { - SendError(ctx, fasthttp.StatusBadRequest, "Unknown client_id") - return - } - var allowedURIs []string - json.Unmarshal([]byte(client.RedirectURIs), &allowedURIs) - uriAllowed := false - for _, allowed := range allowedURIs { - if allowed == redirectURI { - uriAllowed = true - break - } - } - if !uriAllowed { - SendError(ctx, fasthttp.StatusBadRequest, "redirect_uri not registered for this client") - return - } - - // Generate a browser-binding secret so only the initiating browser can resume this flow. - browserSecret, err := generateOpaqueToken(32) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to generate browser secret") - return - } - browserSecretHash := fmt.Sprintf("%x", sha256.Sum256([]byte(browserSecret))) - - // Create a PendingFlow to carry OAuth params through the consent screen. - flow := &tables.TablePerUserOAuthPendingFlow{ - ID: uuid.New().String(), - ClientID: clientID, - RedirectURI: redirectURI, - CodeChallenge: codeChallenge, - State: state, - BrowserSecretHash: browserSecretHash, - ExpiresAt: time.Now().Add(15 * time.Minute), - } - if err := h.store.ConfigStore.CreatePerUserOAuthPendingFlow(ctx, flow); err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("Failed to create pending flow: %v", err)) - return - } - logger.Debug("[oauth/authorize] PendingFlow created: flow_id=%s client_id=%s", flow.ID, clientID) - - // Set HttpOnly cookie binding this flow to the current browser. - var cookie fasthttp.Cookie - cookie.SetKey("__bifrost_flow_secret") - cookie.SetValue(browserSecret) - cookie.SetPath("/") - cookie.SetHTTPOnly(true) - cookie.SetSameSite(fasthttp.CookieSameSiteLaxMode) - isSecure := ctx.IsTLS() || string(ctx.Request.Header.Peek("X-Forwarded-Proto")) == "https" - cookie.SetSecure(isSecure) - cookie.SetMaxAge(15 * 60) // 15 minutes, matching flow TTL - ctx.Response.Header.SetCookie(&cookie) - - // Redirect to consent screen with flow_id (relative path — stays on current origin). - consentURL := fmt.Sprintf("/oauth/consent?flow_id=%s", url.QueryEscape(flow.ID)) - ctx.Redirect(consentURL, fasthttp.StatusFound) -} - -// handleToken handles the OAuth 2.1 token endpoint. -// It validates the authorization code + PKCE verifier and issues access/refresh tokens. -// -// POST /api/oauth/per-user/token -func (h *PerUserOAuthHandler) handleToken(ctx *fasthttp.RequestCtx) { - if h.store.ConfigStore == nil { - SendError(ctx, fasthttp.StatusServiceUnavailable, "OAuth token endpoint unavailable: config store is disabled") - return - } - - if len(h.store.GetPerUserOAuthMCPClients()) == 0 { - sendStringError(ctx, fasthttp.StatusNotFound, "Not found") - return - } - - // Parse form-encoded body - grantType := string(ctx.FormValue("grant_type")) - code := string(ctx.FormValue("code")) - redirectURI := string(ctx.FormValue("redirect_uri")) - clientID := string(ctx.FormValue("client_id")) - codeVerifier := string(ctx.FormValue("code_verifier")) - - if grantType != "authorization_code" { - sendOAuthError(ctx, fasthttp.StatusBadRequest, "unsupported_grant_type", "Only authorization_code grant is supported") - return - } - - if code == "" || codeVerifier == "" { - sendOAuthError(ctx, fasthttp.StatusBadRequest, "invalid_request", "code and code_verifier are required") - return - } - - // Atomically claim authorization code (prevents concurrent redemption) - codeRecord, err := h.store.ConfigStore.ClaimPerUserOAuthCode(ctx, code) - if err != nil { - sendOAuthError(ctx, fasthttp.StatusInternalServerError, "server_error", "Failed to validate code") - return - } - if codeRecord == nil { - sendOAuthError(ctx, fasthttp.StatusBadRequest, "invalid_grant", "Invalid or already used authorization code") - return - } - - // Validate code is not expired - if time.Now().After(codeRecord.ExpiresAt) { - sendOAuthError(ctx, fasthttp.StatusBadRequest, "invalid_grant", "Authorization code expired") - return - } - - // Validate client_id if provided — some public clients omit it (RFC 6749 §4.1.3 allows - // omitting client_id when the client is not authenticating with the server). - // The code record already binds the code to the correct client, so this is safe. - if clientID != "" && codeRecord.ClientID != clientID { - logger.Debug("[oauth/token] client_id mismatch: code_client=%s request_client=%s", codeRecord.ClientID, clientID) - sendOAuthError(ctx, fasthttp.StatusBadRequest, "invalid_grant", "client_id mismatch") - return - } - // Use the client_id from the code record as the authoritative value. - clientID = codeRecord.ClientID - - // Validate redirect_uri matches - if redirectURI != "" && codeRecord.RedirectURI != redirectURI { - logger.Debug("[oauth/token] redirect_uri mismatch: code=%s request=%s", codeRecord.RedirectURI, redirectURI) - sendOAuthError(ctx, fasthttp.StatusBadRequest, "invalid_grant", "redirect_uri mismatch") - return - } - - // Validate PKCE: SHA256(code_verifier) must match code_challenge - verifierHash := sha256.Sum256([]byte(codeVerifier)) - computedChallenge := base64.RawURLEncoding.EncodeToString(verifierHash[:]) - if computedChallenge != codeRecord.CodeChallenge { - logger.Debug("[oauth/token] PKCE verification failed") - sendOAuthError(ctx, fasthttp.StatusBadRequest, "invalid_grant", "PKCE verification failed") - return - } - - // If the code was issued by the consent flow (handleSubmit), the session already exists - // with the upstream tokens transferred to it. Reuse that session's access token so the - // client receives the token that the upstream (Notion, GitHub, etc.) tokens are linked to. - var accessToken string - var expiresAt time.Time - - if codeRecord.SessionID != "" { - existingSession, err := h.store.ConfigStore.GetPerUserOAuthSessionByID(ctx, codeRecord.SessionID) - if err != nil { - logger.Info("[oauth/token] Failed to load existing session: session_id=%s err=%v", codeRecord.SessionID, err) - sendOAuthError(ctx, fasthttp.StatusInternalServerError, "server_error", "Failed to load session") - return - } - if existingSession == nil { - logger.Info("[oauth/token] Existing session not found: session_id=%s", codeRecord.SessionID) - sendOAuthError(ctx, fasthttp.StatusInternalServerError, "server_error", "Session not found") - return - } - if !existingSession.ExpiresAt.After(time.Now()) { - sendOAuthError(ctx, fasthttp.StatusBadRequest, "invalid_grant", "Session expired") - return - } - accessToken = existingSession.AccessToken - expiresAt = existingSession.ExpiresAt - logger.Debug("[oauth/token] reusing consent session: session_id=%s", existingSession.ID) - } else { - // Fallback: no linked session (legacy path) — create a new one. - var newAccessToken, newRefreshToken string - newAccessToken, err = generateOpaqueToken(32) - if err != nil { - sendOAuthError(ctx, fasthttp.StatusInternalServerError, "server_error", "Failed to generate access token") - return - } - newRefreshToken, err = generateOpaqueToken(32) - if err != nil { - sendOAuthError(ctx, fasthttp.StatusInternalServerError, "server_error", "Failed to generate refresh token") - return - } - expiresAt = time.Now().Add(24 * time.Hour) - newSession := &tables.TablePerUserOAuthSession{ - ID: uuid.New().String(), - AccessToken: newAccessToken, - RefreshToken: newRefreshToken, - ClientID: clientID, - ExpiresAt: expiresAt, - } - if err := h.store.ConfigStore.CreatePerUserOAuthSession(ctx, newSession); err != nil { - sendOAuthError(ctx, fasthttp.StatusInternalServerError, "server_error", "Failed to create session") - return - } - accessToken = newAccessToken - logger.Debug("[oauth/token] created new session (legacy path): session_id=%s", newSession.ID) - } - // Return OAuth token response - ctx.SetContentType("application/json") - ctx.SetStatusCode(fasthttp.StatusOK) - SendJSON(ctx, map[string]interface{}{ - "access_token": accessToken, - "token_type": "Bearer", - "expires_in": int(time.Until(expiresAt).Seconds()), - "scope": codeRecord.Scopes, - }) -} - -// sendOAuthError sends an OAuth 2.0 error response per RFC 6749 Section 5.2. -func sendOAuthError(ctx *fasthttp.RequestCtx, statusCode int, errorCode, description string) { - ctx.SetContentType("application/json") - ctx.SetStatusCode(statusCode) - resp, _ := json.Marshal(map[string]string{ - "error": errorCode, - "error_description": description, - }) - ctx.SetBody(resp) -} - -func sendStringError(ctx *fasthttp.RequestCtx, statusCode int, message string) { - ctx.SetContentType("text/plain") - ctx.SetStatusCode(statusCode) - ctx.SetBodyString(message) -} - -// generateOpaqueToken generates a cryptographically secure random token. -// validateFlowBrowserSecret checks that the request carries the __bifrost_flow_secret -// cookie matching the hash stored on the pending flow. Returns true if valid. -func validateFlowBrowserSecret(ctx *fasthttp.RequestCtx, flow *tables.TablePerUserOAuthPendingFlow) bool { - if flow.BrowserSecretHash == "" { - // Legacy flow without browser binding — allow for backwards compatibility. - return true - } - secret := ctx.Request.Header.Cookie("__bifrost_flow_secret") - if len(secret) == 0 { - return false - } - hash := fmt.Sprintf("%x", sha256.Sum256(secret)) - return hash == flow.BrowserSecretHash -} - -func generateOpaqueToken(length int) (string, error) { - bytes := make([]byte, length) - if _, err := rand.Read(bytes); err != nil { - return "", err - } - return base64.RawURLEncoding.EncodeToString(bytes), nil -} - -// handleUpstreamAuthorize handles the upstream OAuth proxy for per-user OAuth. -// When a user needs to authenticate with an upstream MCP server (e.g., Notion), -// this endpoint redirects them to the upstream provider's OAuth authorize URL. -// After the user authenticates, the callback stores their upstream token linked -// to either their Bifrost session (runtime flow) or a PendingFlow (consent flow). -// -// Runtime flow: GET /api/oauth/per-user/upstream/authorize?mcp_client_id=xxx&session=xxx -// Consent flow: GET /api/oauth/per-user/upstream/authorize?mcp_client_id=xxx&flow_id=xxx -func (h *PerUserOAuthHandler) handleUpstreamAuthorize(ctx *fasthttp.RequestCtx) { - if h.store.ConfigStore == nil { - SendError(ctx, fasthttp.StatusServiceUnavailable, "OAuth upstream authorization unavailable: config store is disabled") - return - } - - mcpClientID := string(ctx.QueryArgs().Peek("mcp_client_id")) - sessionID := string(ctx.QueryArgs().Peek("session")) - flowID := string(ctx.QueryArgs().Peek("flow_id")) - - if mcpClientID == "" || (sessionID == "" && flowID == "") { - SendError(ctx, fasthttp.StatusBadRequest, "mcp_client_id and either session or flow_id are required") - return - } - - // Resolve identity depending on whether this is a runtime session or a consent flow. - var virtualKeyID, userID, proxySessionToken, gatewaySessionID string - if flowID != "" { - // Consent flow: use the pending flow for identity and proxy token. - flow, err := h.store.ConfigStore.GetPerUserOAuthPendingFlow(ctx, flowID) - if err != nil || flow == nil || time.Now().After(flow.ExpiresAt) { - SendError(ctx, fasthttp.StatusUnauthorized, "Invalid or expired consent flow") - return - } - if !validateFlowBrowserSecret(ctx, flow) { - SendError(ctx, fasthttp.StatusForbidden, "Flow does not belong to this browser session") - return - } - if strVal(flow.VirtualKeyID) != "" { - virtualKeyID = *flow.VirtualKeyID - } - if strVal(flow.UserID) != "" { - userID = *flow.UserID - } - // Use a prefixed flow token so the callback can detect the consent path. - // Include mcpClientID to avoid unique constraint violations when multiple - // MCP services are connected in the same consent flow. - proxySessionToken = "flow:" + flowID + ":" + mcpClientID - gatewaySessionID = flowID - } else { - // Runtime flow: validate the existing Bifrost session. - bifrostSession, err := h.store.ConfigStore.GetPerUserOAuthSessionByID(ctx, sessionID) - if err != nil || bifrostSession == nil { - SendError(ctx, fasthttp.StatusUnauthorized, "Invalid or expired session") - return - } - if !bifrostSession.ExpiresAt.After(time.Now()) { - SendError(ctx, fasthttp.StatusUnauthorized, "Invalid or expired session") - return - } - virtualKeyID = strVal(bifrostSession.VirtualKeyID) - userID = strVal(bifrostSession.UserID) - proxySessionToken = "runtime:" + sessionID + ":" + mcpClientID - gatewaySessionID = sessionID - } - - // Look up the MCP client config to get the template OAuth config. - mcpClient, err := h.store.ConfigStore.GetMCPClientByID(ctx, mcpClientID) - if err != nil || mcpClient == nil { - SendError(ctx, fasthttp.StatusNotFound, "MCP client not found") - return - } - if mcpClient.AuthType != string(schemas.MCPAuthTypePerUserOauth) { - SendError(ctx, fasthttp.StatusBadRequest, "MCP client does not use per-user OAuth") - return - } - if mcpClient.OauthConfigID == nil || *mcpClient.OauthConfigID == "" { - SendError(ctx, fasthttp.StatusBadRequest, "MCP client has no OAuth configuration") - return - } - - // Load template OAuth config (has upstream authorize_url, client_id, etc.) - templateConfig, err := h.store.ConfigStore.GetOauthConfigByID(ctx, *mcpClient.OauthConfigID) - if err != nil || templateConfig == nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to load OAuth template config") - return - } - - // Generate PKCE challenge for upstream. - codeVerifier, err := generateOpaqueToken(32) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to generate PKCE verifier") - return - } - verifierHash := sha256.Sum256([]byte(codeVerifier)) - codeChallenge := base64.RawURLEncoding.EncodeToString(verifierHash[:]) - - // Generate state for upstream. - state, err := generateOpaqueToken(32) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Failed to generate state token") - return - } - - // Build redirect URI (Bifrost's callback endpoint). - redirectURI := lib.BuildBaseURL(ctx, h.store.GetMCPExternalClientURL()) + "/api/oauth/callback" - var vkId *string - if virtualKeyID != "" { - vkId = &virtualKeyID - } - var uid *string - if userID != "" { - uid = &userID - } - // Store upstream OAuth session linking state → MCP client + identity. - upstreamSession := &tables.TableOauthUserSession{ - ID: uuid.New().String(), - MCPClientID: mcpClientID, - OauthConfigID: *mcpClient.OauthConfigID, - State: state, - CodeVerifier: codeVerifier, - SessionToken: proxySessionToken, // "runtime:xxx" for runtime flow; "flow:xxx" for consent flow - GatewaySessionID: gatewaySessionID, - VirtualKeyID: vkId, - UserID: uid, - Status: "pending", - ExpiresAt: time.Now().Add(15 * time.Minute), - } - logger.Debug("[oauth/upstream-authorize] creating upstream session: mcp_client=%s flow=%s", mcpClientID, proxySessionToken) - if err := h.store.ConfigStore.CreateOauthUserSession(ctx, upstreamSession); err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("Failed to create upstream OAuth session: %v", err)) - return - } - - // Parse scopes from template config. - var scopes []string - if templateConfig.Scopes != "" { - json.Unmarshal([]byte(templateConfig.Scopes), &scopes) - } - - // Build upstream authorize URL with PKCE. - resolvedClientID := templateConfig.GetResolvedClientID() - if strings.TrimSpace(resolvedClientID) == "" { - SendError(ctx, fasthttp.StatusInternalServerError, fmt.Sprintf("OAuth client_id for config %q could not be resolved — check that the referenced environment variable is set", templateConfig.ID)) - return - } - params := url.Values{} - params.Set("response_type", "code") - params.Set("client_id", resolvedClientID) - params.Set("redirect_uri", redirectURI) - params.Set("state", state) - params.Set("code_challenge", codeChallenge) - params.Set("code_challenge_method", "S256") - if len(scopes) > 0 { - params.Set("scope", strings.Join(scopes, " ")) - } - - baseURL, err := url.Parse(templateConfig.AuthorizeURL) - if err != nil { - SendError(ctx, fasthttp.StatusInternalServerError, "Invalid upstream authorize URL") - return - } - existing := baseURL.Query() - for k, vals := range params { - for _, v := range vals { - existing.Set(k, v) - } - } - baseURL.RawQuery = existing.Encode() - ctx.Redirect(baseURL.String(), fasthttp.StatusFound) -} - -// Ensure unused imports are referenced. -var _ = html.EscapeString -var _ configstore.ConfigStore diff --git a/transports/bifrost-http/lib/config.go b/transports/bifrost-http/lib/config.go index 0b02f1d3080..a5eaf5572ea 100644 --- a/transports/bifrost-http/lib/config.go +++ b/transports/bifrost-http/lib/config.go @@ -82,10 +82,6 @@ type HandlerStore interface { ShouldAllowPerRequestStorageOverride() bool // ShouldAllowPerRequestRawOverride returns whether per-request overrides for raw request/response visibility are permitted ShouldAllowPerRequestRawOverride() bool - // GetMCPExternalServerURL returns the configured external base URL for OAuth server-side - // metadata (.well-known endpoints, WWW-Authenticate header), or empty string if not configured - // (falls back to dynamic Host-header-based URL). - GetMCPExternalServerURL() string // GetMCPExternalClientURL returns the configured external base URL Bifrost uses as the // redirect_uri when acting as an OAuth client to upstream MCP servers, or empty string // if not configured (falls back to dynamic Host-header-based URL). @@ -354,6 +350,7 @@ type Config struct { OAuthProvider *oauth2.OAuth2Provider TokenRefreshWorker *oauth2.TokenRefreshWorker + OAuthSweepWorker *oauth2.PerUserOAuthSweepWorker // Async job executor (initialized during setup if LogsStore + governance are available) AsyncJobExecutor *logstore.AsyncJobExecutor @@ -839,10 +836,6 @@ func sanitizeMCPExternalOAuthURLs(client *configstore.ClientConfig) { if client == nil { return } - if err := ValidateBaseURL(client.MCPExternalServerURL.GetValue()); err != nil { - logger.Warn("mcp_external_server_url %v; override will be ignored and OAuth URLs will fall back to the request Host header", err) - client.MCPExternalServerURL = nil - } if err := ValidateBaseURL(client.MCPExternalClientURL.GetValue()); err != nil { logger.Warn("mcp_external_client_url %v; override will be ignored and OAuth URLs will fall back to the request Host header", err) client.MCPExternalClientURL = nil @@ -3215,6 +3208,13 @@ func initFrameworkConfig(ctx context.Context, config *Config, configData *Config config.TokenRefreshWorker.Start(ctx) } + // Start per-user OAuth sweep worker: expires stale pending flows and reaps + // long-orphaned token rows. Orphan retention defaults to 30 days. + config.OAuthSweepWorker = oauth2.NewPerUserOAuthSweepWorker(config.OAuthProvider, 30*24*time.Hour, logger) + if config.OAuthSweepWorker != nil { + config.OAuthSweepWorker.Start(ctx) + } + config.FrameworkConfig = &framework.FrameworkConfig{ Pricing: pricingConfig, } @@ -3502,13 +3502,6 @@ func (c *Config) ShouldAllowPerRequestRawOverride() bool { return c.ClientConfig.AllowPerRequestRawOverride } -// GetMCPExternalServerURL returns the configured external base URL for OAuth server-side -// metadata (.well-known endpoints, WWW-Authenticate header), or empty string if not configured. -// Resolves env var references automatically. -func (c *Config) GetMCPExternalServerURL() string { - return c.ClientConfig.MCPExternalServerURL.GetValue() -} - // GetMCPExternalClientURL returns the configured external base URL Bifrost uses as the // redirect_uri when acting as an OAuth client to upstream MCP servers, or empty string // if not configured. Resolves env var references automatically. @@ -3569,73 +3562,6 @@ func (c *Config) GetAllowOnAllVirtualKeysClients() map[string]string { return result } -// GetPerUserOAuthMCPClients returns a map of clientID -> clientName for all MCP clients -// that have AuthType set to "per_user_oauth". The returned map is a copy, safe for concurrent use. -func (c *Config) GetPerUserOAuthMCPClients() map[string]string { - c.muMCP.RLock() - defer c.muMCP.RUnlock() - - if c.MCPConfig == nil { - return nil - } - result := make(map[string]string) - for _, client := range c.MCPConfig.ClientConfigs { - if client != nil && client.AuthType == schemas.MCPAuthTypePerUserOauth && !client.Disabled { - result[client.ID] = client.Name - } - } - return result -} - -// GetPerUserOAuthMCPClientsForVirtualKey returns a map of clientID -> clientName for -// per_user_oauth MCP clients that the given VK is allowed to use. A client is included if: -// - AllowOnAllVirtualKeys is true, OR -// - The VK has an explicit entry in governance_virtual_key_mcp_configs for that client. -// -// If virtualKeyID is empty, all per-user OAuth clients are returned. If the config store -// is unavailable or the VK lookup fails, only clients with AllowOnAllVirtualKeys=true are returned. -func (c *Config) GetPerUserOAuthMCPClientsForVirtualKey(ctx context.Context, virtualKeyID string) map[string]string { - all := c.GetPerUserOAuthMCPClients() - if virtualKeyID == "" { - return all - } - - // Build set of per-user OAuth clients that allow all virtual keys. - c.muMCP.RLock() - allowAll := make(map[string]string) - if c.MCPConfig != nil { - for _, client := range c.MCPConfig.ClientConfigs { - if client != nil && client.AuthType == schemas.MCPAuthTypePerUserOauth && client.AllowOnAllVirtualKeys { - allowAll[client.ID] = client.Name - } - } - } - c.muMCP.RUnlock() - - if c.ConfigStore == nil { - return allowAll - } - - // Get VK-specific MCP configs (with MCPClient preloaded so we have the string ClientID). - vkConfigs, err := c.ConfigStore.GetVirtualKeyMCPConfigs(ctx, virtualKeyID) - if err != nil { - // Fail closed: only return clients that are allowed on all virtual keys. - return allowAll - } - explicit := make(map[string]bool, len(vkConfigs)) - for _, cfg := range vkConfigs { - explicit[cfg.MCPClient.ClientID] = true - } - - result := make(map[string]string) - for clientID, clientName := range all { - if _, ok := allowAll[clientID]; ok || explicit[clientID] { - result[clientID] = clientName - } - } - return result -} - // GetProvidersForModel returns the list of providers for a given model, sorted // deterministically so callers picking providers[0] always get the same result. func (c *Config) GetProvidersForModel(model string) []schemas.ModelProvider { @@ -3751,6 +3677,9 @@ func (c *Config) Close(ctx context.Context) { if c.TokenRefreshWorker != nil { c.TokenRefreshWorker.Stop() } + if c.OAuthSweepWorker != nil { + c.OAuthSweepWorker.Stop() + } if c.KVStore != nil { c.KVStore.Close() } diff --git a/transports/bifrost-http/lib/config_test.go b/transports/bifrost-http/lib/config_test.go index 4a2bf4074c5..bc08c574ece 100644 --- a/transports/bifrost-http/lib/config_test.go +++ b/transports/bifrost-http/lib/config_test.go @@ -425,14 +425,11 @@ func (m *MockConfigStore) Ping(ctx context.Context) error { retu func (m *MockConfigStore) EncryptPlaintextRows(ctx context.Context) error { return nil } func (m *MockConfigStore) Close(ctx context.Context) error { return nil } func (m *MockConfigStore) DB() *gorm.DB { return nil } +func (m *MockConfigStore) ScopedDB(ctx context.Context) *gorm.DB { return nil } func (m *MockConfigStore) ExecuteTransaction(ctx context.Context, fn func(tx *gorm.DB) error) error { return fn(nil) } -func (m *MockConfigStore) ScopedDB(ctx context.Context) *gorm.DB { - return m.DB() -} - func (m *MockConfigStore) GetOauthConfigByID(ctx context.Context, id string) (*tables.TableOauthConfig, error) { return nil, nil } @@ -1202,15 +1199,11 @@ func (m *MockConfigStore) GetOauthUserSessionByID(ctx context.Context, id string return nil, nil } -func (m *MockConfigStore) GetOauthUserSessionByState(ctx context.Context, state string) (*tables.TableOauthUserSession, error) { - return nil, nil -} - func (m *MockConfigStore) ClaimOauthUserSessionByState(ctx context.Context, state string) (*tables.TableOauthUserSession, error) { return nil, nil } -func (m *MockConfigStore) GetOauthUserSessionBySessionToken(ctx context.Context, sessionToken string) (*tables.TableOauthUserSession, error) { +func (m *MockConfigStore) GetOauthUserSessionByModeIdentityAndMCPClient(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) (*tables.TableOauthUserSession, error) { return nil, nil } @@ -1223,11 +1216,7 @@ func (m *MockConfigStore) UpdateOauthUserSession(ctx context.Context, session *t } // Per-user OAuth token CRUD -func (m *MockConfigStore) GetOauthUserTokenByIdentity(ctx context.Context, virtualKeyID, userID, sessionToken, mcpClientID string) (*tables.TableOauthUserToken, error) { - return nil, nil -} - -func (m *MockConfigStore) GetOauthUserTokenBySessionToken(ctx context.Context, sessionToken string) (*tables.TableOauthUserToken, error) { +func (m *MockConfigStore) GetOauthUserTokenByMode(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) (*tables.TableOauthUserToken, error) { return nil, nil } @@ -1243,85 +1232,36 @@ func (m *MockConfigStore) DeleteOauthUserToken(ctx context.Context, id string) e return nil } -func (m *MockConfigStore) DeleteOauthUserTokensByMCPClient(ctx context.Context, mcpClientID string) error { - return nil -} - -// Per-user OAuth Authorization Server CRUD -func (m *MockConfigStore) GetPerUserOAuthClientByClientID(ctx context.Context, clientID string) (*tables.TablePerUserOAuthClient, error) { - return nil, nil -} - -func (m *MockConfigStore) CreatePerUserOAuthClient(ctx context.Context, client *tables.TablePerUserOAuthClient) error { - return nil -} - -func (m *MockConfigStore) GetPerUserOAuthSessionByAccessToken(ctx context.Context, accessToken string) (*tables.TablePerUserOAuthSession, error) { - return nil, nil -} - -func (m *MockConfigStore) GetPerUserOAuthSessionByID(ctx context.Context, id string) (*tables.TablePerUserOAuthSession, error) { - return nil, nil -} - -func (m *MockConfigStore) CreatePerUserOAuthSession(ctx context.Context, session *tables.TablePerUserOAuthSession) error { +func (m *MockConfigStore) DeleteOauthUserSession(ctx context.Context, id string) error { return nil } -func (m *MockConfigStore) UpdatePerUserOAuthSession(ctx context.Context, session *tables.TablePerUserOAuthSession) error { +func (m *MockConfigStore) DeleteOauthUserSessionsByModeIdentityAndMCPClient(ctx context.Context, mode schemas.MCPAuthMode, identity, mcpClientID string) error { return nil } -func (m *MockConfigStore) DeletePerUserOAuthSession(ctx context.Context, id string) error { +func (m *MockConfigStore) MarkOauthUserTokenNeedsReauthByID(ctx context.Context, tokenID string) error { return nil } -func (m *MockConfigStore) GetPerUserOAuthCodeByCode(ctx context.Context, code string) (*tables.TablePerUserOAuthCode, error) { +func (m *MockConfigStore) GetOauthUserTokenByID(ctx context.Context, id string) (*tables.TableOauthUserToken, error) { return nil, nil } -func (m *MockConfigStore) ClaimPerUserOAuthCode(ctx context.Context, code string) (*tables.TablePerUserOAuthCode, error) { +func (m *MockConfigStore) ListAllOauthUserTokens(ctx context.Context) ([]tables.TableOauthUserToken, error) { return nil, nil } -func (m *MockConfigStore) CreatePerUserOAuthCode(ctx context.Context, code *tables.TablePerUserOAuthCode) error { - return nil -} - -func (m *MockConfigStore) UpdatePerUserOAuthCode(ctx context.Context, code *tables.TablePerUserOAuthCode) error { - return nil -} - -func (m *MockConfigStore) GetPerUserOAuthPendingFlow(ctx context.Context, id string) (*tables.TablePerUserOAuthPendingFlow, error) { +func (m *MockConfigStore) ListAllPendingOauthUserSessions(ctx context.Context) ([]tables.TableOauthUserSession, error) { return nil, nil } -func (m *MockConfigStore) CreatePerUserOAuthPendingFlow(ctx context.Context, flow *tables.TablePerUserOAuthPendingFlow) error { - return nil -} - -func (m *MockConfigStore) UpdatePerUserOAuthPendingFlow(ctx context.Context, flow *tables.TablePerUserOAuthPendingFlow) error { - return nil -} - -func (m *MockConfigStore) DeletePerUserOAuthPendingFlow(ctx context.Context, id string) error { - return nil -} - -func (m *MockConfigStore) ConsumePerUserOAuthPendingFlow(ctx context.Context, id string) (int64, error) { - return 1, nil -} - -func (m *MockConfigStore) GetOauthUserTokensByGatewaySessionID(ctx context.Context, gatewaySessionID string) ([]tables.TableOauthUserToken, error) { - return nil, nil -} - -func (m *MockConfigStore) TransferOauthUserTokensFromGatewaySession(ctx context.Context, gatewaySessionID, realSessionToken, virtualKeyID, userID string) error { - return nil +func (m *MockConfigStore) DeleteExpiredOauthUserSessions(ctx context.Context) (int64, error) { + return 0, nil } -func (m *MockConfigStore) FinalizePerUserOAuthConsent(ctx context.Context, flowID string, session *tables.TablePerUserOAuthSession, code *tables.TablePerUserOAuthCode) (int64, error) { - return 1, nil +func (m *MockConfigStore) DeleteOrphanedOauthUserTokens(ctx context.Context, olderThan time.Duration) (int64, error) { + return 0, nil } // Routing rules diff --git a/transports/bifrost-http/lib/ctx.go b/transports/bifrost-http/lib/ctx.go index 6265dbaa8c9..6226c4af4fb 100644 --- a/transports/bifrost-http/lib/ctx.go +++ b/transports/bifrost-http/lib/ctx.go @@ -319,6 +319,26 @@ func ConvertToBifrostContext(ctx *fasthttp.RequestCtx, store HandlerStore) (*sch return true } } + // Handle MCP session ID header (x-bf-mcp-session-id): a client-issued + // opaque identifier used for session-mode per-user OAuth flows. Any + // non-empty string the caller can re-present on subsequent /mcp calls. + // 255-char cap matches ParseSessionIDFromBaggage so both ingestion + // paths reject oversized lookup keys consistently. + if keyStr == "x-bf-mcp-session-id" { + if v := strings.TrimSpace(string(value)); v != "" { + if len(v) > 255 { + // Don't echo any of the value — x-bf-mcp-session-id is a + // re-presentable lookup key for session-mode OAuth; the + // length alone is enough for debugging. + if logger != nil { + logger.Warn("x-bf-mcp-session-id exceeds 255 chars, ignoring: length=%d (skipped last %d chars)", len(v), len(v)-255) + } + return true + } + bifrostCtx.SetValue(schemas.BifrostContextKeyMCPSessionID, v) + } + return true + } // Handle virtual key header (x-bf-vk, authorization, x-api-key, x-goog-api-key headers) if keyStr == string(schemas.BifrostContextKeyVirtualKey) { bifrostCtx.SetValue(schemas.BifrostContextKeyVirtualKey, string(value)) @@ -600,11 +620,6 @@ func ConvertToBifrostContext(ctx *fasthttp.RequestCtx, store HandlerStore) (*sch }) bifrostCtx.SetValue(schemas.BifrostContextKeyRequestHeaders, allHeaders) - // Extract per-user MCP OAuth user identifier from X-Bf-User-Id header - if mcpUserID := string(ctx.Request.Header.Peek("X-Bf-User-Id")); mcpUserID != "" { - bifrostCtx.SetValue(schemas.BifrostContextKeyMCPUserID, mcpUserID) - } - // Build and set OAuth redirect URI for per-user OAuth flows. Bifrost is acting as // the OAuth client to upstream MCP servers here, so use the client-side override. var externalClientURL string diff --git a/transports/bifrost-http/server/server.go b/transports/bifrost-http/server/server.go index 0ecc92a4e67..bfefeeb47e0 100644 --- a/transports/bifrost-http/server/server.go +++ b/transports/bifrost-http/server/server.go @@ -1151,6 +1151,7 @@ func (s *BifrostHTTPServer) RegisterAPIRoutes(ctx context.Context, callbacks Ser providerHandler := handlers.NewProviderHandler(callbacks, s.Config, s.Client) oauthHandler := handlers.NewOAuthHandler(s.Config.OAuthProvider, s.Client, s.Config) mcpHandler := handlers.NewMCPHandler(callbacks, callbacks, s.Client, s.Config, oauthHandler) + mcpSessionsHandler := handlers.NewMCPSessionsHandler(s.Config) configHandler := handlers.NewConfigHandler(callbacks, s.Config) pluginsHandler := handlers.NewPluginsHandler(callbacks, s.Config.ConfigStore) sessionHandler := handlers.NewSessionHandler(s.Config.ConfigStore, s.WSTicketStore) @@ -1160,15 +1161,9 @@ func (s *BifrostHTTPServer) RegisterAPIRoutes(ctx context.Context, callbacks Ser healthHandler.RegisterRoutes(s.Router, middlewares...) providerHandler.RegisterRoutes(s.Router, middlewares...) mcpHandler.RegisterRoutes(s.Router, middlewares...) + mcpSessionsHandler.RegisterRoutes(s.Router, middlewares...) configHandler.RegisterRoutes(s.Router, middlewares...) oauthHandler.RegisterRoutes(s.Router, middlewares...) - // OAuth metadata + per-user OAuth endpoints (no auth middleware — must be publicly accessible) - oauthMetadataHandler := handlers.NewOAuthMetadataHandler(s.Config) - oauthMetadataHandler.RegisterRoutes(s.Router) - perUserOAuthHandler := handlers.NewPerUserOAuthHandler(s.Config) - perUserOAuthHandler.RegisterRoutes(s.Router) - consentHandler := handlers.NewConsentHandler(s.Config) - consentHandler.RegisterRoutes(s.Router) if pluginsHandler != nil { pluginsHandler.RegisterRoutes(s.Router, middlewares...) } diff --git a/ui/app/workspace/config/views/mcpView.tsx b/ui/app/workspace/config/views/mcpView.tsx index 59baf54c9ae..a93ec566ec3 100644 --- a/ui/app/workspace/config/views/mcpView.tsx +++ b/ui/app/workspace/config/views/mcpView.tsx @@ -1,3 +1,5 @@ +import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { EnvVarInput } from "@/components/ui/envVarInput"; import { Input } from "@/components/ui/input"; @@ -7,6 +9,7 @@ import { getErrorMessage, useGetCoreConfigQuery, useUpdateCoreConfigMutation } f import { CoreConfig, DefaultCoreConfig } from "@/lib/types/config"; import { EnvVar } from "@/lib/types/schemas"; import { RbacOperation, RbacResource, useRbac } from "@enterprise/lib"; +import { AlertTriangle } from "lucide-react"; import { useCallback, useEffect, useMemo, useState } from "react"; import { toast } from "sonner"; @@ -46,7 +49,6 @@ export default function MCPView() { const hasChanges = useMemo(() => { if (!config) return false; - const serverURLChanged = !envVarEquals(localConfig.mcp_external_server_url, config.mcp_external_server_url); const clientURLChanged = !envVarEquals(localConfig.mcp_external_client_url, config.mcp_external_client_url); return ( localConfig.mcp_agent_depth !== config.mcp_agent_depth || @@ -54,7 +56,6 @@ export default function MCPView() { localConfig.mcp_code_mode_binding_level !== (config.mcp_code_mode_binding_level || "server") || localConfig.mcp_tool_sync_interval !== (config.mcp_tool_sync_interval ?? 10) || localConfig.mcp_disable_auto_tool_inject !== (config.mcp_disable_auto_tool_inject ?? false) || - serverURLChanged || clientURLChanged ); }, [config, localConfig]); @@ -103,10 +104,6 @@ export default function MCPView() { })); }, []); - const handleServerURLChange = useCallback((value: EnvVar) => { - setLocalConfig((prev) => ({ ...prev, mcp_external_server_url: value })); - }, []); - const handleClientURLChange = useCallback((value: EnvVar) => { setLocalConfig((prev) => ({ ...prev, mcp_external_client_url: value })); }, []); @@ -277,67 +274,48 @@ export default function MCPView() { )} - {/* External Base URLs */} -
-
-

External Base URLs

-

- Override Bifrost's public base URL when it runs behind a reverse proxy. In most setups both URLs are the same —{" "} - leave them blank to derive the URL from the incoming Host header. Both fields support - env var syntax (e.g. env.BIFROST_EXTERNAL_URL). -

-
- -
-
- -

- Advertised in OAuth server metadata that downstream clients read about Bifrost — e.g.{" "} - /.well-known/oauth-authorization-server and the{" "} - WWW-Authenticate header on /mcp. Example: Claude Code - connects to https://bifrost.example.com/mcp and discovers the authorize/token endpoints - from this URL. -

-
- -
- -
-
+ {/* Advanced Settings — collapsed by default so people don't accidentally + edit the redirect_uri, which would break already-authorized MCP clients. */} + + + + Advanced Settings + +

- Used as the redirect_uri Bifrost registers with upstream OAuth providers{" "} - when it acts as a client to an MCP server. Example: when a user connects an MCP server like Notion or Jira, this is the URL - Notion/Jira will redirect the browser to after login ({"/api/oauth/callback"}). -

-

- Heads up: changing this after MCP clients have already completed OAuth will break them. The upstream - provider locks the redirect_uri to whatever was registered initially, so existing clients - will fail with "Invalid redirect URI". Clear the stored OAuth client credentials for affected MCP servers - and re-authorize so Bifrost re-runs Dynamic Client Registration with the new URL. + Override Bifrost's public base URL when it runs behind a reverse proxy.{" "} + Leave blank to derive the URL from the incoming Host header. Used as the{" "} + redirect_uri Bifrost registers with upstream OAuth providers when it acts as a client to an + MCP server (e.g. Notion or Jira redirect the browser to{" "} + {"/api/oauth/callback"} after login). Supports env var syntax (e.g.{" "} + env.BIFROST_EXTERNAL_URL).

-
- -
-
+ + + + Changing this URL can break existing MCP clients + +

+ Upstream OAuth providers lock the redirect_uri to whatever was registered initially, + so MCP clients that already completed OAuth will fail with "Invalid redirect URI". To recover, + clear the stored OAuth client credentials for the affected MCP servers and re-authorize so Bifrost re-runs Dynamic + Client Registration with the new URL. +

+
+
+ + +
+
+ + + ); +} diff --git a/ui/app/workspace/mcp-sessions/auth/layout.tsx b/ui/app/workspace/mcp-sessions/auth/layout.tsx new file mode 100644 index 00000000000..e22a07d4413 --- /dev/null +++ b/ui/app/workspace/mcp-sessions/auth/layout.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from "@tanstack/react-router"; +import MCPSessionsAuthPage from "./page"; + +function RouteComponent() { + // Public-by-policy in OSS: the backend enforces identity match on the flow + // row itself. We route any incoming caller to the page; if their identity + // doesn't match the flow's, the API returns 403 and the page renders an + // appropriate message. + return ; +} + +export const Route = createFileRoute("/workspace/mcp-sessions/auth")({ + component: RouteComponent, +}); diff --git a/ui/app/workspace/mcp-sessions/auth/page.tsx b/ui/app/workspace/mcp-sessions/auth/page.tsx new file mode 100644 index 00000000000..5f1a324f6e6 --- /dev/null +++ b/ui/app/workspace/mcp-sessions/auth/page.tsx @@ -0,0 +1,281 @@ +// Auth landing route for inline-401 URLs returned by the inference path. +// +// The inference response embeds a frontend URL of the form +// {base}/workspace/mcp-sessions/auth?flow={flowId} +// pointing here. The page fetches the pending flow's metadata, shows the +// user what they're about to authenticate, and on "Authenticate" click +// asks the backend for the upstream provider authorize URL and redirects +// the browser to it. The upstream provider redirects back to +// /api/oauth/callback which completes the flow server-side. + +import FullPageLoader from "@/components/fullPageLoader"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { useToast } from "@/hooks/use-toast"; +import { getErrorMessage, useGetMCPFlowDetailQuery, useStartMCPFlowMutation } from "@/lib/store"; +import { MCPFlowDetail } from "@/lib/types/mcpSessions"; +import { Link } from "@tanstack/react-router"; +import { ExternalLink, Fingerprint, KeyRound, Loader2, ShieldCheck, UserRound } from "lucide-react"; +import { useQueryState } from "nuqs"; + +export default function MCPSessionsAuthPage() { + const { toast } = useToast(); + const [flowId] = useQueryState("flow"); + const skip = !flowId; + const { data: flow, isLoading, isError, error, refetch } = useGetMCPFlowDetailQuery(flowId ?? "", { skip }); + const [startFlow, { isLoading: starting }] = useStartMCPFlowMutation(); + + if (!flowId) { + return ( + +

Missing flow identifier

+

+ This URL is missing the flow query parameter. Open the link from your + inference response or the sessions tab. +

+
+ +
+
+ ); + } + + if (isLoading) { + return ; + } + + if (isError || !flow) { + const status = (error as { status?: number } | undefined)?.status; + if (status === 401) { + return ; + } + if (status === 403) { + return ( + +

This authentication flow isn't yours

+

+ The pending flow belongs to a different identity. Ask the teammate whose VK or user identity triggered the original request + to complete it, or trigger a new request yourself. +

+
+ +
+
+ ); + } + if (status === 404) { + return ( + +

This authentication flow has expired or been completed

+

+ Pending flows expire after a short window. If you still need to authenticate, trigger the original action again so a fresh + flow is created. +

+
+ +
+
+ ); + } + return ( + +

Could not load this authentication flow

+

{getErrorMessage(error)}

+
+ ); + } + + // Flow row exists but isn't pending: it's already been completed, failed, + // or expired. Don't show the "Authenticate" button since startFlow would + // reject (BuildUpstreamAuthorizeURL rejects non-pending flows). + if (flow.status !== "pending") { + return ; + } + + const handleAuthenticate = async () => { + try { + const res = await startFlow(flowId).unwrap(); + window.location.href = res.authorize_url; + } catch (err) { + // The server-side flow could have been completed or expired in + // another tab between the initial query and this click — startFlow + // then rejects. Refetch so the page flips to the completed/expired + // view instead of leaving a stale "Authenticate" CTA visible for a + // retry that can't succeed. + refetch(); + toast({ title: "Failed to start authentication", description: getErrorMessage(err), variant: "destructive" }); + } + }; + + const mcpClientName = flow.mcp_client?.name || flow.mcp_client?.client_id || "MCP server"; + const isReauth = flow.has_active_token === true; + + return ( + +
+ +
+

+ {isReauth ? "Re-authenticate with" : "Authenticate with"} {mcpClientName} +

+

+ {isReauth ? ( + <> + An active credential already exists for the binding below. Completing this flow will replace it with a fresh + credential. You can also close this tab to keep using the existing one. + + ) : ( + <> + You'll be redirected to the provider to sign in and grant access. Bifrost stores the resulting credential against the binding + below so this request and future ones can proceed automatically. + + )} +

+ +
+ + } /> + +
+ +
+ + +
+
+ ); +} + +function CompletedFlowView({ flow }: { flow: MCPFlowDetail }) { + const mcpClientName = flow.mcp_client?.name || flow.mcp_client?.client_id || "this MCP server"; + // has_active_token wins over the flow's row status: a pending flow with an + // existing active token means OAuth was re-initiated unnecessarily. + const effectivelyAuthorized = flow.status === "authorized" || flow.has_active_token; + const title = effectivelyAuthorized + ? "Already authenticated" + : flow.status === "expired" + ? "This authentication flow has expired" + : "This authentication flow can no longer be completed"; + const body = effectivelyAuthorized + ? `The OAuth credential for ${mcpClientName} is already stored. You can close this tab.` + : "Trigger the original action again so a fresh flow is created."; + return ( + +

{title}

+

{body}

+
+ + } /> +
+
+ +
+
+ ); +} + +function DetailRow({ label, value, mono = false }: { label: string; value: React.ReactNode; mono?: boolean }) { + return ( +
+
{label}
+
{value}
+
+ ); +} + +function BindingValue({ flow }: { flow: MCPFlowDetail }) { + if (flow.flow_mode === "user") { + const userID = flow.user_id; + if (!userID) { + return ( + + + First signed-in user + + ); + } + const displayName = flow.user?.name || flow.user?.email; + return ( + + + {displayName ? {displayName} : {userID}} + + ); + } + if (flow.flow_mode === "vk" && flow.virtual_key) { + return ( + + + {flow.virtual_key.name || flow.virtual_key.id} + + ); + } + if (flow.flow_mode === "session" && flow.session_id) { + return ( + + + {flow.session_id} + + ); + } + return Unknown; +} + +function formatExpiry(iso: string): string { + try { + const t = new Date(iso).getTime(); + if (Number.isNaN(t)) return iso; + const diffMs = t - Date.now(); + if (diffMs < 0) return "Expired"; + const mins = Math.floor(diffMs / 60_000); + if (mins < 1) return "in less than a minute"; + if (mins === 1) return "in 1 minute"; + return `in ${mins} minutes`; + } catch { + return iso; + } +} + +function CenteredCard({ children }: { children: React.ReactNode }) { + return ( +
+
{children}
+
+ ); +} + +function SessionsTabLink({ variant = "outline" }: { variant?: "outline" | "ghost" }) { + return ( + + ); +} + +// UnauthenticatedView is the 401 fallback: caller is not logged into the +// dashboard / has no identity in context. Frontend redirects to the dashboard +// login route with a return param so the user lands back here after signing in. +// +// The dashboard-auth-on-but-non-admin-needs-temp-token branch ships in OSS-3 +// alongside the temp-token mint endpoint; this OSS-2 cut just sends the user +// to /login and lets the existing login flow handle it. +function UnauthenticatedView({ flowId }: { flowId: string }) { + const goto = `/workspace/mcp-sessions/auth?flow=${encodeURIComponent(flowId)}`; + const loginURL = `/login?goto=${encodeURIComponent(goto)}`; + return ( + +

Sign in to complete authentication

+

+ Bifrost needs to know who you are before linking this OAuth credential. You'll be sent back here after signing in. +

+
+ +
+
+ ); +} diff --git a/ui/app/workspace/mcp-sessions/layout.tsx b/ui/app/workspace/mcp-sessions/layout.tsx new file mode 100644 index 00000000000..4766c68f8c4 --- /dev/null +++ b/ui/app/workspace/mcp-sessions/layout.tsx @@ -0,0 +1,17 @@ +import { createFileRoute, Outlet, useChildMatches } from "@tanstack/react-router"; +import MCPSessionsPage from "./page"; + +function RouteComponent() { + // Per-user OAuth sessions are scoped to the caller's own identity on the + // backend, so any authenticated dashboard user can view their tab. No RBAC + // resource yet — enterprise can layer DAC scoping on top of the API. + // + // Yield to child routes (/auth, /oauth-callback) when one matches; + // otherwise render the list view as the index of this section. + const childMatches = useChildMatches(); + return childMatches.length === 0 ? : ; +} + +export const Route = createFileRoute("/workspace/mcp-sessions")({ + component: RouteComponent, +}); diff --git a/ui/app/workspace/mcp-sessions/page.tsx b/ui/app/workspace/mcp-sessions/page.tsx new file mode 100644 index 00000000000..437446d0f9c --- /dev/null +++ b/ui/app/workspace/mcp-sessions/page.tsx @@ -0,0 +1,27 @@ +import FullPageLoader from "@/components/fullPageLoader"; +import { getErrorMessage, useGetMCPSessionsQuery } from "@/lib/store"; +import SessionsTable from "./views/sessionsTable"; + +export default function MCPSessionsPage() { + const { data, isLoading, isError, error } = useGetMCPSessionsQuery(); + + if (isLoading) { + return ; + } + + if (isError) { + return ( +
+
+ Failed to load MCP sessions: {getErrorMessage(error)} +
+
+ ); + } + + return ( +
+ +
+ ); +} diff --git a/ui/app/workspace/mcp-sessions/views/sessionsTable.tsx b/ui/app/workspace/mcp-sessions/views/sessionsTable.tsx new file mode 100644 index 00000000000..e1b2794fe6a --- /dev/null +++ b/ui/app/workspace/mcp-sessions/views/sessionsTable.tsx @@ -0,0 +1,373 @@ +// Base sessions table: renders token rows + pending flow rows visible to +// the caller's identity. VK-keyed rows render directly with their VK ID; +// user-keyed rows show the preloaded user.name (falling back to email, +// then raw user_id). The `user` field is populated server-side by the +// enterprise configstore wrapper; OSS leaves it absent and the UI falls +// back to the raw ID. +// +// Status badges: +// active: token row, usable +// orphaned: token row; user lost their last granting VK. Credential +// still alive upstream — auto-reactivates when access is +// restored. Re-auth wouldn't help so the action is hidden. +// needs_reauth: token row; upstream credential dead (refresh failed). +// Re-auth required. +// pending: flow row, user must complete authentication. + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alertDialog"; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdownMenu"; +import { PIN_SHADOW_RIGHT } from "@/components/table/columnPinning"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; +import { Info } from "lucide-react"; +import { useToast } from "@/hooks/use-toast"; +import { getErrorMessage, useReauthMCPSessionMutation, useRevokeMCPSessionMutation } from "@/lib/store"; +import { MCPSessionRow } from "@/lib/types/mcpSessions"; +import { ExternalLink, Fingerprint, KeyRound, Loader2, MoreHorizontal, RefreshCcw, Trash2, UserRound } from "lucide-react"; +import { useState } from "react"; + +interface SessionsTableProps { + sessions: MCPSessionRow[]; +} + +export default function SessionsTable({ sessions }: SessionsTableProps) { + const { toast } = useToast(); + const [reauth, { isLoading: reauthing }] = useReauthMCPSessionMutation(); + const [revoke, { isLoading: revoking }] = useRevokeMCPSessionMutation(); + const [pendingDelete, setPendingDelete] = useState(null); + + const handleReauth = async (row: MCPSessionRow) => { + try { + const res = await reauth(row.id).unwrap(); + // Open the upstream authorize URL. User completes there, then + // is redirected back to /api/oauth/callback by the provider. + window.location.href = res.authorize_url; + } catch (err) { + toast({ title: "Re-authentication failed", description: getErrorMessage(err), variant: "destructive" }); + } + }; + + const confirmRevoke = async () => { + if (!pendingDelete) return; + const row = pendingDelete; + setPendingDelete(null); + try { + await revoke(row.id).unwrap(); + toast({ title: "Session revoked" }); + } catch (err) { + toast({ title: "Failed to revoke session", description: getErrorMessage(err), variant: "destructive" }); + } + }; + + return ( +
+ !open && setPendingDelete(null)}> + + + Revoke this MCP session? + + Bifrost will attempt to revoke the upstream OAuth token and remove the stored credential. Anyone using this binding + will need to re-authenticate. + + + + Cancel + + Revoke + + + + + +
+
+

MCP Auth Sessions

+

+ Per-user OAuth tokens stored for MCP servers, plus any pending authentication flows. +

+
+
+ +
+ + + + MCP Client + + + + + + + + + + Created + + + + + {sessions.length === 0 ? ( + + + + No sessions yet. Sessions appear here when an inference request or MCP gateway call triggers per-user OAuth. + + + + ) : ( + sessions.map((row) => ( + + {row.mcp_client?.name || row.mcp_client?.client_id || "-"} + + + + + + + +
+ {formatAccessExpiry(row)} + {row.last_refreshed_at ? ( + refreshed {formatRelativePast(row.last_refreshed_at)} + ) : null} +
+
+ {formatRelativePast(row.created_at)} + + handleReauth(row)} + onRevoke={() => setPendingDelete(row)} + /> + +
+ )) + )} +
+
+
+
+ ); +} + +function HeaderWithTooltip({ label, tooltip }: { label: string; tooltip: string }) { + return ( + + + + + {label} + + + + {tooltip} + + + ); +} + +function BindingCell({ row }: { row: MCPSessionRow }) { + if (row.auth_mode === "user" && row.user_id) { + const displayName = row.user?.name || row.user?.email; + return ( +
+ + {displayName ? {displayName} : {row.user_id}} +
+ ); + } + if (row.auth_mode === "vk" && row.virtual_key) { + return ( +
+ + {row.virtual_key.name || row.virtual_key.id} +
+ ); + } + if (row.auth_mode === "session" && row.session_id) { + return ( +
+ + {row.session_id} +
+ ); + } + return Session-bound; +} + +function StatusBadge({ status, kind }: { status: string; kind: string }) { + if (kind === "flow") { + return Pending; + } + if (status === "orphaned") { + // Muted amber: distinct from destructive (red, action-required) and + // secondary (gray, in-progress). Signals "informational, no action + // needed from you" — the auto-restore cascade handles it. + return ( + + Orphaned + + ); + } + if (status === "needs_reauth") { + return Needs re-auth; + } + return Active; +} + +interface RowActionsProps { + row: MCPSessionRow; + reauthing: boolean; + revoking: boolean; + onReauth: () => void; + onRevoke: () => void; +} + +function RowActions({ row, reauthing, revoking, onReauth, onRevoke }: RowActionsProps) { + const busy = reauthing || revoking; + return ( + + + + + + {row.kind === "flow" ? ( + row.status === "needs_reauth" ? ( + // The PKCE state on this flow row is dead; a fresh request to the + // MCP client will start a new flow. No action we can offer wires + // up to the existing flow row, so surface guidance instead. + + Trigger a request to re-authenticate + + ) : ( + { + e.preventDefault(); + window.location.href = `/workspace/mcp-sessions/auth?flow=${row.id}`; + }} + > + + Complete authentication + + ) + ) : ( + <> + {row.status !== "orphaned" && ( + // Re-auth on an orphaned row wouldn't help: the upstream + // credential is intact, the user just no longer has any + // granting VK. Surface guidance instead of an action. + { + e.preventDefault(); + onReauth(); + }} + > + + Re-authenticate + + )} + { + e.preventDefault(); + onRevoke(); + }} + > + + Revoke + + + )} + + + ); +} + +function formatRelativePast(iso: string): string { + try { + const t = new Date(iso).getTime(); + if (Number.isNaN(t)) return iso; + const diffMs = Date.now() - t; + if (diffMs < 60_000) return "just now"; + const mins = Math.floor(diffMs / 60_000); + if (mins < 60) return `${mins} min ago`; + const hours = Math.floor(diffMs / 3_600_000); + if (hours < 48) return `${hours}h ago`; + const days = Math.floor(diffMs / 86_400_000); + return `${days}d ago`; + } catch { + return iso; + } +} + +function formatAccessExpiry(row: MCPSessionRow): string { + if (!row.expires_at) return "-"; + try { + const t = new Date(row.expires_at).getTime(); + if (Number.isNaN(t)) return row.expires_at; + const diffMs = t - Date.now(); + if (diffMs < 0) { + // Active rows auto-refresh on next use via the refresh token. + // Orphaned rows still hold a valid upstream credential — the past + // expiry just means the cached access token is stale; if access + // is restored, refresh kicks in. Only 'needs_reauth' is genuinely + // expired (the refresh token itself is dead). + switch (row.status) { + case "active": + return "Refreshes on next use"; + case "orphaned": + return "Refreshes when access is restored"; + default: + return "expired"; + } + } + const days = Math.floor(diffMs / 86_400_000); + if (days > 1) return `in ${days} days`; + const hours = Math.floor(diffMs / 3_600_000); + if (hours > 1) return `in ${hours} hours`; + const mins = Math.floor(diffMs / 60_000); + return `in ${Math.max(mins, 1)} min`; + } catch { + return row.expires_at; + } +} diff --git a/ui/components/sidebar.tsx b/ui/components/sidebar.tsx index 7dfe5a2802f..5d8049c5c98 100644 --- a/ui/components/sidebar.tsx +++ b/ui/components/sidebar.tsx @@ -829,6 +829,13 @@ export default function AppSidebar() { description: "Tool Groups", hasAccess: hasMCPToolGroupsAccess, }, + { + title: "Auth Sessions", + url: "/workspace/mcp-sessions", + icon: KeyRound, + description: "Per-user OAuth sessions", + hasAccess: hasMCPGatewayAccess, + }, { title: "MCP Settings", url: "/workspace/mcp-settings", diff --git a/ui/components/ui/alert.tsx b/ui/components/ui/alert.tsx index 023eb959456..aca6307a0b6 100644 --- a/ui/components/ui/alert.tsx +++ b/ui/components/ui/alert.tsx @@ -12,6 +12,8 @@ const alertVariants = cva( destructive: "border-red-200/30 bg-red-50/30 text-red-900 dark:border-red-800/30 dark:bg-red-950/30 dark:text-red-100 [&>svg]:text-red-600 dark:[&>svg]:text-red-400 *:data-[slot=alert-description]:text-red-700 dark:*:data-[slot=alert-description]:text-red-300", info: "border-blue-200/30 bg-blue-50/30 text-blue-900 dark:border-blue-800/30 dark:bg-blue-950/30 dark:text-blue-100 [&>svg]:text-blue-600 dark:[&>svg]:text-blue-400 *:data-[slot=alert-description]:text-blue-700 dark:*:data-[slot=alert-description]:text-blue-300", + warning: + "border-amber-200/40 bg-amber-50/40 text-amber-900 dark:border-amber-800/40 dark:bg-amber-950/40 dark:text-amber-100 [&>svg]:text-amber-600 dark:[&>svg]:text-amber-400 *:data-[slot=alert-description]:text-amber-800 dark:*:data-[slot=alert-description]:text-amber-200", }, }, defaultVariants: { diff --git a/ui/lib/store/apis/baseApi.ts b/ui/lib/store/apis/baseApi.ts index b0aa69a8cb4..f4a2da2ad87 100644 --- a/ui/lib/store/apis/baseApi.ts +++ b/ui/lib/store/apis/baseApi.ts @@ -8,194 +8,216 @@ import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; // Auth tokens are now stored in HTTP-only cookies (set by server) // No client-side token needed — handled by credentials: "include" export const getTokenFromStorage = (): Promise => { - return Promise.resolve(null); + return Promise.resolve(null); }; // Helper function to set auth token // Non-enterprise: no-op — auth relies on HTTPOnly cookies set by the server // Enterprise: handled separately via tokenManager export const setAuthToken = (_token: string | null) => { - // Non-enterprise auth is cookie-based; no client-side token storage needed. - // Enterprise token management is handled by the tokenManager module. + // Non-enterprise auth is cookie-based; no client-side token storage needed. + // Enterprise token management is handled by the tokenManager module. }; // Helper function to clear all auth-related storage export const clearAuthStorage = () => { - if (typeof window === "undefined") { - return; - } - try { - // Clear traditional auth token - localStorage.removeItem("bifrost-auth-token"); + if (typeof window === "undefined") { + return; + } + try { + // Clear traditional auth token + localStorage.removeItem("bifrost-auth-token"); - // Clear enterprise OAuth tokens using tokenManager - if (IS_ENTERPRISE) { - clearOAuthStorage(); - } - } catch (error) { - console.error("Error clearing auth storage:", error); - } + // Clear enterprise OAuth tokens using tokenManager + if (IS_ENTERPRISE) { + clearOAuthStorage(); + } + } catch (error) { + console.error("Error clearing auth storage:", error); + } }; // Define the base query with authentication headers const baseQuery = fetchBaseQuery({ - baseUrl: getApiBaseUrl(), - credentials: "include", - prepareHeaders: async (headers) => { - headers.set("Content-Type", "application/json"); - // Automatically include token from localStorage in Authorization header - const token = await getTokenFromStorage(); - if (token) { - headers.set("Authorization", `Bearer ${token}`); - } - return headers; - }, + baseUrl: getApiBaseUrl(), + credentials: "include", + prepareHeaders: async (headers) => { + // Default JSON only when an endpoint hasn't already set a content type. + // Forcing application/json unconditionally would clobber multipart + // requests (e.g. FormData uploads) — the browser-generated boundary + // would be lost and the upload would fail. + if (!headers.has("Content-Type")) { + headers.set("Content-Type", "application/json"); + } + // Automatically include token from localStorage in Authorization header + const token = await getTokenFromStorage(); + if (token) { + headers.set("Authorization", `Bearer ${token}`); + } + return headers; + }, }); // Wrap base query with enterprise refresh logic (or passthrough for non-enterprise) const baseQueryWithRefresh = createBaseQueryWithRefresh(baseQuery); // Enhanced base query with error handling -const baseQueryWithErrorHandling: typeof baseQueryWithRefresh = async (args: any, api: any, extraOptions: any) => { - // First apply refresh logic (enterprise-specific, handles 401) - const result = await baseQueryWithRefresh(args, api, extraOptions); +const baseQueryWithErrorHandling: typeof baseQueryWithRefresh = async ( + args: any, + api: any, + extraOptions: any, +) => { + // First apply refresh logic (enterprise-specific, handles 401) + const result = await baseQueryWithRefresh(args, api, extraOptions); - // Then handle other error types - if (result.error) { - const error = result.error as any; + // Then handle other error types + if (result.error) { + const error = result.error as any; - // Handle 401 for non-enterprise (no refresh available) - if (error?.status === 401 && !IS_ENTERPRISE) { - clearAuthStorage(); - if (typeof window !== "undefined" && !window.location.pathname.includes("/login")) { - window.location.href = "/login"; - } - return result; - } + // Handle 401 for non-enterprise (no refresh available) + if (error?.status === 401 && !IS_ENTERPRISE) { + clearAuthStorage(); + if ( + typeof window !== "undefined" && + !window.location.pathname.includes("/login") + ) { + window.location.href = "/login"; + } + return result; + } - // Handle specific error types - if (error?.status === "FETCH_ERROR") { - // Network error - return { - ...result, - error: { - ...error, - data: { - error: { - message: "Network error: Unable to connect to the server", - }, - }, - }, - }; - } + // Handle specific error types + if (error?.status === "FETCH_ERROR") { + // Network error + return { + ...result, + error: { + ...error, + data: { + error: { + message: "Network error: Unable to connect to the server", + }, + }, + }, + }; + } - // Handle other errors with proper BifrostErrorResponse format - if (error?.data) { - const errorData = error.data as BifrostErrorResponse; - if (errorData.error?.message) { - return result; - } - } + // Handle other errors with proper BifrostErrorResponse format + if (error?.data) { + const errorData = error.data as BifrostErrorResponse; + if (errorData.error?.message) { + return result; + } + } - // Fallback error message - return { - ...result, - error: { - ...error, - data: { - error: { - message: "An unexpected error occurred", - }, - }, - }, - }; - } + // Fallback error message + return { + ...result, + error: { + ...error, + data: { + error: { + message: "An unexpected error occurred", + }, + }, + }, + }; + } - return result; + return result; }; // Create the base API export const baseApi = createApi({ - reducerPath: "api", - baseQuery: baseQueryWithErrorHandling, - tagTypes: [ - "Logs", - "MCPLogs", - "Providers", - "MCPClients", - "Config", - "CacheConfig", - "VirtualKeys", - "Teams", - "Customers", - "Budgets", - "RateLimits", - "UsageStats", - "DebugStats", - "HealthCheck", - "DBKeys", - "ProviderKeys", - "Models", - "BaseModels", - "ModelConfigs", - "ProviderGovernance", - "Plugins", - "SCIMProviders", - "User", - "Guardrails", - "ClusterNodes", - "Users", - "GuardrailRules", - "Roles", - "Resources", - "Operations", - "Permissions", - "APIKeys", - "OAuth2Config", - "RoutingRules", - "PricingOverrides", - "MCPToolGroups", - "AuditLogs", - "UserGovernance", - "LargePayloadConfig", - "Folders", - "Prompts", - "Versions", - "Sessions", - "AccessProfiles", - "AccessProfileVirtualKeys", - "BusinessUnits", - "PromptDeployments", - "AuthType", - "FeatureFlags", - ], - endpoints: () => ({}), + reducerPath: "api", + baseQuery: baseQueryWithErrorHandling, + tagTypes: [ + "Logs", + "MCPLogs", + "Providers", + "MCPClients", + "Config", + "CacheConfig", + "VirtualKeys", + "Teams", + "Customers", + "Budgets", + "RateLimits", + "UsageStats", + "DebugStats", + "HealthCheck", + "DBKeys", + "ProviderKeys", + "Models", + "BaseModels", + "ModelConfigs", + "ProviderGovernance", + "Plugins", + "SCIMProviders", + "User", + "Guardrails", + "ClusterNodes", + "Users", + "GuardrailRules", + "Roles", + "Resources", + "Operations", + "Permissions", + "APIKeys", + "OAuth2Config", + "RoutingRules", + "PricingOverrides", + "MCPToolGroups", + "AuditLogs", + "UserGovernance", + "LargePayloadConfig", + "Folders", + "Prompts", + "Versions", + "Sessions", + "AccessProfiles", + "AccessProfileVirtualKeys", + "BusinessUnits", + "PromptDeployments", + "AuthType", + "MCPSessions", + "FeatureFlags", + ], + endpoints: () => ({}), }); // Helper function to extract error message from RTK Query error export const getErrorMessage = (error: unknown): string => { - if (error === undefined || error === null) { - return "An unexpected error occurred"; - } - if (error instanceof Error) { - return error.message; - } - if ( - typeof error === "object" && - error && - "data" in error && - error.data && - typeof error.data === "object" && - "error" in error.data && - error.data.error && - typeof error.data.error === "object" && - "message" in error.data.error && - typeof error.data.error.message === "string" - ) { - return error.data.error.message.charAt(0).toUpperCase() + error.data.error.message.slice(1); - } - if (typeof error === "object" && error && "message" in error && typeof error.message === "string") { - return error.message; - } - return "An unexpected error occurred"; -}; \ No newline at end of file + if (error === undefined || error === null) { + return "An unexpected error occurred"; + } + if (error instanceof Error) { + return error.message; + } + if ( + typeof error === "object" && + error && + "data" in error && + error.data && + typeof error.data === "object" && + "error" in error.data && + error.data.error && + typeof error.data.error === "object" && + "message" in error.data.error && + typeof error.data.error.message === "string" + ) { + return ( + error.data.error.message.charAt(0).toUpperCase() + + error.data.error.message.slice(1) + ); + } + if ( + typeof error === "object" && + error && + "message" in error && + typeof error.message === "string" + ) { + return error.message; + } + return "An unexpected error occurred"; +}; diff --git a/ui/lib/store/apis/index.ts b/ui/lib/store/apis/index.ts index b967a031314..675331b38ca 100644 --- a/ui/lib/store/apis/index.ts +++ b/ui/lib/store/apis/index.ts @@ -9,6 +9,7 @@ export * from "./governanceApi"; export * from "./logsApi"; export * from "./mcpApi"; export * from "./mcpLogsApi"; +export * from "./mcpSessionsApi"; export * from "./pluginsApi"; export * from "./providersApi"; export * from "./promptsApi"; diff --git a/ui/lib/store/apis/mcpSessionsApi.ts b/ui/lib/store/apis/mcpSessionsApi.ts new file mode 100644 index 00000000000..8273d308352 --- /dev/null +++ b/ui/lib/store/apis/mcpSessionsApi.ts @@ -0,0 +1,73 @@ +// RTK Query endpoints for the MCP Auth Sessions tab + auth landing flow. +// Mirrors the backend handler in transports/bifrost-http/handlers/mcp_sessions.go. + +import { + MCPFlowDetail, + MCPFlowStartResponse, + MCPSessionReauthResponse, + MCPSessionsListResponse, +} from "@/lib/types/mcpSessions"; +import { baseApi } from "./baseApi"; + +export const mcpSessionsApi = baseApi.injectEndpoints({ + endpoints: (builder) => ({ + // List token rows + pending flow rows visible to the caller's identity. + getMCPSessions: builder.query({ + query: () => ({ url: "/mcp/sessions" }), + providesTags: ["MCPSessions"], + }), + + // Start a fresh OAuth flow for the MCP client backing this token row. + // Returns the upstream authorize URL the browser should redirect to. + // No cache patch: the existing token row's status doesn't change at + // mutation time — the new flow is only finalized when the upstream + // callback fires, which is out of this client's hand. The browser + // navigates away to the authorize URL anyway, so the next list query + // after the user comes back picks up whatever state landed. + reauthMCPSession: builder.mutation({ + query: (rowId) => ({ url: `/mcp/sessions/${rowId}/reauth`, method: "POST" }), + }), + + // Best-effort upstream revoke + hard-delete the row. + // Optimistic patch over invalidatesTags to avoid the cross-replica + // stale-list window in clustered deployments — drop the row from the + // cached list immediately and roll back if the server rejects. + revokeMCPSession: builder.mutation({ + query: (rowId) => ({ url: `/mcp/sessions/${rowId}`, method: "DELETE" }), + async onQueryStarted(rowId, { dispatch, queryFulfilled }) { + const patchResult = dispatch( + mcpSessionsApi.util.updateQueryData("getMCPSessions", undefined, (draft) => { + draft.sessions = draft.sessions.filter((s) => s.id !== rowId); + }), + ); + try { + await queryFulfilled; + } catch { + patchResult.undo(); + } + }, + }), + + // Flow metadata for the auth landing page. + getMCPFlowDetail: builder.query({ + query: (flowId) => ({ url: `/oauth/per-user/flows/${flowId}` }), + providesTags: (_result, _err, id) => [{ type: "MCPSessions", id }], + }), + + // Returns the upstream provider authorize URL for a pending flow. + // The frontend redirects the browser to that URL. + startMCPFlow: builder.mutation({ + // GET in spirit (no body) but defined as mutation so it can be + // triggered imperatively on button click rather than auto-fetched. + query: (flowId) => ({ url: `/oauth/per-user/flows/${flowId}/start`, method: "GET" }), + }), + }), +}); + +export const { + useGetMCPSessionsQuery, + useReauthMCPSessionMutation, + useRevokeMCPSessionMutation, + useGetMCPFlowDetailQuery, + useStartMCPFlowMutation, +} = mcpSessionsApi; diff --git a/ui/lib/types/config.ts b/ui/lib/types/config.ts index 47f7f3ccab6..d0e593267a7 100644 --- a/ui/lib/types/config.ts +++ b/ui/lib/types/config.ts @@ -502,7 +502,6 @@ export interface CoreConfig { hide_deleted_virtual_keys_in_filters: boolean; routing_chain_max_depth: number; header_filter_config?: GlobalHeaderFilterConfig; - mcp_external_server_url?: EnvVar; mcp_external_client_url?: EnvVar; } diff --git a/ui/lib/types/mcpSessions.ts b/ui/lib/types/mcpSessions.ts new file mode 100644 index 00000000000..1a4846ae1d2 --- /dev/null +++ b/ui/lib/types/mcpSessions.ts @@ -0,0 +1,85 @@ +// Types for the MCP Auth Sessions tab + auth landing flow. +// Mirrors the wire shapes in transports/bifrost-http/handlers/mcp_sessions.go. + +export type AuthMode = "user" | "vk" | "session"; + +export type MCPSessionKind = "token" | "flow"; + +// Status values vary by Kind: +// token: "active" | "orphaned" | "needs_reauth" +// - "active": usable credential +// - "orphaned": access revoked (no granting VK), credential still intact; +// reactivates automatically if access is regained +// - "needs_reauth": refresh token rejected upstream; user must re-authenticate +// flow: "pending" +// - "pending": fresh auth in progress; user must complete OAuth. +// The list endpoint only returns pending flow rows; +// "authorized" / "failed" / "expired" are filtered out +// server-side and never reach the wire here. +export type MCPSessionStatus = "active" | "orphaned" | "pending" | "needs_reauth"; + +export interface MCPClientSummary { + client_id: string; + name: string; +} + +export interface VirtualKeySummary { + id: string; + name: string; +} + +// UserSummary: preloaded on user-keyed session and flow rows by the +// enterprise backend (joins against the SCIM users table). OSS leaves it +// absent — the UI falls back to rendering the raw user_id. +export interface UserSummary { + id: string; + name?: string; + email?: string; +} + +export interface MCPSessionRow { + id: string; + kind: MCPSessionKind; + auth_mode: AuthMode; + user_id?: string | null; + user?: UserSummary | null; + virtual_key?: VirtualKeySummary | null; + mcp_client?: MCPClientSummary | null; + session_id?: string | null; + status: MCPSessionStatus; + expires_at?: string | null; + created_at: string; + last_refreshed_at?: string | null; + oauth_config_id?: string; +} + +export interface MCPSessionsListResponse { + sessions: MCPSessionRow[]; +} + +export interface MCPSessionReauthResponse { + authorize_url: string; + session_id: string; +} + +export interface MCPFlowDetail { + id: string; + flow_mode: AuthMode; + status: "pending" | "authorized" | "failed" | "expired"; + mcp_client?: MCPClientSummary | null; + oauth_config_id: string; + user_id?: string | null; + user?: UserSummary | null; + virtual_key?: VirtualKeySummary | null; + session_id?: string | null; + expires_at: string; + created_at: string; + // True when an active token already exists for this binding. Combined with + // status='pending' it means OAuth was re-initiated unnecessarily — the + // auth page should treat it as already authenticated. + has_active_token?: boolean; +} + +export interface MCPFlowStartResponse { + authorize_url: string; +}