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:
wizardchen
2026-07-20 20:27:56 +08:00
committed by lyingbug
parent b1b42abe23
commit 25ef7b6c68
10 changed files with 301 additions and 70 deletions
+19 -23
View File
@@ -167,27 +167,26 @@
</template>
</div>
</div>
<!-- 批量管理底部操作条 -->
<div v-if="batchMode && !uiStore.sidebarCollapsed" class="batch-inline-footer">
<div class="batch-footer-left">
<t-checkbox :checked="isAllBatchSelected" :indeterminate="isBatchIndeterminate"
@change="toggleBatchSelectAll">
{{ t('batchManage.selectAll') }}
</t-checkbox>
</div>
<div class="batch-footer-right">
<t-button size="small" variant="text" @click="exitBatchMode">
{{ t('batchManage.cancel') }}
</t-button>
<t-button size="small" theme="danger" variant="base" :disabled="batchSelectedIds.length === 0"
:loading="batchDeleting" @click="handleInlineBatchDelete">
{{ t('batchManage.delete') }}{{ batchSelectedIds.length > 0 ? `(${batchDisplayCount})` : '' }}
</t-button>
</div>
</div>
</div>
<!-- 批量管理底部操作条:固定在侧栏底部、用户头像上方 -->
<div v-if="batchMode && !uiStore.sidebarCollapsed" class="batch-inline-footer">
<div class="batch-footer-left">
<t-checkbox :checked="isAllBatchSelected" :indeterminate="isBatchIndeterminate"
@change="toggleBatchSelectAll">
{{ t('batchManage.selectAll') }}
</t-checkbox>
</div>
<div class="batch-footer-right">
<t-button size="small" variant="text" @click="exitBatchMode">
{{ t('batchManage.cancel') }}
</t-button>
<t-button size="small" theme="danger" variant="base" :disabled="batchSelectedIds.length === 0"
:loading="batchDeleting" @click="handleInlineBatchDelete">
{{ t('batchManage.delete') }}{{ batchSelectedIds.length > 0 ? `(${batchDisplayCount})` : '' }}
</t-button>
</div>
</div>
<!-- 下半部分:用户菜单 -->
<div class="menu_bottom">
@@ -748,7 +747,7 @@ const rebuildBucketDefinitions = () => buildBucketDefinitions(
embedChannel: (name) => name,
api: t('menu.apiChats'),
},
{ includeApiBucket: authStore.hasRole('admin') },
{ includeAdminChannelBuckets: authStore.hasRole('admin') },
);
/** 首屏轻量探测各渠道是否有会话(page_size=1 只取 total),避免展示空文件夹 */
@@ -1705,9 +1704,6 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
}
.batch-inline-footer {
position: sticky;
bottom: 0;
z-index: 2;
flex-shrink: 0;
display: flex;
align-items: center;
@@ -4,6 +4,7 @@ import test from 'node:test'
import {
applyBucketCountProbe,
bucketVisible,
buildBucketDefinitions,
createEmptyBucket,
prependSessionToWebBucket,
type BucketDefinition,
@@ -56,3 +57,33 @@ test('prependSessionToWebBucket is idempotent for existing session', () => {
const next = prependSessionToWebBucket(bucket, { id: 'a', title: 'Same' })
assert.equal(next, bucket)
})
test('buildBucketDefinitions hides channel buckets unless admin', () => {
const defs = buildBucketDefinitions(
['feishu'],
{ ch1: 'Embed' },
{
web: 'Chats',
imPlatform: (platform) => platform,
embedChannel: (name) => name,
api: 'API',
},
)
assert.deepEqual(defs.map((def) => def.key), ['web'])
const adminDefs = buildBucketDefinitions(
['feishu'],
{ ch1: 'Embed' },
{
web: 'Chats',
imPlatform: (platform) => platform,
embedChannel: (name) => name,
api: 'API',
},
{ includeAdminChannelBuckets: true },
)
assert.deepEqual(
adminDefs.map((def) => def.key),
['im:feishu', 'embed:ch1', 'api', 'web'],
)
})
@@ -68,8 +68,8 @@ export function isChannelBucketKey(key: string): boolean {
}
// API_SESSION_BUCKET_KEY is the admin-only bucket that lists every API-key
// session in the tenant. It is treated like a channel folder: probed for a
// count first and only surfaced in the source filter when it has sessions.
// session in the tenant. IM and embed folders are also admin-only; they are
// probed for a count first and only surfaced when they have sessions.
export const API_SESSION_BUCKET_KEY = 'api'
export function buildBucketDefinitions(
@@ -81,22 +81,27 @@ export function buildBucketDefinitions(
embedChannel: (name: string) => string
api: string
},
options: { includeApiBucket?: boolean } = {},
options: { includeAdminChannelBuckets?: boolean } = {},
): BucketDefinition[] {
const imDefs = imPlatforms.map((platform) => ({
key: `im:${platform}`,
apiSource: platform,
label: labels.imPlatform(platform),
kind: 'im' as const,
platform,
}))
const embedDefs = Object.entries(embedChannels).map(([id, name]) => ({
key: `embed:${id}`,
apiSource: `embed:${id}`,
label: labels.embedChannel(name || id.slice(0, 8)),
kind: 'embed' as const,
}))
const apiDefs: BucketDefinition[] = options.includeApiBucket
const includeChannels = options.includeAdminChannelBuckets ?? options.includeApiBucket ?? false
const imDefs = includeChannels
? imPlatforms.map((platform) => ({
key: `im:${platform}`,
apiSource: platform,
label: labels.imPlatform(platform),
kind: 'im' as const,
platform,
}))
: []
const embedDefs = includeChannels
? Object.entries(embedChannels).map(([id, name]) => ({
key: `embed:${id}`,
apiSource: `embed:${id}`,
label: labels.embedChannel(name || id.slice(0, 8)),
kind: 'embed' as const,
}))
: []
const apiDefs: BucketDefinition[] = includeChannels
? [
{
key: API_SESSION_BUCKET_KEY,
+70 -22
View File
@@ -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 {
+2 -5
View File
@@ -749,7 +749,7 @@ func (h *EmbedChannelHandler) GetEmbedChannelStats(c *gin.Context) {
return
}
result, err := h.sessionService.ListSessions(ctx, &types.SessionListQuery{
result, err := h.sessionService.CountSessionsBySource(ctx, &types.SessionListQuery{
TenantID: tenantID,
Source: "embed:" + channelID,
Page: 1,
@@ -759,10 +759,7 @@ func (h *EmbedChannelHandler) GetEmbedChannelStats(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
total := int64(0)
if result != nil {
total = result.Total
}
total := result
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
+1 -1
View File
@@ -201,7 +201,7 @@ func (h *Handler) GetSession(c *gin.Context) {
// @Param page query int false "页码"
// @Param page_size query int false "每页数量"
// @Param keyword query string false "标题模糊搜索"
// @Param source query string false "来源过滤:web / embed / api(API Key 会话,需 Admin+)/ feishu / wechat / slack / ..."
// @Param source query string false "来源过滤:web / embed / api / feishu / wechat / slack / ...(api、embed、IM 渠道需 Admin+)"
// @Param agent_id query string false "按 Agent 过滤(仅对 IM 会话生效)"
// @Success 200 {object} map[string]interface{} "会话列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
+5 -1
View File
@@ -12,7 +12,8 @@ type SessionService interface {
// CreateSession creates a session
CreateSession(ctx context.Context, session *types.Session) (*types.Session, error)
// 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.
// Admin+ read fallback for tenant channel sessions (API / IM / embed).
// 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
@@ -41,6 +42,9 @@ type SessionService interface {
// ListSessions returns a page of sessions for the current tenant/user with
// search/source filters and pin-aware ordering. User scope is pulled from ctx.
ListSessions(ctx context.Context, query *types.SessionListQuery) (*types.PageResult, error)
// CountSessionsBySource returns the total for a source filter without the
// Admin+ gate applied by ListSessions (for aggregate stats endpoints).
CountSessionsBySource(ctx context.Context, query *types.SessionListQuery) (int64, error)
// SetSessionPinned pins or unpins the session for the current user scope.
// Returns the number of rows affected; 0 signals "not found" to the handler.
SetSessionPinned(ctx context.Context, sessionID string, pinned bool) (int64, error)
+31 -1
View File
@@ -3,6 +3,7 @@ package types
import (
"database/sql/driver"
"encoding/json"
"strings"
"time"
"github.com/google/uuid"
@@ -139,12 +140,41 @@ func (s *Session) BeforeCreate(tx *gorm.DB) (err error) {
// Owner/admin can observe API-key traffic that is otherwise isolated per key.
const SessionSourceAPI = "api"
// SessionSourceWeb is the source filter for a user's own Web-console chats.
const SessionSourceWeb = "web"
// SessionListSourceRequiresAdmin reports whether a session-list source filter
// exposes tenant-wide channel traffic (API / IM / embed) in the Web console.
func SessionListSourceRequiresAdmin(source string) bool {
src := strings.TrimSpace(source)
if src == "" || strings.EqualFold(src, SessionSourceWeb) {
return false
}
return true
}
// SessionRequiresAdminConsoleRead reports whether a session row is channel-
// managed traffic that non-admin web users must not open from the console.
func SessionRequiresAdminConsoleRead(s *Session, imPlatform string) bool {
if s == nil {
return false
}
if strings.HasPrefix(s.UserID, SessionOwnerAPITenantKeyPrefix) {
return true
}
if strings.HasPrefix(s.Description, EmbedSessionMarkerPrefix) ||
strings.HasPrefix(s.UserID, PrincipalEmbedSession+":") {
return true
}
return strings.TrimSpace(imPlatform) != ""
}
// SessionListQuery bundles the parameters for listing sessions.
// UserID empty means "tenant-wide" (used by API-key callers / legacy rows).
// Keyword matches title ILIKE '%keyword%'.
// Source values: "web" (user chats, no IM/embed), "embed" / "embed:{channelID}",
// "api" (all API-key sessions, Admin+ only), or an IM platform name
// (e.g. "feishu", "wechat").
// (e.g. "feishu", "wechat"). IM and embed sources are also Admin+ only.
// AgentID currently only filters sessions that have an IM channel mapping.
type SessionListQuery struct {
TenantID uint64
+51
View File
@@ -0,0 +1,51 @@
package types
import "testing"
func TestSessionListSourceRequiresAdmin(t *testing.T) {
tests := []struct {
source string
want bool
}{
{"", false},
{"web", false},
{"WEB", false},
{"api", true},
{"embed", true},
{"embed:ch-1", true},
{"feishu", true},
{"qqbot", true},
}
for _, tt := range tests {
if got := SessionListSourceRequiresAdmin(tt.source); got != tt.want {
t.Fatalf("SessionListSourceRequiresAdmin(%q) = %v, want %v", tt.source, got, tt.want)
}
}
}
func TestSessionRequiresAdminConsoleRead(t *testing.T) {
api := &Session{UserID: SessionOwnerAPITenantKeyPrefix + "1:10"}
if !SessionRequiresAdminConsoleRead(api, "") {
t.Fatal("API-key session should require admin")
}
embed := &Session{Description: EmbedSessionMarkerPrefix + "ch-1"}
if !SessionRequiresAdminConsoleRead(embed, "") {
t.Fatal("embed description should require admin")
}
embedOwner := &Session{UserID: PrincipalEmbedSession + ":1:ch-1:sess-1"}
if !SessionRequiresAdminConsoleRead(embedOwner, "") {
t.Fatal("embed owner id should require admin")
}
im := &Session{Title: "hello"}
if !SessionRequiresAdminConsoleRead(im, "feishu") {
t.Fatal("IM-mapped session should require admin")
}
web := &Session{UserID: "alice", Title: "my chat"}
if SessionRequiresAdminConsoleRead(web, "") {
t.Fatal("personal web session should not require admin")
}
}