feat(session): gate IM/embed/API channel sessions behind admin
Restrict channel-managed sessions (API keys, IM, embed) to tenant admin in the Web console for list/read paths, hide channel sidebar buckets from non-admins, and add CountSessionsBySource for aggregate stats without exposing session rows to viewers.
This commit is contained in:
@@ -23,28 +23,47 @@ func sessionUserIDFromContext(ctx context.Context) string {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// an Admin+ fallback that additionally permits reading tenant channel sessions
|
||||
// (API-key, IM, and embed) from the Web console. Non-admin callers must not
|
||||
// open channel-managed rows even when legacy empty user_id scope would match.
|
||||
// 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) {
|
||||
isAdmin := types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin)
|
||||
|
||||
session, err := repo.Get(ctx, tenantID, ownerID, sessionID)
|
||||
if err == nil || !stderrors.Is(err, apperrors.ErrSessionNotFound) {
|
||||
if err == nil {
|
||||
imPlatform, _ := repo.GetIMPlatform(ctx, tenantID, sessionID)
|
||||
if types.SessionRequiresAdminConsoleRead(session, imPlatform) && !isAdmin {
|
||||
return nil, apperrors.ErrSessionNotFound
|
||||
}
|
||||
if imPlatform != "" {
|
||||
session.IMPlatform = imPlatform
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
if !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
|
||||
}
|
||||
if !isAdmin {
|
||||
return nil, err
|
||||
}
|
||||
return nil, err
|
||||
s, e := repo.GetByID(ctx, tenantID, sessionID)
|
||||
if e != nil {
|
||||
return nil, err
|
||||
}
|
||||
imPlatform, _ := repo.GetIMPlatform(ctx, tenantID, sessionID)
|
||||
if !types.SessionRequiresAdminConsoleRead(s, imPlatform) {
|
||||
return nil, err
|
||||
}
|
||||
if imPlatform != "" {
|
||||
s.IMPlatform = imPlatform
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// generateEventID generates a unique event ID with type suffix for better traceability
|
||||
@@ -156,10 +175,12 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess
|
||||
|
||||
// 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)
|
||||
if session.IMPlatform == "" {
|
||||
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)
|
||||
@@ -258,14 +279,14 @@ func (s *sessionService) ListSessions(
|
||||
query = &types.SessionListQuery{}
|
||||
}
|
||||
query.TenantID = types.MustTenantIDFromContext(ctx)
|
||||
// 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) {
|
||||
// API / IM / embed source filters are tenant-wide admin views over channel
|
||||
// traffic. Gate them behind Admin+ and drop the per-user owner scope so an
|
||||
// Owner/admin can observe sessions that are otherwise isolated per key,
|
||||
// visitor, or IM identity; everyone else stays scoped to their own principal.
|
||||
if types.SessionListSourceRequiresAdmin(query.Source) {
|
||||
if !types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
|
||||
return nil, apperrors.NewForbiddenError(
|
||||
"listing API-key sessions requires tenant admin or owner role",
|
||||
"listing channel sessions requires tenant admin or owner role",
|
||||
)
|
||||
}
|
||||
query.UserID = ""
|
||||
@@ -289,6 +310,33 @@ func (s *sessionService) ListSessions(
|
||||
return types.NewPageResult(total, pagination, items), nil
|
||||
}
|
||||
|
||||
// CountSessionsBySource returns the total session count for a source filter
|
||||
// without the Admin+ gate used by ListSessions. Aggregate stats endpoints may
|
||||
// expose counts to Viewer+ while keeping session rows admin-only.
|
||||
func (s *sessionService) CountSessionsBySource(
|
||||
ctx context.Context, query *types.SessionListQuery,
|
||||
) (int64, error) {
|
||||
if query == nil {
|
||||
query = &types.SessionListQuery{}
|
||||
}
|
||||
query.TenantID = types.MustTenantIDFromContext(ctx)
|
||||
if types.SessionListSourceRequiresAdmin(query.Source) {
|
||||
query.UserID = ""
|
||||
} else if uid := types.SessionOwnerIDFromContext(ctx); uid != "" {
|
||||
query.UserID = uid
|
||||
}
|
||||
_, total, err := s.sessionRepo.QueryPaged(ctx, query)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": query.TenantID,
|
||||
"user_id": query.UserID,
|
||||
"source": query.Source,
|
||||
})
|
||||
return 0, err
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
// SetSessionPinned pins or unpins a session for the current user scope.
|
||||
// Returns the number of rows affected; 0 means the session doesn't exist
|
||||
// or is not owned by the caller so the handler can respond 404.
|
||||
|
||||
@@ -223,6 +223,75 @@ func TestListSessionsAPISourceRequiresAdminAndReturnsAllKeys(t *testing.T) {
|
||||
require.EqualValues(t, 2, result.Total)
|
||||
}
|
||||
|
||||
func TestListSessionsIMSourceRequiresAdmin(t *testing.T) {
|
||||
svc, db := newTestSessionService(t)
|
||||
require.NoError(t, db.AutoMigrate(&testListSessionsIMChannelSession{}))
|
||||
|
||||
imSession := &types.Session{TenantID: 1, Title: "feishu chat"}
|
||||
require.NoError(t, db.Create(imSession).Error)
|
||||
require.NoError(t, db.Create(&testListSessionsIMChannelSession{
|
||||
SessionID: imSession.ID, Platform: "feishu",
|
||||
}).Error)
|
||||
|
||||
viewerCtx := testSessionScopeContext(1, "alice")
|
||||
_, err := svc.ListSessions(viewerCtx, &types.SessionListQuery{Source: "feishu"})
|
||||
require.Error(t, err)
|
||||
var appErr *apperrors.AppError
|
||||
require.ErrorAs(t, err, &appErr)
|
||||
require.Equal(t, apperrors.ErrForbidden, appErr.Code)
|
||||
|
||||
adminCtx := context.WithValue(testSessionScopeContext(1, "alice"), types.TenantRoleContextKey, types.TenantRoleAdmin)
|
||||
result, err := svc.ListSessions(adminCtx, &types.SessionListQuery{Source: "feishu"})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, result.Total)
|
||||
}
|
||||
|
||||
func TestListSessionsEmbedSourceRequiresAdmin(t *testing.T) {
|
||||
svc, db := newTestSessionService(t)
|
||||
require.NoError(t, db.AutoMigrate(&testListSessionsIMChannelSession{}))
|
||||
|
||||
embed := &types.Session{
|
||||
TenantID: 1,
|
||||
Title: "embed chat",
|
||||
Description: types.EmbedSessionMarkerPrefix + "ch-1",
|
||||
UserID: types.PrincipalEmbedSession + ":1:ch-1:sess-1",
|
||||
}
|
||||
require.NoError(t, db.Create(embed).Error)
|
||||
|
||||
viewerCtx := testSessionScopeContext(1, "alice")
|
||||
_, err := svc.ListSessions(viewerCtx, &types.SessionListQuery{Source: "embed:ch-1"})
|
||||
require.Error(t, err)
|
||||
var appErr *apperrors.AppError
|
||||
require.ErrorAs(t, err, &appErr)
|
||||
require.Equal(t, apperrors.ErrForbidden, appErr.Code)
|
||||
|
||||
adminCtx := context.WithValue(testSessionScopeContext(1, "alice"), types.TenantRoleContextKey, types.TenantRoleAdmin)
|
||||
result, err := svc.ListSessions(adminCtx, &types.SessionListQuery{Source: "embed:ch-1"})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, result.Total)
|
||||
}
|
||||
|
||||
func TestGetSessionDeniesViewerOnIMSession(t *testing.T) {
|
||||
svc, db := newTestSessionService(t)
|
||||
require.NoError(t, db.AutoMigrate(&testListSessionsIMChannelSession{}))
|
||||
|
||||
imSession := &types.Session{TenantID: 1, Title: "feishu chat"}
|
||||
require.NoError(t, db.Create(imSession).Error)
|
||||
require.NoError(t, db.Create(&testListSessionsIMChannelSession{
|
||||
SessionID: imSession.ID, Platform: "feishu",
|
||||
}).Error)
|
||||
|
||||
viewerCtx := testSessionScopeContext(1, "alice")
|
||||
_, err := svc.GetSession(viewerCtx, imSession.ID)
|
||||
require.ErrorIs(t, err, apperrors.ErrSessionNotFound)
|
||||
|
||||
adminCtx := context.WithValue(testSessionScopeContext(1, "alice"), types.TenantRoleContextKey, types.TenantRoleAdmin)
|
||||
got, err := svc.GetSession(adminCtx, imSession.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, imSession.ID, got.ID)
|
||||
require.Equal(t, "feishu", got.IMPlatform)
|
||||
}
|
||||
|
||||
// testListSessionsIMChannelSession lets QueryPaged's LEFT JOIN resolve against a
|
||||
// real table in the in-memory SQLite database.
|
||||
type testListSessionsIMChannelSession struct {
|
||||
|
||||
Reference in New Issue
Block a user