From 766a6c482f35479f95854bb5171f246a4011eea7 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 14 May 2026 21:07:48 +0800 Subject: [PATCH] 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. --- frontend/src/api/tenant/audit-log.ts | 79 ++++ frontend/src/i18n/locales/en-US.ts | 35 ++ frontend/src/i18n/locales/ko-KR.ts | 35 ++ frontend/src/i18n/locales/ru-RU.ts | 35 ++ frontend/src/i18n/locales/zh-CN.ts | 35 ++ frontend/src/views/settings/TenantMembers.vue | 336 ++++++++++++++++++ internal/application/repository/audit_log.go | 106 ++++++ internal/application/service/audit_log.go | 130 +++++++ .../application/service/audit_log_test.go | 175 +++++++++ internal/application/service/tenant_member.go | 123 ++++++- .../application/service/tenant_member_test.go | 18 +- internal/container/container.go | 3 + internal/handler/audit_log.go | 106 ++++++ internal/handler/audit_log_test.go | 155 ++++++++ internal/middleware/audit_provider.go | 41 +++ internal/middleware/rbac.go | 13 + internal/middleware/rbac_audit_test.go | 137 +++++++ internal/router/router.go | 21 +- internal/types/audit_log.go | 71 ++++ internal/types/interfaces/audit_log.go | 63 ++++ migrations/sqlite/000000_init.down.sql | 1 + migrations/sqlite/000000_init.up.sql | 26 ++ .../versioned/000044_audit_log.down.sql | 25 ++ migrations/versioned/000044_audit_log.up.sql | 56 +++ 24 files changed, 1811 insertions(+), 14 deletions(-) create mode 100644 frontend/src/api/tenant/audit-log.ts create mode 100644 internal/application/repository/audit_log.go create mode 100644 internal/application/service/audit_log.go create mode 100644 internal/application/service/audit_log_test.go create mode 100644 internal/handler/audit_log.go create mode 100644 internal/handler/audit_log_test.go create mode 100644 internal/middleware/audit_provider.go create mode 100644 internal/middleware/rbac_audit_test.go create mode 100644 internal/types/audit_log.go create mode 100644 internal/types/interfaces/audit_log.go create mode 100644 migrations/versioned/000044_audit_log.down.sql create mode 100644 migrations/versioned/000044_audit_log.up.sql diff --git a/frontend/src/api/tenant/audit-log.ts b/frontend/src/api/tenant/audit-log.ts new file mode 100644 index 00000000..3884eca5 --- /dev/null +++ b/frontend/src/api/tenant/audit-log.ts @@ -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 | 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 { + 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 +} diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 93c47545..d582ef0a 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -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', + }, + }, }, } diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index aad90ab3..ec6ce70e 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -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: "거부", + }, + }, }, }; diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 1e3a2071..0b662a68 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -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: 'Отказ', + }, + }, }, } diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index cd75acd5..24c6e703 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -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: "拒绝", + }, + }, }, }; diff --git a/frontend/src/views/settings/TenantMembers.vue b/frontend/src/views/settings/TenantMembers.vue index a4b75387..254d777e 100644 --- a/frontend/src/views/settings/TenantMembers.vue +++ b/frontend/src/views/settings/TenantMembers.vue @@ -5,6 +5,12 @@

{{ $t('tenantMember.sectionDescription') }}

