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.
This commit is contained in:
wizardchen
2026-05-26 20:04:08 +08:00
committed by lyingbug
parent 9cce0c8e5e
commit acdc0a526f
9 changed files with 1534 additions and 55 deletions
+42
View File
@@ -419,3 +419,45 @@ export async function applyDefaultStorageQuotaToAllTenants(): Promise<ApplyDefau
const response = await post('/api/v1/system/admin/tenants/apply-default-storage-quota')
return response as unknown as ApplyDefaultStorageQuotaResult
}
// ---- Platform Audit Log (system-scope) ----
// We reuse the AuditLog / ListAuditLogParams types from the tenant
// audit-log module — the row shape is identical, only the route
// differs (tenant_id=0 rows aren't visible via the per-tenant endpoint).
// Re-exported here so SystemSettings.vue doesn't need to cross-import
// from a tenant-specific module to consume system-scope feeds.
export type {
AuditLog,
AuditAction,
AuditOutcome,
ListAuditLogParams,
ListAuditLogResponse,
} from '@/api/tenant/audit-log'
import type { ListAuditLogParams, ListAuditLogResponse } from '@/api/tenant/audit-log'
/**
* List the platform-wide audit log (system-scope, tenant_id=0).
*
* Backend: GET /api/v1/system/admin/audit-log (SystemAdmin only).
* Covers system.setting_changed / system.admin_promoted /
* system.admin_revoked etc. — events emitted by SystemAdmin actions.
*
* Cursor-paginated by descending id: the first call should pass no
* cursor, each subsequent page should pass `after_id =
* previousResponse.next_cursor` until next_cursor comes back as 0.
*/
export async function listSystemAuditLog(
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/system/admin/audit-log${tail ? '?' + tail : ''}`
return (await get(url)) as unknown as ListAuditLogResponse
}
+57
View File
@@ -2674,6 +2674,56 @@ export default {
success: 'Updated storage quota for {count} tenants to {gb} GB',
failed: 'Failed to apply to all tenants',
},
audit: {
tabLabel: 'Audit log',
description:
'Platform-level events: system setting changes, system admin grants/revocations, bulk quota syncs. Newest first.',
refresh: 'Refresh',
retry: 'Retry',
loading: 'Loading…',
end: 'End of feed.',
empty: 'No platform-level audit events yet.',
forbidden: 'Not allowed to view the platform audit log.',
systemActor: 'System',
errors: {
generic: 'Failed to load audit log',
},
actorRole: {
system_admin: 'System Admin',
},
columns: {
time: 'Time',
actor: 'Actor',
action: 'Event',
target: 'Target',
path: 'Request',
outcome: 'Result',
},
action: {
'system.setting_changed': 'System setting changed',
'system.admin_promoted': 'System admin granted',
'system.admin_revoked': 'System admin revoked',
},
outcome: {
success: 'Success',
denied: 'Denied',
},
target: {
bulkQuota: 'Bulk sync: default storage quota',
bulkQuotaDiff: 'Applied to {count} tenants ({gb} GB)',
promoteIdempotent: 'Target was already a system admin (idempotent)',
revokeNoop: 'Target was not a system admin (idempotent)',
requiredRole: 'Required role: {role}',
valueNull: '(unset)',
},
expanded: {
actorId: 'Actor ID',
targetUserId: 'Target user ID',
targetType: 'Target type',
targetId: 'Target ID',
details: 'Raw details',
},
},
}
},
mcp: {
@@ -4709,6 +4759,13 @@ export default {
success: 'Success',
denied: 'Denied',
},
expanded: {
actorId: 'Actor ID',
targetUserId: 'Target user ID',
targetType: 'Target type',
targetId: 'Target ID',
details: 'Raw details',
},
},
},
tenantInvitation: {
+57
View File
@@ -1916,6 +1916,56 @@ export default {
success: "{count}개 테넌트의 저장 용량을 {gb} GB로 갱신했습니다",
failed: "모든 테넌트에 적용 실패",
},
audit: {
tabLabel: "감사 로그",
description:
"플랫폼 수준의 작업을 기록합니다: 시스템 설정 변경, 시스템 관리자 부여/회수, 할당량 일괄 동기화 등. 최신순으로 표시됩니다.",
refresh: "새로고침",
retry: "다시 시도",
loading: "로딩 중...",
end: "더 이상 항목이 없습니다.",
empty: "플랫폼 감사 이벤트가 없습니다.",
forbidden: "플랫폼 감사 로그를 볼 수 있는 권한이 없습니다.",
systemActor: "시스템",
errors: {
generic: "감사 로그 로드 실패",
},
actorRole: {
system_admin: "시스템 관리자",
},
columns: {
time: "시간",
actor: "작업자",
action: "이벤트",
target: "대상",
path: "요청",
outcome: "결과",
},
action: {
"system.setting_changed": "시스템 설정 변경",
"system.admin_promoted": "시스템 관리자 부여",
"system.admin_revoked": "시스템 관리자 회수",
},
outcome: {
success: "성공",
denied: "거부",
},
target: {
bulkQuota: "일괄 동기화: 기본 저장 할당량",
bulkQuotaDiff: "{count}개 테넌트에 적용됨 ({gb} GB)",
promoteIdempotent: "이미 시스템 관리자임 (멱등)",
revokeNoop: "원래 시스템 관리자가 아니었음 (멱등)",
requiredRole: "필요 역할: {role}",
valueNull: "(없음)",
},
expanded: {
actorId: "작업자 ID",
targetUserId: "대상 사용자 ID",
targetType: "대상 유형",
targetId: "대상 ID",
details: "원본 상세",
},
},
},
},
mcp: {
@@ -4769,6 +4819,13 @@ export default {
success: "성공",
denied: "거부",
},
expanded: {
actorId: "작업자 ID",
targetUserId: "대상 사용자 ID",
targetType: "대상 유형",
targetId: "대상 ID",
details: "원본 상세",
},
},
},
tenantInvitation: {
+57
View File
@@ -1709,6 +1709,56 @@ export default {
confirmBody: 'Перезаписать квоту хранилища всех существующих тенантов значением {value} ГБ. Тенанты, чью квоту вручную правили эксплуатация, также будут перезаписаны. Продолжить?',
success: 'Обновлена квота хранилища у {count} тенантов: {gb} ГБ',
failed: 'Ошибка применения ко всем тенантам'
},
audit: {
tabLabel: 'Журнал аудита',
description:
'События уровня платформы: изменения системных настроек, выдача/отзыв роли системного администратора, массовая синхронизация квот. Сортировка от новых к старым.',
refresh: 'Обновить',
retry: 'Повторить',
loading: 'Загрузка…',
end: 'Конец списка.',
empty: 'Событий аудита платформы пока нет.',
forbidden: 'Нет прав на просмотр журнала аудита платформы.',
systemActor: 'Система',
errors: {
generic: 'Не удалось загрузить журнал аудита'
},
actorRole: {
system_admin: 'Системный администратор'
},
columns: {
time: 'Время',
actor: 'Кто',
action: 'Событие',
target: 'Цель',
path: 'Запрос',
outcome: 'Результат'
},
action: {
'system.setting_changed': 'Изменена системная настройка',
'system.admin_promoted': 'Выдан системный администратор',
'system.admin_revoked': 'Отозван системный администратор'
},
outcome: {
success: 'Успешно',
denied: 'Отказано'
},
target: {
bulkQuota: 'Массовая синхронизация: квота хранилища по умолчанию',
bulkQuotaDiff: 'Применено к {count} тенантам ({gb} ГБ)',
promoteIdempotent: 'Уже системный администратор (идемпотентно)',
revokeNoop: 'И так не был системным администратором (идемпотентно)',
requiredRole: 'Требуемая роль: {role}',
valueNull: '(не задано)'
},
expanded: {
actorId: 'ID инициатора',
targetUserId: 'ID целевого пользователя',
targetType: 'Тип цели',
targetId: 'ID цели',
details: 'Сырые детали'
}
}
}
},
@@ -4661,6 +4711,13 @@ export default {
success: 'Успех',
denied: 'Отказ',
},
expanded: {
actorId: 'ID инициатора',
targetUserId: 'ID целевого пользователя',
targetType: 'Тип цели',
targetId: 'ID цели',
details: 'Сырые детали',
},
},
},
}
+57
View File
@@ -1895,6 +1895,56 @@ export default {
success: "已将 {count} 个租户的存储配额更新为 {gb} GB",
failed: "应用到所有租户失败",
},
audit: {
tabLabel: "审计日志",
description:
"记录平台级操作:系统设置变更、系统管理员授予/回收、配额批量同步等。按时间倒序展示。",
refresh: "刷新",
retry: "重试",
loading: "加载中...",
end: "已经到底了。",
empty: "暂无平台级审计事件。",
forbidden: "无权查看平台审计日志。",
systemActor: "系统",
errors: {
generic: "加载审计日志失败",
},
actorRole: {
system_admin: "系统管理员",
},
columns: {
time: "时间",
actor: "操作人",
action: "事件",
target: "目标",
path: "请求",
outcome: "结果",
},
action: {
"system.setting_changed": "系统设置变更",
"system.admin_promoted": "授予系统管理员",
"system.admin_revoked": "回收系统管理员",
},
outcome: {
success: "成功",
denied: "拒绝",
},
target: {
bulkQuota: "批量同步:默认存储配额",
bulkQuotaDiff: "应用到 {count} 个租户({gb} GB)",
promoteIdempotent: "目标已是系统管理员(幂等)",
revokeNoop: "目标本就不是系统管理员(幂等)",
requiredRole: "需要角色:{role}",
valueNull: "(空)",
},
expanded: {
actorId: "操作人 ID",
targetUserId: "目标用户 ID",
targetType: "目标类型",
targetId: "目标 ID",
details: "原始详情",
},
},
},
},
mcp: {
@@ -4701,6 +4751,13 @@ export default {
success: "成功",
denied: "拒绝",
},
expanded: {
actorId: "操作人 ID",
targetUserId: "目标用户 ID",
targetType: "目标类型",
targetId: "目标 ID",
details: "原始详情",
},
},
},
tenantInvitation: {
+316 -50
View File
@@ -286,14 +286,14 @@
route is g.Admin()-gated; rendering it for lower roles would
just produce an unhelpful 403. Lazy-loaded on first open. -->
<t-drawer v-if="canViewAudit" v-model:visible="auditDrawerVisible" :header="$t('tenantMember.audit.tabLabel')"
drawer-class-name="tenant-members-audit-drawer" size="720px" :footer="false" placement="right" destroy-on-close>
drawer-class-name="tenant-members-audit-drawer" size="880px" :footer="false" placement="right" destroy-on-close>
<div class="audit-drawer-inner audit-panel audit-panel--drawer">
<div class="audit-header">
<span class="audit-desc">{{ $t('tenantMember.audit.description') }}</span>
<t-button theme="primary" variant="outline" shape="square" size="small" class="audit-refresh-btn"
:loading="auditLoading" :title="$t('tenantMember.audit.refresh')"
:aria-label="$t('tenantMember.audit.refresh')" @click="reloadAuditLog">
<t-button variant="text" size="small" class="audit-refresh-btn"
:loading="auditLoading" :disabled="auditLoading" @click="reloadAuditLog">
<template #icon><t-icon name="refresh" /></template>
{{ $t('tenantMember.audit.refresh') }}
</t-button>
</div>
@@ -316,37 +316,84 @@
</div>
<div v-else class="audit-scroll-area narrow-scrollbar audit-drawer-branch" ref="auditScrollRoot">
<div class="data-table-shell">
<t-table row-key="id" :data="auditEntries" :columns="auditColumns" size="medium" hover stripe>
<template #created_at="{ row }">{{ formatDate(row.created_at) }}</template>
<div class="data-table-shell audit-table-shell">
<t-table
row-key="id"
:data="auditEntries"
:columns="auditColumns"
size="medium"
hover
expand-on-row-click
:expanded-row-keys="auditExpandedRowKeys"
@expand-change="onAuditExpandChange"
>
<template #created_at="{ row }">
<div class="audit-time">
<span class="audit-time-date">{{ formatAuditDatePart(row.created_at) }}</span>
<span class="audit-time-clock">{{ formatAuditTimePart(row.created_at) }}</span>
</div>
</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) }}
<div class="audit-actor">
<span class="audit-actor-name">
{{ row.actor_user_id ? actorDisplayName(row.actor_user_id) :
$t('tenantMember.audit.systemActor') }}
</span>
</span>
<span v-if="row.actor_role" class="audit-actor-role">
{{ $t('tenantMember.role.' + row.actor_role) }}
</span>
</div>
</template>
<template #action="{ row }">
<t-tag :theme="auditActionTheme(row.action)" size="small">
<t-tag :theme="auditActionTheme(row.action)" size="small" variant="light-outline">
{{ formatAuditAction(row.action) }}
</t-tag>
</template>
<template #target="{ row }">
<span class="audit-target">{{ formatAuditTarget(row) }}</span>
<div class="audit-target">
<span v-if="auditTargetSubject(row)" class="audit-target-key">{{ auditTargetSubject(row) }}</span>
<span v-if="auditTargetDiff(row)" class="audit-target-diff">{{ auditTargetDiff(row) }}</span>
<span v-else-if="!auditTargetSubject(row)" class="audit-target-empty">—</span>
</div>
</template>
<template #request_path="{ row }">
<span class="audit-path">
<span v-if="row.request_path" class="audit-path">
<span v-if="row.request_method" class="audit-method">{{ row.request_method }}</span>
{{ row.request_path || '-' }}
{{ row.request_path }}
</span>
<span v-else class="audit-target-empty">—</span>
</template>
<template #outcome="{ row }">
<t-tag :theme="auditOutcomeTheme(row.outcome)" size="small">
<t-tag :theme="auditOutcomeTheme(row.outcome)" size="small" variant="light">
{{ $t('tenantMember.audit.outcome.' + row.outcome) }}
</t-tag>
</template>
<template #expandedRow="{ row }">
<div class="audit-expanded">
<div class="audit-expanded-grid">
<div class="audit-expanded-cell">
<span class="audit-expanded-label">{{ $t('tenantMember.audit.expanded.actorId') }}</span>
<span class="audit-expanded-value mono">{{ row.actor_user_id || '—' }}</span>
</div>
<div v-if="row.target_user_id" class="audit-expanded-cell">
<span class="audit-expanded-label">{{ $t('tenantMember.audit.expanded.targetUserId') }}</span>
<span class="audit-expanded-value mono">{{ row.target_user_id }}</span>
</div>
<div v-if="row.target_type" class="audit-expanded-cell">
<span class="audit-expanded-label">{{ $t('tenantMember.audit.expanded.targetType') }}</span>
<span class="audit-expanded-value mono">{{ row.target_type }}</span>
</div>
<div v-if="row.target_id" class="audit-expanded-cell">
<span class="audit-expanded-label">{{ $t('tenantMember.audit.expanded.targetId') }}</span>
<span class="audit-expanded-value mono">{{ row.target_id }}</span>
</div>
</div>
<div class="audit-expanded-details">
<span class="audit-expanded-label">{{ $t('tenantMember.audit.expanded.details') }}</span>
<pre class="audit-expanded-json mono">{{ auditDetailsJSON(row) }}</pre>
</div>
</div>
</template>
</t-table>
</div>
@@ -819,33 +866,58 @@ async function doRevokeInvitation(row: TenantInvitation) {
// ---- Audit-log helpers --------------------------------------------------
/** ellipsis 自带的 Tooltip 默认主题在深色抽屉语境下易产生暗底黑字 */
const auditTableEllipsisTooltip = { theme: 'light' as const }
// Stacked "date / time" cell — mirrors SystemSettings audit table. When
// 50 events fall in the same minute, ellipsing a flat string makes them
// indistinguishable; splitting on two lines keeps the seconds visible
// without eating horizontal budget the diff column needs.
const auditColumns = computed(() => [
{ colKey: 'created_at', title: t('tenantMember.audit.columns.time'), width: 150 },
{
colKey: 'actor',
title: t('tenantMember.audit.columns.actor'),
minWidth: 140,
ellipsis: auditTableEllipsisTooltip,
},
{ colKey: 'created_at', title: t('tenantMember.audit.columns.time'), width: 120 },
{ colKey: 'actor', title: t('tenantMember.audit.columns.actor'), width: 180 },
{ colKey: 'action', title: t('tenantMember.audit.columns.action'), width: 130 },
{
colKey: 'target',
title: t('tenantMember.audit.columns.target'),
minWidth: 140,
ellipsis: auditTableEllipsisTooltip,
// No fixed width / no ellipsis: this is where the role-diff and
// denied-action context live. Wrap rather than clip — losing the
// "Owner → Admin" half of a role change defeats the point.
minWidth: 200,
},
{
colKey: 'request_path',
title: t('tenantMember.audit.columns.path'),
minWidth: 140,
ellipsis: auditTableEllipsisTooltip,
minWidth: 160,
},
{ colKey: 'outcome', title: t('tenantMember.audit.columns.outcome'), width: 90 },
{ colKey: 'outcome', title: t('tenantMember.audit.columns.outcome'), width: 80, align: 'center' as const },
])
function formatAuditDatePart(s: string | undefined): string {
if (!s) return '-'
try {
return new Intl.DateTimeFormat(locale.value || 'zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(new Date(s))
} catch {
return s
}
}
function formatAuditTimePart(s: string | undefined): string {
if (!s) return ''
try {
return new Intl.DateTimeFormat(locale.value || 'zh-CN', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}).format(new Date(s))
} catch {
return ''
}
}
// 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
@@ -896,25 +968,62 @@ function actorDisplayName(userId: string): string {
return userId
}
function formatAuditTarget(row: AuditLog): string {
// Split target rendering into a "subject" (who was acted on) and a
// "diff" (what changed). The cell template stacks them with the
// subject on the first line, diff on the second. Returns '' when a
// piece is unavailable so the v-if branches drop the wrapper cleanly.
function auditDetailsObject(row: AuditLog): Record<string, unknown> | null {
if (row.details && typeof row.details === 'object') {
return row.details as Record<string, unknown>
}
return null
}
function auditTargetSubject(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}`
return ''
}
function auditTargetDiff(row: AuditLog): string {
const d = auditDetailsObject(row)
if (!d) return ''
if (row.action === 'rbac.member_role_changed') {
if (d.old_role && d.new_role) return `${d.old_role} → ${d.new_role}`
}
if (row.action === 'rbac.access_denied') {
if (typeof d.required_role === 'string') {
return t('tenantMember.audit.requiredRole', { role: d.required_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 })
if (row.action === 'rbac.invitation_sent' || row.action === 'rbac.invitation_revoked') {
if (typeof d.role === 'string') return String(d.role)
}
return ''
}
// Expanded row state — local set of ids the user has opened. We keep
// it ephemeral (not persisted) so reopening the drawer always starts
// in the collapsed view.
const auditExpandedRowKeys = ref<number[]>([])
function onAuditExpandChange(value: (string | number)[]) {
auditExpandedRowKeys.value = value
.map((v) => (typeof v === 'number' ? v : Number(v)))
.filter((v) => Number.isFinite(v))
}
function auditDetailsJSON(row: AuditLog): string {
if (row.details === null || row.details === undefined) return '{}'
if (typeof row.details === 'string') return row.details
try {
return JSON.stringify(row.details, null, 2)
} catch {
return String(row.details)
}
return '-'
}
// loadAuditLog fetches a page. `reset=true` discards the current
@@ -1457,6 +1566,47 @@ watch(
}
}
/* Audit drawer's data-table-shell variant: only used inside the audit
drawer, so members-list specific tweaks (role-cell, role-select)
from the base block don't kick in. The selector is more specific
than `.data-table-shell` alone so the per-cell overrides win. */
.audit-table-shell {
&:deep(.t-table td),
&:deep(.t-table th) {
/* See SystemSettings audit table: middle keeps the row weight
unified across single-line tag cells and multi-line diff cells. */
vertical-align: middle;
padding-top: 14px;
padding-bottom: 14px;
}
/* Sticky thead so the column labels survive long scrolls. The drawer's
`.audit-scroll-area` is the scroll container; top:0 pins the
headers there. z-index sits above hover/expand backgrounds, and
the inset shadow replaces the row separator that would otherwise
scroll out of frame. */
&:deep(thead th) {
position: sticky;
top: 0;
z-index: 2;
background-color: var(--td-bg-color-secondarycontainer) !important;
box-shadow: inset 0 -1px 0 var(--td-component-stroke);
}
&:deep(.t-table tbody tr:hover > td) {
background-color: var(--td-bg-color-container-hover);
}
&:deep(.t-table tbody tr.t-table__expanded-row > td) {
padding: 0 !important;
background-color: transparent;
}
&:deep(.t-table__expandable-icon-cell) {
width: 36px;
}
}
.permissions-compact {
padding: 8px;
@@ -1820,26 +1970,79 @@ watch(
margin: 0;
}
.audit-time {
display: flex;
flex-direction: column;
gap: 2px;
line-height: 1.3;
.audit-time-date {
font-size: 12px;
color: var(--td-text-color-secondary);
}
.audit-time-clock {
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
font-variant-numeric: tabular-nums;
}
}
.audit-actor {
font-size: 13px;
color: var(--td-text-color-primary);
display: flex;
flex-direction: column;
gap: 2px;
line-height: 1.3;
min-width: 0;
.audit-actor-name {
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.audit-actor-role {
font-size: 12px;
color: var(--td-text-color-secondary);
margin-left: 2px;
}
}
.audit-target {
font-size: 13px;
color: var(--td-text-color-primary);
word-break: break-all;
display: flex;
flex-direction: column;
gap: 4px;
line-height: 1.35;
min-width: 0;
padding: 2px 0;
.audit-target-key {
font-size: 13px;
color: var(--td-text-color-primary);
word-break: break-all;
}
.audit-target-diff {
font-size: 12px;
color: var(--td-text-color-secondary);
font-family: var(--td-font-family-mono, monospace);
word-break: break-all;
line-height: 1.4;
}
.audit-target-empty {
color: var(--td-text-color-placeholder);
}
}
.audit-path {
font-family: var(--td-font-family-mono, monospace);
font-size: 12px;
color: var(--td-text-color-secondary);
word-break: break-all;
.audit-method {
display: inline-block;
@@ -1848,6 +2051,69 @@ watch(
margin-right: 4px;
}
}
/* Expandable row body. Background steps off-card so the nested
context is clearly distinct from the row strip above it. Mirrors
the platform audit drawer in SystemSettings.vue. */
.audit-expanded {
display: flex;
flex-direction: column;
gap: 12px;
padding: 12px 16px;
background: var(--td-bg-color-container-hover);
}
.audit-expanded-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px 18px;
}
.audit-expanded-cell {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.audit-expanded-label {
font-size: 11px;
font-weight: 600;
color: var(--td-text-color-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.audit-expanded-value {
font-size: 12px;
color: var(--td-text-color-primary);
word-break: break-all;
}
.audit-expanded-details {
display: flex;
flex-direction: column;
gap: 4px;
}
.audit-expanded-json {
margin: 0;
padding: 10px 12px;
font-size: 12px;
line-height: 1.55;
color: var(--td-text-color-primary);
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
white-space: pre-wrap;
word-break: break-all;
max-height: 280px;
overflow: auto;
}
.mono {
font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
}
</style>
<style lang="less">
+855 -3
View File
@@ -33,7 +33,23 @@
-->
<div class="system-settings">
<div class="section-header">
<h2>{{ t('system.globalSettings.title') }}</h2>
<div class="section-header-row">
<h2>{{ t('system.globalSettings.title') }}</h2>
<!-- Platform audit-log entry. SystemAdmin already gated the
whole view via meta.requiresSystemAdmin (router/index.ts)
so we don't re-check role here — every visitor of this
page is eligible. Mirrors the audit button placement in
tenant settings (frontend/src/views/settings/TenantMembers.vue). -->
<t-button
variant="text"
size="small"
class="header-audit-btn"
@click="openAuditDrawer"
>
<template #icon><t-icon name="history" /></template>
{{ t('system.globalSettings.audit.tabLabel') }}
</t-button>
</div>
<p class="section-description">
{{ t('system.globalSettings.description') }}
</p>
@@ -335,11 +351,151 @@
</div>
</div>
</div>
<!-- Platform audit-log drawer. Lazy-loaded on first open; closing
and reopening doesn't re-fetch (refresh is explicit via the
button inside the drawer). Backend route is SystemAdmin-gated,
and this whole view is too, so we don't bother with a role
check — any visitor here is eligible to read the feed. -->
<t-drawer
v-model:visible="auditDrawerVisible"
:header="t('system.globalSettings.audit.tabLabel')"
drawer-class-name="system-settings-audit-drawer"
size="880px"
:footer="false"
placement="right"
destroy-on-close
>
<div class="audit-drawer-inner audit-panel audit-panel--drawer">
<div class="audit-header">
<span class="audit-desc">{{ t('system.globalSettings.audit.description') }}</span>
<t-button
variant="text"
size="small"
class="audit-refresh-btn"
:loading="auditLoading"
:disabled="auditLoading"
@click="reloadAuditLog"
>
<template #icon><t-icon name="refresh" /></template>
{{ t('system.globalSettings.audit.refresh') }}
</t-button>
</div>
<div class="audit-drawer-fill">
<div v-if="auditError" class="audit-drawer-branch audit-drawer-branch--error">
<div class="error-inline">
<t-alert theme="error" :message="auditError">
<template #operation>
<t-button size="small" @click="reloadAuditLog">
{{ t('system.globalSettings.audit.retry') }}
</t-button>
</template>
</t-alert>
</div>
</div>
<div
v-else-if="!auditLoading && auditEntries.length === 0"
class="audit-drawer-branch audit-drawer-branch--empty empty-state empty-state--audit"
>
<t-empty :description="t('system.globalSettings.audit.empty')" />
</div>
<div v-else class="audit-scroll-area narrow-scrollbar audit-drawer-branch" ref="auditScrollRoot">
<div class="data-table-shell audit-table-shell">
<t-table
row-key="id"
:data="auditEntries"
:columns="auditColumns"
size="medium"
hover
expand-on-row-click
:expanded-row-keys="auditExpandedRowKeys"
@expand-change="onAuditExpandChange"
>
<template #created_at="{ row }">
<div class="audit-time">
<span class="audit-time-date">{{ formatAuditDatePart(row.created_at) }}</span>
<span class="audit-time-clock">{{ formatAuditTimePart(row.created_at) }}</span>
</div>
</template>
<template #actor="{ row }">
<div class="audit-actor">
<span class="audit-actor-name">
{{ row.actor_user_id ? auditActorLabel(row.actor_user_id) :
t('system.globalSettings.audit.systemActor') }}
</span>
<span v-if="row.actor_role" class="audit-actor-role">
{{ auditActorRoleLabel(row.actor_role) }}
</span>
</div>
</template>
<template #action="{ row }">
<t-tag :theme="auditActionTheme(row.action)" size="small" variant="light-outline">
{{ formatAuditAction(row.action) }}
</t-tag>
</template>
<template #target="{ row }">
<div class="audit-target">
<span v-if="auditTargetKey(row)" class="audit-target-key">{{ auditTargetKey(row) }}</span>
<span v-if="auditTargetDiff(row)" class="audit-target-diff">{{ auditTargetDiff(row) }}</span>
<span v-else-if="!auditTargetKey(row)" class="audit-target-empty">—</span>
</div>
</template>
<template #outcome="{ row }">
<t-tag :theme="auditOutcomeTheme(row.outcome)" size="small" variant="light">
{{ t('system.globalSettings.audit.outcome.' + row.outcome) }}
</t-tag>
</template>
<template #expandedRow="{ row }">
<div class="audit-expanded">
<div class="audit-expanded-grid">
<div class="audit-expanded-cell">
<span class="audit-expanded-label">{{ t('system.globalSettings.audit.expanded.actorId') }}</span>
<span class="audit-expanded-value mono">{{ row.actor_user_id || '—' }}</span>
</div>
<div v-if="row.target_user_id" class="audit-expanded-cell">
<span class="audit-expanded-label">{{ t('system.globalSettings.audit.expanded.targetUserId') }}</span>
<span class="audit-expanded-value mono">{{ row.target_user_id }}</span>
</div>
<div v-if="row.target_type" class="audit-expanded-cell">
<span class="audit-expanded-label">{{ t('system.globalSettings.audit.expanded.targetType') }}</span>
<span class="audit-expanded-value mono">{{ row.target_type }}</span>
</div>
<div v-if="row.target_id" class="audit-expanded-cell">
<span class="audit-expanded-label">{{ t('system.globalSettings.audit.expanded.targetId') }}</span>
<span class="audit-expanded-value mono">{{ row.target_id }}</span>
</div>
</div>
<div class="audit-expanded-details">
<span class="audit-expanded-label">{{ t('system.globalSettings.audit.expanded.details') }}</span>
<pre class="audit-expanded-json mono">{{ auditDetailsJSON(row) }}</pre>
</div>
</div>
</template>
</t-table>
</div>
<div ref="auditLoadSentinelEl" class="audit-load-sentinel" aria-hidden="true" />
<div v-if="auditLoading && auditEntries.length > 0" class="audit-loading-more">
<t-loading size="small" />
<span>{{ t('system.globalSettings.audit.loading') }}</span>
</div>
<p v-if="!auditHasMore && auditEntries.length > 0 && !auditLoading" class="audit-end-hint">
{{ t('system.globalSettings.audit.end') }}
</p>
</div>
</div>
</div>
</t-drawer>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ref, reactive, onMounted, onUnmounted, computed, nextTick, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import {
@@ -350,14 +506,18 @@ import {
listSystemAdmins,
promoteUserToSystemAdmin,
revokeSystemAdmin,
listSystemAuditLog,
type SystemSettingItem,
type AuditLog,
type AuditAction,
type AuditOutcome,
} from '@/api/system'
import { useAuthStore } from '@/stores/auth'
const authStore = useAuthStore()
const currentUserId = computed(() => authStore.currentUserId)
const { t, te } = useI18n()
const { t, tm, te, locale } = useI18n()
// Friendly labels per key live in i18n (system.globalSettings.keyLabels.*).
// Adding a new entry there must accompany every new key registered in
@@ -961,6 +1121,354 @@ onMounted(() => {
loadSettings()
loadAdmins()
})
// ---- Platform audit log (system-scope, tenant_id=0) ---------------------
//
// Wired against GET /api/v1/system/admin/audit-log (SystemAdmin only).
// The drawer mirrors the structural choices of the tenant audit drawer
// in frontend/src/views/settings/TenantMembers.vue: cursor-paged by
// descending id, lazy-loaded on first open, infinite-scroll via an
// IntersectionObserver pinned to the scroll root. Refresh is explicit
// via a button inside the drawer so closing/reopening doesn't quietly
// fire a new fetch the operator didn't ask for.
const auditDrawerVisible = ref(false)
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
const auditScrollRoot = ref<HTMLElement | null>(null)
const auditLoadSentinelEl = ref<HTMLElement | null>(null)
let auditScrollObserver: IntersectionObserver | null = null
// We render a stacked "date / time" cell rather than ellipsing a single
// flat string — the screenshot review surfaced that the joined form
// reads as a wall of identical timestamps when 50 events fall in the
// same minute. A two-line cell also frees horizontal space for the
// (much more important) target diff column.
const auditColumns = computed(() => [
{ colKey: 'created_at', title: t('system.globalSettings.audit.columns.time'), width: 120 },
{ colKey: 'actor', title: t('system.globalSettings.audit.columns.actor'), width: 180 },
{ colKey: 'action', title: t('system.globalSettings.audit.columns.action'), width: 150 },
{
colKey: 'target',
title: t('system.globalSettings.audit.columns.target'),
// No fixed width / no ellipsis: this is where the diff content
// lives, and clipping it to "..." negates the entire reason we
// synthesise the cell in the first place. CSS handles wrapping.
minWidth: 240,
},
{ colKey: 'outcome', title: t('system.globalSettings.audit.columns.outcome'), width: 80, align: 'center' as const },
])
// Two helpers feeding the stacked time cell. Falling back to the raw
// string keeps the table readable when Intl chokes on a malformed
// timestamp (shouldn't happen, but cheap to defend).
function formatAuditDatePart(s: string | undefined): string {
if (!s) return '-'
try {
return new Intl.DateTimeFormat(locale.value || 'zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(new Date(s))
} catch {
return s
}
}
function formatAuditTimePart(s: string | undefined): string {
if (!s) return ''
try {
return new Intl.DateTimeFormat(locale.value || 'zh-CN', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}).format(new Date(s))
} catch {
return ''
}
}
// Action chip colour: promote is reassuring green; revoke / setting
// change are worth a second look (warning orange); denied / access
// rejections show danger so an operator can scan a chronological feed
// and immediately spot abuse.
function auditActionTheme(
action: AuditAction,
): 'success' | 'warning' | 'danger' | 'primary' | 'default' {
switch (action) {
case 'system.admin_promoted':
return 'success'
case 'system.admin_revoked':
case 'system.setting_changed':
return 'warning'
case 'rbac.access_denied':
return 'danger'
default:
return 'default'
}
}
function auditOutcomeTheme(o: AuditOutcome): 'success' | 'danger' | 'default' {
if (o === 'denied') return 'danger'
if (o === 'success') return 'success'
return 'default'
}
// i18n 键名含点号(system.setting_changed)。用 t(path) 会按路径拆开解析,
// 无法命中 system.globalSettings.audit.action['system.*'] — 必须 tm + 字面量键。
function formatAuditAction(action: AuditAction): string {
const bag = tm('system.globalSettings.audit.action') as unknown
if (bag !== null && typeof bag === 'object' && typeof (bag as Record<string, string>)[action] === 'string') {
return (bag as Record<string, string>)[action]
}
return action
}
// Actor display: most system-admin operations are performed by humans
// whose username we don't have a local mirror of. The audit row only
// carries the UUID, so we fall back to a short prefix for readability.
// If the actor is the current user, we resolve to their own profile.
function auditActorLabel(userId: string): string {
const me = authStore.user
if (me && me.id === userId) {
return me.username?.trim() || me.email?.trim() || userId.slice(0, 8)
}
return userId.slice(0, 8)
}
function auditActorRoleLabel(role: string): string {
const key = `system.globalSettings.audit.actorRole.${role}`
if (te(key)) return t(key)
return role
}
// Target rendering is split into two pieces so the table cell can
// show a structural "subject" (key / user) on its own line and the
// value diff on a second, monospaced line — far more legible than a
// single concatenated string clipped by ellipsis.
function auditDetailsObject(row: AuditLog): Record<string, unknown> | null {
if (row.details && typeof row.details === 'object') {
return row.details as Record<string, unknown>
}
return null
}
// First line of the target cell — the thing being acted on.
// - setting_changed (regular key): the registry key
// - setting_changed (bulk apply): i18n label "(bulk) default storage quota"
// - admin_promoted/revoked: username (email) of the affected user
function auditTargetKey(row: AuditLog): string {
const details = auditDetailsObject(row)
if (row.action === 'system.setting_changed') {
if (row.target_type === 'tenant_storage_quota') {
return t('system.globalSettings.audit.target.bulkQuota')
}
if (details && typeof details.key === 'string' && details.key) return details.key
return row.target_id || row.target_type || ''
}
if (row.action === 'system.admin_promoted' || row.action === 'system.admin_revoked') {
if (!details) return row.target_user_id ? row.target_user_id.slice(0, 8) : ''
const name = typeof details.target_username === 'string' ? details.target_username : ''
const mail = typeof details.target_email === 'string' ? details.target_email : ''
if (name && mail) return `${name} (${mail})`
return name || mail || (row.target_user_id ? row.target_user_id.slice(0, 8) : '')
}
if (row.target_user_id) return row.target_user_id.slice(0, 8)
if (row.target_id) {
return row.target_type ? `${row.target_type}:${row.target_id}` : row.target_id
}
return ''
}
// Second line — the change diff. Returns an empty string when there
// is no meaningful diff to display (the expanded row still surfaces
// the raw JSON for forensics).
function auditTargetDiff(row: AuditLog): string {
const details = auditDetailsObject(row)
if (!details) return ''
if (row.action === 'system.setting_changed') {
if (row.target_type === 'tenant_storage_quota') {
const affected = typeof details.affected === 'number' ? details.affected : null
const gb = typeof details.quota_gb === 'number' ? details.quota_gb : null
if (affected !== null && gb !== null) {
return t('system.globalSettings.audit.target.bulkQuotaDiff', {
count: String(affected),
gb: String(gb),
})
}
return ''
}
return formatSettingDiff(details)
}
if (row.action === 'system.admin_promoted' && typeof details.idempotent === 'boolean') {
if (details.idempotent === true) {
return t('system.globalSettings.audit.target.promoteIdempotent')
}
return ''
}
if (row.action === 'system.admin_revoked' && typeof details.changed === 'boolean') {
if (details.changed === false) {
return t('system.globalSettings.audit.target.revokeNoop')
}
return ''
}
if (row.action === 'rbac.access_denied' && typeof details.required_role === 'string') {
return t('system.globalSettings.audit.target.requiredRole', { role: details.required_role })
}
return ''
}
const SETTING_DIFF_MAX_LEN = 80
function formatSettingDiff(details: Record<string, unknown>): string {
const fmt = (v: unknown): string => {
if (v === null || v === undefined) {
return t('system.globalSettings.audit.target.valueNull')
}
if (typeof v === 'string') return v
if (typeof v === 'number' || typeof v === 'boolean') return String(v)
try {
return JSON.stringify(v)
} catch {
return String(v)
}
}
const truncate = (s: string): string =>
s.length > SETTING_DIFF_MAX_LEN ? s.slice(0, SETTING_DIFF_MAX_LEN - 1) + '…' : s
const oldStr = truncate(fmt(details.old_value))
const newStr = truncate(fmt(details.new_value))
if (oldStr === newStr) return ''
return `${oldStr} → ${newStr}`
}
// Expanded row state — local set of row ids the user has opened.
// We keep it ephemeral (not persisted) so reopening the drawer always
// shows a clean, collapsed view.
const auditExpandedRowKeys = ref<number[]>([])
function onAuditExpandChange(value: (string | number)[]) {
// t-table calls back with the *new* full list of expanded keys.
// Normalise to numbers because AuditLog.id is always a number.
auditExpandedRowKeys.value = value
.map((v) => (typeof v === 'number' ? v : Number(v)))
.filter((v) => Number.isFinite(v))
}
function auditDetailsJSON(row: AuditLog): string {
if (row.details === null || row.details === undefined) return '{}'
if (typeof row.details === 'string') return row.details
try {
return JSON.stringify(row.details, null, 2)
} catch {
return String(row.details)
}
}
async function loadAuditLog(reset: boolean) {
if (auditLoading.value) return
if (!reset && !auditHasMore.value) return
auditLoading.value = true
auditError.value = ''
try {
const resp = await listSystemAuditLog({
after_id: reset ? undefined : auditCursor.value || undefined,
limit: AUDIT_PAGE_SIZE,
})
if (resp.success) {
const rows = resp.data || []
auditEntries.value = reset ? rows : [...auditEntries.value, ...rows]
auditCursor.value = resp.next_cursor || 0
// Same convention as tenant audit: next_cursor=0 means "no
// older rows", regardless of whether the current page was empty.
auditHasMore.value = !!resp.next_cursor && rows.length > 0
auditLoadedOnce.value = true
} else {
auditError.value = resp.message || t('system.globalSettings.audit.errors.generic')
}
} catch (err: any) {
const status = err?.status
if (status === 403) {
auditError.value = t('system.globalSettings.audit.forbidden')
} else {
auditError.value = err?.message || t('system.globalSettings.audit.errors.generic')
}
} finally {
auditLoading.value = false
}
}
function detachAuditInfiniteScroll() {
auditScrollObserver?.disconnect()
auditScrollObserver = null
}
function attachAuditInfiniteScroll() {
detachAuditInfiniteScroll()
const root = auditScrollRoot.value
const sentinel = auditLoadSentinelEl.value
if (!root || !sentinel) return
auditScrollObserver = new IntersectionObserver(
(entries) => {
const hitBottom = entries.some((e) => e.isIntersecting)
if (!hitBottom || !auditHasMore.value || auditLoading.value) return
void loadAuditLog(false)
},
{ root, rootMargin: '100px 0px', threshold: 0 },
)
auditScrollObserver.observe(sentinel)
}
function reloadAuditLog() {
auditCursor.value = 0
auditHasMore.value = true
loadAuditLog(true)
}
function openAuditDrawer() {
auditDrawerVisible.value = true
if (!auditLoadedOnce.value) {
loadAuditLog(true)
}
}
watch(
auditDrawerVisible,
async (open) => {
if (!open) {
detachAuditInfiniteScroll()
return
}
await nextTick()
attachAuditInfiniteScroll()
},
{ flush: 'post' },
)
watch(
() => auditError.value,
async () => {
if (!auditDrawerVisible.value) return
await nextTick()
if (!auditError.value) {
attachAuditInfiniteScroll()
return
}
detachAuditInfiniteScroll()
},
{ flush: 'post' },
)
onUnmounted(() => detachAuditInfiniteScroll())
</script>
<style lang="less" scoped>
@@ -986,6 +1494,328 @@ onMounted(() => {
}
}
/* Title + audit-log entry sit on the same row, parallel to the layout
used in tenant member settings — keeps secondary actions anchored to
the section header instead of floating loose above content. */
.section-header-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
h2 {
margin: 0;
}
}
.header-audit-btn {
flex-shrink: 0;
}
/* ===== Audit drawer (mirrors TenantMembers.vue's audit panel) =========
Kept scoped to this view rather than extracted to a shared component:
the two pages render distinct action labels and target formatters,
and a generic <AuditLogPanel> would have to thread enough props
through to make the abstraction more expensive than the duplication.
Revisit if a third audit surface appears. */
.audit-panel {
display: flex;
flex-direction: column;
gap: 14px;
padding-top: 8px;
}
.audit-panel--drawer {
padding-top: 0;
}
.audit-header {
display: flex;
align-items: center;
justify-content: space-between;
background: var(--td-bg-color-secondarycontainer);
padding: 12px 16px;
border-radius: 8px;
gap: 12px;
.audit-desc {
flex: 1;
min-width: 0;
font-size: 13px;
color: var(--td-text-color-secondary);
}
.audit-refresh-btn {
flex-shrink: 0;
}
}
.audit-drawer-inner {
display: flex;
flex-direction: column;
flex: 1 1 auto;
gap: 14px;
min-height: 0;
width: 100%;
box-sizing: border-box;
}
.audit-drawer-fill {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.audit-drawer-branch {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.audit-drawer-branch--error {
justify-content: center;
.error-inline {
width: 100%;
display: flex;
align-items: center;
gap: 8px;
padding: 20px 0 8px;
}
}
.audit-drawer-branch--empty.empty-state--audit {
flex: 1 1 auto;
justify-content: center;
align-items: center;
padding: 24px 12px;
min-height: 0;
}
.audit-scroll-area {
flex: 1 1 auto;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
}
.audit-load-sentinel {
height: 1px;
width: 100%;
pointer-events: none;
}
.audit-loading-more {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
padding: 12px;
font-size: 12px;
color: var(--td-text-color-secondary);
}
.audit-end-hint {
text-align: center;
font-size: 12px;
color: var(--td-text-color-disabled);
padding: 8px 0 14px;
margin: 0;
}
.audit-time {
display: flex;
flex-direction: column;
gap: 2px;
line-height: 1.3;
.audit-time-date {
font-size: 12px;
color: var(--td-text-color-secondary);
}
.audit-time-clock {
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
font-variant-numeric: tabular-nums;
}
}
.audit-actor {
display: flex;
flex-direction: column;
gap: 2px;
line-height: 1.3;
min-width: 0;
.audit-actor-name {
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.audit-actor-role {
font-size: 12px;
color: var(--td-text-color-secondary);
}
}
.audit-target {
display: flex;
flex-direction: column;
gap: 4px;
line-height: 1.35;
min-width: 0;
padding: 2px 0;
.audit-target-key {
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
word-break: break-all;
font-family: var(--td-font-family-mono, monospace);
}
.audit-target-diff {
font-size: 12px;
color: var(--td-text-color-secondary);
font-family: var(--td-font-family-mono, monospace);
word-break: break-all;
line-height: 1.4;
}
.audit-target-empty {
color: var(--td-text-color-placeholder);
}
}
/* Expanded row: surfaces the raw audit row context (UUIDs, target
type/id, full details JSON) so an investigator never has to hop to
psql for the verbatim event. Background steps off-card to make the
nested context visually distinct from the table rows. */
.audit-expanded {
display: flex;
flex-direction: column;
gap: 12px;
padding: 12px 16px;
background: var(--td-bg-color-container-hover);
}
.audit-expanded-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px 18px;
}
.audit-expanded-cell {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.audit-expanded-label {
font-size: 11px;
font-weight: 600;
color: var(--td-text-color-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.audit-expanded-value {
font-size: 12px;
color: var(--td-text-color-primary);
word-break: break-all;
}
.audit-expanded-details {
display: flex;
flex-direction: column;
gap: 4px;
}
.audit-expanded-json {
margin: 0;
padding: 10px 12px;
font-size: 12px;
line-height: 1.55;
color: var(--td-text-color-primary);
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
white-space: pre-wrap;
word-break: break-all;
max-height: 280px;
overflow: auto;
}
.mono {
font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
}
.data-table-shell {
overflow-x: auto;
border-radius: 10px;
border: 1px solid var(--td-component-stroke);
background-color: var(--td-bg-color-container);
&:deep(thead th) {
font-weight: 600;
font-size: 13px;
background-color: var(--td-bg-color-secondarycontainer) !important;
}
&:deep(.t-table td),
&:deep(.t-table th) {
padding-top: 14px;
padding-bottom: 14px;
/* Center the cell content vertically: most rows have at least one
single-line tag column (action / outcome), and a top-aligned
layout floats those chips above the multi-line target cell —
middle keeps the row's visual weight unified. */
vertical-align: middle;
}
}
/* Audit-specific table polish: no zebra stripes (the per-row "key /
diff" stack already provides enough separation between rows; stripes
on top read as visual noise), softer hover, denser separator. */
.audit-table-shell {
/* Sticky table head: long audit feeds (50+ rows) lose the column
labels once the user scrolls, which makes "what's this column?"
a constant relearn. The drawer's outer scroll container is
`.audit-scroll-area`, so `top: 0` here pins thead to that
container's top. z-index keeps it above row hover/expand
backgrounds, and the explicit background plus bottom border
prevent row content bleeding through during scroll. */
&:deep(thead th) {
position: sticky;
top: 0;
z-index: 2;
box-shadow: inset 0 -1px 0 var(--td-component-stroke);
}
&:deep(.t-table tbody tr:hover > td) {
background-color: var(--td-bg-color-container-hover);
}
&:deep(.t-table tbody tr.t-table__expanded-row > td) {
padding: 0 !important;
background-color: transparent;
}
&:deep(.t-table__expandable-icon-cell) {
width: 36px;
}
}
.priority-hint {
margin-bottom: 24px;
padding: 14px 16px;
@@ -1181,3 +2011,25 @@ onMounted(() => {
}
}
</style>
<style lang="less">
/* t-drawer teleports its content-wrapper to body, so the height-chain
needed for the internal scroll area must be declared globally. Same
pattern as `.tenant-members-audit-drawer` in TenantMembers.vue. */
.t-drawer.system-settings-audit-drawer.t-drawer--right .t-drawer__content-wrapper--right {
box-sizing: border-box;
display: flex;
flex-direction: column;
max-height: 100vh;
height: 100%;
}
.t-drawer.system-settings-audit-drawer .t-drawer__body {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
box-sizing: border-box;
overflow: hidden !important;
}
</style>
+71
View File
@@ -104,3 +104,74 @@ func (h *AuditLogHandler) ListTenantAuditLog(c *gin.Context) {
NextCursor: nextCursor,
})
}
// 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,
})
}
+22 -2
View File
@@ -189,7 +189,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterEvaluationRoutes(v1, params.EvaluationHandler, rbacGuards)
RegisterInitializationRoutes(v1, params.InitializationHandler, rbacGuards)
RegisterSystemRoutes(v1, params.SystemHandler, rbacGuards)
RegisterSystemAdminRoutes(v1, params.SystemHandler, rbacGuards)
RegisterSystemAdminRoutes(v1, params.SystemHandler, params.AuditLogHandler, rbacGuards)
RegisterMCPServiceRoutes(v1, params.MCPServiceHandler, params.MCPCredentialsHandler, rbacGuards)
RegisterWebSearchRoutes(v1, params.WebSearchHandler, rbacGuards)
RegisterWebSearchProviderRoutes(v1, params.WebSearchProviderHandler, params.WebSearchCredentialsHandler, rbacGuards)
@@ -735,7 +735,16 @@ func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g
// Mounted under /api/v1/system/admin/* so the URL scheme stays aligned
// with the existing /api/v1/system/info family. Front-end clients live
// in frontend/src/api/system/index.ts.
func RegisterSystemAdminRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g *rbacGuards) {
//
// auditLogHandler may be nil in environments wired without the audit
// dependency; the /audit-log subroute is then omitted. This mirrors
// the optional wiring in RegisterTenantRoutes.
func RegisterSystemAdminRoutes(
r *gin.RouterGroup,
handler *handler.SystemHandler,
auditLogHandler *handler.AuditLogHandler,
g *rbacGuards,
) {
// Apply SystemAdmin() at the group level — every route below inherits
// the guard, so adding new endpoints can't accidentally drop the gate.
adminRoutes := r.Group("/system/admin", g.SystemAdmin())
@@ -761,6 +770,17 @@ func RegisterSystemAdminRoutes(r *gin.RouterGroup, handler *handler.SystemHandle
"/tenants/apply-default-storage-quota",
handler.ApplyDefaultStorageQuotaToAllTenants,
)
// Platform-wide audit feed (tenant_id=0 rows). Covers
// system.setting_changed / system.admin_promoted /
// system.admin_revoked etc. — events written by the routes
// above. Without this endpoint those audit rows would have
// no UI surface (per-tenant ListTenantAuditLog filters them
// out by tenant_id). Optional: skip when audit deps are
// absent, matching RegisterTenantRoutes' /audit-log handling.
if auditLogHandler != nil {
adminRoutes.GET("/audit-log", auditLogHandler.ListSystemAuditLog)
}
}
}