WeKnora/internal/handler/audit_log.go

258 lines
9.5 KiB
Go
Raw Normal View History

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-14 13:07:48 +00:00
package handler
import (
"net/http"
"strconv"
"github.com/Tencent/WeKnora/internal/errors"
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-14 13:07:48 +00:00
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/middleware"
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-14 13:07:48 +00:00
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// AuditLogHandler exposes the per-tenant audit-log feed (PR 6, #1303).
// The route group lives under /tenants/:id/audit-log, gated by
// PathTenantMatch (URL :id == active tenant) plus an Admin role
// requirement — leaks of denied-action histories should not surface
// to ordinary members.
type AuditLogHandler struct {
auditService interfaces.AuditLogService
}
// NewAuditLogHandler constructs the handler.
func NewAuditLogHandler(auditService interfaces.AuditLogService) *AuditLogHandler {
return &AuditLogHandler{auditService: auditService}
}
2026-07-28 03:07:26 +00:00
// auditLogListResponse is the response envelope for ListTenantAuditLog. The
// cursor is the integer id of the last entry, or 0 if no more rows remain.
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-14 13:07:48 +00:00
type auditLogListResponse struct {
Success bool `json:"success"`
Data []*types.AuditLog `json:"data"`
NextCursor uint64 `json:"next_cursor"`
}
// ListTenantAuditLog godoc
// @Summary 获取空间审计日志
// @Description 返回该空间最近的审计事件,按 id 倒序。游标分页:将上次响应的 next_cursor 作为下一次请求的 after_id。
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-14 13:07:48 +00:00
// @Tags 审计日志
// @Produce json
// @Param id path string true "空间ID"
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-14 13:07:48 +00:00
// @Param after_id query int false "游标:返回 id 小于此值的记录(默认从最新开始)"
// @Param limit query int false "页大小,1-100,默认 50"
// @Param action query string false "按 action 精确过滤(如 rbac.member_added / rbac.access_denied)"
// @Param outcome query string false "按 outcome 精确过滤(success / denied)"
// @Param actor query string false "按 actor_user_id 精确过滤"
// @Success 200 {object} auditLogListResponse
// @Failure 400 {object} errors.AppError
// @Security Bearer
// @Security ApiKeyAuth
// @Router /tenants/{id}/audit-log [get]
func (h *AuditLogHandler) ListTenantAuditLog(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
// parseTenantIDFromPath has already attached an error to gin.
return
}
// after_id cursor — invalid values are tolerated (treated as "from
// the top") so a misconfigured client doesn't see a hard 400 on
// the empty / first request. Tighter validation belongs at the
// frontend.
var afterID uint64
if raw := c.Query("after_id"); raw != "" {
if v, err := strconv.ParseUint(raw, 10, 64); err == nil {
afterID = v
}
}
limit := 0 // 0 lets the repository pick its default (50)
if raw := c.Query("limit"); raw != "" {
if v, err := strconv.Atoi(raw); err == nil && v > 0 {
limit = v
}
}
q := &interfaces.AuditLogQuery{
AfterID: afterID,
Limit: limit,
Action: types.AuditAction(c.Query("action")),
Outcome: types.AuditOutcome(c.Query("outcome")),
ActorUserID: c.Query("actor"),
UnscopedOnly: true,
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-14 13:07:48 +00:00
}
entries, err := h.auditService.List(ctx, tenantID, q)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": tenantID})
c.Error(errors.NewInternalServerError(err.Error()))
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-14 13:07:48 +00:00
return
}
// next_cursor is the smallest id in the page (since rows are sorted
// id DESC). Empty page ⇒ 0, telling the client there's nothing
// older to fetch.
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,
})
}
feat(system): expose platform audit log + polish audit drawers The system_settings update, system admin promote/revoke, and apply-default-storage-quota routes have been writing audit rows since the prior commits, but with TenantID=0 (system-scope). The per-tenant GET /tenants/:id/audit-log endpoint filters by tenant_id and never returns them, so until now those rows existed only in the DB with no UI surface. This commit closes the loop: Backend: - GET /api/v1/system/admin/audit-log: new SystemAdmin-gated endpoint reusing AuditLogService.List with tenant_id=0. Same cursor-paged shape and query params (after_id / limit / action / outcome / actor) as the per-tenant feed, so the frontend reuses the same client logic. - Wired through RegisterSystemAdminRoutes (mounted on the existing adminRoutes group so it inherits the SystemAdmin() guard). The handler dependency is optional: nil auditLogHandler skips the route, mirroring RegisterTenantRoutes' /audit-log handling. Frontend — new platform audit drawer in SystemSettings.vue: - "审计日志" entry button in the section header opens a side drawer (880px) listing system-scope events. Lazy-loaded on first open; refresh is explicit via a button inside the drawer. - Table columns: stacked date/time (so 50 events in the same minute remain distinguishable), stacked actor/role, action tag, structured target (subject key + diff line), outcome. The dead request column (system actions don't go through middleware path capture) is dropped in favour of richer target rendering. - Per-action target formatters: * system.setting_changed: subject = registry key, diff = `old → new` (JSON-encoded, 80-char truncation). Reset shows `old → (空)`. * tenant_storage_quota bulk apply: subject = "批量同步", diff = "applied to N tenants (X GB)". * system.admin_promoted / revoked: subject = "name (email)", diff annotates idempotent / noop branches so an audit reader can tell a real grant from a probe. - Click-to-expand row reveals the full audit context: actor UUID, target_user_id / target_type / target_id, and raw details JSON in monospaced scroll-capped block. No psql round-trip needed for forensic spot checks. - Sticky thead pinned to the scroll container so column labels survive long scrolls. Cells vertical-aligned middle to keep single-line tag cells visually balanced against multi-line target cells. No zebra stripes — the stacked content already provides row separation, and stripes on top read as noise. Frontend — same polish back-ported to TenantMembers.vue audit drawer: - Same drawer width, stacked time / actor cells, structured target + diff layout, expandable raw-details row, sticky thead, vertical- align middle, no stripes. Refresh button reformulated as a text button with label (was an outlined square icon-only). - request_path column kept (rbac.access_denied carries meaningful paths) but empty values render as a placeholder dash so they don't read as broken. - Diff line now covers rbac.invitation_sent / invitation_revoked role in addition to the existing role_changed / access_denied details. API: - frontend/src/api/system/index.ts: listSystemAuditLog() reuses the AuditLog / ListAuditLogParams types from @/api/tenant/audit-log (re-exported) so consumers don't need to cross-import. i18n (zh-CN / en-US / ko-KR / ru-RU): - system.globalSettings.audit.*: full drawer copy + per-action labels (system.setting_changed / admin_promoted / admin_revoked) + target diff templates + expanded-row labels. - tenantMember.audit.expanded.*: expanded-row labels added so the shared drawer treatment renders cleanly under tenant scope.
2026-05-26 12:04:08 +00:00
// 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
}
feat(system): expose platform audit log + polish audit drawers The system_settings update, system admin promote/revoke, and apply-default-storage-quota routes have been writing audit rows since the prior commits, but with TenantID=0 (system-scope). The per-tenant GET /tenants/:id/audit-log endpoint filters by tenant_id and never returns them, so until now those rows existed only in the DB with no UI surface. This commit closes the loop: Backend: - GET /api/v1/system/admin/audit-log: new SystemAdmin-gated endpoint reusing AuditLogService.List with tenant_id=0. Same cursor-paged shape and query params (after_id / limit / action / outcome / actor) as the per-tenant feed, so the frontend reuses the same client logic. - Wired through RegisterSystemAdminRoutes (mounted on the existing adminRoutes group so it inherits the SystemAdmin() guard). The handler dependency is optional: nil auditLogHandler skips the route, mirroring RegisterTenantRoutes' /audit-log handling. Frontend — new platform audit drawer in SystemSettings.vue: - "审计日志" entry button in the section header opens a side drawer (880px) listing system-scope events. Lazy-loaded on first open; refresh is explicit via a button inside the drawer. - Table columns: stacked date/time (so 50 events in the same minute remain distinguishable), stacked actor/role, action tag, structured target (subject key + diff line), outcome. The dead request column (system actions don't go through middleware path capture) is dropped in favour of richer target rendering. - Per-action target formatters: * system.setting_changed: subject = registry key, diff = `old → new` (JSON-encoded, 80-char truncation). Reset shows `old → (空)`. * tenant_storage_quota bulk apply: subject = "批量同步", diff = "applied to N tenants (X GB)". * system.admin_promoted / revoked: subject = "name (email)", diff annotates idempotent / noop branches so an audit reader can tell a real grant from a probe. - Click-to-expand row reveals the full audit context: actor UUID, target_user_id / target_type / target_id, and raw details JSON in monospaced scroll-capped block. No psql round-trip needed for forensic spot checks. - Sticky thead pinned to the scroll container so column labels survive long scrolls. Cells vertical-aligned middle to keep single-line tag cells visually balanced against multi-line target cells. No zebra stripes — the stacked content already provides row separation, and stripes on top read as noise. Frontend — same polish back-ported to TenantMembers.vue audit drawer: - Same drawer width, stacked time / actor cells, structured target + diff layout, expandable raw-details row, sticky thead, vertical- align middle, no stripes. Refresh button reformulated as a text button with label (was an outlined square icon-only). - request_path column kept (rbac.access_denied carries meaningful paths) but empty values render as a placeholder dash so they don't read as broken. - Diff line now covers rbac.invitation_sent / invitation_revoked role in addition to the existing role_changed / access_denied details. API: - frontend/src/api/system/index.ts: listSystemAuditLog() reuses the AuditLog / ListAuditLogParams types from @/api/tenant/audit-log (re-exported) so consumers don't need to cross-import. i18n (zh-CN / en-US / ko-KR / ru-RU): - system.globalSettings.audit.*: full drawer copy + per-action labels (system.setting_changed / admin_promoted / admin_revoked) + target diff templates + expanded-row labels. - tenantMember.audit.expanded.*: expanded-row labels added so the shared drawer treatment renders cleanly under tenant scope.
2026-05-26 12:04:08 +00:00
// ListSystemAuditLog godoc
// @Summary 获取平台审计日志
// @Description 返回 system-scope(tenant_id=0)的审计事件,覆盖 system.setting_changed / system.admin_promoted / system.admin_revoked 等 SystemAdmin 操作。按 id 倒序的游标分页。
// @Tags 审计日志
// @Produce json
// @Param after_id query int false "游标:返回 id 小于此值的记录(默认从最新开始)"
// @Param limit query int false "页大小,1-100,默认 50"
// @Param action query string false "按 action 精确过滤(如 system.setting_changed)"
// @Param outcome query string false "按 outcome 精确过滤(success / denied)"
// @Param actor query string false "按 actor_user_id 精确过滤"
// @Success 200 {object} auditLogListResponse
// @Failure 500 {object} errors.AppError
// @Security Bearer
// @Security ApiKeyAuth
// @Router /system/admin/audit-log [get]
//
// Mounted on /api/v1/system/admin/audit-log under the SystemAdmin()
// guard. Unlike ListTenantAuditLog this route is *not* tenant-scoped:
// the system_settings table, admin promote/revoke, and the
// apply-default-storage-quota bulk write all emit audit rows with
// tenant_id=0 (see audit_log.go for the action constants). Those rows
// would never surface in any tenant's audit feed, so this endpoint
// fixes the "wrote audit, can't see it" gap.
func (h *AuditLogHandler) ListSystemAuditLog(c *gin.Context) {
ctx := c.Request.Context()
// Cursor / page-size parsing mirrors ListTenantAuditLog so the
// frontend can share the same call shape; tolerant of garbage
// because the empty / first request shouldn't bounce.
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
}
}
q := &interfaces.AuditLogQuery{
AfterID: afterID,
Limit: limit,
Action: types.AuditAction(c.Query("action")),
Outcome: types.AuditOutcome(c.Query("outcome")),
ActorUserID: c.Query("actor"),
}
// tenant_id=0 is the system-scope convention; see
// AuditActionSystemSettingChanged comment in types/audit_log.go.
entries, err := h.auditService.List(ctx, 0, q)
if err != nil {
logger.Error(ctx, err)
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,
})
}