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.
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user