From 29bec6c613814966bbd871114bc7905b3e4cb00e Mon Sep 17 00:00:00 2001 From: wizardchen Date: Mon, 20 Jul 2026 19:27:25 +0800 Subject: [PATCH] feat(session): implement strict owner scope for API-key sessions Add GetOwnedSession method to enforce strict ownership checks for session mutations, ensuring tenant admins can read but not modify API-key sessions. Update relevant handlers to utilize this method for operations that alter session data, maintaining security and integrity of API-key sessions. --- internal/application/repository/session.go | 10 +++++--- .../application/repository/session_test.go | 19 +++++++++++++++ internal/application/service/session.go | 14 +++++++++++ .../service/session_user_scope_test.go | 24 +++++++++++++++++++ internal/handler/session/qa.go | 7 ++++-- internal/handler/session/stream.go | 6 +++-- .../handler/session/temporary_document.go | 8 +++++-- internal/handler/session/title.go | 12 ++++++++-- internal/types/interfaces/session.go | 7 +++++- 9 files changed, 95 insertions(+), 12 deletions(-) diff --git a/internal/application/repository/session.go b/internal/application/repository/session.go index dea64ca9..778222fb 100644 --- a/internal/application/repository/session.go +++ b/internal/application/repository/session.go @@ -195,10 +195,14 @@ func (r *sessionRepository) QueryPaged( // and cleared the per-user scope for this source. return db.Where("s.user_id LIKE ?", types.SessionOwnerAPITenantKeyPrefix+"%") case "web": - // User web chats only — exclude embed-widget sessions (same IM-null row). + // User web chats only — exclude embed-widget sessions (same IM-null + // row) and tenant API-key sessions (surfaced only in the admin-only + // "api" bucket). The user_id NULL check keeps legacy tenant-level web + // rows visible, since "col NOT LIKE ?" is unknown (not true) for NULL. return db.Where( - "ics.id IS NULL AND (s.description = '' OR s.description NOT LIKE ?)", - embedPrefix+"%", + "ics.id IS NULL AND (s.description = '' OR s.description NOT LIKE ?) "+ + "AND (s.user_id IS NULL OR s.user_id NOT LIKE ?)", + embedPrefix+"%", types.SessionOwnerAPITenantKeyPrefix+"%", ) case "embed": return db.Where("ics.id IS NULL AND s.description LIKE ?", embedPrefix+"%") diff --git a/internal/application/repository/session_test.go b/internal/application/repository/session_test.go index 73e30f40..a80a543d 100644 --- a/internal/application/repository/session_test.go +++ b/internal/application/repository/session_test.go @@ -246,6 +246,25 @@ func TestSessionRepositoryQueryPagedSplitsWebAndEmbedSessions(t *testing.T) { require.Equal(t, []string{embed.ID}, listItemIDsForTest(embedItems)) } +// The "web" source is user chats only; tenant API-key sessions live in the +// admin-only "api" bucket and must never leak into a tenant-wide web listing. +// Legacy tenant-level rows (user_id "") must still show up in web. +func TestSessionRepositoryQueryPagedWebExcludesAPIKeySessions(t *testing.T) { + repo, db := newSessionRepositoryForTest(t) + require.NoError(t, db.AutoMigrate(&testIMChannelSession{})) + ctx := context.Background() + + legacy := createSessionForTest(t, db, 1, "") // legacy tenant web row + _ = createSessionForTest(t, db, 1, types.SessionOwnerAPITenantKeyPrefix+"1:10") + + items, _, err := repo.QueryPaged(ctx, &types.SessionListQuery{ + TenantID: 1, UserID: "", Source: "web", Page: 1, PageSize: 50, + }) + require.NoError(t, err) + require.Equal(t, []string{legacy.ID}, listItemIDsForTest(items), + "web must keep legacy tenant rows but exclude API-key sessions") +} + func TestSessionRepositoryGetIMPlatform(t *testing.T) { repo, db := newSessionRepositoryForTest(t) require.NoError(t, db.AutoMigrate(&testIMChannelSession{})) diff --git a/internal/application/service/session.go b/internal/application/service/session.go index abc140d5..c6d39cfa 100644 --- a/internal/application/service/session.go +++ b/internal/application/service/session.go @@ -166,6 +166,20 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess return session, nil } +// GetOwnedSession loads a session strictly within the caller's owner scope. +// Unlike GetSession it does NOT apply the Admin+ API-key read fallback +// (loadSessionForRead), so it is the correct check for write/mutation +// endpoints: a tenant admin may open and read an API-key session, but must not +// be able to modify it (title, attachments, streaming state, messages). +func (s *sessionService) GetOwnedSession(ctx context.Context, id string) (*types.Session, error) { + if id == "" { + return nil, stderrors.New("session id is required") + } + tenantID := types.MustTenantIDFromContext(ctx) + userID := sessionUserIDFromContext(ctx) + return s.sessionRepo.Get(ctx, tenantID, userID, id) +} + // 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 == "" { diff --git a/internal/application/service/session_user_scope_test.go b/internal/application/service/session_user_scope_test.go index b5c9669d..74127ef4 100644 --- a/internal/application/service/session_user_scope_test.go +++ b/internal/application/service/session_user_scope_test.go @@ -173,6 +173,30 @@ func TestGetSessionAllowsAdminToOpenAPIKeySessions(t *testing.T) { require.ErrorIs(t, err, apperrors.ErrSessionNotFound) } +func TestGetOwnedSessionDeniesAdminOnAPIKeySessions(t *testing.T) { + svc, db := newTestSessionService(t) + apiSession := &types.Session{ + TenantID: 1, + UserID: types.SessionOwnerAPITenantKeyPrefix + "1:10", + Title: "api key session", + } + require.NoError(t, db.Create(apiSession).Error) + + adminCtx := context.WithValue( + testSessionScopeContext(1, "alice"), types.TenantRoleContextKey, types.TenantRoleAdmin, + ) + + // The read path lets an admin open the API-key session (folder navigation)... + got, err := svc.GetSession(adminCtx, apiSession.ID) + require.NoError(t, err) + require.Equal(t, apiSession.ID, got.ID) + + // ...but the strict owner scope used by write/mutation endpoints (title + // generation, attachments, stop, QA) denies it, so admins stay read-only. + _, err = svc.GetOwnedSession(adminCtx, apiSession.ID) + require.ErrorIs(t, err, apperrors.ErrSessionNotFound) +} + func TestListSessionsAPISourceRequiresAdminAndReturnsAllKeys(t *testing.T) { svc, db := newTestSessionService(t) require.NoError(t, db.AutoMigrate(&testListSessionsIMChannelSession{})) diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 10ed3f94..59eb61e8 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -127,8 +127,11 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo logPrefix, sessionID, secutils.SanitizeForLog(secutils.CompactImageDataURLForLog(string(requestJSON)))) } - // Get session - session, err := h.sessionService.GetSession(ctx, sessionID) + // Get session. QA writes new messages into the session, so use the strict + // owner scope: a tenant admin may read an API-key session but must not be + // able to post messages to it (which would otherwise fail later at message + // creation with a 500 instead of a clean not-found). + session, err := h.sessionService.GetOwnedSession(ctx, sessionID) if err != nil { logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err) return nil, nil, errors.NewNotFoundError("Session not found") diff --git a/internal/handler/session/stream.go b/internal/handler/session/stream.go index 553ee304..cf7e8f3d 100644 --- a/internal/handler/session/stream.go +++ b/internal/handler/session/stream.go @@ -258,8 +258,10 @@ func (h *Handler) StopSession(c *gin.Context) { return } - // Verify message belongs to the current tenant - session, err := h.sessionService.GetSession(ctx, sessionID) + // Verify message belongs to the current tenant. Stopping generation mutates + // an in-flight run, so use the strict owner scope: a tenant admin may read an + // API-key session but must not be able to interrupt its (external) API calls. + session, err := h.sessionService.GetOwnedSession(ctx, sessionID) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ "session_id": sessionID, diff --git a/internal/handler/session/temporary_document.go b/internal/handler/session/temporary_document.go index 7d44f977..9e113ea4 100644 --- a/internal/handler/session/temporary_document.go +++ b/internal/handler/session/temporary_document.go @@ -20,7 +20,9 @@ import ( func (h *Handler) UploadTemporaryDocument(c *gin.Context) { ctx := c.Request.Context() sessionID := c.Param("session_id") - if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil { + // Uploading attaches content to the session, so use the strict owner scope: + // a tenant admin may read an API-key session but must not add attachments. + if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil { c.Error(apperrors.NewNotFoundError("Session not found")) return } @@ -163,7 +165,9 @@ func (h *Handler) PreviewTemporaryDocument(c *gin.Context) { func (h *Handler) DeleteTemporaryDocument(c *gin.Context) { ctx := c.Request.Context() sessionID := sessionIDParam(c) - if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil { + // Deleting mutates the session's attachments, so use the strict owner scope: + // a tenant admin may read an API-key session but must not remove attachments. + if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil { c.Error(apperrors.NewNotFoundError("Session not found")) return } diff --git a/internal/handler/session/title.go b/internal/handler/session/title.go index 575442a4..7854c4c4 100644 --- a/internal/handler/session/title.go +++ b/internal/handler/session/title.go @@ -1,6 +1,7 @@ package session import ( + stderrors "errors" "net/http" "github.com/Tencent/WeKnora/internal/errors" @@ -42,9 +43,16 @@ func (h *Handler) GenerateTitle(c *gin.Context) { return } - // Get session from database - session, err := h.sessionService.GetSession(ctx, sessionID) + // Get session from database. Title generation writes the session row, so use + // the strict owner scope: a tenant admin may read an API-key session but must + // not be able to (re)generate its title. + session, err := h.sessionService.GetOwnedSession(ctx, sessionID) if err != nil { + if stderrors.Is(err, errors.ErrSessionNotFound) { + logger.Warnf(ctx, "Session not found, ID: %s", sessionID) + c.Error(errors.NewNotFoundError(err.Error())) + return + } logger.ErrorWithFields(ctx, err, nil) c.Error(errors.NewInternalServerError(err.Error())) return diff --git a/internal/types/interfaces/session.go b/internal/types/interfaces/session.go index 7c61834d..225826a1 100644 --- a/internal/types/interfaces/session.go +++ b/internal/types/interfaces/session.go @@ -11,8 +11,13 @@ import ( type SessionService interface { // CreateSession creates a session CreateSession(ctx context.Context, session *types.Session) (*types.Session, error) - // GetSession gets a session + // GetSession gets a session, honoring the caller's per-user scope with an + // Admin+ read fallback for tenant API-key sessions. Use only for read paths. GetSession(ctx context.Context, id string) (*types.Session, error) + // GetOwnedSession gets a session strictly within the caller's owner scope + // (no Admin+ API-key fallback). Write/mutation endpoints must use this so a + // tenant admin cannot alter API-key sessions they can only read. + GetOwnedSession(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.