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.
This commit is contained in:
wizardchen
2026-07-20 19:27:25 +08:00
committed by lyingbug
parent 76a4ffe525
commit 29bec6c613
9 changed files with 95 additions and 12 deletions
+7 -3
View File
@@ -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+"%")
@@ -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{}))
+14
View File
@@ -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 == "" {
@@ -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{}))