feat(knowledge): add scoped activity audit trail
This commit is contained in:
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -76,11 +77,12 @@ func (h *AuditLogHandler) ListTenantAuditLog(c *gin.Context) {
|
||||
}
|
||||
|
||||
q := &interfaces.AuditLogQuery{
|
||||
AfterID: afterID,
|
||||
Limit: limit,
|
||||
Action: types.AuditAction(c.Query("action")),
|
||||
Outcome: types.AuditOutcome(c.Query("outcome")),
|
||||
ActorUserID: c.Query("actor"),
|
||||
AfterID: afterID,
|
||||
Limit: limit,
|
||||
Action: types.AuditAction(c.Query("action")),
|
||||
Outcome: types.AuditOutcome(c.Query("outcome")),
|
||||
ActorUserID: c.Query("actor"),
|
||||
UnscopedOnly: true,
|
||||
}
|
||||
|
||||
entries, err := h.auditService.List(ctx, tenantID, q)
|
||||
@@ -105,6 +107,85 @@ func (h *AuditLogHandler) ListTenantAuditLog(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ListKnowledgeBaseActivity returns the durable activity projection for one
|
||||
// knowledge base. The route has already resolved KB access; this handler adds
|
||||
// an owner-tenant check so organization-shared consumers cannot inspect source
|
||||
// workspace actors or configuration history.
|
||||
// @Summary 获取知识库活动记录
|
||||
// @Description 返回知识库的重要变更与后台任务入口。仅知识库创建者或所属空间管理员可读,共享空间不可读。
|
||||
// @Tags 知识库
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param after_id query int false "游标:返回 id 小于此值的记录"
|
||||
// @Param limit query int false "页大小,1-100,默认 50"
|
||||
// @Param action query string false "按 action 精确过滤"
|
||||
// @Param outcome query string false "按 outcome 精确过滤"
|
||||
// @Param actor query string false "按 actor_user_id 精确过滤"
|
||||
// @Success 200 {object} auditLogListResponse
|
||||
// @Failure 403 {object} errors.AppError
|
||||
// @Security Bearer
|
||||
// @Router /knowledge-bases/{id}/activity [get]
|
||||
func (h *AuditLogHandler) ListKnowledgeBaseActivity(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := c.Param("id")
|
||||
access, ok := middleware.KBAccessFromContext(c)
|
||||
if !ok || access == nil || access.KnowledgeBase == nil || access.KnowledgeBase.ID != kbID {
|
||||
c.Error(errors.NewNotFoundError("knowledge base not found"))
|
||||
return
|
||||
}
|
||||
callerTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if callerTenantID == 0 || access.KnowledgeBase.TenantID != callerTenantID {
|
||||
c.Error(errors.NewForbiddenError("knowledge base activity is only available in the owner workspace"))
|
||||
return
|
||||
}
|
||||
actorID, _ := types.UserIDFromContext(ctx)
|
||||
role := types.TenantRoleFromContext(ctx)
|
||||
if access.KnowledgeBase.CreatorID != actorID && !role.HasPermission(types.TenantRoleAdmin) {
|
||||
c.Error(errors.NewForbiddenError("knowledge base activity requires creator or admin access"))
|
||||
return
|
||||
}
|
||||
|
||||
afterID, limit := parseAuditCursor(c)
|
||||
q := &interfaces.AuditLogQuery{
|
||||
AfterID: afterID,
|
||||
Limit: limit,
|
||||
Action: types.AuditAction(c.Query("action")),
|
||||
Outcome: types.AuditOutcome(c.Query("outcome")),
|
||||
ActorUserID: c.Query("actor"),
|
||||
ScopeType: "knowledge_base",
|
||||
ScopeID: kbID,
|
||||
}
|
||||
entries, err := h.auditService.List(ctx, access.KnowledgeBase.TenantID, q)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"knowledge_base_id": kbID})
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
var nextCursor uint64
|
||||
if n := len(entries); n > 0 {
|
||||
nextCursor = entries[n-1].ID
|
||||
}
|
||||
c.JSON(http.StatusOK, auditLogListResponse{
|
||||
Success: true, Data: entries, NextCursor: nextCursor,
|
||||
})
|
||||
}
|
||||
|
||||
func parseAuditCursor(c *gin.Context) (uint64, int) {
|
||||
var afterID uint64
|
||||
if raw := c.Query("after_id"); raw != "" {
|
||||
if v, err := strconv.ParseUint(raw, 10, 64); err == nil {
|
||||
afterID = v
|
||||
}
|
||||
}
|
||||
limit := 0
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
if v, err := strconv.Atoi(raw); err == nil && v > 0 {
|
||||
limit = v
|
||||
}
|
||||
}
|
||||
return afterID, limit
|
||||
}
|
||||
|
||||
// ListSystemAuditLog godoc
|
||||
// @Summary 获取平台审计日志
|
||||
// @Description 返回 system-scope(tenant_id=0)的审计事件,覆盖 system.setting_changed / system.admin_promoted / system.admin_revoked 等 SystemAdmin 操作。按 id 倒序的游标分页。
|
||||
|
||||
@@ -100,6 +100,9 @@ func TestAuditLogHandler_PassesQueryFiltersThrough(t *testing.T) {
|
||||
if q.ActorUserID != "u-probing" {
|
||||
t.Fatalf("expected actor=u-probing, got %q", q.ActorUserID)
|
||||
}
|
||||
if !q.UnscopedOnly {
|
||||
t.Fatalf("tenant audit feed must exclude resource-scoped activity rows")
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
@@ -154,6 +157,81 @@ func TestAuditLogHandler_InvalidTenantIDReturns400(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func newKBActivityHandlerTestRouter(
|
||||
t *testing.T,
|
||||
svc interfaces.AuditLogService,
|
||||
callerTenantID uint64,
|
||||
kb *types.KnowledgeBase,
|
||||
userID string,
|
||||
role types.TenantRole,
|
||||
) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler())
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Set(types.TenantIDContextKey.String(), callerTenantID)
|
||||
c.Set(middleware.KBAccessContextKey, &middleware.KBAccess{KnowledgeBase: kb})
|
||||
ctx := context.WithValue(c.Request.Context(), types.UserIDContextKey, userID)
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, role)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
})
|
||||
h := NewAuditLogHandler(svc)
|
||||
r.GET("/knowledge-bases/:id/activity", h.ListKnowledgeBaseActivity)
|
||||
return r
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseActivityHandler_UsesKBScope(t *testing.T) {
|
||||
svc := &stubAuditService{list: func(_ context.Context, tenantID uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
if tenantID != 7 || q.ScopeType != "knowledge_base" || q.ScopeID != "kb-1" {
|
||||
t.Fatalf("unexpected scope: tenant=%d type=%q id=%q", tenantID, q.ScopeType, q.ScopeID)
|
||||
}
|
||||
if q.AfterID != 30 || q.Limit != 10 || q.Outcome != types.AuditOutcomePartial {
|
||||
t.Fatalf("unexpected filters: %+v", q)
|
||||
}
|
||||
return []*types.AuditLog{{ID: 21, TenantID: 7, ScopeType: q.ScopeType, ScopeID: q.ScopeID}}, nil
|
||||
}}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity?after_id=30&limit=10&outcome=partial", nil)
|
||||
newKBActivityHandlerTestRouter(t, svc, 7,
|
||||
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
|
||||
"creator", types.TenantRoleViewer).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseActivityHandler_BlocksSharedWorkspace(t *testing.T) {
|
||||
svc := &stubAuditService{list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
t.Fatal("audit list must not be called for a shared workspace")
|
||||
return nil, nil
|
||||
}}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity", nil)
|
||||
newKBActivityHandlerTestRouter(t, svc, 8,
|
||||
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
|
||||
"creator", types.TenantRoleOwner).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseActivityHandler_RequiresCreatorOrAdmin(t *testing.T) {
|
||||
svc := &stubAuditService{list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
t.Fatal("audit list must not be called for ordinary members")
|
||||
return nil, nil
|
||||
}}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity", nil)
|
||||
newKBActivityHandlerTestRouter(t, svc, 7,
|
||||
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
|
||||
"other", types.TenantRoleContributor).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ListSystemAuditLog (platform / system-scope feed) ----------------
|
||||
//
|
||||
// Mirrors the per-tenant suite above but covers the new
|
||||
|
||||
@@ -249,6 +249,7 @@ func (h *KnowledgeHandler) enqueueKnowledgeListDelete(
|
||||
payload := types.KnowledgeListDeletePayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeIDs: ids,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
@@ -273,6 +274,7 @@ func (h *KnowledgeHandler) enqueueKnowledgeListReparse(
|
||||
TenantID: tenantID,
|
||||
KnowledgeIDs: ids,
|
||||
ProcessConfig: processConfig,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
@@ -2219,6 +2221,7 @@ func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) {
|
||||
SourceKBID: req.SourceKBID,
|
||||
TargetKBID: req.TargetKBID,
|
||||
Mode: req.Mode,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
|
||||
|
||||
@@ -1081,10 +1081,11 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
|
||||
|
||||
// Create KB clone payload
|
||||
payload := types.KBClonePayload{
|
||||
TenantID: tenantID.(uint64),
|
||||
TaskID: taskID,
|
||||
SourceID: req.SourceID,
|
||||
TargetID: req.TargetID,
|
||||
TenantID: tenantID.(uint64),
|
||||
TaskID: taskID,
|
||||
SourceID: req.SourceID,
|
||||
TargetID: req.TargetID,
|
||||
Initiator: types.TaskInitiatorFromContext(ctx),
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user