feat(audit): 知识库活动记录对 API Key 操作额外显示 Key 名称 (#3405)
* feat(audit): show API key name on knowledge-base activity API-key operations currently look like the first tenant user or "system". Snapshot the key id/name into activity details so the feed can tell which key initiated the change, without restoring key authorization onto async workers. Fixes #3402 * fix(frontend): show activity API key on a second line The 132px actor column truncates "user · API Key · name" into one ellipsis. Keep the person on the first line and the key name below. --------- Co-authored-by: MercuialC <MercuialC@users.noreply.github.com> Co-authored-by: root <root@localhost.localdomain>main
parent
2be7bd4063
commit
aaec920a9c
|
|
@ -2898,6 +2898,8 @@ export default {
|
|||
targetType: 'Target type',
|
||||
targetId: 'Target ID',
|
||||
actorId: 'Initiator ID',
|
||||
apiKeyName: 'API key name',
|
||||
apiKeyId: 'API key ID',
|
||||
details: 'Details'
|
||||
},
|
||||
drawer: {
|
||||
|
|
@ -2907,6 +2909,8 @@ export default {
|
|||
targetChange: 'Change details'
|
||||
},
|
||||
systemActor: 'System',
|
||||
actorWithAPIKey: '{actor} · API Key · {name}',
|
||||
actorAPIKey: 'API Key · {name}',
|
||||
knowledgeBase: 'Knowledge base',
|
||||
countItems: '{count} items',
|
||||
titleWithCount: '{title} and {count} more',
|
||||
|
|
|
|||
|
|
@ -2898,6 +2898,8 @@ export default {
|
|||
targetType: '対象の種類',
|
||||
targetId: '対象ID',
|
||||
actorId: '実行者ID',
|
||||
apiKeyName: 'APIキー名',
|
||||
apiKeyId: 'APIキーID',
|
||||
details: '詳細'
|
||||
},
|
||||
drawer: {
|
||||
|
|
@ -2907,6 +2909,8 @@ export default {
|
|||
targetChange: '変更内容'
|
||||
},
|
||||
systemActor: 'システム',
|
||||
actorWithAPIKey: '{actor} · API Key · {name}',
|
||||
actorAPIKey: 'API Key · {name}',
|
||||
knowledgeBase: 'ナレッジベース',
|
||||
countItems: '{count}件',
|
||||
titleWithCount: '{title}ほか{count}件',
|
||||
|
|
|
|||
|
|
@ -4532,6 +4532,8 @@ export default {
|
|||
end: '이전 기록이 없습니다',
|
||||
loadFailed: '활동 기록을 불러오지 못했습니다',
|
||||
systemActor: '시스템',
|
||||
actorWithAPIKey: '{actor} · API Key · {name}',
|
||||
actorAPIKey: 'API Key · {name}',
|
||||
knowledgeBase: '지식 베이스',
|
||||
countItems: '{count}개 항목',
|
||||
titleWithCount: '{title} 외 {count}개',
|
||||
|
|
@ -4635,6 +4637,8 @@ export default {
|
|||
targetType: '대상 유형',
|
||||
targetId: '대상 ID',
|
||||
actorId: '시작자 ID',
|
||||
apiKeyName: 'API 키 이름',
|
||||
apiKeyId: 'API 키 ID',
|
||||
details: '상세'
|
||||
},
|
||||
columns: {
|
||||
|
|
|
|||
|
|
@ -4532,6 +4532,8 @@ export default {
|
|||
end: 'Более ранних записей нет',
|
||||
loadFailed: 'Не удалось загрузить историю',
|
||||
systemActor: 'Система',
|
||||
actorWithAPIKey: '{actor} · API Key · {name}',
|
||||
actorAPIKey: 'API Key · {name}',
|
||||
knowledgeBase: 'База знаний',
|
||||
countItems: '{count} элем.',
|
||||
titleWithCount: '{title} и ещё {count}',
|
||||
|
|
@ -4635,6 +4637,8 @@ export default {
|
|||
targetType: 'Тип объекта',
|
||||
targetId: 'ID объекта',
|
||||
actorId: 'ID инициатора',
|
||||
apiKeyName: 'Имя API-ключа',
|
||||
apiKeyId: 'ID API-ключа',
|
||||
details: 'Подробности'
|
||||
},
|
||||
columns: {
|
||||
|
|
|
|||
|
|
@ -4534,6 +4534,8 @@ export default {
|
|||
end: '没有更早的记录了',
|
||||
loadFailed: '活动记录加载失败',
|
||||
systemActor: '系统触发',
|
||||
actorWithAPIKey: '{actor} · API Key · {name}',
|
||||
actorAPIKey: 'API Key · {name}',
|
||||
knowledgeBase: '知识库',
|
||||
countItems: '共 {count} 项',
|
||||
titleWithCount: '{title} 等 {count} 项',
|
||||
|
|
@ -4637,6 +4639,8 @@ export default {
|
|||
targetType: '对象类型',
|
||||
targetId: '对象 ID',
|
||||
actorId: '发起人 ID',
|
||||
apiKeyName: 'API Key 名称',
|
||||
apiKeyId: 'API Key ID',
|
||||
details: '详情'
|
||||
},
|
||||
columns: {
|
||||
|
|
|
|||
|
|
@ -161,8 +161,11 @@
|
|||
</div>
|
||||
</template>
|
||||
<template #actor="{ row }">
|
||||
<div class="audit-actor">
|
||||
<span class="audit-actor-name">{{ actorLabel(row) }}</span>
|
||||
<div class="audit-actor" :title="actorLabel(row)">
|
||||
<span class="audit-actor-name">{{ actorPersonLabel(row) }}</span>
|
||||
<span v-if="activityAPIKeyName(row)" class="audit-actor-key">
|
||||
{{ actorAPIKeyLabel(row) }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
<template #outcome="{ row }">
|
||||
|
|
@ -332,7 +335,7 @@ const columns = computed(() => [
|
|||
width: 132,
|
||||
},
|
||||
{ colKey: 'target', title: t('knowledgeEditor.activity.columns.target'), minWidth: 180 },
|
||||
{ colKey: 'actor', title: t('knowledgeEditor.activity.columns.actor'), width: 120 },
|
||||
{ colKey: 'actor', title: t('knowledgeEditor.activity.columns.actor'), width: 132 },
|
||||
{
|
||||
colKey: 'outcome',
|
||||
title: 'outcome-title',
|
||||
|
|
@ -503,7 +506,7 @@ function targetDiff(entry: KnowledgeBaseActivity): string {
|
|||
return ''
|
||||
}
|
||||
|
||||
function actorLabel(entry: KnowledgeBaseActivity): string {
|
||||
function actorPersonLabel(entry: KnowledgeBaseActivity): string {
|
||||
if (!entry.actor_user_id) return t('knowledgeEditor.activity.systemActor')
|
||||
const me = authStore.user
|
||||
if (me?.id === entry.actor_user_id) {
|
||||
|
|
@ -512,6 +515,31 @@ function actorLabel(entry: KnowledgeBaseActivity): string {
|
|||
return entry.actor_user_id.slice(0, 8)
|
||||
}
|
||||
|
||||
function actorAPIKeyLabel(entry: KnowledgeBaseActivity): string {
|
||||
const name = activityAPIKeyName(entry)
|
||||
return name ? t('knowledgeEditor.activity.actorAPIKey', { name }) : ''
|
||||
}
|
||||
|
||||
function actorLabel(entry: KnowledgeBaseActivity): string {
|
||||
const person = actorPersonLabel(entry)
|
||||
const keyName = activityAPIKeyName(entry)
|
||||
if (keyName) {
|
||||
return t('knowledgeEditor.activity.actorWithAPIKey', { actor: person, name: keyName })
|
||||
}
|
||||
return person
|
||||
}
|
||||
|
||||
function activityAPIKeyName(entry: KnowledgeBaseActivity): string {
|
||||
const value = details(entry).api_key_name
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function activityAPIKeyId(entry: KnowledgeBaseActivity): string {
|
||||
const value = details(entry).api_key_id
|
||||
if (value === undefined || value === null || value === '') return ''
|
||||
return String(value)
|
||||
}
|
||||
|
||||
function formatDatePart(value: string): string {
|
||||
if (!value) return '—'
|
||||
try {
|
||||
|
|
@ -613,6 +641,22 @@ function identifierFields(entry: KnowledgeBaseActivity): DetailField[] {
|
|||
value: entry.actor_user_id,
|
||||
})
|
||||
}
|
||||
const keyName = activityAPIKeyName(entry)
|
||||
if (keyName) {
|
||||
fields.push({
|
||||
key: 'apiKeyName',
|
||||
label: t('knowledgeEditor.activity.expanded.apiKeyName'),
|
||||
value: keyName,
|
||||
})
|
||||
}
|
||||
const keyId = activityAPIKeyId(entry)
|
||||
if (keyId) {
|
||||
fields.push({
|
||||
key: 'apiKeyId',
|
||||
label: t('knowledgeEditor.activity.expanded.apiKeyId'),
|
||||
value: keyId,
|
||||
})
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
|
|
@ -945,15 +989,28 @@ onUnmounted(() => detachInfiniteScroll())
|
|||
}
|
||||
|
||||
.audit-actor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
line-height: 1.3;
|
||||
|
||||
.audit-actor-name,
|
||||
.audit-actor-key {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.audit-actor-name {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.audit-actor-key {
|
||||
font-size: var(--app-text-sm, 12px);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,6 +43,16 @@ func kbActivityTrigger(ctx context.Context) string {
|
|||
return "system"
|
||||
}
|
||||
|
||||
func kbActivityAPIKey(ctx context.Context) (uint64, string, bool) {
|
||||
if key, ok := types.AuditAPIKeyFromContext(ctx); ok {
|
||||
return key.ID, key.Name, true
|
||||
}
|
||||
if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok && (scope.KeyID > 0 || scope.Name != "") {
|
||||
return scope.KeyID, scope.Name, true
|
||||
}
|
||||
return 0, "", false
|
||||
}
|
||||
|
||||
// kbActivityAppendSampleTitles adds a bounded, human-readable preview of batch
|
||||
// mutations into activity details. The first sample is also mirrored as title so
|
||||
// list views can show what was affected without opening the drawer.
|
||||
|
|
@ -122,6 +132,14 @@ func recordKBActivity(
|
|||
for key, value := range details {
|
||||
activityDetails[key] = value
|
||||
}
|
||||
if id, name, ok := kbActivityAPIKey(ctx); ok {
|
||||
if _, exists := activityDetails["api_key_id"]; !exists && id > 0 {
|
||||
activityDetails["api_key_id"] = id
|
||||
}
|
||||
if _, exists := activityDetails["api_key_name"]; !exists && name != "" {
|
||||
activityDetails["api_key_name"] = name
|
||||
}
|
||||
}
|
||||
if task, ok := ctx.Value(kbActivityTaskContextKey{}).(kbActivityTaskMetadata); ok {
|
||||
if task.TaskID != "" {
|
||||
if _, exists := activityDetails["task_id"]; !exists {
|
||||
|
|
|
|||
|
|
@ -116,6 +116,71 @@ func TestRecordKBActivityCanSuppressCompositeTaskChildren(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestRecordKBActivityIncludesAPIKeyFromScope(t *testing.T) {
|
||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||
KeyID: 9, Name: "alice-mcp",
|
||||
})
|
||||
audit := &captureKBActivityAudit{}
|
||||
recordKBActivity(ctx, audit, 7, "kb-1", types.AuditActionKnowledgeCreated,
|
||||
"knowledge", "k-1", types.AuditOutcomeSuccess, map[string]any{"title": "doc"})
|
||||
|
||||
if audit.entry == nil {
|
||||
t.Fatal("expected an activity entry")
|
||||
}
|
||||
var details map[string]any
|
||||
if err := json.Unmarshal(audit.entry.Details, &details); err != nil {
|
||||
t.Fatalf("unmarshal details: %v", err)
|
||||
}
|
||||
if details["api_key_id"] != float64(9) || details["api_key_name"] != "alice-mcp" {
|
||||
t.Fatalf("details = %#v", details)
|
||||
}
|
||||
if details["title"] != "doc" {
|
||||
t.Fatalf("business details lost: %#v", details)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordKBActivityIncludesAPIKeyFromInitiatorWithoutScope(t *testing.T) {
|
||||
ctx := types.TaskInitiator{APIKeyID: 4, APIKeyName: "bob-mcp"}.Apply(context.Background())
|
||||
audit := &captureKBActivityAudit{}
|
||||
recordKBActivity(ctx, audit, 7, "kb-1", types.AuditActionKnowledgeCreated,
|
||||
"knowledge", "k-1", types.AuditOutcomeSuccess, nil)
|
||||
|
||||
if audit.entry == nil {
|
||||
t.Fatal("expected an activity entry")
|
||||
}
|
||||
if audit.entry.ActorUserID != "" {
|
||||
t.Fatalf("actor should stay empty for API-key-only initiator, got %q", audit.entry.ActorUserID)
|
||||
}
|
||||
var details map[string]any
|
||||
if err := json.Unmarshal(audit.entry.Details, &details); err != nil {
|
||||
t.Fatalf("unmarshal details: %v", err)
|
||||
}
|
||||
if details["api_key_id"] != float64(4) || details["api_key_name"] != "bob-mcp" {
|
||||
t.Fatalf("details = %#v", details)
|
||||
}
|
||||
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
|
||||
t.Fatal("worker context must not carry TenantAPIKeyScope")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordKBActivityOmitsAPIKeyForJWTUser(t *testing.T) {
|
||||
ctx := types.TaskInitiator{UserID: "user-1", Role: types.TenantRoleAdmin}.Apply(context.Background())
|
||||
audit := &captureKBActivityAudit{}
|
||||
recordKBActivity(ctx, audit, 7, "kb-1", types.AuditActionKnowledgeCreated,
|
||||
"knowledge", "k-1", types.AuditOutcomeSuccess, map[string]any{"count": 1})
|
||||
|
||||
var details map[string]any
|
||||
if err := json.Unmarshal(audit.entry.Details, &details); err != nil {
|
||||
t.Fatalf("unmarshal details: %v", err)
|
||||
}
|
||||
if _, ok := details["api_key_id"]; ok {
|
||||
t.Fatalf("jwt activity should not record api_key_id: %#v", details)
|
||||
}
|
||||
if _, ok := details["api_key_name"]; ok {
|
||||
t.Fatalf("jwt activity should not record api_key_name: %#v", details)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordWikiContentActivityUsesUnifiedActivityFeed(t *testing.T) {
|
||||
audit := &captureKBActivityAudit{}
|
||||
RecordWikiContentActivity(context.Background(), audit, 7, "kb-1", map[string]int{
|
||||
|
|
|
|||
|
|
@ -463,6 +463,7 @@ func attachPlatformAPIKeyAuthContext(c *gin.Context, key *types.TenantAPIKey) {
|
|||
Role: types.TenantRoleViewer,
|
||||
APIKeyScope: &types.TenantAPIKeyScope{
|
||||
KeyID: key.ID,
|
||||
Name: key.Name,
|
||||
ScopeType: types.APIKeyScopePlatform,
|
||||
FullAccess: false,
|
||||
Capabilities: key.Capabilities,
|
||||
|
|
@ -549,6 +550,7 @@ func attachAPIKeyAuthContext(
|
|||
if key != nil {
|
||||
session.APIKeyScope = &types.TenantAPIKeyScope{
|
||||
KeyID: key.ID,
|
||||
Name: key.Name,
|
||||
ScopeType: key.ScopeType,
|
||||
FullAccess: fullAccess,
|
||||
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
||||
|
|
|
|||
|
|
@ -28,6 +28,9 @@ const (
|
|||
PrincipalContextKey ContextKey = "Principal"
|
||||
// TenantAPIKeyScopeContextKey carries per-API-key operation and KB scopes.
|
||||
TenantAPIKeyScopeContextKey ContextKey = "TenantAPIKeyScope"
|
||||
// AuditAPIKeyContextKey carries the API key id/name for activity
|
||||
// attribution only. It is not an authorization grant.
|
||||
AuditAPIKeyContextKey ContextKey = "AuditAPIKey"
|
||||
// TenantRoleContextKey is the context key for the caller's TenantRole
|
||||
// in the currently active tenant (loaded by the auth middleware from
|
||||
// the tenant_members table). See TenantRoleFromContext.
|
||||
|
|
|
|||
|
|
@ -44,6 +44,9 @@ var contextCloneAcrossDetach = map[ContextKey]bool{
|
|||
// Per-API-key operation and KB scopes: a restriction, so dropping it would
|
||||
// hand background work broader reach than the key it came from.
|
||||
TenantAPIKeyScopeContextKey: true,
|
||||
// Display identity for which API key initiated work. Not a grant; dropping
|
||||
// it would only lose activity attribution on detached goroutines.
|
||||
AuditAPIKeyContextKey: true,
|
||||
|
||||
// Session scope. SessionTenantID re-scopes session/message lookups, while
|
||||
// SandboxTenantID keys the session→sandbox binding to the session owner
|
||||
|
|
|
|||
|
|
@ -74,30 +74,72 @@ func WikiEditSourceFromContext(ctx context.Context) string {
|
|||
// initiated the operation, while tasks created by schedulers remain
|
||||
// attributable to the system.
|
||||
type TaskInitiator struct {
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
Role TenantRole `json:"role,omitempty"`
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
Role TenantRole `json:"role,omitempty"`
|
||||
APIKeyID uint64 `json:"api_key_id,omitempty"`
|
||||
APIKeyName string `json:"api_key_name,omitempty"`
|
||||
}
|
||||
|
||||
// AuditAPIKey is the display identity of the API key that initiated work.
|
||||
// It is not an authorization grant and must not be confused with
|
||||
// TenantAPIKeyScope.
|
||||
type AuditAPIKey struct {
|
||||
ID uint64
|
||||
Name string
|
||||
}
|
||||
|
||||
func WithAuditAPIKey(ctx context.Context, key AuditAPIKey) context.Context {
|
||||
if key.ID == 0 && key.Name == "" {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, AuditAPIKeyContextKey, key)
|
||||
}
|
||||
|
||||
func AuditAPIKeyFromContext(ctx context.Context) (AuditAPIKey, bool) {
|
||||
if ctx == nil {
|
||||
return AuditAPIKey{}, false
|
||||
}
|
||||
key, ok := ctx.Value(AuditAPIKeyContextKey).(AuditAPIKey)
|
||||
if !ok || (key.ID == 0 && key.Name == "") {
|
||||
return AuditAPIKey{}, false
|
||||
}
|
||||
return key, true
|
||||
}
|
||||
|
||||
// TaskInitiatorFromContext snapshots the real caller identity for a task
|
||||
// payload. Synthetic API-key users are service identities, not people, and are
|
||||
// intentionally left empty so the activity feed presents them as system work.
|
||||
// The API key id/name is still captured so workers can attribute activity.
|
||||
func TaskInitiatorFromContext(ctx context.Context) TaskInitiator {
|
||||
initiator := TaskInitiator{}
|
||||
if key, ok := AuditAPIKeyFromContext(ctx); ok {
|
||||
initiator.APIKeyID = key.ID
|
||||
initiator.APIKeyName = key.Name
|
||||
} else if scope, ok := TenantAPIKeyScopeFromContext(ctx); ok && (scope.KeyID > 0 || scope.Name != "") {
|
||||
initiator.APIKeyID = scope.KeyID
|
||||
initiator.APIKeyName = scope.Name
|
||||
}
|
||||
userID, ok := UserIDFromContext(ctx)
|
||||
if !ok || IsSyntheticUserID(userID) {
|
||||
return TaskInitiator{}
|
||||
return initiator
|
||||
}
|
||||
return TaskInitiator{UserID: userID, Role: TenantRoleFromContext(ctx)}
|
||||
initiator.UserID = userID
|
||||
initiator.Role = TenantRoleFromContext(ctx)
|
||||
return initiator
|
||||
}
|
||||
|
||||
// Apply restores a captured task initiator onto a worker context. Empty or
|
||||
// legacy payloads are a no-op and therefore retain the system-task fallback.
|
||||
// API key identity is restored for audit display only — not as TenantAPIKeyScope.
|
||||
func (i TaskInitiator) Apply(ctx context.Context) context.Context {
|
||||
if i.UserID == "" {
|
||||
return ctx
|
||||
if i.UserID != "" {
|
||||
ctx = context.WithValue(ctx, UserIDContextKey, i.UserID)
|
||||
if i.Role.IsValid() {
|
||||
ctx = context.WithValue(ctx, TenantRoleContextKey, i.Role)
|
||||
}
|
||||
}
|
||||
ctx = context.WithValue(ctx, UserIDContextKey, i.UserID)
|
||||
if i.Role.IsValid() {
|
||||
ctx = context.WithValue(ctx, TenantRoleContextKey, i.Role)
|
||||
if i.APIKeyID > 0 || i.APIKeyName != "" {
|
||||
ctx = WithAuditAPIKey(ctx, AuditAPIKey{ID: i.APIKeyID, Name: i.APIKeyName})
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,3 +34,55 @@ func TestTaskInitiatorOmitsSyntheticAndLegacyActors(t *testing.T) {
|
|||
t.Fatalf("legacy user = %q, %v", userID, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskInitiatorSnapshotsAPIKeyWithoutRestoringScope(t *testing.T) {
|
||||
requestCtx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||
KeyID: 9, Name: "alice-mcp",
|
||||
})
|
||||
requestCtx = context.WithValue(requestCtx, UserIDContextKey, "system-7")
|
||||
|
||||
initiator := TaskInitiatorFromContext(requestCtx)
|
||||
if initiator.UserID != "" {
|
||||
t.Fatalf("synthetic user should stay empty, got %#v", initiator)
|
||||
}
|
||||
if initiator.APIKeyID != 9 || initiator.APIKeyName != "alice-mcp" {
|
||||
t.Fatalf("TaskInitiatorFromContext() = %#v", initiator)
|
||||
}
|
||||
|
||||
workerCtx := initiator.Apply(context.Background())
|
||||
if _, ok := TenantAPIKeyScopeFromContext(workerCtx); ok {
|
||||
t.Fatal("Apply must not restore TenantAPIKeyScope")
|
||||
}
|
||||
got, ok := AuditAPIKeyFromContext(workerCtx)
|
||||
if !ok || got.ID != 9 || got.Name != "alice-mcp" {
|
||||
t.Fatalf("AuditAPIKeyFromContext() = %#v, %v", got, ok)
|
||||
}
|
||||
if userID, ok := UserIDFromContext(workerCtx); ok || userID != "" {
|
||||
t.Fatalf("worker user = %q, %v", userID, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskInitiatorKeepsHumanActorAndAPIKey(t *testing.T) {
|
||||
requestCtx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||
KeyID: 3, Name: "bob-mcp",
|
||||
})
|
||||
requestCtx = context.WithValue(requestCtx, UserIDContextKey, "user-1")
|
||||
requestCtx = context.WithValue(requestCtx, TenantRoleContextKey, TenantRoleAdmin)
|
||||
|
||||
initiator := TaskInitiatorFromContext(requestCtx)
|
||||
if initiator.UserID != "user-1" || initiator.APIKeyID != 3 || initiator.APIKeyName != "bob-mcp" {
|
||||
t.Fatalf("TaskInitiatorFromContext() = %#v", initiator)
|
||||
}
|
||||
|
||||
workerCtx := initiator.Apply(context.Background())
|
||||
if userID, ok := UserIDFromContext(workerCtx); !ok || userID != "user-1" {
|
||||
t.Fatalf("restored user = %q, %v", userID, ok)
|
||||
}
|
||||
if _, ok := TenantAPIKeyScopeFromContext(workerCtx); ok {
|
||||
t.Fatal("Apply must not restore TenantAPIKeyScope")
|
||||
}
|
||||
got, ok := AuditAPIKeyFromContext(workerCtx)
|
||||
if !ok || got.Name != "bob-mcp" {
|
||||
t.Fatalf("AuditAPIKeyFromContext() = %#v, %v", got, ok)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -268,6 +268,7 @@ func (k *TenantAPIKey) AfterFind(tx *gorm.DB) error {
|
|||
// TenantAPIKeyScope is the request-context projection used by middleware.
|
||||
type TenantAPIKeyScope struct {
|
||||
KeyID uint64
|
||||
Name string
|
||||
ScopeType APIKeyScopeType
|
||||
FullAccess bool
|
||||
KnowledgeBaseIDs StringArray
|
||||
|
|
@ -292,6 +293,7 @@ func TenantAPIKeyScopeFromContext(ctx context.Context) (TenantAPIKeyScope, bool)
|
|||
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
|
||||
return TenantAPIKeyScope{
|
||||
KeyID: s.KeyID,
|
||||
Name: s.Name,
|
||||
ScopeType: NormalizeAPIKeyScopeType(s.ScopeType),
|
||||
FullAccess: s.FullAccess,
|
||||
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
|
||||
|
|
|
|||
|
|
@ -489,6 +489,7 @@ Chunk 类型(`internal/types/chunk.go`):`text`、`parent_text`、`image_oc
|
|||
|
||||
- **活动动作**(`internal/types/audit_log.go`):`kb.created` / `kb.updated` / `kb.deleted` / `kb.duplicated` / `kb.clone_started` / `kb.clone_completed` / `kb.clone_failed`、`kb.share_added` / `kb.share_permission_changed` / `kb.share_removed`,以及知识 / chunk 级的增删改动作;
|
||||
- **触发源**:context 中的 `kbActivityTaskMetadata{TaskID, Trigger}`(`user` 用户操作 / `system` 后台任务)自动并入 details;根据 outcome 自动补 `processing_status`(accepted→pending、success→completed、partial→partial、failed/denied→failed、canceled→canceled);
|
||||
- **API Key 身份**:`X-API-Key` 调用写入 `details.api_key_id` / `details.api_key_name`(名称快照)。活动页在原发起人后额外显示 Key 名称;JWT 网页操作不加这两项。异步任务只把 Key 展示身份放进 `TaskInitiator`,不把 Key 权限 scope 恢复进 worker;
|
||||
- **批量操作样本标题**:`kbActivityAppendSampleTitles` 为批量操作附带最多 5 个去重标题(第一个作为 `title`,其余进 `titles` 数组),保证活动流可读且有界;
|
||||
- **抑制机制**:`withKBActivitySuppressed(ctx)` 可让内部级联操作不产生重复活动记录。
|
||||
|
||||
|
|
|
|||
|
|
@ -162,7 +162,7 @@ Prompt 组装将稳定说明放在前部,动态会话内容放在后部;支
|
|||
| `target_type` / `target_id` / `target_user_id` | varchar | 具体目标资源 / 用户 |
|
||||
| `request_path` / `request_method` | varchar | 路由模板(非原始 URL,防游标爆表;原始 URL 存 Details.raw_path) |
|
||||
| `outcome` | varchar(16) | `success` / `accepted`(异步已受理未终态)/ `denied` / `failed` / `partial` / `canceled` |
|
||||
| `details` | jsonb | 动作特定负载;密钥值**绝不**入库(如 vector_store 只记变更字段名) |
|
||||
| `details` | jsonb | 动作特定负载;密钥值**绝不**入库(如 vector_store 只记变更字段名)。API Key 发起的知识库活动会额外写入 `api_key_id` / `api_key_name`(名称快照,不含明文 Key) |
|
||||
| `created_at` | timestamp | 保留策略清扫依据 |
|
||||
|
||||
#### 审计动作清单 {#_4-2-审计动作清单}
|
||||
|
|
|
|||
|
|
@ -374,7 +374,7 @@ curl "$BASE/api/v1/tenants/1/audit-log?limit=50" -H "Authorization: Bearer $TOKE
|
|||
|
||||
用途:单个 KB 的活动流(只读审计)。权限:KB 创建者 OR Admin+,且对 KB 有 read 权限;仅 JWT。查询参数同上(`after_id/limit/action/outcome/actor`)。注册于 `RegisterKnowledgeBaseActivityRoutes`。
|
||||
|
||||
响应:200 `{"success":true,"data":[AuditLog],"next_cursor":N}`
|
||||
响应:200 `{"success":true,"data":[AuditLog],"next_cursor":N}`。`details` 为动作负载;若该条由 API Key 触发,会包含 `api_key_id` 与 `api_key_name`(名称快照,不含明文 Key)。
|
||||
|
||||
```bash
|
||||
curl $BASE/api/v1/knowledge-bases/kb-1/activity -H "Authorization: Bearer $TOKEN"
|
||||
|
|
|
|||
Loading…
Reference in New Issue