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> </template>
</div> </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> </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"> <div class="menu_bottom">
@@ -748,7 +747,7 @@ const rebuildBucketDefinitions = () => buildBucketDefinitions(
embedChannel: (name) => name, embedChannel: (name) => name,
api: t('menu.apiChats'), api: t('menu.apiChats'),
}, },
{ includeApiBucket: authStore.hasRole('admin') }, { includeAdminChannelBuckets: authStore.hasRole('admin') },
); );
/** 首屏轻量探测各渠道是否有会话(page_size=1 只取 total),避免展示空文件夹 */ /** 首屏轻量探测各渠道是否有会话(page_size=1 只取 total),避免展示空文件夹 */
@@ -1705,9 +1704,6 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
} }
.batch-inline-footer { .batch-inline-footer {
position: sticky;
bottom: 0;
z-index: 2;
flex-shrink: 0; flex-shrink: 0;
display: flex; display: flex;
align-items: center; align-items: center;
@@ -4,6 +4,7 @@ import test from 'node:test'
import { import {
applyBucketCountProbe, applyBucketCountProbe,
bucketVisible, bucketVisible,
buildBucketDefinitions,
createEmptyBucket, createEmptyBucket,
prependSessionToWebBucket, prependSessionToWebBucket,
type BucketDefinition, type BucketDefinition,
@@ -56,3 +57,33 @@ test('prependSessionToWebBucket is idempotent for existing session', () => {
const next = prependSessionToWebBucket(bucket, { id: 'a', title: 'Same' }) const next = prependSessionToWebBucket(bucket, { id: 'a', title: 'Same' })
assert.equal(next, bucket) 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 // 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 // session in the tenant. IM and embed folders are also admin-only; they are
// count first and only surfaced in the source filter when it has sessions. // probed for a count first and only surfaced when they have sessions.
export const API_SESSION_BUCKET_KEY = 'api' export const API_SESSION_BUCKET_KEY = 'api'
export function buildBucketDefinitions( export function buildBucketDefinitions(
@@ -81,22 +81,27 @@ export function buildBucketDefinitions(
embedChannel: (name: string) => string embedChannel: (name: string) => string
api: string api: string
}, },
options: { includeApiBucket?: boolean } = {}, options: { includeAdminChannelBuckets?: boolean } = {},
): BucketDefinition[] { ): BucketDefinition[] {
const imDefs = imPlatforms.map((platform) => ({ const includeChannels = options.includeAdminChannelBuckets ?? options.includeApiBucket ?? false
key: `im:${platform}`, const imDefs = includeChannels
apiSource: platform, ? imPlatforms.map((platform) => ({
label: labels.imPlatform(platform), key: `im:${platform}`,
kind: 'im' as const, apiSource: platform,
platform, label: labels.imPlatform(platform),
})) kind: 'im' as const,
const embedDefs = Object.entries(embedChannels).map(([id, name]) => ({ platform,
key: `embed:${id}`, }))
apiSource: `embed:${id}`, : []
label: labels.embedChannel(name || id.slice(0, 8)), const embedDefs = includeChannels
kind: 'embed' as const, ? Object.entries(embedChannels).map(([id, name]) => ({
})) key: `embed:${id}`,
const apiDefs: BucketDefinition[] = options.includeApiBucket apiSource: `embed:${id}`,
label: labels.embedChannel(name || id.slice(0, 8)),
kind: 'embed' as const,
}))
: []
const apiDefs: BucketDefinition[] = includeChannels
? [ ? [
{ {
key: API_SESSION_BUCKET_KEY, 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 // loadSessionForRead loads a session honoring the caller's per-user scope, with
// an Admin+ fallback that additionally permits reading tenant API-key sessions // an Admin+ fallback that additionally permits reading tenant channel sessions
// (owner id "api_tenant_key:<tenantID>:<keyID>"). This lets a tenant // (API-key, IM, and embed) from the Web console. Non-admin callers must not
// Owner/admin open sessions created via API keys — which are otherwise isolated // open channel-managed rows even when legacy empty user_id scope would match.
// per key — from the Web console, without exposing other users' personal // Write paths keep the strict scope and must not use this helper.
// sessions. Write paths keep the strict scope and must not use this helper.
func loadSessionForRead( func loadSessionForRead(
ctx context.Context, ctx context.Context,
repo interfaces.SessionRepository, repo interfaces.SessionRepository,
tenantID uint64, tenantID uint64,
ownerID, sessionID string, ownerID, sessionID string,
) (*types.Session, error) { ) (*types.Session, error) {
isAdmin := types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin)
session, err := repo.Get(ctx, tenantID, ownerID, sessionID) 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 return session, err
} }
if types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) { if !isAdmin {
if s, e := repo.GetByID(ctx, tenantID, sessionID); e == nil && return nil, err
strings.HasPrefix(s.UserID, types.SessionOwnerAPITenantKeyPrefix) {
return s, nil
}
} }
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 // 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 // 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. // folder on read; a lookup failure must not fail the detail request.
if platform, pErr := s.sessionRepo.GetIMPlatform(ctx, tenantID, session.ID); pErr == nil { if session.IMPlatform == "" {
session.IMPlatform = platform if platform, pErr := s.sessionRepo.GetIMPlatform(ctx, tenantID, session.ID); pErr == nil {
} else { session.IMPlatform = platform
logger.Warnf(ctx, "Failed to resolve IM platform for session %s: %v", session.ID, pErr) } 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) 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 = &types.SessionListQuery{}
} }
query.TenantID = types.MustTenantIDFromContext(ctx) query.TenantID = types.MustTenantIDFromContext(ctx)
// The "api" source is a tenant-wide admin view over API-key sessions, which // API / IM / embed source filters are tenant-wide admin views over channel
// are otherwise isolated per key. Gate it behind Admin+ and drop the // traffic. Gate them behind Admin+ and drop the per-user owner scope so an
// per-user owner scope so the caller sees every key's sessions; everyone // Owner/admin can observe sessions that are otherwise isolated per key,
// else stays scoped to their own principal. // visitor, or IM identity; everyone else stays scoped to their own principal.
if strings.EqualFold(strings.TrimSpace(query.Source), types.SessionSourceAPI) { if types.SessionListSourceRequiresAdmin(query.Source) {
if !types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) { if !types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
return nil, apperrors.NewForbiddenError( 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 = "" query.UserID = ""
@@ -289,6 +310,33 @@ func (s *sessionService) ListSessions(
return types.NewPageResult(total, pagination, items), nil 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. // SetSessionPinned pins or unpins a session for the current user scope.
// Returns the number of rows affected; 0 means the session doesn't exist // 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. // 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) 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 // testListSessionsIMChannelSession lets QueryPaged's LEFT JOIN resolve against a
// real table in the in-memory SQLite database. // real table in the in-memory SQLite database.
type testListSessionsIMChannelSession struct { type testListSessionsIMChannelSession struct {
+2 -5
View File
@@ -749,7 +749,7 @@ func (h *EmbedChannelHandler) GetEmbedChannelStats(c *gin.Context) {
return return
} }
result, err := h.sessionService.ListSessions(ctx, &types.SessionListQuery{ result, err := h.sessionService.CountSessionsBySource(ctx, &types.SessionListQuery{
TenantID: tenantID, TenantID: tenantID,
Source: "embed:" + channelID, Source: "embed:" + channelID,
Page: 1, Page: 1,
@@ -759,10 +759,7 @@ func (h *EmbedChannelHandler) GetEmbedChannelStats(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
total := int64(0) total := result
if result != nil {
total = result.Total
}
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": true, "success": true,
"data": gin.H{ "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 query int false "页码"
// @Param page_size query int false "每页数量" // @Param page_size query int false "每页数量"
// @Param keyword query string 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 会话生效)" // @Param agent_id query string false "按 Agent 过滤(仅对 IM 会话生效)"
// @Success 200 {object} map[string]interface{} "会话列表" // @Success 200 {object} map[string]interface{} "会话列表"
// @Failure 400 {object} errors.AppError "请求参数错误" // @Failure 400 {object} errors.AppError "请求参数错误"
+5 -1
View File
@@ -12,7 +12,8 @@ type SessionService interface {
// CreateSession creates a session // CreateSession creates a session
CreateSession(ctx context.Context, session *types.Session) (*types.Session, error) CreateSession(ctx context.Context, session *types.Session) (*types.Session, error)
// GetSession gets a session, honoring the caller's per-user scope with an // 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) GetSession(ctx context.Context, id string) (*types.Session, error)
// GetOwnedSession gets a session strictly within the caller's owner scope // GetOwnedSession gets a session strictly within the caller's owner scope
// (no Admin+ API-key fallback). Write/mutation endpoints must use this so a // (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 // 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. // search/source filters and pin-aware ordering. User scope is pulled from ctx.
ListSessions(ctx context.Context, query *types.SessionListQuery) (*types.PageResult, error) 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. // SetSessionPinned pins or unpins the session for the current user scope.
// Returns the number of rows affected; 0 signals "not found" to the handler. // Returns the number of rows affected; 0 signals "not found" to the handler.
SetSessionPinned(ctx context.Context, sessionID string, pinned bool) (int64, error) SetSessionPinned(ctx context.Context, sessionID string, pinned bool) (int64, error)
+31 -1
View File
@@ -3,6 +3,7 @@ package types
import ( import (
"database/sql/driver" "database/sql/driver"
"encoding/json" "encoding/json"
"strings"
"time" "time"
"github.com/google/uuid" "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. // Owner/admin can observe API-key traffic that is otherwise isolated per key.
const SessionSourceAPI = "api" 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. // SessionListQuery bundles the parameters for listing sessions.
// UserID empty means "tenant-wide" (used by API-key callers / legacy rows). // UserID empty means "tenant-wide" (used by API-key callers / legacy rows).
// Keyword matches title ILIKE '%keyword%'. // Keyword matches title ILIKE '%keyword%'.
// Source values: "web" (user chats, no IM/embed), "embed" / "embed:{channelID}", // Source values: "web" (user chats, no IM/embed), "embed" / "embed:{channelID}",
// "api" (all API-key sessions, Admin+ only), or an IM platform name // "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. // AgentID currently only filters sessions that have an IM channel mapping.
type SessionListQuery struct { type SessionListQuery struct {
TenantID uint64 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")
}
}