From 5074344c164865deaf3870f313846350e409dd32 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 30 Jun 2026 18:16:44 +0800 Subject: [PATCH] feat(embed): scope OAuth and sessions per visitor principal Add embed visitor principals (X-Embed-Visitor), widen sessions.user_id, embed MCP OAuth/approval routes, OAuth callback context detachment, and CloneContext principal preservation for async QA streams. --- docs/api/tenant.md | 5 +- internal/application/repository/session.go | 27 +++++ internal/application/service/message.go | 3 +- internal/application/service/session.go | 31 ++++- .../service/session_knowledge_qa.go | 6 +- .../service/session_user_scope_test.go | 45 ++++++++ internal/handler/embed_channel.go | 108 +++++++++++++++--- internal/handler/embed_session_test.go | 21 +++- internal/handler/mcp_oauth.go | 22 ++-- internal/handler/session/handler.go | 7 +- internal/logger/logger.go | 2 + internal/logger/logger_test.go | 13 +++ internal/mcp/manager.go | 1 + internal/mcp/oauth_manager.go | 9 ++ internal/router/router.go | 5 + internal/types/const.go | 2 + internal/types/interfaces/session.go | 9 ++ internal/types/principal.go | 103 +++++++++++++++++ internal/types/principal_test.go | 39 +++++++ internal/types/session.go | 6 +- migrations/sqlite/000000_init.up.sql | 2 +- .../000066_sessions_user_id_widen.down.sql | 5 + .../000066_sessions_user_id_widen.up.sql | 10 ++ 23 files changed, 438 insertions(+), 43 deletions(-) create mode 100644 migrations/versioned/000066_sessions_user_id_widen.down.sql create mode 100644 migrations/versioned/000066_sessions_user_id_widen.up.sql diff --git a/docs/api/tenant.md b/docs/api/tenant.md index 14ee99a0..f9973d9c 100644 --- a/docs/api/tenant.md +++ b/docs/api/tenant.md @@ -364,10 +364,11 @@ curl --location --request POST 'http://localhost:8080/api/v1/tenants/10000/api-k Principal **仅**用于按终端用户隔离以下能力: +- **对话 Session**(创建、列表、读取按外部用户分开;`仅租户` 模式仍共用租户级 Session) - **MCP OAuth** 访问令牌(同一租户下不同外部用户各自授权,token 互不共用) -- 对话内 MCP OAuth 提示、MCP 工具审批等与 Principal 绑定的流程 +- 对话内 MCP OAuth 提示、MCP 工具审批等与终端用户绑定的流程 -Principal **不会**缩小 API Key 的 API 权限:`X-API-Key` 认证仍授予租户内 **Admin** 角色,知识库、会话、Agent 等接口**不按**外部用户做 RBAC 隔离。若需要全链路 per-user 权限控制,须在业务侧自行鉴权,不能仅依赖本配置。 +Principal **不会**缩小 API Key 的 API 权限:`X-API-Key` 认证仍授予租户内 **Admin** 角色,知识库、Agent 配置等接口**不按**外部用户做 RBAC 隔离。 ### 模式与安全假设 diff --git a/internal/application/repository/session.go b/internal/application/repository/session.go index 250d13e8..8abc574e 100644 --- a/internal/application/repository/session.go +++ b/internal/application/repository/session.go @@ -57,6 +57,21 @@ func (r *sessionRepository) Get(ctx context.Context, tenantID uint64, userID str return &session, nil } +// GetByID retrieves a session by tenant and id without user scoping. +func (r *sessionRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error) { + var session types.Session + err := r.db.WithContext(ctx). + Where("tenant_id = ? AND id = ?", tenantID, id). + First(&session).Error + if err != nil { + if stderrors.Is(err, gorm.ErrRecordNotFound) { + return nil, apperrors.ErrSessionNotFound + } + return nil, err + } + return &session, nil +} + // GetByTenantID retrieves all sessions for a tenant func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint64, userID string) ([]*types.Session, error) { var sessions []*types.Session @@ -263,6 +278,18 @@ func (r *sessionRepository) Update(ctx context.Context, session *types.Session, return res.RowsAffected, res.Error } +// SetOwnerID assigns sessions.user_id for a tenant-scoped row. +func (r *sessionRepository) SetOwnerID(ctx context.Context, tenantID uint64, id, ownerID string) (int64, error) { + res := r.db.WithContext(ctx). + Model(&types.Session{}). + Where("tenant_id = ? AND id = ?", tenantID, id). + Updates(map[string]interface{}{ + "user_id": ownerID, + "updated_at": time.Now(), + }) + return res.RowsAffected, res.Error +} + // UpdateLastRequestState writes only the agent_config column (used here to // store SessionLastRequestState) and bumps updated_at. We deliberately bypass // the regular Update path so the call doesn't perturb title/description and diff --git a/internal/application/service/message.go b/internal/application/service/message.go index a0349b48..b8d56237 100644 --- a/internal/application/service/message.go +++ b/internal/application/service/message.go @@ -69,8 +69,7 @@ func sessionUserIDForLookup(ctx context.Context) string { // Shared-agent pipelines resolve the session owner tenant first; keep that internal lookup tenant-scoped. return "" } - userID, _ := types.UserIDFromContext(ctx) - return userID + return types.SessionOwnerIDFromContext(ctx) } // CreateMessage creates a new message within an existing session diff --git a/internal/application/service/session.go b/internal/application/service/session.go index 6ecd8f51..340cd13d 100644 --- a/internal/application/service/session.go +++ b/internal/application/service/session.go @@ -19,8 +19,7 @@ import ( ) func sessionUserIDFromContext(ctx context.Context) string { - userID, _ := types.UserIDFromContext(ctx) - return userID + return types.SessionOwnerIDFromContext(ctx) } // generateEventID generates a unique event ID with type suffix for better traceability @@ -134,6 +133,32 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess return session, nil } +// GetSessionByID loads a session by tenant and id without user scoping. +func (s *sessionService) GetSessionByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error) { + if id == "" { + return nil, stderrors.New("session id is required") + } + if tenantID == 0 { + return nil, stderrors.New("tenant id is required") + } + return s.sessionRepo.GetByID(ctx, tenantID, id) +} + +// SetSessionOwnerID assigns sessions.user_id for the given session row. +func (s *sessionService) SetSessionOwnerID(ctx context.Context, tenantID uint64, sessionID, ownerID string) error { + if sessionID == "" || ownerID == "" || tenantID == 0 { + return stderrors.New("tenant id, session id and owner id are required") + } + affected, err := s.sessionRepo.SetOwnerID(ctx, tenantID, sessionID, ownerID) + if err != nil { + return err + } + if affected == 0 { + return apperrors.ErrSessionNotFound + } + return nil +} + // GetSessionsByTenant retrieves all sessions for the current tenant func (s *sessionService) GetSessionsByTenant(ctx context.Context) ([]*types.Session, error) { // Get tenant ID from context @@ -186,7 +211,7 @@ func (s *sessionService) ListSessions( query = &types.SessionListQuery{} } query.TenantID = types.MustTenantIDFromContext(ctx) - if uid, ok := types.UserIDFromContext(ctx); ok { + if uid := types.SessionOwnerIDFromContext(ctx); uid != "" { query.UserID = uid } diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go index 9e1ad706..a71e805f 100644 --- a/internal/application/service/session_knowledge_qa.go +++ b/internal/application/service/session_knowledge_qa.go @@ -99,8 +99,8 @@ func (s *sessionService) KnowledgeQA( len(searchTargets), ) - // Get UserID from context - userID, _ := types.UserIDFromContext(ctx) + // Scope memory and pipeline attribution to the same owner as the session. + userID := types.SessionOwnerIDFromContext(ctx) chatManage := &types.ChatManage{ PipelineRequest: types.PipelineRequest{ @@ -734,7 +734,7 @@ func (s *sessionService) SearchKnowledge(ctx context.Context, } // Create default retrieval parameters — prefer tenant RetrievalConfig, fallback to built-in defaults - userID, _ := types.UserIDFromContext(ctx) + userID := types.SessionOwnerIDFromContext(ctx) // Load tenant-level retrieval config (nil is safe — GetEffective* methods handle nil receiver) var rc *types.RetrievalConfig diff --git a/internal/application/service/session_user_scope_test.go b/internal/application/service/session_user_scope_test.go index 69d043c0..2afbb89e 100644 --- a/internal/application/service/session_user_scope_test.go +++ b/internal/application/service/session_user_scope_test.go @@ -20,6 +20,15 @@ func testSessionScopeContext(tenantID uint64, userID string) context.Context { return ctx } +func testAPISessionScopeContext(tenantID uint64, externalUserID string) context.Context { + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, tenantID) + ctx = context.WithValue(ctx, types.UserIDContextKey, "system-7") + return types.WithPrincipal(ctx, types.Principal{ + Type: types.PrincipalAPIExternalUser, + ID: externalUserID, + }) +} + func newTestSessionService(t *testing.T) (*sessionService, *gorm.DB) { t.Helper() @@ -95,3 +104,39 @@ func TestUpdateSessionIsScopedToCurrentUserAndAllowsNoOp(t *testing.T) { }) require.NoError(t, err) } + +func TestGetSessionIsScopedToAPIExternalUser(t *testing.T) { + svc, db := newTestSessionService(t) + aliceSession := &types.Session{ + TenantID: 1, + UserID: "api_external_user:7:alice", + Title: "alice api session", + } + require.NoError(t, db.Create(aliceSession).Error) + bobSession := &types.Session{ + TenantID: 1, + UserID: "api_external_user:7:bob", + Title: "bob api session", + } + require.NoError(t, db.Create(bobSession).Error) + tenantSession := &types.Session{ + TenantID: 1, + UserID: "system-7", + Title: "tenant api session", + } + require.NoError(t, db.Create(tenantSession).Error) + + _, err := svc.GetSession(testAPISessionScopeContext(1, "7:alice"), bobSession.ID) + require.ErrorIs(t, err, apperrors.ErrSessionNotFound) + + got, err := svc.GetSession(testAPISessionScopeContext(1, "7:alice"), aliceSession.ID) + require.NoError(t, err) + require.Equal(t, aliceSession.ID, got.ID) + + _, err = svc.GetSession(testAPISessionScopeContext(1, "7:alice"), tenantSession.ID) + require.ErrorIs(t, err, apperrors.ErrSessionNotFound) + + got, err = svc.GetSession(testSessionScopeContext(1, "system-7"), tenantSession.ID) + require.NoError(t, err) + require.Equal(t, tenantSession.ID, got.ID) +} diff --git a/internal/handler/embed_channel.go b/internal/handler/embed_channel.go index 14add5e1..96fc7b80 100644 --- a/internal/handler/embed_channel.go +++ b/internal/handler/embed_channel.go @@ -26,11 +26,13 @@ import ( // EmbedChannelHandler manages web embed channel CRUD and public embed endpoints. type EmbedChannelHandler struct { - embedSvc interfaces.EmbedChannelService - sessionService interfaces.SessionService - sessionHandler *session.Handler - messageHandler *MessageHandler - redis *redis.Client + embedSvc interfaces.EmbedChannelService + sessionService interfaces.SessionService + sessionHandler *session.Handler + messageHandler *MessageHandler + mcpOAuthHandler *MCPOAuthHandler + mcpServiceHandler *MCPServiceHandler + redis *redis.Client } func NewEmbedChannelHandler( @@ -38,14 +40,18 @@ func NewEmbedChannelHandler( sessionService interfaces.SessionService, sessionHandler *session.Handler, messageHandler *MessageHandler, + mcpOAuthHandler *MCPOAuthHandler, + mcpServiceHandler *MCPServiceHandler, redisClient *redis.Client, ) *EmbedChannelHandler { return &EmbedChannelHandler{ - embedSvc: embedSvc, - sessionService: sessionService, - sessionHandler: sessionHandler, - messageHandler: messageHandler, - redis: redisClient, + embedSvc: embedSvc, + sessionService: sessionService, + sessionHandler: sessionHandler, + messageHandler: messageHandler, + mcpOAuthHandler: mcpOAuthHandler, + mcpServiceHandler: mcpServiceHandler, + redis: redisClient, } } @@ -422,6 +428,12 @@ func (h *EmbedChannelHandler) CreateEmbedSession(c *gin.Context) { c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create session"}) return } + ownerID := types.EmbedSessionPrincipal(tenantID, ch.ID, created.ID).StorageID() + if err := h.sessionService.SetSessionOwnerID(ctx, tenantID, created.ID, ownerID); err != nil { + logger.Warnf(ctx, "failed to assign embed session owner for %s: %v", created.ID, err) + } else { + created.UserID = ownerID + } // Hand back a signed handle bound to this session; the widget must echo it // (X-Embed-Session header) on every subsequent load/chat call. sig := service.SignEmbedSessionHandle(ch, created.ID) @@ -450,6 +462,61 @@ func (h *EmbedChannelHandler) EmbedStopSession(c *gin.Context) { h.sessionHandler.StopSession(c) } +func (h *EmbedChannelHandler) EmbedResolveMCPOAuth(c *gin.Context) { + if err := h.ensureEmbedSession(c); err != nil { + return + } + if h.mcpOAuthHandler == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth handler unavailable"}) + return + } + h.mcpOAuthHandler.ResolveMCPOAuth(c) +} + +func (h *EmbedChannelHandler) EmbedCancelMCPOAuth(c *gin.Context) { + if err := h.ensureEmbedSession(c); err != nil { + return + } + if h.mcpOAuthHandler == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth handler unavailable"}) + return + } + h.mcpOAuthHandler.CancelMCPOAuth(c) +} + +func (h *EmbedChannelHandler) EmbedMCPOAuthAuthorizeURL(c *gin.Context) { + if err := h.ensureEmbedSession(c); err != nil { + return + } + if h.mcpOAuthHandler == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth handler unavailable"}) + return + } + h.mcpOAuthHandler.AuthorizeURL(c) +} + +func (h *EmbedChannelHandler) EmbedMCPOAuthStatus(c *gin.Context) { + if err := h.ensureEmbedSession(c); err != nil { + return + } + if h.mcpOAuthHandler == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth handler unavailable"}) + return + } + h.mcpOAuthHandler.Status(c) +} + +func (h *EmbedChannelHandler) EmbedResolveToolApproval(c *gin.Context) { + if err := h.ensureEmbedSession(c); err != nil { + return + } + if h.mcpServiceHandler == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "tool approval handler unavailable"}) + return + } + h.mcpServiceHandler.ResolveToolApproval(c) +} + type embedWebhookEventRequest struct { Type string `json:"type"` SessionID string `json:"session_id"` @@ -535,7 +602,7 @@ func (h *EmbedChannelHandler) ensureEmbedSession(c *gin.Context) error { c.JSON(http.StatusBadRequest, gin.H{"error": "session_id is required"}) return apperrors.NewBadRequestError("session_id is required") } - sess, err := h.sessionService.GetSession(c.Request.Context(), sessionID) + sess, err := h.sessionService.GetSessionByID(c.Request.Context(), ch.TenantID, sessionID) if err != nil || sess == nil { c.JSON(http.StatusNotFound, gin.H{"error": "session not found"}) return apperrors.NewNotFoundError("session not found") @@ -545,6 +612,12 @@ func (h *EmbedChannelHandler) ensureEmbedSession(c *gin.Context) error { c.JSON(http.StatusForbidden, gin.H{"error": "session not allowed for this embed channel"}) return apperrors.NewForbiddenError("session not allowed") } + ownerID := types.EmbedSessionPrincipal(ch.TenantID, ch.ID, sessionID).StorageID() + if strings.TrimSpace(sess.UserID) == "" { + if err := h.sessionService.SetSessionOwnerID(c.Request.Context(), ch.TenantID, sessionID, ownerID); err != nil { + logger.Warnf(c.Request.Context(), "failed to backfill embed session owner for %s: %v", sessionID, err) + } + } // Require the signed handle minted at creation. This is the per-visitor // authorization secret: knowing the session id alone (e.g. from a leaked // access log) is insufficient without the matching signature. @@ -553,12 +626,17 @@ func (h *EmbedChannelHandler) ensureEmbedSession(c *gin.Context) error { c.JSON(http.StatusForbidden, gin.H{"error": "session signature invalid"}) return apperrors.NewForbiddenError("session signature invalid") } - principal := types.Principal{ - Type: types.PrincipalEmbedSession, - ID: fmt.Sprintf("%d:%s:%s", ch.TenantID, ch.ID, sessionID), + principal := types.EmbedSessionPrincipal(ch.TenantID, ch.ID, sessionID) + ctx := c.Request.Context() + if visitorID := strings.TrimSpace(c.GetHeader(types.EmbedVisitorHeader)); visitorID != "" { + if err := types.ValidateEmbedVisitorID(visitorID); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid embed visitor id"}) + return apperrors.NewBadRequestError("invalid embed visitor id") + } + ctx = types.WithEmbedVisitorID(ctx, visitorID) } c.Set(types.PrincipalContextKey.String(), principal) - c.Request = c.Request.WithContext(types.WithPrincipal(c.Request.Context(), principal)) + c.Request = c.Request.WithContext(types.WithPrincipal(ctx, principal)) return nil } diff --git a/internal/handler/embed_session_test.go b/internal/handler/embed_session_test.go index 951aa728..43634cf0 100644 --- a/internal/handler/embed_session_test.go +++ b/internal/handler/embed_session_test.go @@ -38,6 +38,23 @@ func (s *stubSessionServiceForEmbed) GetSession(_ context.Context, id string) (* return sess, nil } +func (s *stubSessionServiceForEmbed) GetSessionByID(_ context.Context, tenantID uint64, id string) (*types.Session, error) { + sess, ok := s.sessions[id] + if !ok || sess.TenantID != tenantID { + return nil, errors.New("session not found") + } + return sess, nil +} + +func (s *stubSessionServiceForEmbed) SetSessionOwnerID(_ context.Context, tenantID uint64, sessionID, ownerID string) error { + sess, ok := s.sessions[sessionID] + if !ok || sess.TenantID != tenantID { + return errors.New("session not found") + } + sess.UserID = ownerID + return nil +} + func (s *stubSessionServiceForEmbed) CreateSession(_ context.Context, session *types.Session) (*types.Session, error) { created := *session if created.ID == "" { @@ -170,8 +187,8 @@ func TestEnsureEmbedSessionWrongTenant(t *testing.T) { if err := h.ensureEmbedSession(c); err == nil { t.Fatal("expected error for cross-tenant session") } - if w.Code != http.StatusForbidden { - t.Fatalf("status = %d, body = %s", w.Code, w.Body.String()) + if w.Code != http.StatusNotFound { + t.Fatalf("status = %d, want %d, body = %s", w.Code, http.StatusNotFound, w.Body.String()) } } diff --git a/internal/handler/mcp_oauth.go b/internal/handler/mcp_oauth.go index 8bd28726..252dca21 100644 --- a/internal/handler/mcp_oauth.go +++ b/internal/handler/mcp_oauth.go @@ -36,10 +36,14 @@ func NewMCPOAuthHandler( return &MCPOAuthHandler{oauth: oauth, mcpManager: mcpManager, svc: svc, gate: gate} } -func mcpOAuthPrincipalFromContext(ctx *gin.Context) (types.Principal, string) { - principal, _ := types.PrincipalFromContext(ctx.Request.Context()) - principal = principal.Normalize() - return principal, principal.StorageID() +func mcpOAuthPrincipalsFromContext(ctx *gin.Context) (tokenPrincipal types.Principal, gateUserID string) { + raw, _ := types.PrincipalFromContext(ctx.Request.Context()) + raw = raw.Normalize() + tokenPrincipal = types.MCPOAuthPrincipalFromContext(ctx.Request.Context()) + if raw.Valid() { + gateUserID = raw.StorageID() + } + return tokenPrincipal, gateUserID } type mcpOAuthAuthorizeRequest struct { @@ -69,7 +73,7 @@ func (h *MCPOAuthHandler) AuthorizeURL(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") tenantID := c.GetUint64(types.TenantIDContextKey.String()) - principal, _ := mcpOAuthPrincipalFromContext(c) + principal, _ := mcpOAuthPrincipalsFromContext(c) if tenantID == 0 || !principal.Valid() { c.Error(errors.NewUnauthorizedError("authentication required")) return @@ -169,7 +173,7 @@ func (h *MCPOAuthHandler) Status(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") tenantID := c.GetUint64(types.TenantIDContextKey.String()) - principal, _ := mcpOAuthPrincipalFromContext(c) + principal, _ := mcpOAuthPrincipalsFromContext(c) if tenantID == 0 || !principal.Valid() { c.Error(errors.NewUnauthorizedError("authentication required")) return @@ -198,7 +202,7 @@ func (h *MCPOAuthHandler) Revoke(c *gin.Context) { ctx := c.Request.Context() serviceID := c.Param("id") tenantID := c.GetUint64(types.TenantIDContextKey.String()) - principal, _ := mcpOAuthPrincipalFromContext(c) + principal, _ := mcpOAuthPrincipalsFromContext(c) if tenantID == 0 || !principal.Valid() { c.Error(errors.NewUnauthorizedError("authentication required")) return @@ -244,7 +248,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) { ctx := c.Request.Context() pendingID := c.Param("pending_id") tenantID := c.GetUint64(types.TenantIDContextKey.String()) - principal, gateUserID := mcpOAuthPrincipalFromContext(c) + principal, gateUserID := mcpOAuthPrincipalsFromContext(c) if tenantID == 0 || !principal.Valid() || gateUserID == "" { c.Error(errors.NewUnauthorizedError("authentication required")) return @@ -352,7 +356,7 @@ func (h *MCPOAuthHandler) CancelMCPOAuth(c *gin.Context) { ctx := c.Request.Context() pendingID := c.Param("pending_id") tenantID := c.GetUint64(types.TenantIDContextKey.String()) - _, gateUserID := mcpOAuthPrincipalFromContext(c) + _, gateUserID := mcpOAuthPrincipalsFromContext(c) if tenantID == 0 || strings.TrimSpace(gateUserID) == "" { c.Error(errors.NewUnauthorizedError("authentication required")) return diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go index 3be73cc3..d02c037b 100644 --- a/internal/handler/session/handler.go +++ b/internal/handler/session/handler.go @@ -116,9 +116,10 @@ func (h *Handler) CreateSession(c *gin.Context) { Description: request.Description, } // Attach the calling user as the session owner when available. - // API-key / legacy callers without a user id fall back to tenant-level visibility. - if userID, ok := types.UserIDFromContext(ctx); ok { - createdSession.UserID = userID + // API-key callers scope sessions per external user when configured; + // otherwise they fall back to the synthetic tenant user. + if ownerID := types.SessionOwnerIDFromContext(ctx); ownerID != "" { + createdSession.UserID = ownerID } // Call service to create session diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 2f0ff8d0..4c96f299 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -499,6 +499,7 @@ func CloneContext(ctx context.Context) context.Context { types.TenantInfoContextKey, types.UserIDContextKey, types.UserContextKey, + types.PrincipalContextKey, // TenantRoleContextKey: the caller's resolved role in the // active tenant (PR 2 #1303). Must be propagated for the same // reason as TenantIDContextKey — any handler that does @@ -510,6 +511,7 @@ func CloneContext(ctx context.Context) context.Context { types.LanguageContextKey, types.SessionTenantIDContextKey, types.EmbedQueryContextKey, + types.EmbedVisitorContextKey, // Keep the Langfuse trace alive across CloneContext boundaries so // LLM/Embedder/Reranker/VLM/ASR wrappers attach their generations // to the same trace opened by GinMiddleware, instead of each call diff --git a/internal/logger/logger_test.go b/internal/logger/logger_test.go index 42da1f42..aa31d7bb 100644 --- a/internal/logger/logger_test.go +++ b/internal/logger/logger_test.go @@ -1,10 +1,12 @@ package logger import ( + "context" "strings" "testing" "time" + "github.com/Tencent/WeKnora/internal/types" "github.com/sirupsen/logrus" ) @@ -164,3 +166,14 @@ func TestLevelColorFor(t *testing.T) { } } } + +func TestCloneContextPreservesPrincipal(t *testing.T) { + t.Parallel() + + ctx := types.WithPrincipal(context.Background(), types.EmbedSessionPrincipal(10000, "ch1", "sess1")) + cloned := CloneContext(ctx) + + if got := types.SessionOwnerIDFromContext(cloned); got != "embed_session:10000:ch1:sess1" { + t.Fatalf("SessionOwnerIDFromContext(cloned) = %q", got) + } +} diff --git a/internal/mcp/manager.go b/internal/mcp/manager.go index 0977f0ff..1a06f57e 100644 --- a/internal/mcp/manager.go +++ b/internal/mcp/manager.go @@ -71,6 +71,7 @@ func (m *MCPManager) GetOrCreateClient(ctx context.Context, service *types.MCPSe if service.AuthConfig.IsOAuth() { tenantID, _ = types.TenantIDFromContext(ctx) principal, _ = types.PrincipalFromContext(ctx) + principal = types.MCPOAuthPrincipalFromContext(ctx) if !principal.Valid() { return nil, fmt.Errorf("principal context is required to connect to OAuth MCP service %s", service.Name) } diff --git a/internal/mcp/oauth_manager.go b/internal/mcp/oauth_manager.go index f1ab7496..4762abb8 100644 --- a/internal/mcp/oauth_manager.go +++ b/internal/mcp/oauth_manager.go @@ -3,6 +3,7 @@ package mcp import ( "context" "fmt" + "time" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" @@ -15,6 +16,11 @@ import ( // registration (RFC 7591). const clientRegistrationName = "WeKnora" +// oauthCallbackTimeout bounds token exchange after the browser lands on the +// public callback route. The Gin request context is canceled once the client +// receives the redirect, so CompleteAuthorization must detach from it. +const oauthCallbackTimeout = 60 * time.Second + // 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, principal, service); @@ -143,6 +149,9 @@ func (m *OAuthManager) StartAuthorization( func (m *OAuthManager) CompleteAuthorization( ctx context.Context, state, code string, ) (frontendRedirect string, err error) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), oauthCallbackTimeout) + defer cancel() + st, err := m.states.Take(ctx, state) if err != nil { return "", err diff --git a/internal/router/router.go b/internal/router/router.go index 11d39ff5..e1a6b605 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -1164,6 +1164,11 @@ func RegisterEmbedPublicRoutes( embed.GET("/messages/:session_id/load", embedHandler.EmbedLoadMessages) embed.POST("/sessions/:session_id/stop", embedHandler.EmbedStopSession) embed.POST("/sessions/:session_id/events", embedHandler.EmbedRelayWebhookEvent) + embed.POST("/sessions/:session_id/mcp-oauth-resolutions/:pending_id", embedHandler.EmbedResolveMCPOAuth) + embed.POST("/sessions/:session_id/mcp-oauth-resolutions/:pending_id/cancel", embedHandler.EmbedCancelMCPOAuth) + embed.POST("/sessions/:session_id/mcp-services/:id/oauth/authorize-url", embedHandler.EmbedMCPOAuthAuthorizeURL) + embed.GET("/sessions/:session_id/mcp-services/:id/oauth/status", embedHandler.EmbedMCPOAuthStatus) + embed.POST("/sessions/:session_id/tool-approvals/:pending_id", embedHandler.EmbedResolveToolApproval) // Serve images embedded in bot replies (e.g. chart exports). EmbedAuth // injects the channel's tenant, and the handler enforces that the // requested path belongs to that tenant. diff --git a/internal/types/const.go b/internal/types/const.go index aff12894..a37e42cd 100644 --- a/internal/types/const.go +++ b/internal/types/const.go @@ -29,6 +29,8 @@ const ( EmbedQueryContextKey ContextKey = "EmbedQuery" // LanguageContextKey is the context key for user language preference (e.g. "zh-CN", "en-US") LanguageContextKey ContextKey = "Language" + // EmbedVisitorContextKey is the anonymous visitor id for embed OAuth isolation. + EmbedVisitorContextKey ContextKey = "EmbedVisitorID" // LangfuseTraceContextKey carries the active Langfuse *Trace across the // request lifecycle. Defined here (not inside the langfuse package) so // that logger.CloneContext can preserve it without importing langfuse. diff --git a/internal/types/interfaces/session.go b/internal/types/interfaces/session.go index a0f58637..b1564a24 100644 --- a/internal/types/interfaces/session.go +++ b/internal/types/interfaces/session.go @@ -13,6 +13,10 @@ type SessionService interface { CreateSession(ctx context.Context, session *types.Session) (*types.Session, error) // GetSession gets a session GetSession(ctx context.Context, id string) (*types.Session, error) + // GetSessionByID loads a session by tenant and id without user scoping. + GetSessionByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error) + // SetSessionOwnerID assigns sessions.user_id for the given session row. + SetSessionOwnerID(ctx context.Context, tenantID uint64, sessionID, ownerID string) error // GetSessionsByTenant gets all sessions of a tenant GetSessionsByTenant(ctx context.Context) ([]*types.Session, error) // GetPagedSessionsByTenant gets paged sessions of a tenant @@ -61,6 +65,9 @@ type SessionRepository interface { Create(ctx context.Context, session *types.Session) (*types.Session, error) // Get gets a session visible to the tenant/user scope. Get(ctx context.Context, tenantID uint64, userID string, id string) (*types.Session, error) + // GetByID loads a session by tenant and id without user scoping. Callers + // must enforce access (e.g. embed channel + session signature). + GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error) // GetByTenantID gets all sessions visible to the tenant/user scope. GetByTenantID(ctx context.Context, tenantID uint64, userID string) ([]*types.Session, error) // GetPagedByTenantID gets paged sessions visible to the tenant/user scope. @@ -69,6 +76,8 @@ type SessionRepository interface { QueryPaged(ctx context.Context, q *types.SessionListQuery) ([]*types.SessionListItem, int64, error) // Update updates a session visible to the tenant/user scope. Update(ctx context.Context, session *types.Session, userID string) (int64, error) + // SetOwnerID assigns sessions.user_id for a tenant-scoped row. + SetOwnerID(ctx context.Context, tenantID uint64, id, ownerID string) (int64, error) // UpdateLastRequestState persists the most recent input-bar state for a // session (agent, model, KB scope, etc.) so the chat UI can restore it // when the session is reopened. Scope rules match Update. diff --git a/internal/types/principal.go b/internal/types/principal.go index e5ac66e1..5660c7c2 100644 --- a/internal/types/principal.go +++ b/internal/types/principal.go @@ -2,6 +2,7 @@ package types import ( "context" + "fmt" "strings" ) @@ -12,8 +13,13 @@ const ( PrincipalIMUser = "im_user" PrincipalEmbedChannel = "embed_channel" PrincipalEmbedSession = "embed_session" + PrincipalEmbedVisitor = "embed_visitor" ) +// EmbedVisitorHeader is sent by the embed widget to identify a browser visitor +// across chat sessions within the same channel. +const EmbedVisitorHeader = "X-Embed-Visitor" + // Principal represents the terminal caller for per-subject isolation features. // It is intentionally separate from UserID: many principals, such as IM users // or embed visitors, are not WeKnora accounts and must not imply RBAC rights. @@ -62,3 +68,100 @@ func PrincipalFromContext(ctx context.Context) (Principal, bool) { } return Principal{}, false } + +func WithEmbedVisitorID(ctx context.Context, visitorID string) context.Context { + visitorID = strings.TrimSpace(visitorID) + if visitorID == "" { + return ctx + } + return context.WithValue(ctx, EmbedVisitorContextKey, visitorID) +} + +func EmbedVisitorIDFromContext(ctx context.Context) string { + if ctx == nil { + return "" + } + if v, ok := ctx.Value(EmbedVisitorContextKey).(string); ok { + return strings.TrimSpace(v) + } + return "" +} + +// EmbedSessionPrincipal identifies a single embed visitor chat session. +func EmbedSessionPrincipal(tenantID uint64, channelID, sessionID string) Principal { + return Principal{ + Type: PrincipalEmbedSession, + ID: fmt.Sprintf("%d:%s:%s", tenantID, strings.TrimSpace(channelID), strings.TrimSpace(sessionID)), + } +} + +// EmbedVisitorPrincipal identifies one anonymous embed visitor (browser). +func EmbedVisitorPrincipal(tenantID uint64, channelID, visitorID string) Principal { + return Principal{ + Type: PrincipalEmbedVisitor, + ID: fmt.Sprintf("%d:%s:%s", tenantID, strings.TrimSpace(channelID), strings.TrimSpace(visitorID)), + } +} + +// ValidateEmbedVisitorID checks the client-supplied anonymous visitor id. +func ValidateEmbedVisitorID(id string) error { + id = strings.TrimSpace(id) + if id == "" { + return fmt.Errorf("empty embed visitor id") + } + if len(id) > 128 { + return fmt.Errorf("embed visitor id too long (max 128)") + } + for _, r := range id { + if r < 0x20 || r == 0x7f { + return fmt.Errorf("embed visitor id contains invalid characters") + } + } + return nil +} + +// MCPOAuthPrincipalFromContext resolves the OAuth token principal for ctx. +// Embed chat sessions map to a per-visitor principal when X-Embed-Visitor is +// present; otherwise OAuth falls back to the chat session principal. +func MCPOAuthPrincipalFromContext(ctx context.Context) Principal { + p, ok := PrincipalFromContext(ctx) + if !ok { + return Principal{} + } + p = p.Normalize() + if p.Type != PrincipalEmbedSession { + return p + } + visitorID := EmbedVisitorIDFromContext(ctx) + if visitorID == "" { + return p + } + parts := strings.SplitN(p.ID, ":", 3) + if len(parts) < 2 { + return p + } + tenantPart := strings.TrimSpace(parts[0]) + channelPart := strings.TrimSpace(parts[1]) + if tenantPart == "" || channelPart == "" { + return p + } + var tenantID uint64 + if _, err := fmt.Sscanf(tenantPart, "%d", &tenantID); err != nil || tenantID == 0 { + return Principal{Type: PrincipalEmbedVisitor, ID: tenantPart + ":" + channelPart + ":" + visitorID} + } + return EmbedVisitorPrincipal(tenantID, channelPart, visitorID) +} + +// SessionOwnerIDFromContext returns the sessions.user_id scope for the current +// caller. API external users and embed chat sessions use principal-derived IDs; +// MCP OAuth token storage uses MCPOAuthPrincipalFromContext (visitor-level for embed). +func SessionOwnerIDFromContext(ctx context.Context) string { + if p, ok := PrincipalFromContext(ctx); ok { + switch p.Type { + case PrincipalAPIExternalUser, PrincipalEmbedSession: + return p.StorageID() + } + } + userID, _ := UserIDFromContext(ctx) + return userID +} diff --git a/internal/types/principal_test.go b/internal/types/principal_test.go index a7fd6c02..4540148f 100644 --- a/internal/types/principal_test.go +++ b/internal/types/principal_test.go @@ -32,3 +32,42 @@ func TestPrincipalStorageID(t *testing.T) { t.Fatalf("StorageID() = %q", got) } } + +func TestSessionOwnerIDFromContextUsesAPIExternalPrincipal(t *testing.T) { + ctx := WithPrincipal(context.Background(), Principal{ + Type: PrincipalAPIExternalUser, + ID: "7:alice", + }) + ctx = context.WithValue(ctx, UserIDContextKey, "system-7") + + if got := SessionOwnerIDFromContext(ctx); got != "api_external_user:7:alice" { + t.Fatalf("SessionOwnerIDFromContext() = %q", got) + } +} + +func TestSessionOwnerIDFromContextFallsBackToUserID(t *testing.T) { + ctx := context.WithValue(context.Background(), UserIDContextKey, "system-7") + + if got := SessionOwnerIDFromContext(ctx); got != "system-7" { + t.Fatalf("SessionOwnerIDFromContext() = %q", got) + } +} + +func TestSessionOwnerIDFromContextUsesEmbedSessionPrincipal(t *testing.T) { + ctx := WithPrincipal(context.Background(), EmbedSessionPrincipal(10000, "ch1", "sess1")) + ctx = context.WithValue(ctx, UserIDContextKey, "embed-ch1") + + if got := SessionOwnerIDFromContext(ctx); got != "embed_session:10000:ch1:sess1" { + t.Fatalf("SessionOwnerIDFromContext() = %q", got) + } +} + +func TestMCPOAuthPrincipalMapsEmbedSessionToVisitor(t *testing.T) { + sess := EmbedSessionPrincipal(10000, "ch1", "sess1") + ctx := WithEmbedVisitorID(context.Background(), "visitor-abc") + got := MCPOAuthPrincipalFromContext(WithPrincipal(ctx, sess)) + want := "embed_visitor:10000:ch1:visitor-abc" + if got.StorageID() != want { + t.Fatalf("MCPOAuthPrincipalFromContext() = %q, want %q", got.StorageID(), want) + } +} diff --git a/internal/types/session.go b/internal/types/session.go index 34180747..d0ac2173 100644 --- a/internal/types/session.go +++ b/internal/types/session.go @@ -81,9 +81,9 @@ type Session struct { Description string `json:"description"` // Tenant ID TenantID uint64 `json:"tenant_id" gorm:"index"` - // UserID is the owner of the session. Empty for legacy rows (visible at - // tenant level) and for IM-created sessions that do not map to a WeKnora user. - UserID string `json:"user_id,omitempty" gorm:"type:varchar(36);index"` + // UserID is the owner scope for this session. WeKnora user UUIDs, API + // external-user principals, and embed visitor principals all use this column. + UserID string `json:"user_id,omitempty" gorm:"type:varchar(512);index"` // IsPinned indicates whether the session is pinned in the list. IsPinned bool `json:"is_pinned" gorm:"default:false"` // PinnedAt records when the session was pinned; nil when not pinned. diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql index 9a98d57b..0f03ad8d 100644 --- a/migrations/sqlite/000000_init.up.sql +++ b/migrations/sqlite/000000_init.up.sql @@ -140,7 +140,7 @@ CREATE TABLE IF NOT EXISTS sessions ( agent_config TEXT DEFAULT NULL, context_config TEXT DEFAULT NULL, agent_id VARCHAR(36), - user_id VARCHAR(36), + user_id VARCHAR(512), is_pinned BOOLEAN NOT NULL DEFAULT 0, pinned_at DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, diff --git a/migrations/versioned/000066_sessions_user_id_widen.down.sql b/migrations/versioned/000066_sessions_user_id_widen.down.sql new file mode 100644 index 00000000..c8c33c9d --- /dev/null +++ b/migrations/versioned/000066_sessions_user_id_widen.down.sql @@ -0,0 +1,5 @@ +-- Migration: 000066_sessions_user_id_widen (down) +-- Note: fails if any row has user_id longer than 36 characters. + +ALTER TABLE sessions + ALTER COLUMN user_id TYPE VARCHAR(36); diff --git a/migrations/versioned/000066_sessions_user_id_widen.up.sql b/migrations/versioned/000066_sessions_user_id_widen.up.sql new file mode 100644 index 00000000..690669b3 --- /dev/null +++ b/migrations/versioned/000066_sessions_user_id_widen.up.sql @@ -0,0 +1,10 @@ +-- Migration: 000066_sessions_user_id_widen +-- Description: Widen sessions.user_id to store principal-based owner IDs +-- (embed_session, api_external_user, etc.), not only UUIDs. + +DO $$ BEGIN RAISE NOTICE '[Migration 000066] Widening sessions.user_id to VARCHAR(512)'; END $$; + +ALTER TABLE sessions + ALTER COLUMN user_id TYPE VARCHAR(512); + +DO $$ BEGIN RAISE NOTICE '[Migration 000066] sessions.user_id widened'; END $$;