Elffuss BraidHub

kikocis/utopia public

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