Elffuss BraidHub

kikocis/utopia public

dev · 6.5 KiBRawPermalink
1//! 审计日志:谁在何时对什么做了什么。纯审计——只记录与展示,不承载回滚等衍生功能。
2//! 记录失败绝不影响业务操作(调用方一律 `let _ =`)。
3
4use sqlx::PgPool;
5use utopia_core::models::AuditEventView;
6use utopia_core::AppResult;
7use uuid::Uuid;
8
9pub async fn record(
10 pool: &PgPool,
11 kb_id: Option<Uuid>,
12 actor_id: Uuid,
13 action: &str,
14 target_kind: &str,
15 target_id: Option<Uuid>,
16 detail: serde_json::Value,
17) -> AppResult<()> {
18 record_opt(
19 pool,
20 kb_id,
21 Some(actor_id),
22 action,
23 target_kind,
24 target_id,
25 detail,
26 )
27 .await
28}
29
30/// 请求的来源信息。由 HTTP 层在每个请求外层 scope 进 [`CLIENT`],`record_opt`
31/// 自行读取——否则 25 个调用点每一个都要多带两个与业务无关的参数。
32///
33/// 后台任务(攒批裁决、定时同步)不在任何请求之内,读到的是 None,本就该如此:
34/// 那些动作确实没有客户端。
35#[derive(Debug, Clone, Default)]
36pub struct ClientContext {
37 pub ip: Option<String>,
38 pub user_agent: Option<String>,
39}
40
41tokio::task_local! {
42 pub static CLIENT: ClientContext;
43}
44
45/// 取当前请求的来源;不在请求上下文中(后台任务)时返回全空。
46fn client_context() -> ClientContext {
47 CLIENT.try_with(|c| c.clone()).unwrap_or_default()
48}
49
50/// 无人类操作者的系统事件(如 AI 裁决自动合并)走这里:actor 为 NULL。
51pub async fn record_opt(
52 pool: &PgPool,
53 kb_id: Option<Uuid>,
54 actor_id: Option<Uuid>,
55 action: &str,
56 target_kind: &str,
57 target_id: Option<Uuid>,
58 detail: serde_json::Value,
59) -> AppResult<()> {
60 let ctx = client_context();
61 // 身份快照:用户日后被删除时(0025 之后行会留下),台账仍认得出是谁,而不是
62 // 只剩一串 UUID。此刻查是可靠的——操作正在发生,人还在。
63 let actor_label: Option<String> = match actor_id {
64 Some(id) => sqlx::query_scalar("SELECT email FROM users WHERE id = $1")
65 .bind(id)
66 .fetch_optional(pool)
67 .await
68 .ok()
69 .flatten(),
70 None => None,
71 };
72 sqlx::query(
73 "INSERT INTO audit_events
74 (id, kb_id, actor_id, action, target_kind, target_id, detail,
75 client_ip, user_agent, actor_label)
76 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
77 )
78 .bind(Uuid::now_v7())
79 .bind(kb_id)
80 .bind(actor_id)
81 .bind(action)
82 .bind(target_kind)
83 .bind(target_id)
84 .bind(detail)
85 .bind(ctx.ip)
86 .bind(ctx.user_agent)
87 .bind(actor_label)
88 .execute(pool)
89 .await?;
90 Ok(())
91}
92
93/// 审核决策台账:只取 review 域的动作(review./fact./conflict./merge.),服务端分页。
94pub async fn review_history(
95 pool: &PgPool,
96 kb_id: Uuid,
97 limit: i64,
98 offset: i64,
99) -> AppResult<(Vec<AuditEventView>, i64)> {
100 const COND: &str = "e.kb_id = $1 AND (e.action LIKE 'review.%' OR e.action LIKE 'fact.%'
101 OR e.action LIKE 'conflict.%' OR e.action LIKE 'merge.%')";
102 let rows: Vec<AuditEventView> = sqlx::query_as(&format!(
103 "SELECT e.id, e.action, e.target_kind, e.target_id, e.detail,
104 e.actor_id, u.display_name AS actor_name, e.created_at
105 FROM audit_events e LEFT JOIN users u ON u.id = e.actor_id
106 WHERE {COND} ORDER BY e.created_at DESC LIMIT $2 OFFSET $3"
107 ))
108 .bind(kb_id)
109 .bind(limit)
110 .bind(offset)
111 .fetch_all(pool)
112 .await?;
113 let (total,): (i64,) =
114 sqlx::query_as(&format!("SELECT count(*) FROM audit_events e WHERE {COND}"))
115 .bind(kb_id)
116 .fetch_one(pool)
117 .await?;
118 Ok((rows, total))
119}
120
121/// 一个知识库的审计台账,**带分页与筛选**。
122///
123/// 从前是固定最近 100 条、无分页无筛选——而台账是合规材料,「只看得到最近
124/// 一百条」等于查不了历史。三个筛选是按真实的查法挑的:
125///
126/// - `action`:查一类动作(「谁改过类型」「有哪些拒绝」)。前缀匹配而不是
127/// 全等,因为动作名本身分层(`entity.retyped` / `entity.renamed`),
128/// 传 `entity.` 就能把一族捞出来
129/// - `actor`:查一个人做过什么。合规审计最常见的问题
130/// - `since` / `until`:查一段时间。事故复盘要的就是这个
131///
132/// 一并回总数,否则分页器不知道有几页——而「不知道有几页」正是这一档
133/// 从前那个 100 的翻版。
134#[allow(clippy::too_many_arguments)]
135pub async fn list_for_kb(
136 pool: &PgPool,
137 kb_id: Uuid,
138 action: Option<&str>,
139 actor: Option<Uuid>,
140 since: Option<chrono::DateTime<chrono::Utc>>,
141 until: Option<chrono::DateTime<chrono::Utc>>,
142 limit: i64,
143 offset: i64,
144) -> AppResult<(Vec<AuditEventView>, i64)> {
145 // 四个筛选都写成「参数为空就不生效」,这样一条 SQL 覆盖全部组合——
146 // 拼字符串会在这里长出十六个分支,而每个分支都是一次注入面
147 const WHERE: &str = "WHERE e.kb_id = $1
148 AND ($2::text IS NULL OR e.action LIKE $2 || '%')
149 AND ($3::uuid IS NULL OR e.actor_id = $3)
150 AND ($4::timestamptz IS NULL OR e.created_at >= $4)
151 AND ($5::timestamptz IS NULL OR e.created_at < $5)";
152
153 let rows: Vec<AuditEventView> = sqlx::query_as(&format!(
154 "SELECT e.id, e.action, e.target_kind, e.target_id, e.detail,
155 e.actor_id, u.display_name AS actor_name, e.created_at
156 FROM audit_events e LEFT JOIN users u ON u.id = e.actor_id
157 {WHERE}
158 ORDER BY e.created_at DESC LIMIT $6 OFFSET $7"
159 ))
160 .bind(kb_id)
161 .bind(action)
162 .bind(actor)
163 .bind(since)
164 .bind(until)
165 .bind(limit)
166 .bind(offset)
167 .fetch_all(pool)
168 .await?;
169
170 let (total,): (i64,) = sqlx::query_as(&format!("SELECT count(*) FROM audit_events e {WHERE}"))
171 .bind(kb_id)
172 .bind(action)
173 .bind(actor)
174 .bind(since)
175 .bind(until)
176 .fetch_one(pool)
177 .await?;
178 Ok((rows, total))
179}
180
181/// 这个库的台账里出现过哪些动作。**筛选下拉要按实际有的填**——列一个
182/// 全部动作的硬编码清单,用户会看到一堆这个库从来没发生过的选项。
183pub async fn actions_for_kb(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<String>> {
184 Ok(
185 sqlx::query_scalar("SELECT DISTINCT action FROM audit_events WHERE kb_id = $1 ORDER BY 1")
186 .bind(kb_id)
187 .fetch_all(pool)
188 .await?,
189 )
190}