+ + + @@ -161,6 +167,107 @@ + + + + +
+
+ {{ $t('tenantMember.audit.description') }} + + {{ $t('tenantMember.audit.refresh') }} + +
+ +
+ + + +
+ +
+ +
+ + + + + + + + + + + + +
+
+
@@ -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(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([]) +const auditLoading = ref(false) +const auditError = ref('') +const auditCursor = ref(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(() => (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 + 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 + 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); + } +} diff --git a/internal/application/repository/audit_log.go b/internal/application/repository/audit_log.go new file mode 100644 index 00000000..e8ef8c17 --- /dev/null +++ b/internal/application/repository/audit_log.go @@ -0,0 +1,106 @@ +package repository + +import ( + "context" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "gorm.io/gorm" +) + +// auditLogRepository persists audit events to the audit_logs table. +// Rows are append-only — there is no Update, no soft-delete, no +// Modify hook. The cursor pagination uses the monotonic id column, +// not created_at, so duplicate timestamps don't break iteration. +type auditLogRepository struct { + db *gorm.DB +} + +// NewAuditLogRepository constructs the production audit log repository +// backed by the shared GORM connection. +func NewAuditLogRepository(db *gorm.DB) interfaces.AuditLogRepository { + return &auditLogRepository{db: db} +} + +// Create inserts a single audit row. Validation is light — Action is +// the only required field at the schema level; CreatedAt is filled by +// the database default if zero. Service-layer Log() fills both before +// calling here so this is mostly a pass-through. +func (r *auditLogRepository) Create(ctx context.Context, entry *types.AuditLog) error { + return r.db.WithContext(ctx).Create(entry).Error +} + +// auditLogListLimitMax is the hard ceiling regardless of caller input. +// Keeps a misconfigured client from triggering an unbounded scan; the +// frontend's default page size is 50 so this is comfortable headroom. +const auditLogListLimitMax = 100 + +// List returns audit log rows for a tenant, newest-first, applying the +// optional cursor and filters from AuditLogQuery. Both Action and +// Outcome are exact-match — the filter set is small enough that we +// don't need substring matching yet. +func (r *auditLogRepository) List( + ctx context.Context, + tenantID uint64, + q *interfaces.AuditLogQuery, +) ([]*types.AuditLog, error) { + limit := 50 + if q != nil && q.Limit > 0 { + limit = q.Limit + } + if limit > auditLogListLimitMax { + limit = auditLogListLimitMax + } + + tx := r.db.WithContext(ctx). + Where("tenant_id = ?", tenantID) + if q != nil { + if q.AfterID > 0 { + tx = tx.Where("id < ?", q.AfterID) + } + if q.Action != "" { + tx = tx.Where("action = ?", q.Action) + } + if q.Outcome != "" { + tx = tx.Where("outcome = ?", q.Outcome) + } + if q.ActorUserID != "" { + tx = tx.Where("actor_user_id = ?", q.ActorUserID) + } + } + + var entries []*types.AuditLog + if err := tx.Order("id DESC").Limit(limit).Find(&entries).Error; err != nil { + return nil, err + } + return entries, nil +} + +// CountSinceForDedup powers AuditLogService.LogDenied's sliding-window +// dedup. The (tenant_id, action) index makes the count cheap; the +// remaining filters are applied as additional WHERE clauses on the +// indexed result set. +// +// Returning early on the first match would be slightly cheaper, but +// gorm's Count works on the same plan and the constant overhead is +// negligible compared to the dedup benefit. +func (r *auditLogRepository) CountSinceForDedup( + ctx context.Context, + tenantID uint64, + actorUserID string, + action types.AuditAction, + requestPath string, + since time.Time, +) (int64, error) { + var count int64 + err := r.db.WithContext(ctx). + Model(&types.AuditLog{}). + Where("tenant_id = ?", tenantID). + Where("actor_user_id = ?", actorUserID). + Where("action = ?", action). + Where("request_path = ?", requestPath). + Where("created_at >= ?", since). + Count(&count).Error + return count, err +} diff --git a/internal/application/service/audit_log.go b/internal/application/service/audit_log.go new file mode 100644 index 00000000..48f0b17d --- /dev/null +++ b/internal/application/service/audit_log.go @@ -0,0 +1,130 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// auditLogService is the high-level wrapper around AuditLogRepository. +// It owns: +// - timestamp defaulting (Log fills CreatedAt if zero so callers +// don't have to). +// - the 1-minute sliding-window dedup that LogDenied applies to keep +// a probing client from filling the audit_logs table. +// +// The service is intentionally nil-tolerant when consumed: the +// tenant_member service holds it as an optional field, so a future +// container reshuffle that constructs tenant_member before audit_log +// won't crash. Callers should still aim to inject a real instance — +// the nil path is a degraded mode, not a default. +type auditLogService struct { + repo interfaces.AuditLogRepository + now func() time.Time +} + +// NewAuditLogService constructs the production service. +func NewAuditLogService(repo interfaces.AuditLogRepository) interfaces.AuditLogService { + return &auditLogService{repo: repo, now: time.Now} +} + +// denyDedupWindow caps how often LogDenied will write a durable row +// for the same (tenant, actor, path, action) tuple. 1 minute is +// short enough that bursts across distinct paths still each show up +// in the table (one row per path per minute), long enough that a +// single hammered endpoint at 100 RPS produces 1 row/minute, not 6000. +const denyDedupWindow = 1 * time.Minute + +// Log is the canonical write path. The repo's Create defaults +// CreatedAt at the SQL level, but we also fill it here so tests and +// callers that read entry.CreatedAt right after Log() get a sensible +// value without round-tripping through the database. +func (s *auditLogService) Log(ctx context.Context, entry *types.AuditLog) error { + if entry == nil { + return fmt.Errorf("audit log: nil entry") + } + if entry.Action == "" { + return fmt.Errorf("audit log: action is required") + } + if entry.Outcome == "" { + entry.Outcome = types.AuditOutcomeSuccess + } + if entry.CreatedAt.IsZero() { + entry.CreatedAt = s.now() + } + if err := s.repo.Create(ctx, entry); err != nil { + // Log loudly but do NOT propagate the error to the caller in + // the production wiring (see callers in tenant_member service + // and rbac middleware — both ignore the return). Audit failure + // must never break the underlying business operation. + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "audit_action": entry.Action, + "audit_target": entry.TargetID, + }) + return err + } + return nil +} + +// LogDenied records a middleware-level rejection. Subject to a +// 1-minute sliding-window dedup keyed by +// (tenant_id, actor_user_id, action, request_path) so a probing +// client cannot flood the table. +// +// The non-durable advisory log line `[rbac] role insufficient: ...` +// continues to fire on every reject (in middleware/rbac.go) — the +// dedup only suppresses durable writes, not stderr observability. +func (s *auditLogService) LogDenied( + ctx context.Context, + c *gin.Context, + tenantID uint64, + actorUserID, actorRole string, + requiredRole types.TenantRole, +) error { + requestPath := "" + requestMethod := "" + if c != nil && c.Request != nil { + requestPath = c.Request.URL.Path + requestMethod = c.Request.Method + } + + // Dedup probe: skip the durable write if this exact tuple already + // has a row in the trailing window. Failure here is non-fatal — + // degraded behaviour is "write a duplicate" which is preferable to + // "skip the audit because the count failed". + since := s.now().Add(-denyDedupWindow) + if n, err := s.repo.CountSinceForDedup( + ctx, tenantID, actorUserID, types.AuditActionAccessDenied, requestPath, since, + ); err == nil && n > 0 { + return nil + } + + details, _ := json.Marshal(map[string]string{"required_role": string(requiredRole)}) + return s.Log(ctx, &types.AuditLog{ + TenantID: tenantID, + ActorUserID: actorUserID, + ActorRole: actorRole, + Action: types.AuditActionAccessDenied, + RequestPath: requestPath, + RequestMethod: requestMethod, + Outcome: types.AuditOutcomeDenied, + Details: types.JSON(details), + }) +} + +// List proxies to the repository. The handler layer applies the +// PathTenantMatch + Admin guard before this is reached, so we don't +// re-check tenant scope here. +func (s *auditLogService) List( + ctx context.Context, + tenantID uint64, + q *interfaces.AuditLogQuery, +) ([]*types.AuditLog, error) { + return s.repo.List(ctx, tenantID, q) +} diff --git a/internal/application/service/audit_log_test.go b/internal/application/service/audit_log_test.go new file mode 100644 index 00000000..d32d5969 --- /dev/null +++ b/internal/application/service/audit_log_test.go @@ -0,0 +1,175 @@ +package service + +import ( + "context" + "errors" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// stubAuditRepo collects Create calls and answers CountSinceForDedup +// from the in-memory state. Embeds the interface so any unstubbed +// method will nil-panic, surfacing a contract drift loudly instead of +// silently returning zero-values. +type stubAuditRepo struct { + interfaces.AuditLogRepository + + mu sync.Mutex + created []*types.AuditLog + // countErr lets a test inject a transient lookup failure. + countErr error +} + +func (s *stubAuditRepo) Create(_ context.Context, entry *types.AuditLog) error { + s.mu.Lock() + defer s.mu.Unlock() + s.created = append(s.created, entry) + return nil +} + +func (s *stubAuditRepo) CountSinceForDedup( + _ context.Context, tenantID uint64, actorUserID string, + action types.AuditAction, requestPath string, since time.Time, +) (int64, error) { + if s.countErr != nil { + return 0, s.countErr + } + s.mu.Lock() + defer s.mu.Unlock() + var n int64 + for _, e := range s.created { + if e.TenantID == tenantID && + e.ActorUserID == actorUserID && + e.Action == action && + e.RequestPath == requestPath && + !e.CreatedAt.Before(since) { + n++ + } + } + return n, nil +} + +// fakeClock returns a controllable time source so the dedup-window +// tests can simulate "1 minute later" without sleeping. +type fakeClock struct{ t time.Time } + +func (f *fakeClock) Now() time.Time { return f.t } +func (f *fakeClock) Advance(by time.Duration) { f.t = f.t.Add(by) } + +func newSvcForTest() (*auditLogService, *stubAuditRepo, *fakeClock) { + clock := &fakeClock{t: time.Date(2026, 5, 14, 10, 0, 0, 0, time.UTC)} + repo := &stubAuditRepo{} + svc := &auditLogService{repo: repo, now: clock.Now} + return svc, repo, clock +} + +func newDeniedCtx(t *testing.T, method, path string) *gin.Context { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(method, path, nil) + return c +} + +func TestAuditLog_Log_FillsCreatedAtAndOutcome(t *testing.T) { + svc, repo, clock := newSvcForTest() + entry := &types.AuditLog{ + TenantID: 7, + Action: types.AuditActionMemberAdded, + // CreatedAt left zero, Outcome left empty + } + if err := svc.Log(context.Background(), entry); err != nil { + t.Fatalf("Log: %v", err) + } + if len(repo.created) != 1 { + t.Fatalf("expected 1 written entry, got %d", len(repo.created)) + } + if !entry.CreatedAt.Equal(clock.Now()) { + t.Fatalf("expected CreatedAt to default to clock time, got %v", entry.CreatedAt) + } + if entry.Outcome != types.AuditOutcomeSuccess { + t.Fatalf("expected Outcome to default to success, got %q", entry.Outcome) + } +} + +func TestAuditLog_Log_RejectsEmptyAction(t *testing.T) { + // Schema requires action; the service guards the contract upfront so + // callers get a clean error instead of a constraint violation later. + svc, _, _ := newSvcForTest() + err := svc.Log(context.Background(), &types.AuditLog{TenantID: 7}) + if err == nil { + t.Fatalf("expected error when Action is empty") + } +} + +func TestAuditLog_LogDenied_DedupesRepeatedRejectsWithinWindow(t *testing.T) { + // First denied write hits the table; second within the window does + // NOT — the dedup primitive is the headline durability guarantee + // against probing clients filling the audit table at line rate. + svc, repo, _ := newSvcForTest() + c := newDeniedCtx(t, "PUT", "/api/v1/tenants/7") + + if err := svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin); err != nil { + t.Fatalf("LogDenied: %v", err) + } + if err := svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin); err != nil { + t.Fatalf("LogDenied second call: %v", err) + } + if len(repo.created) != 1 { + t.Fatalf("expected dedup to drop second write, got %d entries", len(repo.created)) + } +} + +func TestAuditLog_LogDenied_WritesAgainAfterWindowExpires(t *testing.T) { + // The dedup is a sliding window, not a once-per-tuple lock — once + // the trailing window is empty, the next denied call must record. + svc, repo, clock := newSvcForTest() + c := newDeniedCtx(t, "PUT", "/api/v1/tenants/7") + + _ = svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin) + clock.Advance(denyDedupWindow + time.Second) + _ = svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin) + + if len(repo.created) != 2 { + t.Fatalf("expected window-expiry to allow second write, got %d entries", len(repo.created)) + } +} + +func TestAuditLog_LogDenied_DedupIsPerActorAndPath(t *testing.T) { + // Two distinct actors hitting the same endpoint, or the same actor + // hitting two distinct endpoints, must each record. The dedup key + // is (tenant, actor, action, path) — anything else collides. + svc, repo, _ := newSvcForTest() + c1 := newDeniedCtx(t, "PUT", "/api/v1/tenants/7") + c2 := newDeniedCtx(t, "PUT", "/api/v1/agents/abc") + + _ = svc.LogDenied(context.Background(), c1, 7, "u-viewer-a", "viewer", types.TenantRoleAdmin) + _ = svc.LogDenied(context.Background(), c1, 7, "u-viewer-b", "viewer", types.TenantRoleAdmin) + _ = svc.LogDenied(context.Background(), c2, 7, "u-viewer-a", "viewer", types.TenantRoleAdmin) + + if len(repo.created) != 3 { + t.Fatalf("expected 3 distinct (actor,path) writes, got %d", len(repo.created)) + } +} + +func TestAuditLog_LogDenied_DegradesGracefullyOnDedupLookupError(t *testing.T) { + // If the dedup count returns an error (DB hiccup, transient), we + // must NOT silently skip the audit row. Better to write a + // duplicate than to lose a denied event during incident response. + svc, repo, _ := newSvcForTest() + repo.countErr = errors.New("transient") + c := newDeniedCtx(t, "PUT", "/api/v1/tenants/7") + + if err := svc.LogDenied(context.Background(), c, 7, "u-viewer", "viewer", types.TenantRoleAdmin); err != nil { + t.Fatalf("LogDenied with dedup error: %v", err) + } + if len(repo.created) != 1 { + t.Fatalf("expected fallthrough write on dedup error, got %d entries", len(repo.created)) + } +} diff --git a/internal/application/service/tenant_member.go b/internal/application/service/tenant_member.go index bdf473c1..0a9b0204 100644 --- a/internal/application/service/tenant_member.go +++ b/internal/application/service/tenant_member.go @@ -2,6 +2,7 @@ package service import ( "context" + "encoding/json" "errors" "time" @@ -34,13 +35,48 @@ var ( // tenantMemberService implements interfaces.TenantMemberService. type tenantMemberService struct { - repo interfaces.TenantMemberRepository + repo interfaces.TenantMemberRepository + audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed } // NewTenantMemberService constructs the service. Wired up via the DI -// container alongside the other application services. -func NewTenantMemberService(repo interfaces.TenantMemberRepository) interfaces.TenantMemberService { - return &tenantMemberService{repo: repo} +// container alongside the other application services. The auditService +// is optional — passing nil disables durable audit but keeps the +// underlying mutations working, so a container reshuffle that +// constructs tenant_member before audit_log won't crash and tests +// don't need to stub the dependency unless they care about audit +// behaviour. +func NewTenantMemberService( + repo interfaces.TenantMemberRepository, + audit interfaces.AuditLogService, +) interfaces.TenantMemberService { + return &tenantMemberService{repo: repo, audit: audit} +} + +// emitAudit is the per-mutation audit hook. Best-effort: a nil audit +// service or a write failure is logged inside the audit service itself +// and never bubbles up to the caller. RBAC mutations succeed even if +// audit is unavailable; the alternative (failing the business op when +// the audit table is down) is far worse. +func (s *tenantMemberService) emitAudit(ctx context.Context, entry *types.AuditLog) { + if s.audit == nil { + return + } + _ = s.audit.Log(ctx, entry) +} + +// auditActorRole picks up the caller's role at write-time. Empty if +// auth middleware didn't set it (e.g. service-internal flows like +// EnsureOwner during register, where there is no "caller"). +func auditActorRole(ctx context.Context) string { + return string(types.TenantRoleFromContext(ctx)) +} + +// auditActor returns the calling user id from context, "" when no +// authenticated caller is present (service-internal paths). +func auditActor(ctx context.Context) string { + uid, _ := types.UserIDFromContext(ctx) + return uid } // AddMember inserts a new active membership row. Returns @@ -74,6 +110,15 @@ func (s *tenantMemberService) AddMember( if err := s.repo.Create(ctx, member); err != nil { return nil, err } + s.emitAudit(ctx, &types.AuditLog{ + TenantID: tenantID, + ActorUserID: auditActor(ctx), + ActorRole: auditActorRole(ctx), + Action: types.AuditActionMemberAdded, + TargetType: "tenant_member", + TargetUserID: userID, + Outcome: types.AuditOutcomeSuccess, + }) return member, nil } @@ -154,6 +199,7 @@ func (s *tenantMemberService) UpdateRole( if current.Role == newRole { return nil } + oldRole := current.Role // Owner demotion is the dangerous path: two concurrent demotions of // two different Owners with the old "Get → Count → Update" sequence // could each observe count=2 and both commit, leaving the tenant @@ -168,15 +214,51 @@ func (s *tenantMemberService) UpdateRole( case err != nil: return err } + s.emitRoleChangeAudit(ctx, tenantID, userID, oldRole, newRole) return nil } - return s.repo.UpdateRole(ctx, userID, tenantID, newRole) + if err := s.repo.UpdateRole(ctx, userID, tenantID, newRole); err != nil { + return err + } + s.emitRoleChangeAudit(ctx, tenantID, userID, oldRole, newRole) + return nil +} + +// emitRoleChangeAudit packs the old/new role into Details so the +// audit-log UI can render "promoted Alice from contributor to admin" +// without a separate column per role transition. +func (s *tenantMemberService) emitRoleChangeAudit( + ctx context.Context, + tenantID uint64, + targetUserID string, + oldRole, newRole types.TenantRole, +) { + details, _ := json.Marshal(map[string]string{ + "old_role": string(oldRole), + "new_role": string(newRole), + }) + s.emitAudit(ctx, &types.AuditLog{ + TenantID: tenantID, + ActorUserID: auditActor(ctx), + ActorRole: auditActorRole(ctx), + Action: types.AuditActionMemberRoleChanged, + TargetType: "tenant_member", + TargetUserID: targetUserID, + Outcome: types.AuditOutcomeSuccess, + Details: types.JSON(details), + }) } // RemoveMember enforces the "cannot remove the last Owner" invariant // before soft-deleting the membership. For Owner removals it routes // through the repo's transactional helper so the count + delete commit // atomically (no TOCTOU between checking owner count and deleting). +// +// The audit row distinguishes "voluntary leave" (caller == target, +// driven by POST /leave) from "kicked" (caller != target, driven by +// DELETE /tenants/:id/members/:user_id). Both go through this same +// service method but the recorded action differs so an audit reader +// can tell the two apart. func (s *tenantMemberService) RemoveMember(ctx context.Context, userID string, tenantID uint64) error { current, err := s.repo.Get(ctx, userID, tenantID) if err != nil { @@ -193,7 +275,36 @@ func (s *tenantMemberService) RemoveMember(ctx context.Context, userID string, t case err != nil: return err } + s.emitRemovalAudit(ctx, tenantID, userID) return nil } - return s.repo.SoftDelete(ctx, userID, tenantID) + if err := s.repo.SoftDelete(ctx, userID, tenantID); err != nil { + return err + } + s.emitRemovalAudit(ctx, tenantID, userID) + return nil +} + +// emitRemovalAudit picks AuditActionMemberLeft when the caller is +// removing themselves, AuditActionMemberRemoved otherwise. Caller +// detection uses the user-id from the request context — the same +// source the LeaveTenant handler uses to derive its `userID` arg. +func (s *tenantMemberService) emitRemovalAudit( + ctx context.Context, + tenantID uint64, + targetUserID string, +) { + action := types.AuditActionMemberRemoved + if actor := auditActor(ctx); actor != "" && actor == targetUserID { + action = types.AuditActionMemberLeft + } + s.emitAudit(ctx, &types.AuditLog{ + TenantID: tenantID, + ActorUserID: auditActor(ctx), + ActorRole: auditActorRole(ctx), + Action: action, + TargetType: "tenant_member", + TargetUserID: targetUserID, + Outcome: types.AuditOutcomeSuccess, + }) } diff --git a/internal/application/service/tenant_member_test.go b/internal/application/service/tenant_member_test.go index 0889d307..2bd7cd9d 100644 --- a/internal/application/service/tenant_member_test.go +++ b/internal/application/service/tenant_member_test.go @@ -27,12 +27,12 @@ type fakeTenantMemberRepo struct { nextID uint64 // failGet, failHasAny etc. let tests inject transient errors on the // matching method to exercise error paths. - failGet error - failHasAny error - failCountOwners error - failUpdateRole error - failSoftDelete error - failCreate error + failGet error + failHasAny error + failCountOwners error + failUpdateRole error + failSoftDelete error + failCreate error } func newFakeRepo() *fakeTenantMemberRepo { return &fakeTenantMemberRepo{} } @@ -207,7 +207,11 @@ var _ interfaces.TenantMemberRepository = (*fakeTenantMemberRepo)(nil) func newServiceWithRepo() (interfaces.TenantMemberService, *fakeTenantMemberRepo) { r := newFakeRepo() - return NewTenantMemberService(r), r + // Audit dependency is intentionally nil — these tests pre-date PR 6 + // and exercise membership invariants only. The service's audit + // hooks are nil-safe (see emitAudit), so passing nil keeps existing + // coverage intact without forcing a stub. + return NewTenantMemberService(r, nil), r } func TestTenantMemberService_AddMember_RejectsInvalidRole(t *testing.T) { diff --git a/internal/container/container.go b/internal/container/container.go index d788035b..acbbbdf0 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -136,6 +136,7 @@ func BuildContainer(container *dig.Container) *dig.Container { logger.Debugf(ctx, "[Container] Registering repositories...") must(container.Provide(repository.NewTenantRepository)) must(container.Provide(repository.NewTenantMemberRepository)) + must(container.Provide(repository.NewAuditLogRepository)) must(container.Provide(repository.NewKnowledgeBaseRepository)) must(container.Provide(repository.NewKnowledgeRepository)) must(container.Provide(repository.NewChunkRepository)) @@ -170,6 +171,7 @@ func BuildContainer(container *dig.Container) *dig.Container { logger.Debugf(ctx, "[Container] Registering business services...") must(container.Provide(service.NewTenantService)) must(container.Provide(service.NewTenantMemberService)) + must(container.Provide(service.NewAuditLogService)) must(container.Provide(service.NewKnowledgeBaseService)) must(container.Provide(service.NewOrganizationService)) must(container.Provide(service.NewKBShareService)) // KBShareService must be registered before KnowledgeService and KnowledgeTagService @@ -283,6 +285,7 @@ func BuildContainer(container *dig.Container) *dig.Container { logger.Debugf(ctx, "[Container] Registering HTTP handlers...") must(container.Provide(handler.NewTenantHandler)) must(container.Provide(handler.NewTenantMemberHandler)) + must(container.Provide(handler.NewAuditLogHandler)) must(container.Provide(handler.NewKnowledgeBaseHandler)) must(container.Provide(handler.NewKnowledgeHandler)) must(container.Provide(handler.NewChunkHandler)) diff --git a/internal/handler/audit_log.go b/internal/handler/audit_log.go new file mode 100644 index 00000000..ecbe9469 --- /dev/null +++ b/internal/handler/audit_log.go @@ -0,0 +1,106 @@ +package handler + +import ( + "net/http" + "strconv" + + apperrors "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// AuditLogHandler exposes the per-tenant audit-log feed (PR 6, #1303). +// The route group lives under /tenants/:id/audit-log, gated by +// PathTenantMatch (URL :id == active tenant) plus an Admin role +// requirement — leaks of denied-action histories should not surface +// to ordinary members. +type AuditLogHandler struct { + auditService interfaces.AuditLogService +} + +// NewAuditLogHandler constructs the handler. +func NewAuditLogHandler(auditService interfaces.AuditLogService) *AuditLogHandler { + return &AuditLogHandler{auditService: auditService} +} + +// auditLogListResponse is the response envelope for ListTenantAuditLog. +// Mirrors wiki_log_entries' shape: data array + an opaque cursor (here +// the integer id of the last entry, or 0 if no more rows). +type auditLogListResponse struct { + Success bool `json:"success"` + Data []*types.AuditLog `json:"data"` + NextCursor uint64 `json:"next_cursor"` +} + +// ListTenantAuditLog godoc +// @Summary 获取租户审计日志 +// @Description 返回该租户最近的审计事件,按 id 倒序。游标分页:将上次响应的 next_cursor 作为下一次请求的 after_id。 +// @Tags 审计日志 +// @Produce json +// @Param id path string true "租户ID" +// @Param after_id query int false "游标:返回 id 小于此值的记录(默认从最新开始)" +// @Param limit query int false "页大小,1-100,默认 50" +// @Param action query string false "按 action 精确过滤(如 rbac.member_added / rbac.access_denied)" +// @Param outcome query string false "按 outcome 精确过滤(success / denied)" +// @Param actor query string false "按 actor_user_id 精确过滤" +// @Success 200 {object} auditLogListResponse +// @Failure 400 {object} errors.AppError +// @Security Bearer +// @Security ApiKeyAuth +// @Router /tenants/{id}/audit-log [get] +func (h *AuditLogHandler) ListTenantAuditLog(c *gin.Context) { + ctx := c.Request.Context() + tenantID, ok := parseTenantIDFromPath(c) + if !ok { + // parseTenantIDFromPath has already attached an error to gin. + return + } + + // after_id cursor — invalid values are tolerated (treated as "from + // the top") so a misconfigured client doesn't see a hard 400 on + // the empty / first request. Tighter validation belongs at the + // frontend. + var afterID uint64 + if raw := c.Query("after_id"); raw != "" { + if v, err := strconv.ParseUint(raw, 10, 64); err == nil { + afterID = v + } + } + limit := 0 // 0 lets the repository pick its default (50) + if raw := c.Query("limit"); raw != "" { + if v, err := strconv.Atoi(raw); err == nil && v > 0 { + limit = v + } + } + + q := &interfaces.AuditLogQuery{ + AfterID: afterID, + Limit: limit, + Action: types.AuditAction(c.Query("action")), + Outcome: types.AuditOutcome(c.Query("outcome")), + ActorUserID: c.Query("actor"), + } + + entries, err := h.auditService.List(ctx, tenantID, q) + if err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": tenantID}) + c.Error(apperrors.NewInternalServerError(err.Error())) + return + } + + // next_cursor is the smallest id in the page (since rows are sorted + // id DESC). Empty page ⇒ 0, telling the client there's nothing + // older to fetch. + var nextCursor uint64 + if n := len(entries); n > 0 { + nextCursor = entries[n-1].ID + } + + c.JSON(http.StatusOK, auditLogListResponse{ + Success: true, + Data: entries, + NextCursor: nextCursor, + }) +} diff --git a/internal/handler/audit_log_test.go b/internal/handler/audit_log_test.go new file mode 100644 index 00000000..3cd12eab --- /dev/null +++ b/internal/handler/audit_log_test.go @@ -0,0 +1,155 @@ +package handler + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + + "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// stubAuditService implements just AuditLogService.List for the +// handler tests. Embeds the interface so any other call panics — +// surfaces a contract drift loudly instead of silently working. +type stubAuditService struct { + interfaces.AuditLogService + list func(ctx context.Context, tenantID uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) +} + +func (s *stubAuditService) List( + ctx context.Context, tenantID uint64, q *interfaces.AuditLogQuery, +) ([]*types.AuditLog, error) { + return s.list(ctx, tenantID, q) +} + +// newAuditHandlerTestRouter mounts the handler with the production +// ErrorHandler so c.Error renders the canonical envelope. Path :id is +// resolved by parseTenantIDFromPath; tenant context is not required by +// the handler (PathTenantMatch is stripped from this layer because the +// tests focus on the handler's own surface). +func newAuditHandlerTestRouter(svc interfaces.AuditLogService) *gin.Engine { + gin.SetMode(gin.TestMode) + r := gin.New() + r.Use(middleware.ErrorHandler()) + h := NewAuditLogHandler(svc) + r.GET("/tenants/:id/audit-log", h.ListTenantAuditLog) + return r +} + +func TestAuditLogHandler_ReturnsEnvelopeAndCursor(t *testing.T) { + // Two rows: smallest id appears in the next_cursor field so the + // frontend can re-request older pages without re-parsing the body. + svc := &stubAuditService{ + list: func(_ context.Context, tenantID uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) { + if tenantID != 7 { + t.Fatalf("expected tenant 7, got %d", tenantID) + } + return []*types.AuditLog{ + {ID: 102, TenantID: 7, Action: types.AuditActionMemberAdded}, + {ID: 95, TenantID: 7, Action: types.AuditActionAccessDenied, Outcome: types.AuditOutcomeDenied}, + }, nil + }, + } + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/tenants/7/audit-log", nil) + newAuditHandlerTestRouter(svc).ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String()) + } + var got auditLogListResponse + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if !got.Success { + t.Fatalf("expected success=true") + } + if len(got.Data) != 2 { + t.Fatalf("expected 2 entries, got %d", len(got.Data)) + } + if got.NextCursor != 95 { + t.Fatalf("expected next_cursor to be the smallest id (95), got %d", got.NextCursor) + } +} + +func TestAuditLogHandler_PassesQueryFiltersThrough(t *testing.T) { + // The handler must propagate after_id / limit / action / outcome / + // actor exactly as the service expects them. A regression here + // would silently drop a filter and over-return rows on the wire. + svc := &stubAuditService{ + list: func(_ context.Context, _ uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) { + if q.AfterID != 100 { + t.Fatalf("expected after_id=100, got %d", q.AfterID) + } + if q.Limit != 25 { + t.Fatalf("expected limit=25, got %d", q.Limit) + } + if q.Action != types.AuditActionAccessDenied { + t.Fatalf("expected action=access_denied, got %q", q.Action) + } + if q.Outcome != types.AuditOutcomeDenied { + t.Fatalf("expected outcome=denied, got %q", q.Outcome) + } + if q.ActorUserID != "u-probing" { + t.Fatalf("expected actor=u-probing, got %q", q.ActorUserID) + } + return nil, nil + }, + } + w := httptest.NewRecorder() + q := "after_id=100&limit=25&action=rbac.access_denied&outcome=denied&actor=u-probing" + req := httptest.NewRequest(http.MethodGet, "/tenants/7/audit-log?"+q, nil) + newAuditHandlerTestRouter(svc).ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String()) + } +} + +func TestAuditLogHandler_EmptyResultProducesZeroCursor(t *testing.T) { + // next_cursor=0 is the documented "no more rows" signal; the frontend + // stops paginating when it sees this, so a regression that returns + // the previous cursor on an empty page would loop forever. + svc := &stubAuditService{ + list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) { + return nil, nil + }, + } + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/tenants/7/audit-log", nil) + newAuditHandlerTestRouter(svc).ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String()) + } + var got auditLogListResponse + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if got.NextCursor != 0 { + t.Fatalf("expected next_cursor=0 on empty page, got %d", got.NextCursor) + } +} + +func TestAuditLogHandler_InvalidTenantIDReturns400(t *testing.T) { + // parseTenantIDFromPath rejects non-numeric tenant ids with 400 so + // the handler never even calls the service. The harness still has + // to not crash on an empty service if it's reached — guard with a + // service that fails the test loudly. + svc := &stubAuditService{ + list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) { + return nil, fmt.Errorf("must not be called") + }, + } + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/tenants/not-a-number/audit-log", nil) + newAuditHandlerTestRouter(svc).ServeHTTP(w, req) + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400 for non-numeric tenant id, got %d body=%s", w.Code, w.Body.String()) + } +} diff --git a/internal/middleware/audit_provider.go b/internal/middleware/audit_provider.go new file mode 100644 index 00000000..59c5771c --- /dev/null +++ b/internal/middleware/audit_provider.go @@ -0,0 +1,41 @@ +package middleware + +import ( + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// auditServiceContextKey is the gin context key used by +// AuditServiceProvider to stash the running AuditLogService so that +// middleware functions (rbac.go's RequireRole / RequireOwnershipOrRole) +// can pull it out without needing the service threaded into their +// signatures. Same pattern as the langfuse gin middleware. +const auditServiceContextKey = "weknora.audit_service" + +// AuditServiceProvider returns a gin middleware that injects the audit +// service into every request's gin.Context. Wiring is centralised in +// router.NewRouter so each request gets the same instance for the +// lifetime of the process; the middleware is a no-op when svc is nil +// (e.g. lite mode where audit isn't configured) so the rbac reject +// path degrades gracefully. +func AuditServiceProvider(svc interfaces.AuditLogService) gin.HandlerFunc { + return func(c *gin.Context) { + if svc != nil { + c.Set(auditServiceContextKey, svc) + } + c.Next() + } +} + +// AuditServiceFromContext fetches the audit service injected by +// AuditServiceProvider, or returns nil if no provider was wired +// upstream. Callers MUST nil-check before invoking — audit failure +// must never break the underlying business operation. +func AuditServiceFromContext(c *gin.Context) interfaces.AuditLogService { + if v, ok := c.Get(auditServiceContextKey); ok { + if svc, ok := v.(interfaces.AuditLogService); ok { + return svc + } + } + return nil +} diff --git a/internal/middleware/rbac.go b/internal/middleware/rbac.go index 685ce896..a9f459c9 100644 --- a/internal/middleware/rbac.go +++ b/internal/middleware/rbac.go @@ -88,6 +88,14 @@ func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc { logger.Warnf(ctx, "[rbac] role insufficient: user=%s have=%s need=%s path=%s", uid, role, min, c.Request.URL.Path) + // Durable audit row for the reject. AuditServiceProvider + // injects the service; subject to 1-minute sliding-window + // dedup inside the service so probing clients can't fill the + // table. + if svc := AuditServiceFromContext(c); svc != nil { + tenantID, _ := types.TenantIDFromContext(ctx) + _ = svc.LogDenied(ctx, c, tenantID, uid, string(role), min) + } c.JSON(http.StatusForbidden, gin.H{ "error": "Forbidden: insufficient tenant role", }) @@ -181,6 +189,11 @@ func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *con logger.Warnf(ctx, "[rbac] ownership/role insufficient: user=%s have=%s need=%s creator=%q path=%s", uid, role, min, creator, c.Request.URL.Path) + // Same durable audit hook as RequireRole — subject to dedup. + if svc := AuditServiceFromContext(c); svc != nil { + tenantID, _ := types.TenantIDFromContext(ctx) + _ = svc.LogDenied(ctx, c, tenantID, uid, string(role), min) + } c.JSON(http.StatusForbidden, gin.H{ "error": "Forbidden: must own the resource or have the required role", }) diff --git a/internal/middleware/rbac_audit_test.go b/internal/middleware/rbac_audit_test.go new file mode 100644 index 00000000..a4e295bd --- /dev/null +++ b/internal/middleware/rbac_audit_test.go @@ -0,0 +1,137 @@ +package middleware + +import ( + "context" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// PR 6 (#1303): the rbac middleware's two reject paths now call +// AuditServiceFromContext(c).LogDenied so denials are durably +// recorded. These tests pin that wiring — without them, a future +// refactor that drops the AuditServiceProvider middleware (or breaks +// the context-stash key) would silently lose the durable audit +// without any coverage signal. + +// stubDenyAudit captures LogDenied calls. Embeds the interface so any +// other method panics on use — keeps tests honest about which API +// they're exercising. +type stubDenyAudit struct { + interfaces.AuditLogService + mu sync.Mutex + calls []denyCall +} + +type denyCall struct { + tenantID uint64 + actorUserID string + actorRole string + required types.TenantRole +} + +func (s *stubDenyAudit) LogDenied( + _ context.Context, + _ *gin.Context, + tenantID uint64, + actorUserID, actorRole string, + requiredRole types.TenantRole, +) error { + s.mu.Lock() + defer s.mu.Unlock() + s.calls = append(s.calls, denyCall{tenantID, actorUserID, actorRole, requiredRole}) + return nil +} + +// auditableHarness mirrors rbacTestHarness but additionally wires +// AuditServiceProvider with the supplied stub so the rejection +// paths can exercise the audit hook. +func auditableHarness( + t *testing.T, role types.TenantRole, userID string, tenantID uint64, + audit interfaces.AuditLogService, mw gin.HandlerFunc, +) *httptest.ResponseRecorder { + t.Helper() + gin.SetMode(gin.TestMode) + r := gin.New() + r.Use(AuditServiceProvider(audit)) + r.Use(func(c *gin.Context) { + ctx := context.WithValue(c.Request.Context(), types.TenantRoleContextKey, role) + ctx = context.WithValue(ctx, types.UserIDContextKey, userID) + ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID) + c.Request = c.Request.WithContext(ctx) + c.Next() + }) + r.GET("/protected", mw, func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"ok": true}) + }) + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/protected", nil) + r.ServeHTTP(w, req) + return w +} + +func TestRequireRole_RejectFiresAuditHook(t *testing.T) { + audit := &stubDenyAudit{} + w := auditableHarness(t, types.TenantRoleContributor, "u1", 7, audit, + RequireRole(types.TenantRoleAdmin, cfgRBAC(true))) + if w.Code != http.StatusForbidden { + t.Fatalf("expected 403, got %d", w.Code) + } + if len(audit.calls) != 1 { + t.Fatalf("expected exactly one audit hook call, got %d", len(audit.calls)) + } + got := audit.calls[0] + if got.tenantID != 7 || got.actorUserID != "u1" || + got.actorRole != string(types.TenantRoleContributor) || + got.required != types.TenantRoleAdmin { + t.Fatalf("audit hook payload mismatch: %+v", got) + } +} + +func TestRequireRole_DormantModeDoesNotFireAuditHook(t *testing.T) { + // EnableRBAC=false: middleware logs but does NOT 403, so the + // durable audit must NOT fire either — the dormant rollout window + // would otherwise generate audit noise for non-rejections. + audit := &stubDenyAudit{} + w := auditableHarness(t, types.TenantRoleViewer, "u1", 7, audit, + RequireRole(types.TenantRoleOwner, cfgRBAC(false))) + if w.Code != http.StatusOK { + t.Fatalf("expected 200 in dormant mode, got %d", w.Code) + } + if len(audit.calls) != 0 { + t.Fatalf("dormant mode must not fire audit, got %d calls", len(audit.calls)) + } +} + +func TestRequireOwnershipOrRole_RejectFiresAuditHook(t *testing.T) { + // Mirror of TestRequireRole_RejectFiresAuditHook but for the + // ownership variant — the audit hook lives at a different reject + // site and must NOT skip the durable write. + audit := &stubDenyAudit{} + lookup := func(_ *gin.Context) (string, error) { + return "someone-else", nil // creator != caller, role too low + } + w := auditableHarness(t, types.TenantRoleContributor, "u1", 7, audit, + RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true))) + if w.Code != http.StatusForbidden { + t.Fatalf("expected 403, got %d", w.Code) + } + if len(audit.calls) != 1 { + t.Fatalf("expected exactly one audit hook call, got %d", len(audit.calls)) + } +} + +func TestRequireRole_NilAuditServiceDoesNotPanic(t *testing.T) { + // AuditServiceProvider(nil) is a deliberate no-op; the rbac path + // must degrade to "log to stderr only" rather than crashing. + w := auditableHarness(t, types.TenantRoleContributor, "u1", 7, nil, + RequireRole(types.TenantRoleAdmin, cfgRBAC(true))) + if w.Code != http.StatusForbidden { + t.Fatalf("expected 403 even with nil audit service, got %d", w.Code) + } +} diff --git a/internal/router/router.go b/internal/router/router.go index 2fb4ef0f..aa7fb26e 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -50,6 +50,8 @@ type RouterParams struct { TenantService interfaces.TenantService TenantMemberService interfaces.TenantMemberService TenantMemberHandler *handler.TenantMemberHandler + AuditLogHandler *handler.AuditLogHandler + AuditLogService interfaces.AuditLogService ChunkHandler *handler.ChunkHandler SessionHandler *session.Handler MessageHandler *handler.MessageHandler @@ -139,6 +141,13 @@ func NewRouter(params RouterParams) *gin.Engine { // The middleware is registered unconditionally; when disabled it's a no-op. r.Use(langfuse.GinMiddleware()) + // Audit log injection — middleware/rbac.go's reject paths and the + // admin-only /tenants/:id/audit-log endpoint pull the service out + // of the gin context. Provider is a no-op when AuditLogService is + // nil (e.g. lite mode without DB), so the rbac path degrades to + // "log to stderr only" instead of crashing. + r.Use(middleware.AuditServiceProvider(params.AuditLogService)) + // 需要认证的API路由 v1 := r.Group("/api/v1") { @@ -157,7 +166,7 @@ func NewRouter(params RouterParams) *gin.Engine { ) RegisterAuthRoutes(v1, params.AuthHandler) - RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, rbacGuards) + RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, params.AuditLogHandler, rbacGuards) RegisterKnowledgeBaseRoutes(v1, params.KBHandler, rbacGuards) RegisterKnowledgeTagRoutes(v1, params.TagHandler, rbacGuards) RegisterKnowledgeRoutes(v1, params.KnowledgeHandler, rbacGuards) @@ -453,6 +462,7 @@ func RegisterTenantRoutes( r *gin.RouterGroup, handler *handler.TenantHandler, memberHandler *handler.TenantMemberHandler, + auditLogHandler *handler.AuditLogHandler, g *rbacGuards, ) { // Cross-tenant superuser endpoints — promoted from handler if-blocks @@ -494,6 +504,15 @@ func RegisterTenantRoutes( tenantByID.DELETE("/members/:user_id", g.Owner(), memberHandler.RemoveMember) tenantByID.POST("/leave", g.Viewer(), memberHandler.LeaveTenant) } + + // Audit log feed (PR 6 of #1303). Admin+ so denied-action + // histories don't surface to ordinary members; the + // PathTenantMatch group already prevents cross-tenant + // reads. nil-skip mirrors the memberHandler pattern above + // for environments wired without the audit dependency. + if auditLogHandler != nil { + tenantByID.GET("/audit-log", g.Admin(), auditLogHandler.ListTenantAuditLog) + } } } } diff --git a/internal/types/audit_log.go b/internal/types/audit_log.go new file mode 100644 index 00000000..d909717f --- /dev/null +++ b/internal/types/audit_log.go @@ -0,0 +1,71 @@ +package types + +import ( + "time" +) + +// AuditAction names a single audited action class. Action constants are +// dot-namespaced (`.`) so future PRs can plug in their own +// areas (e.g. `kb.shared`, `agent.copied`) without colliding with the +// RBAC events PR 6 ships. +type AuditAction string + +const ( + // AuditActionMemberAdded fires when a tenant Owner / Admin adds a + // new tenant_members row. The actor is the inviter; the target is + // the invited user. + AuditActionMemberAdded AuditAction = "rbac.member_added" + // AuditActionMemberRemoved fires when an Owner / Admin removes a + // tenant_members row. Distinct from MemberLeft so an audit reader + // can tell "kicked out" from "left voluntarily". + AuditActionMemberRemoved AuditAction = "rbac.member_removed" + // AuditActionMemberRoleChanged fires for promote/demote operations. + // The Details payload carries old_role and new_role. + AuditActionMemberRoleChanged AuditAction = "rbac.member_role_changed" + // AuditActionMemberLeft fires on POST /tenants/:id/leave — the + // actor and target are the same user. + AuditActionMemberLeft AuditAction = "rbac.member_left" + // AuditActionAccessDenied fires when middleware/rbac.go's + // RequireRole or RequireOwnershipOrRole rejects a request under + // EnableRBAC=true. Subject to 1-minute sliding-window dedup so a + // probing client cannot fill the table. + AuditActionAccessDenied AuditAction = "rbac.access_denied" +) + +// AuditOutcome distinguishes successful mutations from middleware-level +// rejections. The split lets the audit-log UI highlight denials in red +// without needing to enumerate every action class. +type AuditOutcome string + +const ( + AuditOutcomeSuccess AuditOutcome = "success" + AuditOutcomeDenied AuditOutcome = "denied" +) + +// AuditLog is a single immutable audit event. The schema is intentionally +// generic: PR 6 wires only RBAC events, but TargetType / TargetID / +// Details are set up to absorb KB / agent / datasource events in +// follow-up PRs without another migration. +// +// Rows are append-only — no UpdatedAt, no soft-delete column. The +// monotonic ID acts as both primary key and pagination cursor (newest- +// first is `WHERE id < AfterID ORDER BY id DESC`). +type AuditLog struct { + ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"` + TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_audit_logs_tenant_id_desc,priority:1;index:idx_audit_logs_tenant_action,priority:1"` + ActorUserID string `json:"actor_user_id" gorm:"type:varchar(36);default:'';index:idx_audit_logs_actor"` + ActorRole string `json:"actor_role" gorm:"type:varchar(32);default:''"` + Action AuditAction `json:"action" gorm:"type:varchar(64);not null;index:idx_audit_logs_tenant_action,priority:2"` + TargetType string `json:"target_type" gorm:"type:varchar(32);default:''"` + TargetID string `json:"target_id" gorm:"type:varchar(64);default:''"` + TargetUserID string `json:"target_user_id" gorm:"type:varchar(36);default:''"` + RequestPath string `json:"request_path" gorm:"type:varchar(512);default:''"` + RequestMethod string `json:"request_method" gorm:"type:varchar(16);default:''"` + Outcome AuditOutcome `json:"outcome" gorm:"type:varchar(16);default:success"` + Details JSON `json:"details" gorm:"type:jsonb;default:'{}'"` + CreatedAt time.Time `json:"created_at" gorm:"index:idx_audit_logs_tenant_id_desc,priority:2,sort:desc"` +} + +// TableName pins the table name even if a future GORM convention +// pluralisation refactor would otherwise rename it. +func (AuditLog) TableName() string { return "audit_logs" } diff --git a/internal/types/interfaces/audit_log.go b/internal/types/interfaces/audit_log.go new file mode 100644 index 00000000..ca396cf2 --- /dev/null +++ b/internal/types/interfaces/audit_log.go @@ -0,0 +1,63 @@ +package interfaces + +import ( + "context" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/gin-gonic/gin" +) + +// AuditLogQuery is the cursor + filter set for listing audit log +// entries. AfterID is the last id from the previous page (rows with +// id < AfterID are returned, newest first); 0 means "from the top". +// Limit is capped at 100 inside the repository regardless of caller +// input — keeps unbounded scans off the table. +type AuditLogQuery struct { + AfterID uint64 + Limit int + Action types.AuditAction + Outcome types.AuditOutcome + ActorUserID string +} + +// AuditLogRepository is the storage primitive for the audit table. +// All writes are inserts (immutable rows); the only "update" surface +// is none — once written, an entry is permanent. +type AuditLogRepository interface { + Create(ctx context.Context, entry *types.AuditLog) error + List(ctx context.Context, tenantID uint64, q *AuditLogQuery) ([]*types.AuditLog, error) + // CountSinceForDedup is the rate-limit primitive for LogDenied — + // returns the count of matching rows in the trailing window so the + // service can skip writing duplicates. Filter is + // (tenant_id, actor_user_id, action, request_path, created_at >= since). + CountSinceForDedup( + ctx context.Context, + tenantID uint64, + actorUserID string, + action types.AuditAction, + requestPath string, + since time.Time, + ) (int64, error) +} + +// AuditLogService is the high-level audit API the rest of the codebase +// uses. It owns timestamp defaulting (Log) and rate-limit dedup +// (LogDenied) so callers don't have to think about either. +type AuditLogService interface { + // Log writes a single audit entry. Callers fill TenantID + Action + + // any per-event fields; the service fills CreatedAt if zero. + Log(ctx context.Context, entry *types.AuditLog) error + // LogDenied records a middleware-level reject decision. Subject to + // 1-minute sliding-window dedup keyed by + // (tenant_id, actor_user_id, action, request_path) so a probing + // client cannot flood the table. + LogDenied( + ctx context.Context, + c *gin.Context, + tenantID uint64, + actorUserID, actorRole string, + requiredRole types.TenantRole, + ) error + List(ctx context.Context, tenantID uint64, q *AuditLogQuery) ([]*types.AuditLog, error) +} diff --git a/migrations/sqlite/000000_init.down.sql b/migrations/sqlite/000000_init.down.sql index 34cf8485..951bbe6c 100644 --- a/migrations/sqlite/000000_init.down.sql +++ b/migrations/sqlite/000000_init.down.sql @@ -9,6 +9,7 @@ DROP TABLE IF EXISTS mcp_tool_approvals; DROP TABLE IF EXISTS mcp_services; DROP TABLE IF EXISTS knowledge_tags; DROP TABLE IF EXISTS auth_tokens; +DROP TABLE IF EXISTS audit_logs; DROP TABLE IF EXISTS tenant_members; DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS chunks; diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql index 31bbe1c9..53960e6f 100644 --- a/migrations/sqlite/000000_init.up.sql +++ b/migrations/sqlite/000000_init.up.sql @@ -271,6 +271,32 @@ CREATE INDEX IF NOT EXISTS idx_tenant_members_tenant_role CREATE INDEX IF NOT EXISTS idx_tenant_members_user ON tenant_members(user_id); +-- audit_logs is the generic per-tenant durability for RBAC events +-- (and future KB / agent / datasource events). Sqlite mirror of the +-- 000044_audit_log migration; same column shape with INTEGER for the +-- BIGSERIAL id and TEXT in place of JSONB for details. +CREATE TABLE IF NOT EXISTS audit_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + tenant_id INTEGER NOT NULL, + actor_user_id VARCHAR(36) NOT NULL DEFAULT '', + actor_role VARCHAR(32) NOT NULL DEFAULT '', + action VARCHAR(64) NOT NULL, + target_type VARCHAR(32) NOT NULL DEFAULT '', + target_id VARCHAR(64) NOT NULL DEFAULT '', + target_user_id VARCHAR(36) NOT NULL DEFAULT '', + request_path VARCHAR(512) NOT NULL DEFAULT '', + request_method VARCHAR(16) NOT NULL DEFAULT '', + outcome VARCHAR(16) NOT NULL DEFAULT 'success', + details TEXT NOT NULL DEFAULT '{}', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_id_desc + ON audit_logs(tenant_id, id DESC); +CREATE INDEX IF NOT EXISTS idx_audit_logs_actor + ON audit_logs(actor_user_id); +CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_action + ON audit_logs(tenant_id, action); + CREATE TABLE IF NOT EXISTS knowledge_tags ( id VARCHAR(36) PRIMARY KEY, tenant_id INTEGER NOT NULL, diff --git a/migrations/versioned/000044_audit_log.down.sql b/migrations/versioned/000044_audit_log.down.sql new file mode 100644 index 00000000..68a74c48 --- /dev/null +++ b/migrations/versioned/000044_audit_log.down.sql @@ -0,0 +1,25 @@ +-- Migration 000044 down: drop audit_logs table. +-- +-- DANGER: This drops the audit_logs table. All durable RBAC and +-- resource-action history is lost UNRECOVERABLY. Only intended +-- for development rollbacks, never for production. +-- +-- Operators who really need to run this in a non-dev environment must +-- set the session-level GUC `weknora.allow_destructive_migration` to +-- 'true' first. Otherwise the migration aborts before touching any data. +DO $$ +BEGIN + IF coalesce(current_setting('weknora.allow_destructive_migration', true), 'false') <> 'true' THEN + RAISE EXCEPTION + '[Migration 000044 down] BLOCKED: refuse to drop audit_logs. ' + 'Set weknora.allow_destructive_migration = ''true'' in this session to override.'; + END IF; + RAISE WARNING '[Migration 000044 down] Dropping audit_logs — durable history will be lost'; +END $$; + +DROP INDEX IF EXISTS idx_audit_logs_tenant_action; +DROP INDEX IF EXISTS idx_audit_logs_actor; +DROP INDEX IF EXISTS idx_audit_logs_tenant_id_desc; +DROP TABLE IF EXISTS audit_logs; + +DO $$ BEGIN RAISE NOTICE '[Migration 000044 down] audit_logs dropped'; END $$; diff --git a/migrations/versioned/000044_audit_log.up.sql b/migrations/versioned/000044_audit_log.up.sql new file mode 100644 index 00000000..77728734 --- /dev/null +++ b/migrations/versioned/000044_audit_log.up.sql @@ -0,0 +1,56 @@ +-- Migration: 000044_audit_log +-- Adds a generic per-tenant audit log table (issue #1303 PR 6). +-- +-- Scope: +-- - PR 6 wires the table to RBAC events (member add/remove/role-change/ +-- leave) and middleware-level enforcement denials. +-- - The schema is intentionally generic (action, target_type, target_id, +-- details JSONB) so future PRs (KB ops, agent ops, datasource sync) +-- can plug in new action constants without another migration. +-- +-- Indexes: +-- - (tenant_id, id DESC) for the cursor-paginated feed query +-- ("show this tenant's audit log newest-first"). +-- - (actor_user_id) for "what did Alice do" lookups. +-- - (tenant_id, action) for action-class filtering and powering the +-- 1-minute sliding-window dedup that LogDenied uses to keep a +-- probing client from filling the table. +DO $$ BEGIN RAISE NOTICE '[Migration 000044] Creating table: audit_logs'; END $$; + +CREATE TABLE IF NOT EXISTS audit_logs ( + id BIGSERIAL PRIMARY KEY, + tenant_id BIGINT NOT NULL, + actor_user_id VARCHAR(36) NOT NULL DEFAULT '', + actor_role VARCHAR(32) NOT NULL DEFAULT '', + action VARCHAR(64) NOT NULL, + target_type VARCHAR(32) NOT NULL DEFAULT '', + target_id VARCHAR(64) NOT NULL DEFAULT '', + target_user_id VARCHAR(36) NOT NULL DEFAULT '', + request_path VARCHAR(512) NOT NULL DEFAULT '', + request_method VARCHAR(16) NOT NULL DEFAULT '', + outcome VARCHAR(16) NOT NULL DEFAULT 'success', + details JSONB NOT NULL DEFAULT '{}'::JSONB, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- Primary list query: newest-first cursor pagination per tenant. Using id +-- (BIGSERIAL, monotonic) as the cursor sidesteps the duplicate-timestamp +-- tie-breaking that a created_at cursor would require — same approach as +-- wiki_log_entries (migration 000040). +CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_id_desc + ON audit_logs (tenant_id, id DESC); + +-- Filter by actor (e.g. "what did Alice do"). Useful for incident +-- response and for user-scoped self-audit screens (out of v1 scope but +-- the index is cheap and the column is already there). +CREATE INDEX IF NOT EXISTS idx_audit_logs_actor + ON audit_logs (actor_user_id); + +-- Powers two queries: (a) the audit-log feed filtered by action class, +-- and (b) the LogDenied dedup `count rows where (tenant_id, action) and +-- created_at >= since`. Without this index the dedup count would scan +-- the entire table on every denied request. +CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_action + ON audit_logs (tenant_id, action); + +DO $$ BEGIN RAISE NOTICE '[Migration 000044] audit_logs table ready'; END $$;