diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index 0c10b9ba..7f9998d8 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -419,3 +419,45 @@ export async function applyDefaultStorageQuotaToAllTenants(): Promise { + 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 +} diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index b256c2f2..57885156 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -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: { diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 5759ef0d..26c8b807 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -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: { diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index ece7ae10..24430982 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -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: 'Сырые детали', + }, }, }, } diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index e21237c0..76c2bdd9 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -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: { diff --git a/frontend/src/views/settings/TenantMembers.vue b/frontend/src/views/settings/TenantMembers.vue index 2a4af850..fd83b70f 100644 --- a/frontend/src/views/settings/TenantMembers.vue +++ b/frontend/src/views/settings/TenantMembers.vue @@ -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. --> + drawer-class-name="tenant-members-audit-drawer" size="880px" :footer="false" placement="right" destroy-on-close>
{{ $t('tenantMember.audit.description') }} - + + {{ $t('tenantMember.audit.refresh') }}
@@ -316,37 +316,84 @@
-
- - +
+ + +
@@ -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 | null { + if (row.details && typeof row.details === 'object') { + return row.details as Record + } + 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 - 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 - 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([]) + +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); +} + + diff --git a/internal/handler/audit_log.go b/internal/handler/audit_log.go index cf0c4887..5f06b047 100644 --- a/internal/handler/audit_log.go +++ b/internal/handler/audit_log.go @@ -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, + }) +} diff --git a/internal/router/router.go b/internal/router/router.go index 69092108..16f97730 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -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) + } } }