feat(session): add admin API session bucket and stabilize sidebar filter

Let tenant admins list and open API-key sessions from the Web console while
keeping per-key isolation for everyone else. Pin the session source filter so
it no longer jumps when switching buckets, and resolve session origin on read
so deep links stay in sync with the active folder after refresh.
This commit is contained in:
wizardchen
2026-07-20 18:23:35 +08:00
committed by lyingbug
parent eab91d2f7f
commit 76a4ffe525
18 changed files with 317 additions and 65 deletions
@@ -72,6 +72,25 @@ func (r *sessionRepository) GetByID(ctx context.Context, tenantID uint64, id str
return &session, nil
}
// GetIMPlatform returns the IM platform bound to a session, or "" when none.
// It intentionally ignores soft-deleted mappings' visibility rules used by
// QueryPaged: any mapping (active or cleared) marks the session as IM-origin.
func (r *sessionRepository) GetIMPlatform(
ctx context.Context, tenantID uint64, sessionID string,
) (string, error) {
var platform string
err := r.db.WithContext(ctx).
Table("im_channel_sessions AS ics").
Joins("JOIN sessions AS s ON s.id = ics.session_id").
Where("ics.session_id = ? AND s.tenant_id = ?", sessionID, tenantID).
Limit(1).
Pluck("ics.platform", &platform).Error
if err != nil {
return "", err
}
return platform, 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
@@ -169,6 +188,12 @@ func (r *sessionRepository) QueryPaged(
switch lower {
case "":
return db
case types.SessionSourceAPI:
// Tenant-wide view of API-key sessions. Their owner id is
// "api_tenant_key:<tenantID>:<keyID>", so a prefix match selects
// every key's sessions. The service layer already enforced Admin+
// 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).
return db.Where(
@@ -245,3 +245,49 @@ func TestSessionRepositoryQueryPagedSplitsWebAndEmbedSessions(t *testing.T) {
require.NoError(t, err)
require.Equal(t, []string{embed.ID}, listItemIDsForTest(embedItems))
}
func TestSessionRepositoryGetIMPlatform(t *testing.T) {
repo, db := newSessionRepositoryForTest(t)
require.NoError(t, db.AutoMigrate(&testIMChannelSession{}))
ctx := context.Background()
imSession := createSessionForTest(t, db, 1, "alice")
require.NoError(t, db.Create(&testIMChannelSession{
ID: "ics-1", SessionID: imSession.ID, Platform: "feishu",
}).Error)
webSession := createSessionForTest(t, db, 1, "alice")
platform, err := repo.GetIMPlatform(ctx, 1, imSession.ID)
require.NoError(t, err)
require.Equal(t, "feishu", platform)
platform, err = repo.GetIMPlatform(ctx, 1, webSession.ID)
require.NoError(t, err)
require.Equal(t, "", platform)
// Cross-tenant lookup must not leak the mapping.
platform, err = repo.GetIMPlatform(ctx, 2, imSession.ID)
require.NoError(t, err)
require.Equal(t, "", platform)
}
func TestSessionRepositoryQueryPagedAPISourceReturnsAllTenantAPIKeySessions(t *testing.T) {
repo, db := newSessionRepositoryForTest(t)
require.NoError(t, db.AutoMigrate(&testIMChannelSession{}))
ctx := context.Background()
// Two different API keys plus a web user and a cross-tenant API session.
key1 := createSessionForTest(t, db, 1, types.SessionOwnerAPITenantKeyPrefix+"1:10")
key2 := createSessionForTest(t, db, 1, types.SessionOwnerAPITenantKeyPrefix+"1:20")
_ = createSessionForTest(t, db, 1, "alice")
_ = createSessionForTest(t, db, 2, types.SessionOwnerAPITenantKeyPrefix+"2:30")
// The admin view clears UserID, so every API-key session in the tenant is
// returned regardless of which key created it.
items, total, err := repo.QueryPaged(ctx, &types.SessionListQuery{
TenantID: 1, UserID: "", Source: types.SessionSourceAPI, Page: 1, PageSize: 50,
})
require.NoError(t, err)
require.EqualValues(t, 2, total)
require.ElementsMatch(t, []string{key1.ID, key2.ID}, listItemIDsForTest(items))
}
+4 -4
View File
@@ -108,7 +108,7 @@ func (s *messageService) GetMessage(ctx context.Context, sessionID string, messa
tenantID := types.MustTenantIDFromContext(ctx)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
_, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, sessionUserIDForLookup(ctx), sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
@@ -137,7 +137,7 @@ func (s *messageService) GetMessagesBySession(ctx context.Context,
tenantID := types.MustTenantIDFromContext(ctx)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
_, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, sessionUserIDForLookup(ctx), sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
@@ -171,7 +171,7 @@ func (s *messageService) GetRecentMessagesBySession(ctx context.Context,
return nil, errors.New("workspace ID not found in context")
}
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
_, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, sessionUserIDForLookup(ctx), sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
@@ -204,7 +204,7 @@ func (s *messageService) GetMessagesBySessionBeforeTime(ctx context.Context,
return nil, errors.New("workspace ID not found in context")
}
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
_, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, sessionUserIDForLookup(ctx), sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
+46 -2
View File
@@ -22,6 +22,31 @@ func sessionUserIDFromContext(ctx context.Context) string {
return types.SessionOwnerIDFromContext(ctx)
}
// loadSessionForRead loads a session honoring the caller's per-user scope, with
// an Admin+ fallback that additionally permits reading tenant API-key sessions
// (owner id "api_tenant_key:<tenantID>:<keyID>"). This lets a tenant
// Owner/admin open sessions created via API keys — which are otherwise isolated
// per key — from the Web console, without exposing other users' personal
// sessions. Write paths keep the strict scope and must not use this helper.
func loadSessionForRead(
ctx context.Context,
repo interfaces.SessionRepository,
tenantID uint64,
ownerID, sessionID string,
) (*types.Session, error) {
session, err := repo.Get(ctx, tenantID, ownerID, sessionID)
if err == nil || !stderrors.Is(err, apperrors.ErrSessionNotFound) {
return session, err
}
if types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
if s, e := repo.GetByID(ctx, tenantID, sessionID); e == nil &&
strings.HasPrefix(s.UserID, types.SessionOwnerAPITenantKeyPrefix) {
return s, nil
}
}
return nil, err
}
// generateEventID generates a unique event ID with type suffix for better traceability
func generateEventID(suffix string) string {
return fmt.Sprintf("%s-%s", uuid.New().String()[:8], suffix)
@@ -120,7 +145,7 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess
logger.Infof(ctx, "Retrieving session, ID: %s, tenant ID: %d", id, tenantID)
// Get session from repository
session, err := s.sessionRepo.Get(ctx, tenantID, userID, id)
session, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, userID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": id,
@@ -129,6 +154,14 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess
return nil, err
}
// Best-effort IM origin so the Web console can classify the session's
// folder on read; a lookup failure must not fail the detail request.
if platform, pErr := s.sessionRepo.GetIMPlatform(ctx, tenantID, session.ID); pErr == nil {
session.IMPlatform = platform
} else {
logger.Warnf(ctx, "Failed to resolve IM platform for session %s: %v", session.ID, pErr)
}
logger.Infof(ctx, "Session retrieved successfully, ID: %s, tenant ID: %d", session.ID, session.TenantID)
return session, nil
}
@@ -211,7 +244,18 @@ func (s *sessionService) ListSessions(
query = &types.SessionListQuery{}
}
query.TenantID = types.MustTenantIDFromContext(ctx)
if uid := types.SessionOwnerIDFromContext(ctx); uid != "" {
// The "api" source is a tenant-wide admin view over API-key sessions, which
// are otherwise isolated per key. Gate it behind Admin+ and drop the
// per-user owner scope so the caller sees every key's sessions; everyone
// else stays scoped to their own principal.
if strings.EqualFold(strings.TrimSpace(query.Source), types.SessionSourceAPI) {
if !types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
return nil, apperrors.NewForbiddenError(
"listing API-key sessions requires tenant admin or owner role",
)
}
query.UserID = ""
} else if uid := types.SessionOwnerIDFromContext(ctx); uid != "" {
query.UserID = uid
}
@@ -140,3 +140,76 @@ func TestGetSessionIsScopedToAPIExternalUser(t *testing.T) {
require.NoError(t, err)
require.Equal(t, tenantSession.ID, got.ID)
}
func TestGetSessionAllowsAdminToOpenAPIKeySessions(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)
otherUserSession := &types.Session{
TenantID: 1,
UserID: "bob",
Title: "bob private session",
}
require.NoError(t, db.Create(otherUserSession).Error)
// A non-admin web user cannot open the API-key session.
viewerCtx := testSessionScopeContext(1, "alice")
_, err := svc.GetSession(viewerCtx, apiSession.ID)
require.ErrorIs(t, err, apperrors.ErrSessionNotFound)
// An admin can open the API-key session.
adminCtx := context.WithValue(testSessionScopeContext(1, "alice"), types.TenantRoleContextKey, types.TenantRoleAdmin)
got, err := svc.GetSession(adminCtx, apiSession.ID)
require.NoError(t, err)
require.Equal(t, apiSession.ID, got.ID)
// The admin fallback is limited to API-key sessions; another user's
// personal session stays hidden.
_, err = svc.GetSession(adminCtx, otherUserSession.ID)
require.ErrorIs(t, err, apperrors.ErrSessionNotFound)
}
func TestListSessionsAPISourceRequiresAdminAndReturnsAllKeys(t *testing.T) {
svc, db := newTestSessionService(t)
require.NoError(t, db.AutoMigrate(&testListSessionsIMChannelSession{}))
key1 := &types.Session{TenantID: 1, UserID: types.SessionOwnerAPITenantKeyPrefix + "1:10", Title: "key1"}
key2 := &types.Session{TenantID: 1, UserID: types.SessionOwnerAPITenantKeyPrefix + "1:20", Title: "key2"}
web := &types.Session{TenantID: 1, UserID: "alice", Title: "alice web"}
require.NoError(t, db.Create(key1).Error)
require.NoError(t, db.Create(key2).Error)
require.NoError(t, db.Create(web).Error)
// A non-admin (viewer) web user is rejected.
viewerCtx := testSessionScopeContext(1, "alice")
_, err := svc.ListSessions(viewerCtx, &types.SessionListQuery{Source: types.SessionSourceAPI})
require.Error(t, err)
var appErr *apperrors.AppError
require.ErrorAs(t, err, &appErr)
require.Equal(t, apperrors.ErrForbidden, appErr.Code)
// An admin sees every API-key session in the tenant, not just their own.
adminCtx := context.WithValue(testSessionScopeContext(1, "alice"), types.TenantRoleContextKey, types.TenantRoleAdmin)
result, err := svc.ListSessions(adminCtx, &types.SessionListQuery{Source: types.SessionSourceAPI})
require.NoError(t, err)
require.EqualValues(t, 2, result.Total)
}
// testListSessionsIMChannelSession lets QueryPaged's LEFT JOIN resolve against a
// real table in the in-memory SQLite database.
type testListSessionsIMChannelSession struct {
ID uint64 `gorm:"primaryKey;autoIncrement"`
SessionID string `gorm:"column:session_id"`
Platform string `gorm:"column:platform"`
ChatID string `gorm:"column:chat_id"`
ThreadID string `gorm:"column:thread_id"`
UserID string `gorm:"column:user_id"`
AgentID string `gorm:"column:agent_id"`
IMChannelID string `gorm:"column:im_channel_id"`
}
func (testListSessionsIMChannelSession) TableName() string { return "im_channel_sessions" }