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:
wizardchen
2026-06-30 18:16:44 +08:00
committed by lyingbug
parent 168b1d4cfe
commit 5074344c16
23 changed files with 438 additions and 43 deletions
+2
View File
@@ -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.
+9
View File
@@ -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.
+103
View File
@@ -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
}
+39
View File
@@ -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)
}
}
+3 -3
View File
@@ -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.