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
+79
View File
@@ -0,0 +1,79 @@
import { get } from '@/utils/request'
// AuditAction mirrors internal/types/audit_log.go's namespaced action
// enum. The dot prefix (`rbac.`) is deliberate — future PRs will add
// `kb.*` / `agent.*` namespaces without a schema change, and the
// backend already treats this column as an opaque string. Keep this
// list in sync with types/audit_log.go.
export type AuditAction =
| 'rbac.member_added'
| 'rbac.member_removed'
| 'rbac.member_role_changed'
| 'rbac.member_left'
| 'rbac.access_denied'
| string // forward-compat: future namespaces shouldn't break the type
export type AuditOutcome = 'success' | 'denied'
// AuditLog mirrors internal/types/audit_log.go. `details` is the JSONB
// blob — for role changes it carries `{"old_role":..., "new_role":...}`,
// for access_denied it carries `{"required_role":...}`. We keep it as
// an opaque record so future detail shapes don't need a frontend
// breaking change.
export interface AuditLog {
id: number
tenant_id: number
actor_user_id: string
actor_role: string
action: AuditAction
target_type: string
target_id: string
target_user_id: string
request_path: string
request_method: string
outcome: AuditOutcome
details: Record<string, unknown> | string | null
created_at: string
}
export interface ListAuditLogResponse {
success: boolean
data?: AuditLog[]
next_cursor?: number
message?: string
}
export interface ListAuditLogParams {
// Cursor: rows with id < after_id, newest first. Pass the
// previous response's `next_cursor`. Omit on first page.
after_id?: number
// Page size, 1–100. Server defaults to 50 if omitted.
limit?: number
// Optional filters; backend matches on equality.
action?: AuditAction
outcome?: AuditOutcome
actor?: string
}
/**
* List the per-tenant audit log. Cursor-paginated by descending id.
* Backend: GET /api/v1/tenants/:id/audit-log (Admin+).
*
* The first call should pass no cursor. Each subsequent page should
* pass `after_id = previousResponse.next_cursor` until next_cursor
* comes back as 0 (no older rows).
*/
export async function listAuditLog(
tenantId: number,
params: ListAuditLogParams = {},
): Promise<ListAuditLogResponse> {
const qs = new URLSearchParams()
if (params.after_id) qs.append('after_id', String(params.after_id))
if (params.limit) qs.append('limit', String(params.limit))
if (params.action) qs.append('action', params.action)
if (params.outcome) qs.append('outcome', params.outcome)
if (params.actor) qs.append('actor', params.actor)
const tail = qs.toString()
const url = `/api/v1/tenants/${tenantId}/audit-log${tail ? '?' + tail : ''}`
return (await get(url)) as unknown as ListAuditLogResponse
}
+35
View File
@@ -4376,5 +4376,40 @@ export default {
invalidRole: 'Role must be one of owner / admin / contributor / viewer.',
generic: 'Something went wrong. Please try again.',
},
tabs: {
members: 'Members',
audit: 'Audit log',
},
audit: {
tabLabel: 'Audit log',
description:
'Records every membership change and access denial in this tenant. Newest first. Repeated denials within a minute are deduplicated.',
refresh: 'Refresh',
loadMore: 'Load older',
end: 'End of log.',
empty: 'No audit events yet.',
forbidden: 'You do not have permission to view the audit log.',
systemActor: 'System',
requiredRole: 'Required role: {role}',
columns: {
time: 'Time',
actor: 'Actor',
action: 'Action',
target: 'Target',
path: 'Request',
outcome: 'Outcome',
},
action: {
'rbac.member_added': 'Member added',
'rbac.member_removed': 'Member removed',
'rbac.member_role_changed': 'Role changed',
'rbac.member_left': 'Member left',
'rbac.access_denied': 'Access denied',
},
outcome: {
success: 'Success',
denied: 'Denied',
},
},
},
}
+35
View File
@@ -4436,5 +4436,40 @@ export default {
invalidRole: "역할은 owner / admin / contributor / viewer 중 하나여야 합니다.",
generic: "오류가 발생했습니다. 다시 시도해 주세요.",
},
tabs: {
members: "멤버",
audit: "감사 로그",
},
audit: {
tabLabel: "감사 로그",
description:
"이 테넌트의 멤버 변경 및 접근 거부 이벤트를 최신순으로 기록합니다. 1분 이내의 반복 거부는 자동으로 중복 제거됩니다.",
refresh: "새로고침",
loadMore: "이전 항목 더 보기",
end: "마지막 항목입니다.",
empty: "감사 이벤트가 없습니다.",
forbidden: "감사 로그를 볼 권한이 없습니다.",
systemActor: "시스템",
requiredRole: "필요한 역할: {role}",
columns: {
time: "시간",
actor: "수행자",
action: "이벤트",
target: "대상",
path: "요청",
outcome: "결과",
},
action: {
"rbac.member_added": "멤버 추가",
"rbac.member_removed": "멤버 제거",
"rbac.member_role_changed": "역할 변경",
"rbac.member_left": "멤버 탈퇴",
"rbac.access_denied": "접근 거부",
},
outcome: {
success: "성공",
denied: "거부",
},
},
},
};
+35
View File
@@ -4336,5 +4336,40 @@ export default {
invalidRole: 'Роль должна быть owner / admin / contributor / viewer.',
generic: 'Что-то пошло не так. Попробуйте ещё раз.',
},
tabs: {
members: 'Участники',
audit: 'Журнал аудита',
},
audit: {
tabLabel: 'Журнал аудита',
description:
'Регистрирует все изменения участников и отказы в доступе в этом тенанте, в обратном хронологическом порядке. Повторные отказы в течение минуты дедуплицируются.',
refresh: 'Обновить',
loadMore: 'Показать ещё',
end: 'Конец журнала.',
empty: 'Событий аудита пока нет.',
forbidden: 'Нет прав для просмотра журнала аудита.',
systemActor: 'Система',
requiredRole: 'Требуемая роль: {role}',
columns: {
time: 'Время',
actor: 'Инициатор',
action: 'Событие',
target: 'Цель',
path: 'Запрос',
outcome: 'Результат',
},
action: {
'rbac.member_added': 'Добавлен участник',
'rbac.member_removed': 'Удалён участник',
'rbac.member_role_changed': 'Изменение роли',
'rbac.member_left': 'Участник вышел',
'rbac.access_denied': 'Доступ запрещён',
},
outcome: {
success: 'Успех',
denied: 'Отказ',
},
},
},
}
+35
View File
@@ -4369,5 +4369,40 @@ export default {
invalidRole: "角色必须是 owner / admin / contributor / viewer 之一。",
generic: "操作失败,请稍后重试。",
},
tabs: {
members: "成员",
audit: "审计日志",
},
audit: {
tabLabel: "审计日志",
description:
"记录当前租户的成员变更与访问拒绝事件,按时间倒序展示。一分钟内的重复拒绝会自动去重。",
refresh: "刷新",
loadMore: "加载更多",
end: "已经到底了。",
empty: "暂无审计事件。",
forbidden: "无权查看审计日志。",
systemActor: "系统",
requiredRole: "需要角色:{role}",
columns: {
time: "时间",
actor: "操作人",
action: "事件",
target: "目标",
path: "请求",
outcome: "结果",
},
action: {
"rbac.member_added": "新增成员",
"rbac.member_removed": "移除成员",
"rbac.member_role_changed": "角色变更",
"rbac.member_left": "成员退出",
"rbac.access_denied": "访问被拒",
},
outcome: {
success: "成功",
denied: "拒绝",
},
},
},
};
@@ -5,6 +5,12 @@
<p class="section-description">{{ $t('tenantMember.sectionDescription') }}</p>
</div>
<!-- Two-tab layout. The Members tab is the original UI verbatim; the
Audit log tab is gated to Admin+ because it can leak denial
histories and member-management activity that ordinary members
shouldn't see. -->
<t-tabs v-model="activeTab" placement="top">
<t-tab-panel value="members" :label="$t('tenantMember.tabs.members')">
<!-- Compact role-permissions matrix. Mirrors the OrganizationSettingsModal
pattern so Owners (and Admins, who can't add members) understand
what each role can actually do before they invite or promote. -->
@@ -161,6 +167,107 @@
</t-form-item>
</t-form>
</t-dialog>
</t-tab-panel>
<!-- Audit log tab. Only rendered for Admin+ because the backend
route is g.Admin()-gated; rendering it for lower roles would
just produce an unhelpful 403. -->
<t-tab-panel
v-if="canViewAudit"
value="audit"
:label="$t('tenantMember.audit.tabLabel')"
>
<div class="audit-panel">
<div class="audit-header">
<span class="audit-desc">{{ $t('tenantMember.audit.description') }}</span>
<t-button
size="small"
variant="outline"
:loading="auditLoading"
@click="reloadAuditLog"
>
{{ $t('tenantMember.audit.refresh') }}
</t-button>
</div>
<div v-if="auditError" class="error-inline">
<t-alert theme="error" :message="auditError">
<template #operation>
<t-button size="small" @click="reloadAuditLog">
{{ $t('tenantMember.retry') }}
</t-button>
</template>
</t-alert>
</div>
<div
v-else-if="!auditLoading && auditEntries.length === 0"
class="empty-state"
>
<t-empty :description="$t('tenantMember.audit.empty')" />
</div>
<t-table
v-else
row-key="id"
:data="auditEntries"
:columns="auditColumns"
size="medium"
hover
stripe
>
<template #created_at="{ row }">{{ formatDate(row.created_at) }}</template>
<template #actor="{ row }">
<span class="audit-actor">
{{ row.actor_user_id ? actorDisplayName(row.actor_user_id) : $t('tenantMember.audit.systemActor') }}
<span v-if="row.actor_role" class="audit-actor-role">
· {{ $t('tenantMember.role.' + row.actor_role) }}
</span>
</span>
</template>
<template #action="{ row }">
<t-tag :theme="auditActionTheme(row.action)" size="small">
{{ formatAuditAction(row.action) }}
</t-tag>
</template>
<template #target="{ row }">
<span class="audit-target">{{ formatAuditTarget(row) }}</span>
</template>
<template #request_path="{ row }">
<span class="audit-path">
<span v-if="row.request_method" class="audit-method">{{ row.request_method }}</span>
{{ row.request_path || '-' }}
</span>
</template>
<template #outcome="{ row }">
<t-tag :theme="auditOutcomeTheme(row.outcome)" size="small">
{{ $t('tenantMember.audit.outcome.' + row.outcome) }}
</t-tag>
</template>
</t-table>
<!-- Footer: load-more cursor. We avoid actual infinite-scroll
(IntersectionObserver) because the table sits inside a
scroll container that's already deep in the settings
panel; an explicit button keeps behaviour predictable
under unusual layouts. -->
<div class="audit-footer">
<t-button
v-if="auditHasMore"
size="small"
variant="outline"
:loading="auditLoading"
@click="loadAuditLog(false)"
>
{{ $t('tenantMember.audit.loadMore') }}
</t-button>
<span v-else-if="auditEntries.length > 0" class="audit-end">
{{ $t('tenantMember.audit.end') }}
</span>
</div>
</div>
</t-tab-panel>
</t-tabs>
</div>
</template>
@@ -178,6 +285,12 @@ import {
type TenantMember,
type TenantRole,
} from '@/api/tenant/members'
import {
listAuditLog,
type AuditLog,
type AuditAction,
type AuditOutcome,
} from '@/api/tenant/audit-log'
const { t, locale } = useI18n()
const authStore = useAuthStore()
@@ -191,6 +304,22 @@ const addDialogVisible = ref(false)
const addFormRef = ref<any>(null)
const searchQuery = ref('')
// Tab state. Default to "members" — audit-log is the secondary view
// even for admins, who still mostly come here to manage members.
const activeTab = ref<'members' | 'audit'>('members')
// Audit-log state. Cursor-paginated by descending id; once
// `next_cursor` comes back as 0 we stop offering "load more". Page
// size is 50 (server default), large enough to feel responsive while
// keeping the table tractable on a small settings panel.
const auditEntries = ref<AuditLog[]>([])
const auditLoading = ref(false)
const auditError = ref('')
const auditCursor = ref<number>(0) // 0 = "from the top"
const auditHasMore = ref(true)
const auditLoadedOnce = ref(false)
const AUDIT_PAGE_SIZE = 50
// Add dialog model — reset on each open. Default role is contributor:
// inviting a fresh member with viewer is too restrictive for the
// expected "let them collaborate on KBs" use case, and admin/owner
@@ -211,6 +340,15 @@ const currentRole = computed<TenantRole | ''>(() => (authStore.currentTenantRole
const canManage = computed(
() => currentRole.value === 'owner' || authStore.canAccessAllTenants === true,
)
// Admin+ (and cross-tenant superusers) can view the audit log. Mirrors
// the server's g.Admin() guard on /tenants/:id/audit-log so we don't
// render a tab that would just 403.
const canViewAudit = computed(
() =>
currentRole.value === 'owner' ||
currentRole.value === 'admin' ||
authStore.canAccessAllTenants === true,
)
// Anyone except the last Owner can leave; we additionally hide the
// button for Owner-the-only-one because clicking would just bounce off
// the server's last-Owner check. The server is still the source of
@@ -371,6 +509,144 @@ async function loadMembers() {
}
}
// ---- Audit-log helpers --------------------------------------------------
const auditColumns = computed(() => [
{ colKey: 'created_at', title: t('tenantMember.audit.columns.time'), width: 170 },
{ colKey: 'actor', title: t('tenantMember.audit.columns.actor'), width: 200, ellipsis: true },
{ colKey: 'action', title: t('tenantMember.audit.columns.action'), width: 170 },
{ colKey: 'target', title: t('tenantMember.audit.columns.target'), ellipsis: true },
{ colKey: 'request_path', title: t('tenantMember.audit.columns.path'), ellipsis: true },
{ colKey: 'outcome', title: t('tenantMember.audit.columns.outcome'), width: 110 },
])
// Action chip colour: rejection events are loud (danger) so an
// operator can scan a chronological feed and immediately spot abuse;
// member adds are reassuring green; removals/role changes warning
// orange because they're worth a second look but aren't intrinsically
// suspicious.
function auditActionTheme(
action: AuditAction,
): 'success' | 'warning' | 'danger' | 'primary' | 'default' {
switch (action) {
case 'rbac.access_denied':
return 'danger'
case 'rbac.member_added':
return 'success'
case 'rbac.member_removed':
case 'rbac.member_left':
case 'rbac.member_role_changed':
return 'warning'
default:
return 'default'
}
}
function auditOutcomeTheme(o: AuditOutcome): 'success' | 'danger' | 'default' {
if (o === 'denied') return 'danger'
if (o === 'success') return 'success'
return 'default'
}
// Render a `rbac.member_added` action either via i18n (when the key
// exists) or as a humanised fallback. The fallback matters because
// future PRs may push new namespaces (e.g. `kb.shared`) that aren't
// in the locale file yet — we still want them to render readably.
function formatAuditAction(action: AuditAction): string {
const key = `tenantMember.audit.action.${action}`
const translated = t(key)
if (translated && translated !== key) return translated
return action
}
// Resolve a user id to a display name using the already-loaded member
// list. Falls back to the raw uuid when the actor is no longer a
// member (e.g. a long-since-removed contributor whose denial events
// are still on the feed).
function actorDisplayName(userId: string): string {
const m = members.value.find((x) => x.user_id === userId)
return m?.username || m?.email || userId
}
function formatAuditTarget(row: AuditLog): string {
if (row.target_user_id) return actorDisplayName(row.target_user_id)
if (row.target_id) {
return row.target_type ? `${row.target_type}:${row.target_id}` : row.target_id
}
// Role-change details often carry old_role/new_role; surface that
// inline so an operator doesn't have to expand the row to see
// what actually changed.
if (row.action === 'rbac.member_role_changed' && row.details && typeof row.details === 'object') {
const d = row.details as Record<string, unknown>
if (d.old_role && d.new_role) {
return `${d.old_role} → ${d.new_role}`
}
}
if (row.action === 'rbac.access_denied' && row.details && typeof row.details === 'object') {
const d = row.details as Record<string, unknown>
if (d.required_role) return t('tenantMember.audit.requiredRole', { role: d.required_role })
}
return '-'
}
// loadAuditLog fetches a page. `reset=true` discards the current
// list and starts from cursor=0. Used by the refresh button and the
// initial tab-switch trigger.
async function loadAuditLog(reset: boolean) {
if (!activeTenantId.value || !canViewAudit.value) return
if (auditLoading.value) return
if (!reset && !auditHasMore.value) return
auditLoading.value = true
auditError.value = ''
try {
const resp = await listAuditLog(activeTenantId.value, {
after_id: reset ? undefined : auditCursor.value || undefined,
limit: AUDIT_PAGE_SIZE,
})
if (resp.success) {
const rows = resp.data || []
if (reset) {
auditEntries.value = rows
} else {
auditEntries.value = [...auditEntries.value, ...rows]
}
auditCursor.value = resp.next_cursor || 0
// The server returns next_cursor=0 when the page is empty OR
// when the last row is the smallest possible id. Both mean
// "stop paginating".
auditHasMore.value = !!resp.next_cursor && rows.length > 0
auditLoadedOnce.value = true
} else {
auditError.value = resp.message || t('tenantMember.errors.generic')
}
} catch (err: any) {
const status = err?.status
if (status === 403) {
auditError.value = t('tenantMember.audit.forbidden')
} else {
auditError.value = err?.message || t('tenantMember.errors.generic')
}
} finally {
auditLoading.value = false
}
}
function reloadAuditLog() {
auditCursor.value = 0
auditHasMore.value = true
loadAuditLog(true)
}
// Lazy-load the audit log on first tab switch. Fetching it on every
// settings-panel mount would waste a request for the (common) case
// where the operator only wants to manage members.
watch(activeTab, (tab) => {
if (tab === 'audit' && !auditLoadedOnce.value) {
loadAuditLog(true)
}
})
function openAddDialog() {
addForm.email = ''
addForm.role = 'contributor'
@@ -667,4 +943,64 @@ onMounted(() => {
display: flex;
justify-content: center;
}
.audit-panel {
display: flex;
flex-direction: column;
gap: 12px;
padding-top: 8px;
}
.audit-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
.audit-desc {
font-size: 13px;
color: var(--td-text-color-secondary);
}
}
.audit-actor {
font-size: 13px;
color: var(--td-text-color-primary);
.audit-actor-role {
color: var(--td-text-color-secondary);
margin-left: 2px;
}
}
.audit-target {
font-size: 13px;
color: var(--td-text-color-primary);
word-break: break-all;
}
.audit-path {
font-family: var(--td-font-family-mono, monospace);
font-size: 12px;
color: var(--td-text-color-secondary);
.audit-method {
display: inline-block;
font-weight: 600;
color: var(--td-text-color-primary);
margin-right: 4px;
}
}
.audit-footer {
display: flex;
justify-content: center;
align-items: center;
padding: 12px 0 4px;
.audit-end {
font-size: 12px;
color: var(--td-text-color-disabled);
}
}
</style>