Elffuss BraidHub

kikocis/utopia public

95c87338cdc8 · 9.1 KiBRawPermalink
1//! 问数数据源:系统层注册(凭据集中、跨 KB 复用)+ 知识库层挂载(权限跟 KB 走)。
2//! 查询执行时的安全闸(只读会话、SQL 解析白名单、LIMIT/超时)在 server 侧。
3
4use chrono::{DateTime, Utc};
5use sqlx::PgPool;
6use utopia_core::models::DataSourceView;
7use utopia_core::{AppError, AppResult};
8use uuid::Uuid;
9
10/// data_sources 的行投影,list 与 mounted 共用。
11type DataSourceRow = (
12 Uuid,
13 String,
14 String,
15 String,
16 DateTime<Utc>,
17 Option<DateTime<Utc>>,
18 Option<bool>,
19);
20
21/// 连接串 → 无凭据摘要(host:port/db)。解析失败给占位符,绝不回显原串。
22pub fn conn_summary(conn: &str) -> String {
23 url::Url::parse(conn)
24 .ok()
25 .map(|u| {
26 format!(
27 "{}:{}{}",
28 u.host_str().unwrap_or("?"),
29 u.port()
30 .map(|p| p.to_string())
31 .unwrap_or_else(|| "5432".into()),
32 u.path()
33 )
34 })
35 .unwrap_or_else(|| "(unparsed)".into())
36}
37
38/// 行 → 视图。**连接串在这里换成无凭据摘要**,是它不外流的那道关口;
39/// 四条查询共用一份,免得哪天新加一条忘了换
40fn row_to_view(
41 (id, name, engine, conn, created_at, last_test_at, last_test_ok): DataSourceRow,
42) -> DataSourceView {
43 DataSourceView {
44 id,
45 name,
46 engine,
47 summary: conn_summary(&conn),
48 created_at,
49 last_test_at,
50 last_test_ok,
51 }
52}
53
54/// 部署里全部的源。**只给系统管理员的注册台用。**
55/// 从前可挂载列表也走它,那是 0014 关掉的门——KB 侧现在走
56/// `granted_to_workspace`。
57pub async fn list(pool: &PgPool) -> AppResult<Vec<DataSourceView>> {
58 let rows: Vec<DataSourceRow> = sqlx::query_as(
59 "SELECT id, name, engine, conn_string, created_at, last_test_at, last_test_ok
60 FROM data_sources ORDER BY name",
61 )
62 .fetch_all(pool)
63 .await?;
64 Ok(rows.into_iter().map(row_to_view).collect())
65}
66
67pub async fn create(
68 pool: &PgPool,
69 name: &str,
70 engine: &str,
71 conn_string: &str,
72 created_by: Uuid,
73) -> AppResult<Uuid> {
74 if name.trim().is_empty() {
75 return Err(AppError::invalid(
76 "ds_name_required",
77 "Data source name is required",
78 ));
79 }
80 if engine != "postgres" {
81 return Err(AppError::invalid(
82 "only_postgres",
83 "Only the postgres engine is supported for now",
84 ));
85 }
86 if !conn_string.starts_with("postgres://") && !conn_string.starts_with("postgresql://") {
87 return Err(AppError::invalid(
88 "bad_conn_string",
89 "Connection string must start with postgres://",
90 ));
91 }
92 let id = Uuid::now_v7();
93 sqlx::query(
94 "INSERT INTO data_sources (id, name, engine, conn_string, created_by)
95 VALUES ($1, $2, $3, $4, $5)",
96 )
97 .bind(id)
98 .bind(name.trim())
99 .bind(engine)
100 .bind(conn_string.trim())
101 .bind(created_by)
102 .execute(pool)
103 .await?;
104 Ok(id)
105}
106
107pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
108 let res = sqlx::query("DELETE FROM data_sources WHERE id = $1")
109 .bind(id)
110 .execute(pool)
111 .await?;
112 if res.rows_affected() == 0 {
113 return Err(AppError::NotFound);
114 }
115 Ok(())
116}
117
118/// 连接串只在服务端内部流转(测试连接/查询执行)。
119pub async fn conn_string(pool: &PgPool, id: Uuid) -> AppResult<String> {
120 let row: Option<(String,)> =
121 sqlx::query_as("SELECT conn_string FROM data_sources WHERE id = $1")
122 .bind(id)
123 .fetch_optional(pool)
124 .await?;
125 row.map(|(c,)| c).ok_or(AppError::NotFound)
126}
127
128pub async fn record_test(pool: &PgPool, id: Uuid, ok: bool) -> AppResult<()> {
129 sqlx::query("UPDATE data_sources SET last_test_at = now(), last_test_ok = $2 WHERE id = $1")
130 .bind(id)
131 .bind(ok)
132 .execute(pool)
133 .await?;
134 Ok(())
135}
136
137// ---------------------------------------------------------------------------
138// KB 挂载
139// ---------------------------------------------------------------------------
140
141pub async fn mount(pool: &PgPool, kb_id: Uuid, data_source_id: Uuid) -> AppResult<()> {
142 sqlx::query(
143 "INSERT INTO kb_data_sources (kb_id, data_source_id) VALUES ($1, $2)
144 ON CONFLICT DO NOTHING",
145 )
146 .bind(kb_id)
147 .bind(data_source_id)
148 .execute(pool)
149 .await?;
150 Ok(())
151}
152
153pub async fn unmount(pool: &PgPool, kb_id: Uuid, data_source_id: Uuid) -> AppResult<()> {
154 sqlx::query("DELETE FROM kb_data_sources WHERE kb_id = $1 AND data_source_id = $2")
155 .bind(kb_id)
156 .bind(data_source_id)
157 .execute(pool)
158 .await?;
159 Ok(())
160}
161
162pub async fn mounted(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<DataSourceView>> {
163 let rows: Vec<DataSourceRow> = sqlx::query_as(
164 "SELECT d.id, d.name, d.engine, d.conn_string, d.created_at,
165 d.last_test_at, d.last_test_ok
166 FROM kb_data_sources m JOIN data_sources d ON d.id = m.data_source_id
167 WHERE m.kb_id = $1 ORDER BY d.name",
168 )
169 .bind(kb_id)
170 .fetch_all(pool)
171 .await?;
172 Ok(rows.into_iter().map(row_to_view).collect())
173}
174
175/// (engine, conn_string):查询执行/测试/拉 schema 用(凭据不出服务端)。
176pub async fn engine_and_conn(pool: &PgPool, id: Uuid) -> AppResult<(String, String)> {
177 let row: Option<(String, String)> =
178 sqlx::query_as("SELECT engine, conn_string FROM data_sources WHERE id = $1")
179 .bind(id)
180 .fetch_optional(pool)
181 .await?;
182 row.ok_or(AppError::NotFound)
183}
184
185/// 这个工作区被授权用哪些源(0014)。
186///
187/// **可挂载列表从此走这里,不再走 `list`。** 从前那条路给 KB 管理员看的是
188/// `datasources::list(pool)`——全部署每一个源,不过滤。于是任何库的管理员
189/// 都能把任意生产库挂进自己库,而挂上之后该库每个 Viewer 都能对它跑只读 SQL。
190pub async fn granted_to_workspace(
191 pool: &PgPool,
192 workspace_id: Uuid,
193) -> AppResult<Vec<DataSourceView>> {
194 let rows: Vec<DataSourceRow> = sqlx::query_as(
195 "SELECT d.id, d.name, d.engine, d.conn_string, d.created_at,
196 d.last_test_at, d.last_test_ok
197 FROM data_source_grants g JOIN data_sources d ON d.id = g.data_source_id
198 WHERE g.workspace_id = $1 ORDER BY d.name",
199 )
200 .bind(workspace_id)
201 .fetch_all(pool)
202 .await?;
203 Ok(rows.into_iter().map(row_to_view).collect())
204}
205
206/// 这个源授权给了哪些工作区。管理台读它。
207pub async fn grants_for_source(
208 pool: &PgPool,
209 data_source_id: Uuid,
210) -> AppResult<Vec<(Uuid, String)>> {
211 Ok(sqlx::query_as(
212 "SELECT w.id, w.name FROM data_source_grants g
213 JOIN workspaces w ON w.id = g.workspace_id
214 WHERE g.data_source_id = $1 ORDER BY w.name",
215 )
216 .bind(data_source_id)
217 .fetch_all(pool)
218 .await?)
219}
220
221/// 授权一个工作区用这个源。幂等。
222pub async fn grant(
223 pool: &PgPool,
224 data_source_id: Uuid,
225 workspace_id: Uuid,
226 actor: Uuid,
227) -> AppResult<()> {
228 sqlx::query(
229 "INSERT INTO data_source_grants (data_source_id, workspace_id, granted_by)
230 VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",
231 )
232 .bind(data_source_id)
233 .bind(workspace_id)
234 .bind(actor)
235 .execute(pool)
236 .await?;
237 Ok(())
238}
239
240/// 收回授权,**连同该工作区里已经挂上的那些一起卸掉**。
241///
242/// 只删授权行不够:`mounted` 读的是 `kb_data_sources`,问数也读它。留着挂载
243/// 就等于收回了授权而访问照旧——一个不生效的权限撤销比没有还危险。
244///
245/// 一个事务里做完:两条 DELETE 之间如果崩了,留下的正是「无授权却挂着」那种
246/// 状态,而那恰恰是这条迁移要消灭的东西。
247pub async fn revoke(pool: &PgPool, data_source_id: Uuid, workspace_id: Uuid) -> AppResult<u64> {
248 let mut tx = pool.begin().await?;
249 let unmounted = sqlx::query(
250 "DELETE FROM kb_data_sources
251 WHERE data_source_id = $1
252 AND kb_id IN (SELECT id FROM knowledge_bases WHERE workspace_id = $2)",
253 )
254 .bind(data_source_id)
255 .bind(workspace_id)
256 .execute(&mut *tx)
257 .await?
258 .rows_affected();
259 sqlx::query("DELETE FROM data_source_grants WHERE data_source_id = $1 AND workspace_id = $2")
260 .bind(data_source_id)
261 .bind(workspace_id)
262 .execute(&mut *tx)
263 .await?;
264 tx.commit().await?;
265 Ok(unmounted)
266}
267
268/// 这个源对这个知识库是不是授权过的。**挂载前必查**——守卫不能只在列表那一侧:
269/// 列表过滤挡的是「看得见」,而挂载端点是照着 id 调的,谁都能自己拼一个。
270pub async fn is_granted(pool: &PgPool, kb_id: Uuid, data_source_id: Uuid) -> AppResult<bool> {
271 let found: Option<(i32,)> = sqlx::query_as(
272 "SELECT 1 FROM data_source_grants g
273 JOIN knowledge_bases kb ON kb.workspace_id = g.workspace_id
274 WHERE kb.id = $1 AND g.data_source_id = $2",
275 )
276 .bind(kb_id)
277 .bind(data_source_id)
278 .fetch_optional(pool)
279 .await?;
280 Ok(found.is_some())
281}