Files
Enterprise-Knowledge-Base/internal/application/repository/audit_log.go
T
wizardchen 766a6c482f 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.
2026-05-18 17:28:58 +08:00

107 lines
3.2 KiB
Go

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
}