feat(mcp): add OAuth2 authorization for MCP services
Support connecting to MCP servers that require OAuth2, with a Cursor-like zero-config flow: the user provides only a URL and the system performs metadata discovery, dynamic client registration (DCR), and the authorization code flow with PKCE on first connect. - Persist per-user access/refresh tokens and per-service DCR client credentials, encrypted at rest (AES-256-GCM) - Store the PKCE verifier/state during the flow via Redis with an in-memory fallback for Lite mode - Cache MCP clients per (service, user) so tokens stay user-isolated - Add endpoints for authorize-url, callback, status, and token revoke; the callback is allowlisted for unauthenticated access - Surface a structured "authorization required" hint when a tool call hits an unauthorized MCP service - Frontend: add an auth-type selector with OAuth config, inline authorization status/actions, and render the connection test result inline in the editor drawer instead of a stacked centered dialog
This commit is contained in:
+71
-10
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/mark3labs/mcp-go/client"
|
||||
"github.com/mark3labs/mcp-go/client/transport"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
@@ -49,6 +50,13 @@ type MCPClient interface {
|
||||
// ClientConfig represents configuration for creating an MCP client
|
||||
type ClientConfig struct {
|
||||
Service *types.MCPService
|
||||
|
||||
// OAuth wiring (only used when Service.AuthConfig.AuthType == oauth).
|
||||
// The token store is scoped to (TenantID, UserID, Service.ID) so each
|
||||
// user connects with their own access/refresh token.
|
||||
TenantID uint64
|
||||
UserID string
|
||||
OAuthRepo interfaces.MCPOAuthRepository
|
||||
}
|
||||
|
||||
// mcpGoClient wraps mark3labs/mcp-go client to implement our MCPClient interface
|
||||
@@ -92,18 +100,33 @@ func NewMCPClient(config *ClientConfig) (MCPClient, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Build OAuth config when this service uses the OAuth strategy. The
|
||||
// client_id comes from the dynamically-registered client persisted at
|
||||
// authorization time; the token store loads the invoking user's token
|
||||
// and transparently refreshes it.
|
||||
oauthConfig, useOAuth, err := buildOAuthConfig(config, httpClient)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create client based on transport type
|
||||
var mcpClient *client.Client
|
||||
var err error
|
||||
switch config.Service.TransportType {
|
||||
case types.MCPTransportSSE:
|
||||
if config.Service.URL == nil || *config.Service.URL == "" {
|
||||
return nil, fmt.Errorf("URL is required for SSE transport")
|
||||
}
|
||||
mcpClient, err = client.NewSSEMCPClient(*config.Service.URL,
|
||||
client.WithHTTPClient(httpClient),
|
||||
client.WithHeaders(headers),
|
||||
)
|
||||
if useOAuth {
|
||||
mcpClient, err = client.NewOAuthSSEClient(*config.Service.URL, oauthConfig,
|
||||
transport.WithHTTPClient(httpClient),
|
||||
transport.WithHeaders(headers),
|
||||
)
|
||||
} else {
|
||||
mcpClient, err = client.NewSSEMCPClient(*config.Service.URL,
|
||||
client.WithHTTPClient(httpClient),
|
||||
client.WithHeaders(headers),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create SSE client: %w", err)
|
||||
}
|
||||
@@ -111,11 +134,18 @@ func NewMCPClient(config *ClientConfig) (MCPClient, error) {
|
||||
if config.Service.URL == nil || *config.Service.URL == "" {
|
||||
return nil, fmt.Errorf("URL is required for HTTP Streamable transport")
|
||||
}
|
||||
// For HTTP streamable, we need to use transport options
|
||||
mcpClient, err = client.NewStreamableHttpClient(*config.Service.URL,
|
||||
transport.WithHTTPBasicClient(httpClient),
|
||||
transport.WithHTTPHeaders(headers),
|
||||
)
|
||||
if useOAuth {
|
||||
mcpClient, err = client.NewOAuthStreamableHttpClient(*config.Service.URL, oauthConfig,
|
||||
transport.WithHTTPBasicClient(httpClient),
|
||||
transport.WithHTTPHeaders(headers),
|
||||
)
|
||||
} else {
|
||||
// For HTTP streamable, we need to use transport options
|
||||
mcpClient, err = client.NewStreamableHttpClient(*config.Service.URL,
|
||||
transport.WithHTTPBasicClient(httpClient),
|
||||
transport.WithHTTPHeaders(headers),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create HTTP streamable client: %w", err)
|
||||
}
|
||||
@@ -134,6 +164,37 @@ func NewMCPClient(config *ClientConfig) (MCPClient, error) {
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
// buildOAuthConfig returns the OAuth configuration for an OAuth-enabled MCP
|
||||
// service, or (_, false, nil) when the service does not use OAuth. It loads
|
||||
// the dynamically-registered client_id and wires a per-user token store so
|
||||
// the transport injects the invoking user's bearer token and refreshes it.
|
||||
func buildOAuthConfig(config *ClientConfig, httpClient *http.Client) (transport.OAuthConfig, bool, error) {
|
||||
svc := config.Service
|
||||
if !svc.AuthConfig.IsOAuth() {
|
||||
return transport.OAuthConfig{}, false, nil
|
||||
}
|
||||
if config.OAuthRepo == nil {
|
||||
return transport.OAuthConfig{}, false, fmt.Errorf("OAuth repository is required for OAuth MCP services")
|
||||
}
|
||||
if config.UserID == "" {
|
||||
return transport.OAuthConfig{}, false, fmt.Errorf("user context is required to connect to an OAuth MCP service")
|
||||
}
|
||||
|
||||
oauthCfg := transport.OAuthConfig{
|
||||
Scopes: svc.AuthConfig.Scopes,
|
||||
TokenStore: newDBTokenStore(config.OAuthRepo, config.TenantID, config.UserID, svc.ID),
|
||||
PKCEEnabled: true,
|
||||
AuthServerMetadataURL: svc.AuthConfig.AuthServerMetadataURL,
|
||||
HTTPClient: httpClient,
|
||||
}
|
||||
if regClient, err := config.OAuthRepo.GetClient(context.Background(), config.TenantID, svc.ID); err == nil && regClient != nil {
|
||||
oauthCfg.ClientID = regClient.ClientID
|
||||
oauthCfg.ClientSecret = regClient.ClientSecret
|
||||
oauthCfg.RedirectURI = regClient.RedirectURI
|
||||
}
|
||||
return oauthCfg, true, nil
|
||||
}
|
||||
|
||||
// onConnectionLost callback when the connection is lost
|
||||
func (c *mcpGoClient) onConnectionLost(err error) {
|
||||
_ = c.Disconnect()
|
||||
|
||||
+57
-22
@@ -3,29 +3,34 @@ package mcp
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// MCPManager manages MCP client connections
|
||||
type MCPManager struct {
|
||||
clients map[string]MCPClient // serviceID -> client
|
||||
clients map[string]MCPClient // cacheKey -> client
|
||||
clientsMu sync.RWMutex
|
||||
oauthRepo interfaces.MCPOAuthRepository
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// NewMCPManager creates a new MCP manager
|
||||
func NewMCPManager() *MCPManager {
|
||||
// NewMCPManager creates a new MCP manager. oauthRepo is used to wire per-user
|
||||
// OAuth token stores for OAuth-enabled MCP services.
|
||||
func NewMCPManager(oauthRepo interfaces.MCPOAuthRepository) *MCPManager {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
manager := &MCPManager{
|
||||
clients: make(map[string]MCPClient),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
clients: make(map[string]MCPClient),
|
||||
oauthRepo: oauthRepo,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
|
||||
// Start cleanup goroutine
|
||||
@@ -34,10 +39,23 @@ func NewMCPManager() *MCPManager {
|
||||
return manager
|
||||
}
|
||||
|
||||
// cacheKey computes the connection-cache key for a service. OAuth services are
|
||||
// keyed per user (each user connects with their own token); all other services
|
||||
// share a single connection per service ID.
|
||||
func cacheKey(service *types.MCPService, userID string) string {
|
||||
if service.AuthConfig.IsOAuth() {
|
||||
return service.ID + "\x00" + userID
|
||||
}
|
||||
return service.ID
|
||||
}
|
||||
|
||||
// GetOrCreateClient gets an existing client or creates a new one
|
||||
// Caches and reuses existing connections for SSE/HTTP Streamable
|
||||
// Note: Stdio transport is disabled for security reasons
|
||||
func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, error) {
|
||||
//
|
||||
// For OAuth-enabled services the connection is keyed per user (derived from
|
||||
// ctx) so each user connects with their own token.
|
||||
func (m *MCPManager) GetOrCreateClient(ctx context.Context, service *types.MCPService) (MCPClient, error) {
|
||||
// Check if service is enabled
|
||||
if !service.Enabled {
|
||||
return nil, fmt.Errorf("MCP service %s is not enabled", service.Name)
|
||||
@@ -48,9 +66,20 @@ func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, er
|
||||
return nil, fmt.Errorf("stdio transport is disabled for security reasons; please use SSE or HTTP Streamable transport instead")
|
||||
}
|
||||
|
||||
var tenantID uint64
|
||||
var userID string
|
||||
if service.AuthConfig.IsOAuth() {
|
||||
tenantID, _ = types.TenantIDFromContext(ctx)
|
||||
userID, _ = types.UserIDFromContext(ctx)
|
||||
if userID == "" {
|
||||
return nil, fmt.Errorf("user context is required to connect to OAuth MCP service %s", service.Name)
|
||||
}
|
||||
}
|
||||
key := cacheKey(service, userID)
|
||||
|
||||
// For SSE/HTTP Streamable, check if client already exists and reuse
|
||||
m.clientsMu.RLock()
|
||||
client, exists := m.clients[service.ID]
|
||||
client, exists := m.clients[key]
|
||||
m.clientsMu.RUnlock()
|
||||
|
||||
if exists && client.IsConnected() {
|
||||
@@ -62,14 +91,17 @@ func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, er
|
||||
defer m.clientsMu.Unlock()
|
||||
|
||||
// Double check after acquiring write lock
|
||||
client, exists = m.clients[service.ID]
|
||||
client, exists = m.clients[key]
|
||||
if exists && client.IsConnected() {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Create new client
|
||||
config := &ClientConfig{
|
||||
Service: service,
|
||||
Service: service,
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
OAuthRepo: m.oauthRepo,
|
||||
}
|
||||
|
||||
client, err := NewMCPClient(config)
|
||||
@@ -89,7 +121,7 @@ func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, er
|
||||
}
|
||||
|
||||
// Store client (only for non-stdio transports)
|
||||
m.clients[service.ID] = client
|
||||
m.clients[key] = client
|
||||
|
||||
logger.GetLogger(m.ctx).Infof("MCP client created and initialized for service: %s", service.Name)
|
||||
return client, nil
|
||||
@@ -128,22 +160,25 @@ func (m *MCPManager) GetClient(serviceID string) (MCPClient, bool) {
|
||||
return client, exists
|
||||
}
|
||||
|
||||
// CloseClient closes and removes a specific client
|
||||
// CloseClient closes and removes all cached connections for a service. For
|
||||
// OAuth services this spans every per-user connection (keys are prefixed with
|
||||
// the service ID).
|
||||
func (m *MCPManager) CloseClient(serviceID string) error {
|
||||
m.clientsMu.Lock()
|
||||
defer m.clientsMu.Unlock()
|
||||
|
||||
client, exists := m.clients[serviceID]
|
||||
if !exists {
|
||||
return nil
|
||||
for key, client := range m.clients {
|
||||
// Match the plain service-ID key as well as per-user OAuth keys
|
||||
// ("<serviceID>\x00<userID>").
|
||||
if key != serviceID && !strings.HasPrefix(key, serviceID+"\x00") {
|
||||
continue
|
||||
}
|
||||
if err := client.Disconnect(); err != nil {
|
||||
logger.GetLogger(m.ctx).Errorf("Failed to disconnect MCP client %s: %v", key, err)
|
||||
}
|
||||
delete(m.clients, key)
|
||||
logger.GetLogger(m.ctx).Infof("MCP client closed: %s", key)
|
||||
}
|
||||
|
||||
if err := client.Disconnect(); err != nil {
|
||||
logger.GetLogger(m.ctx).Errorf("Failed to disconnect MCP client %s: %v", serviceID, err)
|
||||
}
|
||||
|
||||
delete(m.clients, serviceID)
|
||||
logger.GetLogger(m.ctx).Infof("MCP client closed: %s", serviceID)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/mark3labs/mcp-go/client/transport"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// clientRegistrationName is sent as client_name during dynamic client
|
||||
// registration (RFC 7591).
|
||||
const clientRegistrationName = "WeKnora"
|
||||
|
||||
// OAuthManager orchestrates the MCP OAuth2 authorization-code flow:
|
||||
// discovery, dynamic client registration, the authorize redirect, and the
|
||||
// callback code exchange. Tokens are persisted per (tenant, user, service);
|
||||
// the registered client is persisted per (tenant, service) and reused.
|
||||
type OAuthManager struct {
|
||||
repo interfaces.MCPOAuthRepository
|
||||
serviceRepo interfaces.MCPServiceRepository
|
||||
states *oauthStateStore
|
||||
}
|
||||
|
||||
// NewOAuthManager constructs the OAuth manager. rdb may be nil (Lite mode),
|
||||
// in which case in-flight authorization states are kept in memory.
|
||||
func NewOAuthManager(
|
||||
repo interfaces.MCPOAuthRepository,
|
||||
serviceRepo interfaces.MCPServiceRepository,
|
||||
rdb *redis.Client,
|
||||
) *OAuthManager {
|
||||
return &OAuthManager{
|
||||
repo: repo,
|
||||
serviceRepo: serviceRepo,
|
||||
states: newOAuthStateStore(rdb),
|
||||
}
|
||||
}
|
||||
|
||||
// newHandler builds an OAuth handler bound to a service + per-user token store.
|
||||
func (m *OAuthManager) newHandler(
|
||||
ctx context.Context, service *types.MCPService, tenantID uint64, userID, redirectURI string,
|
||||
) (*transport.OAuthHandler, error) {
|
||||
if service.URL == nil || *service.URL == "" {
|
||||
return nil, fmt.Errorf("MCP service URL is required for OAuth")
|
||||
}
|
||||
cfg := transport.OAuthConfig{
|
||||
RedirectURI: redirectURI,
|
||||
Scopes: service.AuthConfig.Scopes,
|
||||
TokenStore: newDBTokenStore(m.repo, tenantID, userID, service.ID),
|
||||
PKCEEnabled: true,
|
||||
AuthServerMetadataURL: service.AuthConfig.AuthServerMetadataURL,
|
||||
}
|
||||
if existing, err := m.repo.GetClient(ctx, tenantID, service.ID); err == nil && existing != nil {
|
||||
cfg.ClientID = existing.ClientID
|
||||
cfg.ClientSecret = existing.ClientSecret
|
||||
}
|
||||
h := transport.NewOAuthHandler(cfg)
|
||||
h.SetBaseURL(*service.URL)
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// StartAuthorization performs discovery + (one-time) dynamic client
|
||||
// registration, then returns the authorization URL the browser should visit.
|
||||
// redirectURI is the backend callback URL registered with the auth server;
|
||||
// frontendRedirect is where the callback bounces the browser when finished.
|
||||
func (m *OAuthManager) StartAuthorization(
|
||||
ctx context.Context,
|
||||
service *types.MCPService,
|
||||
tenantID uint64,
|
||||
userID, redirectURI, frontendRedirect string,
|
||||
) (string, error) {
|
||||
if !service.AuthConfig.IsOAuth() {
|
||||
return "", fmt.Errorf("MCP service %s does not use OAuth", service.ID)
|
||||
}
|
||||
|
||||
h, err := m.newHandler(ctx, service, tenantID, userID, redirectURI)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Register a client dynamically if we don't have one yet for this service.
|
||||
existing, _ := m.repo.GetClient(ctx, tenantID, service.ID)
|
||||
if existing == nil {
|
||||
if err := h.RegisterClient(ctx, clientRegistrationName); err != nil {
|
||||
return "", fmt.Errorf("dynamic client registration failed: %w", err)
|
||||
}
|
||||
clientID := h.GetClientID()
|
||||
if clientID == "" {
|
||||
return "", fmt.Errorf("dynamic client registration returned an empty client_id")
|
||||
}
|
||||
if err := m.repo.SaveClient(ctx, &types.MCPOAuthClient{
|
||||
TenantID: tenantID,
|
||||
ServiceID: service.ID,
|
||||
ClientID: clientID,
|
||||
RedirectURI: redirectURI,
|
||||
}); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("failed to persist MCP oauth client: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
verifier, err := transport.GenerateCodeVerifier()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to generate PKCE verifier: %w", err)
|
||||
}
|
||||
challenge := transport.GenerateCodeChallenge(verifier)
|
||||
state, err := transport.GenerateState()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to generate state: %w", err)
|
||||
}
|
||||
|
||||
authURL, err := h.GetAuthorizationURL(ctx, state, challenge)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to build authorization URL: %w", err)
|
||||
}
|
||||
|
||||
if err := m.states.Put(ctx, state, OAuthState{
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
ServiceID: service.ID,
|
||||
CodeVerifier: verifier,
|
||||
ClientID: h.GetClientID(),
|
||||
RedirectURI: redirectURI,
|
||||
FrontendRedirect: frontendRedirect,
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("failed to persist authorization state: %w", err)
|
||||
}
|
||||
|
||||
return authURL, nil
|
||||
}
|
||||
|
||||
// CompleteAuthorization handles the provider callback: it validates state,
|
||||
// exchanges the code for tokens (PKCE), and persists the per-user token.
|
||||
// Returns the frontend redirect URL recorded at StartAuthorization time.
|
||||
func (m *OAuthManager) CompleteAuthorization(
|
||||
ctx context.Context, state, code string,
|
||||
) (frontendRedirect string, err error) {
|
||||
st, err := m.states.Take(ctx, state)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
frontendRedirect = st.FrontendRedirect
|
||||
|
||||
service, err := m.serviceRepo.GetByID(ctx, st.TenantID, st.ServiceID)
|
||||
if err != nil {
|
||||
return frontendRedirect, fmt.Errorf("failed to load MCP service: %w", err)
|
||||
}
|
||||
if service == nil {
|
||||
return frontendRedirect, fmt.Errorf("MCP service not found")
|
||||
}
|
||||
|
||||
h, err := m.newHandler(ctx, service, st.TenantID, st.UserID, st.RedirectURI)
|
||||
if err != nil {
|
||||
return frontendRedirect, err
|
||||
}
|
||||
// Re-prime the expected state so the library's CSRF check passes after
|
||||
// reconstructing the handler in this separate request.
|
||||
h.SetExpectedState(state)
|
||||
|
||||
if err := h.ProcessAuthorizationResponse(ctx, code, state, st.CodeVerifier); err != nil {
|
||||
return frontendRedirect, fmt.Errorf("token exchange failed: %w", err)
|
||||
}
|
||||
// ProcessAuthorizationResponse persists the token via the TokenStore.
|
||||
logger.GetLogger(ctx).Infof(
|
||||
"MCP OAuth authorized: service=%s user=%s", st.ServiceID, st.UserID,
|
||||
)
|
||||
return frontendRedirect, nil
|
||||
}
|
||||
|
||||
// IsAuthorized reports whether the given user has a stored (non-empty) token
|
||||
// for the service.
|
||||
func (m *OAuthManager) IsAuthorized(
|
||||
ctx context.Context, tenantID uint64, userID, serviceID string,
|
||||
) (bool, error) {
|
||||
tok, err := m.repo.GetToken(ctx, tenantID, userID, serviceID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return tok != nil && tok.AccessToken != "", nil
|
||||
}
|
||||
|
||||
// Revoke removes the user's stored token for the service.
|
||||
func (m *OAuthManager) Revoke(
|
||||
ctx context.Context, tenantID uint64, userID, serviceID string,
|
||||
) error {
|
||||
return m.repo.DeleteToken(ctx, tenantID, userID, serviceID)
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// oauthStateTTL bounds how long an in-flight authorization may take from
|
||||
// "authorize-url issued" to "callback received".
|
||||
const oauthStateTTL = 10 * time.Minute
|
||||
|
||||
// OAuthState is the transient data needed to complete an authorization-code
|
||||
// exchange. It is keyed by the opaque OAuth `state` parameter and MUST hold
|
||||
// the PKCE code_verifier, which is a secret that must never reach the
|
||||
// authorization server — hence server-side storage rather than encoding it
|
||||
// into the state parameter.
|
||||
type OAuthState struct {
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
UserID string `json:"user_id"`
|
||||
ServiceID string `json:"service_id"`
|
||||
CodeVerifier string `json:"code_verifier"`
|
||||
ClientID string `json:"client_id"`
|
||||
RedirectURI string `json:"redirect_uri"`
|
||||
// FrontendRedirect is where the backend callback redirects the browser
|
||||
// after completing (or failing) the exchange.
|
||||
FrontendRedirect string `json:"frontend_redirect"`
|
||||
}
|
||||
|
||||
// oauthStateStore persists in-flight OAuth states. Backed by Redis when
|
||||
// available (so the callback can land on any backend replica); falls back to
|
||||
// a TTL in-memory map for single-instance / Lite deployments.
|
||||
type oauthStateStore struct {
|
||||
rdb *redis.Client
|
||||
|
||||
mu sync.Mutex
|
||||
mem map[string]memStateEntry
|
||||
}
|
||||
|
||||
type memStateEntry struct {
|
||||
value OAuthState
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
func newOAuthStateStore(rdb *redis.Client) *oauthStateStore {
|
||||
s := &oauthStateStore{rdb: rdb, mem: make(map[string]memStateEntry)}
|
||||
if rdb == nil {
|
||||
go s.gcLoop()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *oauthStateStore) key(state string) string {
|
||||
ns := strings.TrimSpace(os.Getenv("WEKNORA_REDIS_NAMESPACE"))
|
||||
if ns != "" {
|
||||
return "weknora:mcp_oauth_state:" + ns + ":" + state
|
||||
}
|
||||
return "weknora:mcp_oauth_state:" + state
|
||||
}
|
||||
|
||||
// Put stores a state with a fixed TTL.
|
||||
func (s *oauthStateStore) Put(ctx context.Context, state string, value OAuthState) error {
|
||||
if s.rdb != nil {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.rdb.Set(ctx, s.key(state), data, oauthStateTTL).Err()
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.mem[state] = memStateEntry{value: value, expiresAt: time.Now().Add(oauthStateTTL)}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Take retrieves and deletes a state (single-use). Returns an error if the
|
||||
// state is unknown or expired.
|
||||
func (s *oauthStateStore) Take(ctx context.Context, state string) (OAuthState, error) {
|
||||
if s.rdb != nil {
|
||||
data, err := s.rdb.GetDel(ctx, s.key(state)).Bytes()
|
||||
if err != nil {
|
||||
if err == redis.Nil {
|
||||
return OAuthState{}, fmt.Errorf("oauth state not found or expired")
|
||||
}
|
||||
return OAuthState{}, err
|
||||
}
|
||||
var v OAuthState
|
||||
if err := json.Unmarshal(data, &v); err != nil {
|
||||
return OAuthState{}, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
entry, ok := s.mem[state]
|
||||
if !ok {
|
||||
return OAuthState{}, fmt.Errorf("oauth state not found or expired")
|
||||
}
|
||||
delete(s.mem, state)
|
||||
if time.Now().After(entry.expiresAt) {
|
||||
return OAuthState{}, fmt.Errorf("oauth state not found or expired")
|
||||
}
|
||||
return entry.value, nil
|
||||
}
|
||||
|
||||
func (s *oauthStateStore) gcLoop() {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
now := time.Now()
|
||||
s.mu.Lock()
|
||||
for k, v := range s.mem {
|
||||
if now.After(v.expiresAt) {
|
||||
delete(s.mem, k)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/mark3labs/mcp-go/client/transport"
|
||||
)
|
||||
|
||||
// dbTokenStore is a transport.TokenStore backed by the MCPOAuthRepository,
|
||||
// scoped to a single (tenant, user, service) tuple. The mcp-go OAuth handler
|
||||
// calls GetToken before each request (refreshing via refresh_token when
|
||||
// expired) and SaveToken after a successful authorization or refresh, so this
|
||||
// store transparently persists refreshed tokens back to the database.
|
||||
type dbTokenStore struct {
|
||||
repo interfaces.MCPOAuthRepository
|
||||
tenantID uint64
|
||||
userID string
|
||||
serviceID string
|
||||
}
|
||||
|
||||
// newDBTokenStore creates a per-user, per-service token store.
|
||||
func newDBTokenStore(
|
||||
repo interfaces.MCPOAuthRepository, tenantID uint64, userID, serviceID string,
|
||||
) *dbTokenStore {
|
||||
return &dbTokenStore{repo: repo, tenantID: tenantID, userID: userID, serviceID: serviceID}
|
||||
}
|
||||
|
||||
// GetToken returns the persisted token, or transport.ErrNoToken when the user
|
||||
// has not authorized this service yet.
|
||||
func (s *dbTokenStore) GetToken(ctx context.Context) (*transport.Token, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row, err := s.repo.GetToken(ctx, s.tenantID, s.userID, s.serviceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if row == nil || row.AccessToken == "" {
|
||||
return nil, transport.ErrNoToken
|
||||
}
|
||||
return &transport.Token{
|
||||
AccessToken: row.AccessToken,
|
||||
RefreshToken: row.RefreshToken,
|
||||
TokenType: row.TokenType,
|
||||
ExpiresAt: row.ExpiresAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SaveToken persists a freshly issued or refreshed token.
|
||||
func (s *dbTokenStore) SaveToken(ctx context.Context, token *transport.Token) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
expiresAt := token.ExpiresAt
|
||||
if expiresAt.IsZero() && token.ExpiresIn > 0 {
|
||||
expiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
|
||||
}
|
||||
return s.repo.SaveToken(ctx, &types.MCPOAuthToken{
|
||||
TenantID: s.tenantID,
|
||||
UserID: s.userID,
|
||||
ServiceID: s.serviceID,
|
||||
AccessToken: token.AccessToken,
|
||||
RefreshToken: token.RefreshToken,
|
||||
TokenType: token.TokenType,
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user