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
+71
View File
@@ -0,0 +1,71 @@
package types
import (
"time"
)
// AuditAction names a single audited action class. Action constants are
// dot-namespaced (`<area>.<event>`) so future PRs can plug in their own
// areas (e.g. `kb.shared`, `agent.copied`) without colliding with the
// RBAC events PR 6 ships.
type AuditAction string
const (
// AuditActionMemberAdded fires when a tenant Owner / Admin adds a
// new tenant_members row. The actor is the inviter; the target is
// the invited user.
AuditActionMemberAdded AuditAction = "rbac.member_added"
// AuditActionMemberRemoved fires when an Owner / Admin removes a
// tenant_members row. Distinct from MemberLeft so an audit reader
// can tell "kicked out" from "left voluntarily".
AuditActionMemberRemoved AuditAction = "rbac.member_removed"
// AuditActionMemberRoleChanged fires for promote/demote operations.
// The Details payload carries old_role and new_role.
AuditActionMemberRoleChanged AuditAction = "rbac.member_role_changed"
// AuditActionMemberLeft fires on POST /tenants/:id/leave — the
// actor and target are the same user.
AuditActionMemberLeft AuditAction = "rbac.member_left"
// AuditActionAccessDenied fires when middleware/rbac.go's
// RequireRole or RequireOwnershipOrRole rejects a request under
// EnableRBAC=true. Subject to 1-minute sliding-window dedup so a
// probing client cannot fill the table.
AuditActionAccessDenied AuditAction = "rbac.access_denied"
)
// 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.
type AuditOutcome string
const (
AuditOutcomeSuccess AuditOutcome = "success"
AuditOutcomeDenied AuditOutcome = "denied"
)
// 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.
//
// 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"`
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"`
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:''"`
RequestPath string `json:"request_path" gorm:"type:varchar(512);default:''"`
RequestMethod string `json:"request_method" gorm:"type:varchar(16);default:''"`
Outcome AuditOutcome `json:"outcome" gorm:"type:varchar(16);default:success"`
Details JSON `json:"details" gorm:"type:jsonb;default:'{}'"`
CreatedAt time.Time `json:"created_at" gorm:"index:idx_audit_logs_tenant_id_desc,priority:2,sort:desc"`
}
// TableName pins the table name even if a future GORM convention
// pluralisation refactor would otherwise rename it.
func (AuditLog) TableName() string { return "audit_logs" }
+63
View File
@@ -0,0 +1,63 @@
package interfaces
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// AuditLogQuery is the cursor + filter set for listing audit log
// entries. AfterID is the last id from the previous page (rows with
// id < AfterID are returned, newest first); 0 means "from the top".
// 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
}
// AuditLogRepository is the storage primitive for the audit table.
// All writes are inserts (immutable rows); the only "update" surface
// is none — once written, an entry is permanent.
type AuditLogRepository interface {
Create(ctx context.Context, entry *types.AuditLog) error
List(ctx context.Context, tenantID uint64, q *AuditLogQuery) ([]*types.AuditLog, error)
// CountSinceForDedup is the rate-limit primitive for LogDenied —
// returns the count of matching rows in the trailing window so the
// service can skip writing duplicates. Filter is
// (tenant_id, actor_user_id, action, request_path, created_at >= since).
CountSinceForDedup(
ctx context.Context,
tenantID uint64,
actorUserID string,
action types.AuditAction,
requestPath string,
since time.Time,
) (int64, error)
}
// AuditLogService is the high-level audit API the rest of the codebase
// uses. It owns timestamp defaulting (Log) and rate-limit dedup
// (LogDenied) so callers don't have to think about either.
type AuditLogService interface {
// Log writes a single audit entry. Callers fill TenantID + Action +
// any per-event fields; the service fills CreatedAt if zero.
Log(ctx context.Context, entry *types.AuditLog) error
// LogDenied records a middleware-level reject decision. Subject to
// 1-minute sliding-window dedup keyed by
// (tenant_id, actor_user_id, action, request_path) so a probing
// client cannot flood the table.
LogDenied(
ctx context.Context,
c *gin.Context,
tenantID uint64,
actorUserID, actorRole string,
requiredRole types.TenantRole,
) error
List(ctx context.Context, tenantID uint64, q *AuditLogQuery) ([]*types.AuditLog, error)
}