feat(rbac): per-tenant audit log for RBAC events (PR 6, #1303)

PR 1-5 of the multi-tenant RBAC series enforce the role matrix; what
they don't do is keep a durable record of who did what. Today the
RBAC middleware logs "[rbac] role insufficient ..." to stderr -
perishable, not searchable. Operators cannot answer "who removed
Alice from tenant T-foo on Tuesday" or "did we 403 a probing user
200 times last hour" after the fact.

This PR adds a generic per-tenant audit log that:

- Captures mutating RBAC actions (member add/remove/role-change/leave)
  durably from the tenant_member service after the repo write succeeds.
- Captures enforcement rejections (RequireRole / RequireOwnershipOrRole
  denies under EnableRBAC=true) via a gin-context-injected hook.
- Sliding-window dedup (1 minute) on (tenant, actor, action, path)
  for denied events so a probing client cannot flood audit_logs.
- Default-on - no extra env flag. Schema is generic enough for future
  KB / agent / datasource events to reuse via new action namespaces
  without another migration.

Schema (migration 000044) mirrors wiki_log_entries' shape: a single
audit_logs table with action, target_type/id, request path/method,
outcome, and a JSONB details column. Three indexes: (tenant_id, id
DESC) for the per-tenant cursor feed, actor_user_id for "what did
Alice do", (tenant_id, action) for both the action filter and the
dedup lookup. Sqlite mirror added for Lite mode.

Wiring is nil-safe: the audit field on tenantMemberService and the
gin-context lookup in rbac.go both tolerate a nil service so existing
tests construct without a stub and dormant deployments degrade
gracefully if the provider is misconfigured.

The query API is GET /tenants/:id/audit-log, gated by Admin+ on top
of the existing PathTenantMatch (denial histories should not surface
to ordinary members). Cursor-paginated by descending id (sidesteps
the duplicate-timestamp tie-breaking that BIGSERIAL trivially solves).

Frontend: TenantMembers.vue gets a t-tabs wrapper with Members
(existing) and Audit log (new) tabs; the audit tab is gated to
Admin+ to mirror the server, lazy-loads on first open, paginates via
the next_cursor pattern, and renders coloured chips per
action/outcome so an operator can scan for anomalies. i18n keys
added in all four locales.

Tests: 14 new tests across service (6), middleware (4), and handler
(4). Service tests pin the dedup window behaviour (writes again
after expiry, dedup is per-actor-per-path, degrades on lookup
error). Middleware tests pin both reject sites' audit hook and the
"dormant mode does not fire" + "nil audit does not panic"
invariants. Handler tests pin the cursor envelope and that an empty
page returns next_cursor=0.

Out of scope: per-action ACL on the audit log, retention/TTL job,
KB/agent/datasource event wiring (schema supports it - just no
emitters yet), async writes, frontend filter UI.
This commit is contained in:
wizardchen
2026-05-14 21:07:48 +08:00
committed by lyingbug
parent d42a41b784
commit 766a6c482f
24 changed files with 1811 additions and 14 deletions
@@ -0,0 +1,106 @@
package repository
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// auditLogRepository persists audit events to the audit_logs table.
// Rows are append-only — there is no Update, no soft-delete, no
// Modify hook. The cursor pagination uses the monotonic id column,
// not created_at, so duplicate timestamps don't break iteration.
type auditLogRepository struct {
db *gorm.DB
}
// NewAuditLogRepository constructs the production audit log repository
// backed by the shared GORM connection.
func NewAuditLogRepository(db *gorm.DB) interfaces.AuditLogRepository {
return &auditLogRepository{db: db}
}
// Create inserts a single audit row. Validation is light — Action is
// the only required field at the schema level; CreatedAt is filled by
// the database default if zero. Service-layer Log() fills both before
// calling here so this is mostly a pass-through.
func (r *auditLogRepository) Create(ctx context.Context, entry *types.AuditLog) error {
return r.db.WithContext(ctx).Create(entry).Error
}
// auditLogListLimitMax is the hard ceiling regardless of caller input.
// Keeps a misconfigured client from triggering an unbounded scan; the
// frontend's default page size is 50 so this is comfortable headroom.
const auditLogListLimitMax = 100
// List returns audit log rows for a tenant, newest-first, applying the
// optional cursor and filters from AuditLogQuery. Both Action and
// Outcome are exact-match — the filter set is small enough that we
// don't need substring matching yet.
func (r *auditLogRepository) List(
ctx context.Context,
tenantID uint64,
q *interfaces.AuditLogQuery,
) ([]*types.AuditLog, error) {
limit := 50
if q != nil && q.Limit > 0 {
limit = q.Limit
}
if limit > auditLogListLimitMax {
limit = auditLogListLimitMax
}
tx := r.db.WithContext(ctx).
Where("tenant_id = ?", tenantID)
if q != nil {
if q.AfterID > 0 {
tx = tx.Where("id < ?", q.AfterID)
}
if q.Action != "" {
tx = tx.Where("action = ?", q.Action)
}
if q.Outcome != "" {
tx = tx.Where("outcome = ?", q.Outcome)
}
if q.ActorUserID != "" {
tx = tx.Where("actor_user_id = ?", q.ActorUserID)
}
}
var entries []*types.AuditLog
if err := tx.Order("id DESC").Limit(limit).Find(&entries).Error; err != nil {
return nil, err
}
return entries, nil
}
// CountSinceForDedup powers AuditLogService.LogDenied's sliding-window
// dedup. The (tenant_id, action) index makes the count cheap; the
// remaining filters are applied as additional WHERE clauses on the
// indexed result set.
//
// Returning early on the first match would be slightly cheaper, but
// gorm's Count works on the same plan and the constant overhead is
// negligible compared to the dedup benefit.
func (r *auditLogRepository) CountSinceForDedup(
ctx context.Context,
tenantID uint64,
actorUserID string,
action types.AuditAction,
requestPath string,
since time.Time,
) (int64, error) {
var count int64
err := r.db.WithContext(ctx).
Model(&types.AuditLog{}).
Where("tenant_id = ?", tenantID).
Where("actor_user_id = ?", actorUserID).
Where("action = ?", action).
Where("request_path = ?", requestPath).
Where("created_at >= ?", since).
Count(&count).Error
return count, err
}
+130
View File
@@ -0,0 +1,130 @@
package service
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// auditLogService is the high-level wrapper around AuditLogRepository.
// It owns:
// - timestamp defaulting (Log fills CreatedAt if zero so callers
// don't have to).
// - the 1-minute sliding-window dedup that LogDenied applies to keep
// a probing client from filling the audit_logs table.
//
// The service is intentionally nil-tolerant when consumed: the
// tenant_member service holds it as an optional field, so a future
// container reshuffle that constructs tenant_member before audit_log
// won't crash. Callers should still aim to inject a real instance —
// the nil path is a degraded mode, not a default.
type auditLogService struct {
repo interfaces.AuditLogRepository
now func() time.Time
}
// NewAuditLogService constructs the production service.
func NewAuditLogService(repo interfaces.AuditLogRepository) interfaces.AuditLogService {
return &auditLogService{repo: repo, now: time.Now}
}
// denyDedupWindow caps how often LogDenied will write a durable row
// for the same (tenant, actor, path, action) tuple. 1 minute is
// short enough that bursts across distinct paths still each show up
// in the table (one row per path per minute), long enough that a
// single hammered endpoint at 100 RPS produces 1 row/minute, not 6000.
const denyDedupWindow = 1 * time.Minute
// Log is the canonical write path. The repo's Create defaults
// CreatedAt at the SQL level, but we also fill it here so tests and
// callers that read entry.CreatedAt right after Log() get a sensible
// value without round-tripping through the database.
func (s *auditLogService) Log(ctx context.Context, entry *types.AuditLog) error {
if entry == nil {
return fmt.Errorf("audit log: nil entry")
}
if entry.Action == "" {
return fmt.Errorf("audit log: action is required")
}
if entry.Outcome == "" {
entry.Outcome = types.AuditOutcomeSuccess
}
if entry.CreatedAt.IsZero() {
entry.CreatedAt = s.now()
}
if err := s.repo.Create(ctx, entry); err != nil {
// Log loudly but do NOT propagate the error to the caller in
// the production wiring (see callers in tenant_member service
// and rbac middleware — both ignore the return). Audit failure
// must never break the underlying business operation.
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"audit_action": entry.Action,
"audit_target": entry.TargetID,
})
return err
}
return nil
}
// LogDenied records a middleware-level rejection. Subject to a
// 1-minute sliding-window dedup keyed by
// (tenant_id, actor_user_id, action, request_path) so a probing
// client cannot flood the table.
//
// The non-durable advisory log line `[rbac] role insufficient: ...`
// continues to fire on every reject (in middleware/rbac.go) — the
// dedup only suppresses durable writes, not stderr observability.
func (s *auditLogService) LogDenied(
ctx context.Context,
c *gin.Context,
tenantID uint64,
actorUserID, actorRole string,
requiredRole types.TenantRole,
) error {
requestPath := ""
requestMethod := ""
if c != nil && c.Request != nil {
requestPath = c.Request.URL.Path
requestMethod = c.Request.Method
}
// Dedup probe: skip the durable write if this exact tuple already
// has a row in the trailing window. Failure here is non-fatal —
// degraded behaviour is "write a duplicate" which is preferable to
// "skip the audit because the count failed".
since := s.now().Add(-denyDedupWindow)
if n, err := s.repo.CountSinceForDedup(
ctx, tenantID, actorUserID, types.AuditActionAccessDenied, requestPath, since,
); err == nil && n > 0 {
return nil
}
details, _ := json.Marshal(map[string]string{"required_role": string(requiredRole)})
return s.Log(ctx, &types.AuditLog{
TenantID: tenantID,
ActorUserID: actorUserID,
ActorRole: actorRole,
Action: types.AuditActionAccessDenied,
RequestPath: requestPath,
RequestMethod: requestMethod,
Outcome: types.AuditOutcomeDenied,
Details: types.JSON(details),
})
}
// List proxies to the repository. The handler layer applies the
// PathTenantMatch + Admin guard before this is reached, so we don't
// re-check tenant scope here.
func (s *auditLogService) List(
ctx context.Context,
tenantID uint64,
q *interfaces.AuditLogQuery,
) ([]*types.AuditLog, error) {
return s.repo.List(ctx, tenantID, q)
}
@@ -0,0 +1,175 @@
package service
import (
"context"
"errors"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// stubAuditRepo collects Create calls and answers CountSinceForDedup
// from the in-memory state. Embeds the interface so any unstubbed
// method will nil-panic, surfacing a contract drift loudly instead of
// silently returning zero-values.
type stubAuditRepo struct {
interfaces.AuditLogRepository
mu sync.Mutex
created []*types.AuditLog
// countErr lets a test inject a transient lookup failure.
countErr error
}
func (s *stubAuditRepo) Create(_ context.Context, entry *types.AuditLog) error {
s.mu.Lock()
defer s.mu.Unlock()
s.created = append(s.created, entry)
return nil
}
func (s *stubAuditRepo) CountSinceForDedup(
_ context.Context, tenantID uint64, actorUserID string,
action types.AuditAction, requestPath string, since time.Time,
) (int64, error) {
if s.countErr != nil {
return 0, s.countErr
}
s.mu.Lock()
defer s.mu.Unlock()
var n int64
for _, e := range s.created {
if e.TenantID == tenantID &&
e.ActorUserID == actorUserID &&
e.Action == action &&
e.RequestPath == requestPath &&
!e.CreatedAt.Before(since) {
n++
}
}
return n, nil
}
// fakeClock returns a controllable time source so the dedup-window
// tests can simulate "1 minute later" without sleeping.
type fakeClock struct{ t time.Time }
func (f *fakeClock) Now() time.Time { return f.t }
func (f *fakeClock) Advance(by time.Duration) { f.t = f.t.Add(by) }
func newSvcForTest() (*auditLogService, *stubAuditRepo, *fakeClock) {
clock := &fakeClock{t: time.Date(2026, 5, 14, 10, 0, 0, 0, time.UTC)}
repo := &stubAuditRepo{}
svc := &auditLogService{repo: repo, now: clock.Now}
return svc, repo, clock
}
func newDeniedCtx(t *testing.T, method, path string) *gin.Context {
t.Helper()
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(method, path, nil)
return c
}
func TestAuditLog_Log_FillsCreatedAtAndOutcome(t *testing.T) {
svc, repo, clock := newSvcForTest()
entry := &types.AuditLog{
TenantID: 7,
Action: types.AuditActionMemberAdded,
// CreatedAt left zero, Outcome left empty
}
if err := svc.Log(context.Background(), entry); err != nil {
t.Fatalf("Log: %v", err)
}
if len(repo.created) != 1 {
t.Fatalf("expected 1 written entry, got %d", len(repo.created))
}
if !entry.CreatedAt.Equal(clock.Now()) {
t.Fatalf("expected CreatedAt to default to clock time, got %v", entry.CreatedAt)
}
if entry.Outcome != types.AuditOutcomeSuccess {
t.Fatalf("expected Outcome to default to success, got %q", entry.Outcome)
}
}
func TestAuditLog_Log_RejectsEmptyAction(t *testing.T) {
// Schema requires action; the service guards the contract upfront so
// callers get a clean error instead of a constraint violation later.
svc, _, _ := newSvcForTest()
err := svc.Log(context.Background(), &types.AuditLog{TenantID: 7})
if err == nil {
t.Fatalf("expected error when Action is empty")
}
}
func TestAuditLog_LogDenied_DedupesRepeatedRejectsWithinWindow(t *testing.T) {
// First denied write hits the table; second within the window does
// NOT — the dedup primitive is the headline durability guarantee
// against probing clients filling the audit table at line rate.
svc, repo, _ := newSvcForTest()
c := newDeniedCtx(t, "PUT", "/api/v1/tenants/7")
if err := svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin); err != nil {
t.Fatalf("LogDenied: %v", err)
}
if err := svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin); err != nil {
t.Fatalf("LogDenied second call: %v", err)
}
if len(repo.created) != 1 {
t.Fatalf("expected dedup to drop second write, got %d entries", len(repo.created))
}
}
func TestAuditLog_LogDenied_WritesAgainAfterWindowExpires(t *testing.T) {
// The dedup is a sliding window, not a once-per-tuple lock — once
// the trailing window is empty, the next denied call must record.
svc, repo, clock := newSvcForTest()
c := newDeniedCtx(t, "PUT", "/api/v1/tenants/7")
_ = svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin)
clock.Advance(denyDedupWindow + time.Second)
_ = svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin)
if len(repo.created) != 2 {
t.Fatalf("expected window-expiry to allow second write, got %d entries", len(repo.created))
}
}
func TestAuditLog_LogDenied_DedupIsPerActorAndPath(t *testing.T) {
// Two distinct actors hitting the same endpoint, or the same actor
// hitting two distinct endpoints, must each record. The dedup key
// is (tenant, actor, action, path) — anything else collides.
svc, repo, _ := newSvcForTest()
c1 := newDeniedCtx(t, "PUT", "/api/v1/tenants/7")
c2 := newDeniedCtx(t, "PUT", "/api/v1/agents/abc")
_ = svc.LogDenied(context.Background(), c1, 7, "u-viewer-a", "viewer", types.TenantRoleAdmin)
_ = svc.LogDenied(context.Background(), c1, 7, "u-viewer-b", "viewer", types.TenantRoleAdmin)
_ = svc.LogDenied(context.Background(), c2, 7, "u-viewer-a", "viewer", types.TenantRoleAdmin)
if len(repo.created) != 3 {
t.Fatalf("expected 3 distinct (actor,path) writes, got %d", len(repo.created))
}
}
func TestAuditLog_LogDenied_DegradesGracefullyOnDedupLookupError(t *testing.T) {
// If the dedup count returns an error (DB hiccup, transient), we
// must NOT silently skip the audit row. Better to write a
// duplicate than to lose a denied event during incident response.
svc, repo, _ := newSvcForTest()
repo.countErr = errors.New("transient")
c := newDeniedCtx(t, "PUT", "/api/v1/tenants/7")
if err := svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin); err != nil {
t.Fatalf("LogDenied with dedup error: %v", err)
}
if len(repo.created) != 1 {
t.Fatalf("expected fallthrough write on dedup error, got %d entries", len(repo.created))
}
}
+117 -6
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
"encoding/json"
"errors"
"time"
@@ -34,13 +35,48 @@ var (
// tenantMemberService implements interfaces.TenantMemberService.
type tenantMemberService struct {
repo interfaces.TenantMemberRepository
repo interfaces.TenantMemberRepository
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
}
// NewTenantMemberService constructs the service. Wired up via the DI
// container alongside the other application services.
func NewTenantMemberService(repo interfaces.TenantMemberRepository) interfaces.TenantMemberService {
return &tenantMemberService{repo: repo}
// container alongside the other application services. The auditService
// is optional — passing nil disables durable audit but keeps the
// underlying mutations working, so a container reshuffle that
// constructs tenant_member before audit_log won't crash and tests
// don't need to stub the dependency unless they care about audit
// behaviour.
func NewTenantMemberService(
repo interfaces.TenantMemberRepository,
audit interfaces.AuditLogService,
) interfaces.TenantMemberService {
return &tenantMemberService{repo: repo, audit: audit}
}
// emitAudit is the per-mutation audit hook. Best-effort: a nil audit
// service or a write failure is logged inside the audit service itself
// and never bubbles up to the caller. RBAC mutations succeed even if
// audit is unavailable; the alternative (failing the business op when
// the audit table is down) is far worse.
func (s *tenantMemberService) emitAudit(ctx context.Context, entry *types.AuditLog) {
if s.audit == nil {
return
}
_ = s.audit.Log(ctx, entry)
}
// auditActorRole picks up the caller's role at write-time. Empty if
// auth middleware didn't set it (e.g. service-internal flows like
// EnsureOwner during register, where there is no "caller").
func auditActorRole(ctx context.Context) string {
return string(types.TenantRoleFromContext(ctx))
}
// auditActor returns the calling user id from context, "" when no
// authenticated caller is present (service-internal paths).
func auditActor(ctx context.Context) string {
uid, _ := types.UserIDFromContext(ctx)
return uid
}
// AddMember inserts a new active membership row. Returns
@@ -74,6 +110,15 @@ func (s *tenantMemberService) AddMember(
if err := s.repo.Create(ctx, member); err != nil {
return nil, err
}
s.emitAudit(ctx, &types.AuditLog{
TenantID: tenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: types.AuditActionMemberAdded,
TargetType: "tenant_member",
TargetUserID: userID,
Outcome: types.AuditOutcomeSuccess,
})
return member, nil
}
@@ -154,6 +199,7 @@ func (s *tenantMemberService) UpdateRole(
if current.Role == newRole {
return nil
}
oldRole := current.Role
// Owner demotion is the dangerous path: two concurrent demotions of
// two different Owners with the old "Get → Count → Update" sequence
// could each observe count=2 and both commit, leaving the tenant
@@ -168,15 +214,51 @@ func (s *tenantMemberService) UpdateRole(
case err != nil:
return err
}
s.emitRoleChangeAudit(ctx, tenantID, userID, oldRole, newRole)
return nil
}
return s.repo.UpdateRole(ctx, userID, tenantID, newRole)
if err := s.repo.UpdateRole(ctx, userID, tenantID, newRole); err != nil {
return err
}
s.emitRoleChangeAudit(ctx, tenantID, userID, oldRole, newRole)
return nil
}
// emitRoleChangeAudit packs the old/new role into Details so the
// audit-log UI can render "promoted Alice from contributor to admin"
// without a separate column per role transition.
func (s *tenantMemberService) emitRoleChangeAudit(
ctx context.Context,
tenantID uint64,
targetUserID string,
oldRole, newRole types.TenantRole,
) {
details, _ := json.Marshal(map[string]string{
"old_role": string(oldRole),
"new_role": string(newRole),
})
s.emitAudit(ctx, &types.AuditLog{
TenantID: tenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: types.AuditActionMemberRoleChanged,
TargetType: "tenant_member",
TargetUserID: targetUserID,
Outcome: types.AuditOutcomeSuccess,
Details: types.JSON(details),
})
}
// RemoveMember enforces the "cannot remove the last Owner" invariant
// before soft-deleting the membership. For Owner removals it routes
// through the repo's transactional helper so the count + delete commit
// atomically (no TOCTOU between checking owner count and deleting).
//
// The audit row distinguishes "voluntary leave" (caller == target,
// driven by POST /leave) from "kicked" (caller != target, driven by
// DELETE /tenants/:id/members/:user_id). Both go through this same
// service method but the recorded action differs so an audit reader
// can tell the two apart.
func (s *tenantMemberService) RemoveMember(ctx context.Context, userID string, tenantID uint64) error {
current, err := s.repo.Get(ctx, userID, tenantID)
if err != nil {
@@ -193,7 +275,36 @@ func (s *tenantMemberService) RemoveMember(ctx context.Context, userID string, t
case err != nil:
return err
}
s.emitRemovalAudit(ctx, tenantID, userID)
return nil
}
return s.repo.SoftDelete(ctx, userID, tenantID)
if err := s.repo.SoftDelete(ctx, userID, tenantID); err != nil {
return err
}
s.emitRemovalAudit(ctx, tenantID, userID)
return nil
}
// emitRemovalAudit picks AuditActionMemberLeft when the caller is
// removing themselves, AuditActionMemberRemoved otherwise. Caller
// detection uses the user-id from the request context — the same
// source the LeaveTenant handler uses to derive its `userID` arg.
func (s *tenantMemberService) emitRemovalAudit(
ctx context.Context,
tenantID uint64,
targetUserID string,
) {
action := types.AuditActionMemberRemoved
if actor := auditActor(ctx); actor != "" && actor == targetUserID {
action = types.AuditActionMemberLeft
}
s.emitAudit(ctx, &types.AuditLog{
TenantID: tenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: action,
TargetType: "tenant_member",
TargetUserID: targetUserID,
Outcome: types.AuditOutcomeSuccess,
})
}
@@ -27,12 +27,12 @@ type fakeTenantMemberRepo struct {
nextID uint64
// failGet, failHasAny etc. let tests inject transient errors on the
// matching method to exercise error paths.
failGet error
failHasAny error
failCountOwners error
failUpdateRole error
failSoftDelete error
failCreate error
failGet error
failHasAny error
failCountOwners error
failUpdateRole error
failSoftDelete error
failCreate error
}
func newFakeRepo() *fakeTenantMemberRepo { return &fakeTenantMemberRepo{} }
@@ -207,7 +207,11 @@ var _ interfaces.TenantMemberRepository = (*fakeTenantMemberRepo)(nil)
func newServiceWithRepo() (interfaces.TenantMemberService, *fakeTenantMemberRepo) {
r := newFakeRepo()
return NewTenantMemberService(r), r
// Audit dependency is intentionally nil — these tests pre-date PR 6
// and exercise membership invariants only. The service's audit
// hooks are nil-safe (see emitAudit), so passing nil keeps existing
// coverage intact without forcing a stub.
return NewTenantMemberService(r, nil), r
}
func TestTenantMemberService_AddMember_RejectsInvalidRole(t *testing.T) {