feat(knowledge): add scoped activity audit trail

This commit is contained in:
wizardchen
2026-07-22 19:15:27 +08:00
committed by lyingbug
parent f195e0494c
commit a3a0308b62
44 changed files with 2429 additions and 81 deletions
+56 -7
View File
@@ -131,32 +131,81 @@ const (
AuditActionSystemQueueTaskDeleted AuditAction = "system.queue_task_deleted"
AuditActionSystemQueueTaskRunNow AuditAction = "system.queue_task_run_now"
AuditActionSystemQueueTaskCancelled AuditAction = "system.queue_task_cancelled"
// Knowledge-base activity actions. These rows use scope_type=knowledge_base
// and scope_id=<kb id>; TargetType/TargetID identify the concrete child
// resource when the operation is about a document, tag, data source, or share.
AuditActionKBCreated AuditAction = "kb.created"
AuditActionKBUpdated AuditAction = "kb.updated"
AuditActionKBDeleted AuditAction = "kb.deleted"
AuditActionKBDuplicated AuditAction = "kb.duplicated"
AuditActionKBCloneStarted AuditAction = "kb.clone_started"
AuditActionKBCloneCompleted AuditAction = "kb.clone_completed"
AuditActionKBCloneFailed AuditAction = "kb.clone_failed"
AuditActionKnowledgeCreated AuditAction = "knowledge.created"
AuditActionKnowledgeUpdated AuditAction = "knowledge.updated"
AuditActionKnowledgeDeleted AuditAction = "knowledge.deleted"
AuditActionKnowledgeBatchDeleted AuditAction = "knowledge.batch_deleted"
AuditActionKnowledgeReparseStarted AuditAction = "knowledge.reparse_started"
AuditActionKnowledgeParseCanceled AuditAction = "knowledge.parse_canceled"
AuditActionKnowledgeMoveStarted AuditAction = "knowledge.move_started"
AuditActionKnowledgeMoveCompleted AuditAction = "knowledge.move_completed"
AuditActionKnowledgeMoveFailed AuditAction = "knowledge.move_failed"
AuditActionTagCreated AuditAction = "tag.created"
AuditActionTagUpdated AuditAction = "tag.updated"
AuditActionTagDeleted AuditAction = "tag.deleted"
AuditActionDataSourceCreated AuditAction = "datasource.created"
AuditActionDataSourceUpdated AuditAction = "datasource.updated"
AuditActionDataSourceDeleted AuditAction = "datasource.deleted"
AuditActionDataSourceSyncStarted AuditAction = "datasource.sync_started"
AuditActionDataSourceSyncCompleted AuditAction = "datasource.sync_completed"
AuditActionDataSourceSyncFailed AuditAction = "datasource.sync_failed"
AuditActionDataSourcePaused AuditAction = "datasource.paused"
AuditActionDataSourceResumed AuditAction = "datasource.resumed"
AuditActionKBShareAdded AuditAction = "kb.share_added"
AuditActionKBSharePermissionChanged AuditAction = "kb.share_permission_changed"
AuditActionKBShareRemoved AuditAction = "kb.share_removed"
AuditActionWikiContentChanged AuditAction = "wiki.content_changed"
)
// AuditOutcome distinguishes successful mutations from middleware-level
// rejections. The split lets the audit-log UI highlight denials in red
// without needing to enumerate every action class.
// AuditOutcome separates asynchronous acceptance from terminal business
// results and middleware-level rejections. The UI can therefore avoid
// presenting a queued operation as already completed.
type AuditOutcome string
const (
AuditOutcomeSuccess AuditOutcome = "success"
AuditOutcomeDenied AuditOutcome = "denied"
// Accepted means the durable request was created and asynchronous work was
// submitted, but the background operation has not reached a terminal state.
AuditOutcomeAccepted AuditOutcome = "accepted"
AuditOutcomeDenied AuditOutcome = "denied"
AuditOutcomeFailed AuditOutcome = "failed"
AuditOutcomePartial AuditOutcome = "partial"
AuditOutcomeCanceled AuditOutcome = "canceled"
)
// AuditLog is a single immutable audit event. The schema is intentionally
// generic: PR 6 wires only RBAC events, but TargetType / TargetID /
// Details are set up to absorb KB / agent / datasource events in
// follow-up PRs without another migration.
// follow-up PRs without another migration. Knowledge-base task events use a
// bounded convention inside Details: task_id, trigger, processing_status,
// source/target ids, aggregate counts, and operation-specific mode/attempt.
//
// Rows are append-only — no UpdatedAt, no soft-delete column. The
// monotonic ID acts as both primary key and pagination cursor (newest-
// first is `WHERE id < AfterID ORDER BY id DESC`).
type AuditLog struct {
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_audit_logs_tenant_id_desc,priority:1;index:idx_audit_logs_tenant_action,priority:1"`
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement;index:idx_audit_logs_tenant_scope_desc,priority:4,sort:desc"`
TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_audit_logs_tenant_id_desc,priority:1;index:idx_audit_logs_tenant_action,priority:1;index:idx_audit_logs_tenant_scope_desc,priority:1"`
ActorUserID string `json:"actor_user_id" gorm:"type:varchar(36);default:'';index:idx_audit_logs_actor"`
ActorRole string `json:"actor_role" gorm:"type:varchar(32);default:''"`
Action AuditAction `json:"action" gorm:"type:varchar(64);not null;index:idx_audit_logs_tenant_action,priority:2"`
ScopeType string `json:"scope_type" gorm:"type:varchar(32);default:'';index:idx_audit_logs_tenant_scope_desc,priority:2"`
ScopeID string `json:"scope_id" gorm:"type:varchar(64);default:'';index:idx_audit_logs_tenant_scope_desc,priority:3"`
TargetType string `json:"target_type" gorm:"type:varchar(32);default:''"`
TargetID string `json:"target_id" gorm:"type:varchar(64);default:''"`
TargetUserID string `json:"target_user_id" gorm:"type:varchar(36);default:''"`
+33
View File
@@ -54,6 +54,39 @@ func UserIDFromContext(ctx context.Context) (string, bool) {
return v, ok && v != ""
}
// TaskInitiator is the authenticated caller that submitted an asynchronous
// task. Workers restore it into their context so audit entries describe who
// 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"`
}
// 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.
func TaskInitiatorFromContext(ctx context.Context) TaskInitiator {
userID, ok := UserIDFromContext(ctx)
if !ok || IsSyntheticUserID(userID) {
return TaskInitiator{}
}
return TaskInitiator{UserID: userID, Role: TenantRoleFromContext(ctx)}
}
// 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.
func (i TaskInitiator) Apply(ctx context.Context) context.Context {
if i.UserID == "" {
return ctx
}
ctx = context.WithValue(ctx, UserIDContextKey, i.UserID)
if i.Role.IsValid() {
ctx = context.WithValue(ctx, TenantRoleContextKey, i.Role)
}
return ctx
}
// IsSyntheticUserID reports whether id refers to the synthetic system
// user that the X-API-Key auth path attaches to each tenant
// (User.ID = "system-<tenantID>"). These users have no real human
+3
View File
@@ -415,6 +415,9 @@ func (e *SyncItemError) UnmarshalJSON(b []byte) error {
// DataSourceSyncPayload represents the asynq task payload for data source sync
type DataSourceSyncPayload struct {
TracingContext
Initiator TaskInitiator `json:"initiator,omitempty"`
// Trigger distinguishes a user-requested run from a scheduler-created run.
Trigger string `json:"trigger,omitempty"`
// Data source ID to sync
DataSourceID string `json:"data_source_id"`
+8 -5
View File
@@ -14,11 +14,14 @@ import (
// Limit is capped at 100 inside the repository regardless of caller
// input — keeps unbounded scans off the table.
type AuditLogQuery struct {
AfterID uint64
Limit int
Action types.AuditAction
Outcome types.AuditOutcome
ActorUserID string
AfterID uint64
Limit int
Action types.AuditAction
Outcome types.AuditOutcome
ActorUserID string
ScopeType string
ScopeID string
UnscopedOnly bool
}
// AuditLogRepository is the storage primitive for the audit table.
+24 -20
View File
@@ -29,19 +29,19 @@ const (
// name "low" so tasks enqueued by older releases remain consumable during a
// rolling deployment. New code uses the business-semantic constant.
const (
QueueDefault = "default"
QueueDefault = "default"
// QueueChatAttachment carries session-scoped chat attachment parsing. It
// lives in the core pool but with a higher weight than QueueDefault so
// interactive chat uploads are not starved by knowledge-base batch imports.
QueueChatAttachment = "chat_attachment"
QueuePostProcess = "postprocess"
QueueSummary = "summary"
QueueMultimodal = "multimodal"
QueueGraph = "graph"
QueueQuestion = "question"
QueueSync = "sync"
QueueMaintenance = "low"
QueueWiki = "wiki"
QueueSummary = "summary"
QueueMultimodal = "multimodal"
QueueGraph = "graph"
QueueQuestion = "question"
QueueSync = "sync"
QueueMaintenance = "low"
QueueWiki = "wiki"
)
// QueueDefinition is the single source of truth for queue topology. Worker
@@ -367,10 +367,11 @@ type SummaryGenerationPayload struct {
// KBClonePayload represents the knowledge base clone task payload
type KBClonePayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
TaskID string `json:"task_id"`
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
TenantID uint64 `json:"tenant_id"`
TaskID string `json:"task_id"`
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
Initiator TaskInitiator `json:"initiator,omitempty"`
}
// IndexDeletePayload represents the index delete task payload
@@ -403,8 +404,9 @@ type KBDeletePayload struct {
// KnowledgeListDeletePayload represents the batch knowledge delete task payload
type KnowledgeListDeletePayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
KnowledgeIDs []string `json:"knowledge_ids"`
TenantID uint64 `json:"tenant_id"`
KnowledgeIDs []string `json:"knowledge_ids"`
Initiator TaskInitiator `json:"initiator,omitempty"`
}
// KnowledgeListReparsePayload represents the batch knowledge reparse task payload
@@ -413,17 +415,19 @@ type KnowledgeListReparsePayload struct {
TenantID uint64 `json:"tenant_id"`
KnowledgeIDs []string `json:"knowledge_ids"`
ProcessConfig *KnowledgeProcessOverrides `json:"process_config,omitempty"`
Initiator TaskInitiator `json:"initiator,omitempty"`
}
// KnowledgeMovePayload represents the knowledge move task payload
type KnowledgeMovePayload struct {
TracingContext
TenantID uint64 `json:"tenant_id"`
TaskID string `json:"task_id"`
KnowledgeIDs []string `json:"knowledge_ids"`
SourceKBID string `json:"source_kb_id"`
TargetKBID string `json:"target_kb_id"`
Mode string `json:"mode"` // "reuse_vectors" or "reparse"
TenantID uint64 `json:"tenant_id"`
TaskID string `json:"task_id"`
KnowledgeIDs []string `json:"knowledge_ids"`
SourceKBID string `json:"source_kb_id"`
TargetKBID string `json:"target_kb_id"`
Mode string `json:"mode"` // "reuse_vectors" or "reparse"
Initiator TaskInitiator `json:"initiator,omitempty"`
}
// KnowledgeMoveProgress represents the progress of a knowledge move task
+36
View File
@@ -0,0 +1,36 @@
package types
import (
"context"
"testing"
)
func TestTaskInitiatorRoundTrip(t *testing.T) {
requestCtx := context.WithValue(context.Background(), UserIDContextKey, "user-1")
requestCtx = context.WithValue(requestCtx, TenantRoleContextKey, TenantRoleAdmin)
initiator := TaskInitiatorFromContext(requestCtx)
if initiator.UserID != "user-1" || initiator.Role != TenantRoleAdmin {
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 role := TenantRoleFromContext(workerCtx); role != TenantRoleAdmin {
t.Fatalf("restored role = %q", role)
}
}
func TestTaskInitiatorOmitsSyntheticAndLegacyActors(t *testing.T) {
synthetic := context.WithValue(context.Background(), UserIDContextKey, "system-42")
if got := TaskInitiatorFromContext(synthetic); got.UserID != "" {
t.Fatalf("synthetic initiator = %#v", got)
}
legacyCtx := (TaskInitiator{}).Apply(context.Background())
if userID, ok := UserIDFromContext(legacyCtx); ok || userID != "" {
t.Fatalf("legacy user = %q, %v", userID, ok)
}
}