Changesets · Branches · Tags · Compare
| Changeset | 18eb6b0051a2960c0d74a4355cf2c1f6cb07b5de30962af9f5958c2aeefce014 |
|---|---|
| Author | WaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-08-31 18:50 +08:00 |
| Committer | GitHub <noreply@github.com> · 2026-08-31 18:50 +08:00 |
| Parents | 1258cb420edf |
9 files changed
modified crates/utopia-server/src/api/datasource_routes.rs +84 −4
| @@ -103,15 +103,19 @@ | ||
| 103 | 103 | Ok(Json(json!({ "data_sources": mounted }))) |
| 104 | 104 | } |
| 105 | 105 | |
| 106 | -/// 库 admin 从系统已注册的源里挑选挂载(列表给 name/summary,不含凭据)。 | |
| 106 | +/// 库 admin 能挂哪些(列表给 name/summary,不含凭据)。 | |
| 107 | +/// | |
| 108 | +/// **只列授权给本工作区的(0014)。** 从前这里返回 `datasources::list`—— | |
| 109 | +/// 全部署每一个源,于是任何库的管理员都看得见并挂得上任意生产库。 | |
| 107 | 110 | pub async fn mountable( |
| 108 | 111 | State(state): State<AppState>, |
| 109 | 112 | AuthUser(user): AuthUser, |
| 110 | 113 | Path(kb_id): Path<Uuid>, |
| 111 | 114 | ) -> ApiResult<Json<serde_json::Value>> { |
| 112 | - require_kb(&state, &user, kb_id, Role::Admin).await?; | |
| 113 | - let all = utopia_store::datasources::list(&state.pool).await?; | |
| 114 | - Ok(Json(json!({ "data_sources": all }))) | |
| 115 | + let kb = require_kb(&state, &user, kb_id, Role::Admin).await?; | |
| 116 | + let granted = | |
| 117 | + utopia_store::datasources::granted_to_workspace(&state.pool, kb.workspace_id).await?; | |
| 118 | + Ok(Json(json!({ "data_sources": granted }))) | |
| 115 | 119 | } |
| 116 | 120 | |
| 117 | 121 | pub async fn mount( |
| @@ -120,6 +124,15 @@ | ||
| 120 | 124 | Path((kb_id, ds_id)): Path<(Uuid, Uuid)>, |
| 121 | 125 | ) -> ApiResult<Json<serde_json::Value>> { |
| 122 | 126 | require_kb(&state, &user, kb_id, Role::Admin).await?; |
| 127 | + // **列表过滤不是守卫。** 那只挡「看得见」,而这个端点是照着 id 调的—— | |
| 128 | + // 谁都能自己拼一个 uuid 打过来。授权在这里再查一次 | |
| 129 | + if !utopia_store::datasources::is_granted(&state.pool, kb_id, ds_id).await? { | |
| 130 | + return Err(AppError::invalid( | |
| 131 | + "source_not_granted", | |
| 132 | + "This data source is not available to this workspace", | |
| 133 | + ) | |
| 134 | + .into()); | |
| 135 | + } | |
| 123 | 136 | utopia_store::datasources::mount(&state.pool, kb_id, ds_id).await?; |
| 124 | 137 | // 挂载即摄取 schema:Chat 写 SQL 前能检索到表结构 |
| 125 | 138 | let synced = sync_schema_doc(&state, kb_id, ds_id) |
| @@ -247,3 +260,70 @@ | ||
| 247 | 260 | state.emit_source(kb_id); |
| 248 | 261 | Ok(tables) |
| 249 | 262 | } |
| 263 | + | |
| 264 | +// --------------------------------------------------------------------------- | |
| 265 | +// 系统层:授权(0014) | |
| 266 | +// | |
| 267 | +// 授权与挂载是两层,各有各的主人: | |
| 268 | +// 授权 = 系统管理员说「这个源可以给哪些工作区用」 ← 这里 | |
| 269 | +// 挂载 = KB 管理员说「我这个库挂哪几个」 ← 上面那组 | |
| 270 | +// 两层都是多对多。挂载只能在授权过的集合里挑。 | |
| 271 | +// --------------------------------------------------------------------------- | |
| 272 | + | |
| 273 | +/// 这个源授权给了哪些工作区。 | |
| 274 | +pub async fn grants( | |
| 275 | + State(state): State<AppState>, | |
| 276 | + AuthUser(user): AuthUser, | |
| 277 | + Path(id): Path<Uuid>, | |
| 278 | +) -> ApiResult<Json<serde_json::Value>> { | |
| 279 | + require_admin(&user)?; | |
| 280 | + let rows = utopia_store::datasources::grants_for_source(&state.pool, id).await?; | |
| 281 | + let workspaces: Vec<serde_json::Value> = rows | |
| 282 | + .into_iter() | |
| 283 | + .map(|(id, name)| json!({ "id": id, "name": name })) | |
| 284 | + .collect(); | |
| 285 | + Ok(Json(json!({ "workspaces": workspaces }))) | |
| 286 | +} | |
| 287 | + | |
| 288 | +pub async fn grant( | |
| 289 | + State(state): State<AppState>, | |
| 290 | + AuthUser(user): AuthUser, | |
| 291 | + Path((id, workspace_id)): Path<(Uuid, Uuid)>, | |
| 292 | +) -> ApiResult<Json<serde_json::Value>> { | |
| 293 | + require_admin(&user)?; | |
| 294 | + utopia_store::datasources::grant(&state.pool, id, workspace_id, user.id).await?; | |
| 295 | + let _ = utopia_store::audit::record( | |
| 296 | + &state.pool, | |
| 297 | + None, | |
| 298 | + user.id, | |
| 299 | + "data_source.granted", | |
| 300 | + "data_source", | |
| 301 | + Some(id), | |
| 302 | + json!({ "workspace_id": workspace_id }), | |
| 303 | + ) | |
| 304 | + .await; | |
| 305 | + Ok(Json(json!({ "ok": true }))) | |
| 306 | +} | |
| 307 | + | |
| 308 | +/// 收回授权。**连同该工作区里已挂上的一起卸掉**——只删授权行的话, | |
| 309 | +/// 问数读的还是 `kb_data_sources`,撤销就不生效。返回卸掉了几个, | |
| 310 | +/// 好让界面说得出「顺带卸了 3 个库」而不是悄悄断人家的连接。 | |
| 311 | +pub async fn revoke( | |
| 312 | + State(state): State<AppState>, | |
| 313 | + AuthUser(user): AuthUser, | |
| 314 | + Path((id, workspace_id)): Path<(Uuid, Uuid)>, | |
| 315 | +) -> ApiResult<Json<serde_json::Value>> { | |
| 316 | + require_admin(&user)?; | |
| 317 | + let unmounted = utopia_store::datasources::revoke(&state.pool, id, workspace_id).await?; | |
| 318 | + let _ = utopia_store::audit::record( | |
| 319 | + &state.pool, | |
| 320 | + None, | |
| 321 | + user.id, | |
| 322 | + "data_source.revoked", | |
| 323 | + "data_source", | |
| 324 | + Some(id), | |
| 325 | + json!({ "workspace_id": workspace_id, "unmounted": unmounted }), | |
| 326 | + ) | |
| 327 | + .await; | |
| 328 | + Ok(Json(json!({ "ok": true, "unmounted": unmounted }))) | |
| 329 | +} |
modified crates/utopia-server/src/api/mod.rs +8 −0
| @@ -111,6 +111,14 @@ | ||
| 111 | 111 | "/admin/data-sources/{id}/test", |
| 112 | 112 | post(datasource_routes::test), |
| 113 | 113 | ) |
| 114 | + .route( | |
| 115 | + "/admin/data-sources/{id}/grants", | |
| 116 | + get(datasource_routes::grants), | |
| 117 | + ) | |
| 118 | + .route( | |
| 119 | + "/admin/data-sources/{id}/grants/{workspace_id}", | |
| 120 | + axum::routing::put(datasource_routes::grant).delete(datasource_routes::revoke), | |
| 121 | + ) | |
| 114 | 122 | .route("/kbs/{id}/mappings", get(mapping_routes::list)) |
| 115 | 123 | .route( |
| 116 | 124 | "/kbs/{id}/mappings/{mapping_id}", |
modified crates/utopia-store/src/datasources.rs +119 −28
| @@ -35,6 +35,25 @@ | ||
| 35 | 35 | .unwrap_or_else(|| "(unparsed)".into()) |
| 36 | 36 | } |
| 37 | 37 | |
| 38 | +/// 行 → 视图。**连接串在这里换成无凭据摘要**,是它不外流的那道关口; | |
| 39 | +/// 四条查询共用一份,免得哪天新加一条忘了换 | |
| 40 | +fn 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`。 | |
| 38 | 57 | pub async fn list(pool: &PgPool) -> AppResult<Vec<DataSourceView>> { |
| 39 | 58 | let rows: Vec<DataSourceRow> = sqlx::query_as( |
| 40 | 59 | "SELECT id, name, engine, conn_string, created_at, last_test_at, last_test_ok |
| @@ -42,20 +61,7 @@ | ||
| 42 | 61 | ) |
| 43 | 62 | .fetch_all(pool) |
| 44 | 63 | .await?; |
| 45 | - Ok(rows | |
| 46 | - .into_iter() | |
| 47 | - .map( | |
| 48 | - |(id, name, engine, conn, created_at, last_test_at, last_test_ok)| DataSourceView { | |
| 49 | - id, | |
| 50 | - name, | |
| 51 | - engine, | |
| 52 | - summary: conn_summary(&conn), | |
| 53 | - created_at, | |
| 54 | - last_test_at, | |
| 55 | - last_test_ok, | |
| 56 | - }, | |
| 57 | - ) | |
| 58 | - .collect()) | |
| 64 | + Ok(rows.into_iter().map(row_to_view).collect()) | |
| 59 | 65 | } |
| 60 | 66 | |
| 61 | 67 | pub async fn create( |
| @@ -163,20 +169,7 @@ | ||
| 163 | 169 | .bind(kb_id) |
| 164 | 170 | .fetch_all(pool) |
| 165 | 171 | .await?; |
| 166 | - Ok(rows | |
| 167 | - .into_iter() | |
| 168 | - .map( | |
| 169 | - |(id, name, engine, conn, created_at, last_test_at, last_test_ok)| DataSourceView { | |
| 170 | - id, | |
| 171 | - name, | |
| 172 | - engine, | |
| 173 | - summary: conn_summary(&conn), | |
| 174 | - created_at, | |
| 175 | - last_test_at, | |
| 176 | - last_test_ok, | |
| 177 | - }, | |
| 178 | - ) | |
| 179 | - .collect()) | |
| 172 | + Ok(rows.into_iter().map(row_to_view).collect()) | |
| 180 | 173 | } |
| 181 | 174 | |
| 182 | 175 | /// (engine, conn_string):查询执行/测试/拉 schema 用(凭据不出服务端)。 |
| @@ -188,3 +181,101 @@ | ||
| 188 | 181 | .await?; |
| 189 | 182 | row.ok_or(AppError::NotFound) |
| 190 | 183 | } |
| 184 | + | |
| 185 | +/// 这个工作区被授权用哪些源(0014)。 | |
| 186 | +/// | |
| 187 | +/// **可挂载列表从此走这里,不再走 `list`。** 从前那条路给 KB 管理员看的是 | |
| 188 | +/// `datasources::list(pool)`——全部署每一个源,不过滤。于是任何库的管理员 | |
| 189 | +/// 都能把任意生产库挂进自己库,而挂上之后该库每个 Viewer 都能对它跑只读 SQL。 | |
| 190 | +pub 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 | +/// 这个源授权给了哪些工作区。管理台读它。 | |
| 207 | +pub 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 | +/// 授权一个工作区用这个源。幂等。 | |
| 222 | +pub 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 | +/// 状态,而那恰恰是这条迁移要消灭的东西。 | |
| 247 | +pub 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 调的,谁都能自己拼一个。 | |
| 270 | +pub 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 | +} |
added crates/utopia-store/tests/a_source_reaches_only_where_it_was_granted.rs +173 −0
| @@ -0,0 +1,173 @@ | ||
| 1 | +//! 数据源授权(0014)。 | |
| 2 | +//! | |
| 3 | +//! 补的洞:注册是部署级动作,而挂载的守卫是 `require_kb(kb_id, Role::Admin)` | |
| 4 | +//! ——请求者自己那个库的管理员。可挂载列表返回的又是全部署每一个源。于是任何 | |
| 5 | +//! 一个知识库的管理员,都能把任意生产库挂进自己库,而挂上之后该库每个 Viewer | |
| 6 | +//! 都能通过 `query_data` 对它跑只读 SQL。 | |
| 7 | +//! | |
| 8 | +//! 这里钉三件事: | |
| 9 | +//! | |
| 10 | +//! - **看不见**:没授权的源不进可挂载列表 | |
| 11 | +//! - **也挂不上**:列表过滤只挡「看得见」,而挂载端点是照着 id 调的—— | |
| 12 | +//! 守卫必须在两侧都有,这条测的是端点那一侧 | |
| 13 | +//! - **收回是真收回**:撤授权连同已挂上的一起卸掉。只删授权行的话,问数读的 | |
| 14 | +//! 还是 `kb_data_sources`,等于撤销不生效——一个不生效的权限撤销比没有还危险 | |
| 15 | + | |
| 16 | +use sqlx::PgPool; | |
| 17 | +use utopia_store::datasources; | |
| 18 | +use uuid::Uuid; | |
| 19 | + | |
| 20 | +struct Fixture { | |
| 21 | + org: Uuid, | |
| 22 | + /// 授权给它的工作区 | |
| 23 | + ours: Uuid, | |
| 24 | + /// 没授权的工作区——它的库不该够得着这个源 | |
| 25 | + theirs: Uuid, | |
| 26 | + our_kb: Uuid, | |
| 27 | + their_kb: Uuid, | |
| 28 | + source: Uuid, | |
| 29 | + actor: Uuid, | |
| 30 | +} | |
| 31 | + | |
| 32 | +async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> { | |
| 33 | + let org = Uuid::now_v7(); | |
| 34 | + let (ours, theirs) = (Uuid::now_v7(), Uuid::now_v7()); | |
| 35 | + let (our_kb, their_kb) = (Uuid::now_v7(), Uuid::now_v7()); | |
| 36 | + let (source, actor) = (Uuid::now_v7(), Uuid::now_v7()); | |
| 37 | + | |
| 38 | + sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'grant-test')") | |
| 39 | + .bind(org) | |
| 40 | + .execute(pool) | |
| 41 | + .await?; | |
| 42 | + for (id, name) in [(ours, "ours"), (theirs, "theirs")] { | |
| 43 | + sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, $3)") | |
| 44 | + .bind(id) | |
| 45 | + .bind(org) | |
| 46 | + .bind(name) | |
| 47 | + .execute(pool) | |
| 48 | + .await?; | |
| 49 | + } | |
| 50 | + for (kb, ws, name) in [(our_kb, ours, "our-kb"), (their_kb, theirs, "their-kb")] { | |
| 51 | + sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, $3)") | |
| 52 | + .bind(kb) | |
| 53 | + .bind(ws) | |
| 54 | + .bind(name) | |
| 55 | + .execute(pool) | |
| 56 | + .await?; | |
| 57 | + } | |
| 58 | + sqlx::query( | |
| 59 | + "INSERT INTO users (id, org_id, email, password_hash, display_name, is_admin) | |
| 60 | + VALUES ($1, $2, $3, 'x', 'Grant Test', TRUE)", | |
| 61 | + ) | |
| 62 | + .bind(actor) | |
| 63 | + .bind(org) | |
| 64 | + .bind(format!("{actor}@grant.test")) | |
| 65 | + .execute(pool) | |
| 66 | + .await?; | |
| 67 | + sqlx::query( | |
| 68 | + "INSERT INTO data_sources (id, name, engine, conn_string, created_by) | |
| 69 | + VALUES ($1, $2, 'postgres', 'postgres://u:p@db.test:5432/w', $3)", | |
| 70 | + ) | |
| 71 | + .bind(source) | |
| 72 | + .bind(format!("warehouse-{source}")) | |
| 73 | + .bind(actor) | |
| 74 | + .execute(pool) | |
| 75 | + .await?; | |
| 76 | + | |
| 77 | + Ok(Fixture { | |
| 78 | + org, | |
| 79 | + ours, | |
| 80 | + theirs, | |
| 81 | + our_kb, | |
| 82 | + their_kb, | |
| 83 | + source, | |
| 84 | + actor, | |
| 85 | + }) | |
| 86 | +} | |
| 87 | + | |
| 88 | +#[tokio::test] | |
| 89 | +async fn a_source_reaches_only_where_it_was_granted() -> anyhow::Result<()> { | |
| 90 | + let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else { | |
| 91 | + eprintln!("跳过:未设 UTOPIA_DATABASE_URL"); | |
| 92 | + return Ok(()); | |
| 93 | + }; | |
| 94 | + let pool = PgPool::connect(&url).await?; | |
| 95 | + let f = seed(&pool).await?; | |
| 96 | + | |
| 97 | + let run = async { | |
| 98 | + // ---- 一、没授权 = 谁都够不着 | |
| 99 | + assert!( | |
| 100 | + datasources::granted_to_workspace(&pool, f.ours) | |
| 101 | + .await? | |
| 102 | + .is_empty(), | |
| 103 | + "没授权过,可挂载列表就该是空的" | |
| 104 | + ); | |
| 105 | + assert!( | |
| 106 | + !datasources::is_granted(&pool, f.our_kb, f.source).await?, | |
| 107 | + "没授权,挂载端点的守卫必须说不" | |
| 108 | + ); | |
| 109 | + | |
| 110 | + // ---- 二、授权一个工作区,另一个不受影响 | |
| 111 | + datasources::grant(&pool, f.source, f.ours, f.actor).await?; | |
| 112 | + let ours = datasources::granted_to_workspace(&pool, f.ours).await?; | |
| 113 | + assert_eq!(ours.len(), 1, "授权过的工作区看得见它"); | |
| 114 | + assert!( | |
| 115 | + !ours[0].summary.contains("p@"), | |
| 116 | + "列表里只能有 host:port/db 摘要,凭据不出服务端" | |
| 117 | + ); | |
| 118 | + assert!( | |
| 119 | + datasources::granted_to_workspace(&pool, f.theirs) | |
| 120 | + .await? | |
| 121 | + .is_empty(), | |
| 122 | + "**授权是逐工作区的**:给了一个不等于给了全部署" | |
| 123 | + ); | |
| 124 | + | |
| 125 | + // ---- 三、端点侧的守卫:列表过滤只挡「看得见」 | |
| 126 | + assert!(datasources::is_granted(&pool, f.our_kb, f.source).await?); | |
| 127 | + assert!( | |
| 128 | + !datasources::is_granted(&pool, f.their_kb, f.source).await?, | |
| 129 | + "没授权的工作区,就算自己拼一个 uuid 打过来也挂不上" | |
| 130 | + ); | |
| 131 | + | |
| 132 | + // ---- 四、一个源可授权给多个工作区(多对多,不是一对多) | |
| 133 | + datasources::grant(&pool, f.source, f.theirs, f.actor).await?; | |
| 134 | + assert_eq!( | |
| 135 | + datasources::grants_for_source(&pool, f.source).await?.len(), | |
| 136 | + 2, | |
| 137 | + "同一个数仓要能同时服务多个工作区" | |
| 138 | + ); | |
| 139 | + datasources::grant(&pool, f.source, f.theirs, f.actor).await?; | |
| 140 | + assert_eq!( | |
| 141 | + datasources::grants_for_source(&pool, f.source).await?.len(), | |
| 142 | + 2, | |
| 143 | + "重复授权是幂等的" | |
| 144 | + ); | |
| 145 | + | |
| 146 | + // ---- 五、收回连同挂载一起收 | |
| 147 | + datasources::mount(&pool, f.our_kb, f.source).await?; | |
| 148 | + datasources::mount(&pool, f.their_kb, f.source).await?; | |
| 149 | + let unmounted = datasources::revoke(&pool, f.source, f.theirs).await?; | |
| 150 | + assert_eq!(unmounted, 1, "撤授权要把那个工作区里已挂上的一起卸掉"); | |
| 151 | + assert!( | |
| 152 | + datasources::mounted(&pool, f.their_kb).await?.is_empty(), | |
| 153 | + "**留着挂载 = 撤销不生效**:问数读的是 kb_data_sources" | |
| 154 | + ); | |
| 155 | + assert_eq!( | |
| 156 | + datasources::mounted(&pool, f.our_kb).await?.len(), | |
| 157 | + 1, | |
| 158 | + "另一个工作区的挂载不受牵连" | |
| 159 | + ); | |
| 160 | + Ok::<_, anyhow::Error>(()) | |
| 161 | + } | |
| 162 | + .await; | |
| 163 | + | |
| 164 | + sqlx::query("DELETE FROM data_sources WHERE id = $1") | |
| 165 | + .bind(f.source) | |
| 166 | + .execute(&pool) | |
| 167 | + .await?; | |
| 168 | + sqlx::query("DELETE FROM organizations WHERE id = $1") | |
| 169 | + .bind(f.org) | |
| 170 | + .execute(&pool) | |
| 171 | + .await?; | |
| 172 | + run | |
| 173 | +} |
added migrations/0014_data_source_grants.sql +44 −0
| @@ -0,0 +1,44 @@ | ||
| 1 | +-- 数据源授权:这个库可以给哪些工作区用。 | |
| 2 | +-- | |
| 3 | +-- **在此之前这一层不存在。** 注册是部署级动作(`require_admin`),而挂载的 | |
| 4 | +-- 守卫是 `require_kb(kb_id, Role::Admin)`——请求者自己那个库的管理员。可挂载 | |
| 5 | +-- 列表返回的又是 `datasources::list(pool)`:全部署每一个源,不过滤。 | |
| 6 | +-- | |
| 7 | +-- 于是任何一个知识库的管理员,都能列出部署里每一个已注册数据库,并把任意一个 | |
| 8 | +-- 挂进自己库。挂上之后该库的每个 Viewer 都能通过 `query_data` 对它跑只读 SQL | |
| 9 | +-- (问数是读,viewer 亦可用)。多工作区部署下这是跨租户的。 | |
| 10 | +-- | |
| 11 | +-- **为什么是新表,而不是给 `data_sources` 加一列 `workspace_id`:** | |
| 12 | +-- 那一列意味着每个数据源只属于一个工作区。公司只有一个数仓、几个部门各自一个 | |
| 13 | +-- 工作区时,这个数仓就只能给一个部门用——把一个本该多对多的关系退化成了一对多。 | |
| 14 | +-- 授权本身就是多对多的:一个源可授权给多个工作区,一个工作区可拿到多个源。 | |
| 15 | +-- | |
| 16 | +-- **与 `kb_data_sources` 的分工**(那张表一个字段都不动): | |
| 17 | +-- | |
| 18 | +-- 授权 = 系统管理员说「这个库可以给哪些工作区用」 ← 本表 | |
| 19 | +-- 挂载 = KB 管理员说「我这个库挂哪几个」 ← kb_data_sources | |
| 20 | +-- | |
| 21 | +-- 两层都是 M2M,各有各的主人。挂载不再能凭空发生:只能在授权过的集合里挑。 | |
| 22 | +CREATE TABLE data_source_grants ( | |
| 23 | + data_source_id UUID NOT NULL REFERENCES data_sources(id) ON DELETE CASCADE, | |
| 24 | + workspace_id UUID NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, | |
| 25 | + granted_at TIMESTAMPTZ NOT NULL DEFAULT now(), | |
| 26 | + -- 授权的人。**裸外键**,与 entity_merges.merged_by 那几处一致: | |
| 27 | + -- 用户是软删除的,生产代码里没有 DELETE FROM users,所以归因保得住 | |
| 28 | + granted_by UUID REFERENCES users(id), | |
| 29 | + PRIMARY KEY (data_source_id, workspace_id) | |
| 30 | +); | |
| 31 | + | |
| 32 | +-- 「这个工作区能用哪些源」是热路径(每次开数据映射页都问一次); | |
| 33 | +-- 主键已覆盖反向的「这个源给了谁」 | |
| 34 | +CREATE INDEX data_source_grants_workspace_idx ON data_source_grants (workspace_id); | |
| 35 | + | |
| 36 | +-- 存量授权:把已经挂着的补上,否则这条迁移一上线就把正在用的源全断掉。 | |
| 37 | +-- | |
| 38 | +-- **补的是既成事实,不是补一个宽松默认**:只授权给「确实已经挂载过它」的 | |
| 39 | +-- 那些工作区。没挂过的一个都不给——那正是这条迁移要关掉的门。 | |
| 40 | +INSERT INTO data_source_grants (data_source_id, workspace_id) | |
| 41 | +SELECT DISTINCT kds.data_source_id, kb.workspace_id | |
| 42 | + FROM kb_data_sources kds | |
| 43 | + JOIN knowledge_bases kb ON kb.id = kds.kb_id | |
| 44 | +ON CONFLICT DO NOTHING; |
modified web/src/api.ts +17 −0
| @@ -1015,6 +1015,23 @@ | ||
| 1015 | 1015 | request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, { |
| 1016 | 1016 | method: "POST", |
| 1017 | 1017 | }), |
| 1018 | + /** 这个源授权给了哪些工作区(0014)。授权与挂载是两层: | |
| 1019 | + * 授权由系统管理员写,挂载由 KB 管理员在授权过的集合里挑 */ | |
| 1020 | + dataSourceGrants: (id: string) => | |
| 1021 | + request<{ workspaces: { id: string; name: string }[] }>( | |
| 1022 | + `/api/v1/admin/data-sources/${id}/grants`, | |
| 1023 | + ), | |
| 1024 | + grantDataSource: (id: string, workspaceId: string) => | |
| 1025 | + request<{ ok: boolean }>( | |
| 1026 | + `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`, | |
| 1027 | + { method: "PUT" }, | |
| 1028 | + ), | |
| 1029 | + /** 收回授权。**连同该工作区里已挂上的一起卸掉**,返回卸了几个 */ | |
| 1030 | + revokeDataSource: (id: string, workspaceId: string) => | |
| 1031 | + request<{ ok: boolean; unmounted: number }>( | |
| 1032 | + `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`, | |
| 1033 | + { method: "DELETE" }, | |
| 1034 | + ), | |
| 1018 | 1035 | |
| 1019 | 1036 | /** 一页口径。**Viewer 就能看**——问数的答案直接由口径决定, |
| 1020 | 1037 | * 看得见答案却看不见口径,等于要人信一个不给看的算法 */ |
modified web/src/i18n/en.ts +15 −0
| @@ -56,6 +56,9 @@ | ||
| 56 | 56 | "Pick the date this fact ended — the new one does not say when it started.", |
| 57 | 57 | empty_query: "Type something to search for.", |
| 58 | 58 | no_data_sources: "No databases are mounted on this knowledge base.", |
| 59 | + // 授权是逐工作区的(0014):源没授权给本库所属的工作区 | |
| 60 | + source_not_granted: | |
| 61 | + "This data source is not granted to this workspace. Ask a deployment admin to grant it in System settings → Data sources.", | |
| 59 | 62 | memory_source_permanent: |
| 60 | 63 | "The Memory source is part of the knowledge base and stays.", |
| 61 | 64 | source_name_required: "Give this source a name.", |
| @@ -734,6 +737,18 @@ | ||
| 734 | 737 | testFail: "Failed", |
| 735 | 738 | neverTested: "Untested", |
| 736 | 739 | remove: "Remove", |
| 740 | + grants: "Available to", | |
| 741 | + grantsHint: | |
| 742 | + "Which workspaces may use this source. **Once granted, KB admins in those workspaces choose whether to mount it** — " + | |
| 743 | + "this controls what they can reach, not what they have mounted.", | |
| 744 | + grantsNone: | |
| 745 | + "Not granted to any workspace — no knowledge base can mount it.", | |
| 746 | + grantAdd: "Grant a workspace…", | |
| 747 | + grantRevoke: "Revoke", | |
| 748 | + grantRevoked: (n: number) => | |
| 749 | + n === 0 | |
| 750 | + ? "Revoked." | |
| 751 | + : `Revoked, and unmounted it from ${n} knowledge base(s).`, | |
| 737 | 752 | }, |
| 738 | 753 | kbs: { |
| 739 | 754 | hint: |
modified web/src/i18n/zh.ts +12 −0
| @@ -52,6 +52,9 @@ | ||
| 52 | 52 | close_at_required: "选一个这条事实结束的日期——新的那条没说自己何时开始。", |
| 53 | 53 | empty_query: "输入点什么再检索。", |
| 54 | 54 | no_data_sources: "这个知识库没有挂载任何数据库。", |
| 55 | + // 授权是逐工作区的(0014):源没授权给本库所属的工作区 | |
| 56 | + source_not_granted: | |
| 57 | + "这个数据源没有授权给本工作区。请部署管理员在「系统设置 → 数据源」里授权。", | |
| 55 | 58 | memory_source_permanent: "「记忆」是知识库自带的来源,会一直在。", |
| 56 | 59 | source_name_required: "给这个来源起个名字。", |
| 57 | 60 | bad_cron: "这个 cron 表达式解析不了。", |
| @@ -670,6 +673,15 @@ | ||
| 670 | 673 | testFail: "失败", |
| 671 | 674 | neverTested: "未测试", |
| 672 | 675 | remove: "移除", |
| 676 | + grants: "可用于", | |
| 677 | + grantsHint: | |
| 678 | + "授权哪些工作区可以用这个源。**授权之后,那些工作区的知识库管理员自己挑挂不挂**——" + | |
| 679 | + "这里管的是「能不能拿到」,不是「挂没挂」。", | |
| 680 | + grantsNone: "还没授权给任何工作区——现在没有知识库挂得上它。", | |
| 681 | + grantAdd: "授权工作区…", | |
| 682 | + grantRevoke: "收回", | |
| 683 | + grantRevoked: (n: number) => | |
| 684 | + n === 0 ? "已收回。" : `已收回,顺带卸掉了 ${n} 个知识库上的挂载。`, | |
| 673 | 685 | }, |
| 674 | 686 | kbs: { |
| 675 | 687 | hint: |
modified web/src/pages/Settings.tsx +141 −35
| @@ -5,8 +5,109 @@ | ||
| 5 | 5 | import { api } from "../api"; |
| 6 | 6 | import { LANG_NAMES, S } from "../i18n"; |
| 7 | 7 | import { useKb } from "../kb"; |
| 8 | +import { toast } from "../toast"; | |
| 9 | +import { SearchSelect } from "../ui"; | |
| 8 | 10 | import { Members } from "./Members"; |
| 9 | 11 | |
| 12 | +/** 一个源授权给了哪些工作区(0014)。 | |
| 13 | + * | |
| 14 | + * **授权与挂载是两层**:这里说「这个源可以给谁用」,KB 管理员再在授权过的 | |
| 15 | + * 集合里挑挂不挂。从前没有这一层——可挂载列表返回全部署每一个源,于是任何 | |
| 16 | + * 库的管理员都能把任意生产库挂进自己库。 | |
| 17 | + * | |
| 18 | + * 两层都是多对多:一个源可授权给多个工作区,一个工作区可拿到多个源。 */ | |
| 19 | +function SourceGrants({ sourceId }: { sourceId: string }) { | |
| 20 | + const queryClient = useQueryClient(); | |
| 21 | + const [picked, setPicked] = useState(""); | |
| 22 | + const [notice, setNotice] = useState<string | null>(null); | |
| 23 | + | |
| 24 | + const grants = useQuery({ | |
| 25 | + queryKey: ["dataSourceGrants", sourceId], | |
| 26 | + queryFn: () => api.dataSourceGrants(sourceId), | |
| 27 | + }); | |
| 28 | + const workspaces = useQuery({ | |
| 29 | + queryKey: ["workspaces"], | |
| 30 | + queryFn: api.workspaces, | |
| 31 | + }); | |
| 32 | + const invalidate = () => | |
| 33 | + queryClient.invalidateQueries({ queryKey: ["dataSourceGrants", sourceId] }); | |
| 34 | + | |
| 35 | + const grant = useMutation({ | |
| 36 | + mutationFn: (wsId: string) => api.grantDataSource(sourceId, wsId), | |
| 37 | + onSuccess: () => { | |
| 38 | + setPicked(""); | |
| 39 | + setNotice(null); | |
| 40 | + invalidate(); | |
| 41 | + }, | |
| 42 | + onError: (e: unknown) => toast.error((e as Error).message), | |
| 43 | + }); | |
| 44 | + const revoke = useMutation({ | |
| 45 | + mutationFn: (wsId: string) => api.revokeDataSource(sourceId, wsId), | |
| 46 | + // 卸了几个要说出来:收回授权会顺带断掉正在用的挂载, | |
| 47 | + // 悄悄断比断本身更糟 | |
| 48 | + onSuccess: (r) => { | |
| 49 | + setNotice(S.settings.datasources.grantRevoked(r.unmounted)); | |
| 50 | + invalidate(); | |
| 51 | + }, | |
| 52 | + onError: (e: unknown) => toast.error((e as Error).message), | |
| 53 | + }); | |
| 54 | + | |
| 55 | + const granted = grants.data?.workspaces ?? []; | |
| 56 | + const grantedIds = new Set(granted.map((w) => w.id)); | |
| 57 | + const grantable = (workspaces.data ?? []).filter( | |
| 58 | + (w) => !grantedIds.has(w.id), | |
| 59 | + ); | |
| 60 | + | |
| 61 | + return ( | |
| 62 | + <div className="border-t border-white/5 pt-3 space-y-2"> | |
| 63 | + <div className="flex items-baseline gap-2"> | |
| 64 | + <span className="text-[11px] text-neutral-500"> | |
| 65 | + {S.settings.datasources.grants} | |
| 66 | + </span> | |
| 67 | + {granted.length === 0 ? ( | |
| 68 | + <span className="text-[11px] text-neutral-600"> | |
| 69 | + {S.settings.datasources.grantsNone} | |
| 70 | + </span> | |
| 71 | + ) : ( | |
| 72 | + <div className="flex flex-wrap gap-1.5"> | |
| 73 | + {granted.map((w) => ( | |
| 74 | + <span | |
| 75 | + key={w.id} | |
| 76 | + className="u-chip u-chip-neutral text-[11px] flex items-center gap-1" | |
| 77 | + > | |
| 78 | + {w.name} | |
| 79 | + <button | |
| 80 | + className="text-neutral-500 hover:text-[var(--u-danger)]" | |
| 81 | + title={S.settings.datasources.grantRevoke} | |
| 82 | + disabled={revoke.isPending} | |
| 83 | + onClick={() => revoke.mutate(w.id)} | |
| 84 | + > | |
| 85 | + <X size={10} /> | |
| 86 | + </button> | |
| 87 | + </span> | |
| 88 | + ))} | |
| 89 | + </div> | |
| 90 | + )} | |
| 91 | + </div> | |
| 92 | + {grantable.length > 0 && ( | |
| 93 | + <div className="flex items-center gap-2"> | |
| 94 | + <SearchSelect | |
| 95 | + className="flex-1" | |
| 96 | + value={picked} | |
| 97 | + options={grantable.map((w) => ({ value: w.id, label: w.name }))} | |
| 98 | + onChange={(v) => { | |
| 99 | + setPicked(v); | |
| 100 | + if (v) grant.mutate(v); | |
| 101 | + }} | |
| 102 | + placeholder={S.settings.datasources.grantAdd} | |
| 103 | + /> | |
| 104 | + </div> | |
| 105 | + )} | |
| 106 | + {notice && <p className="text-[11px] text-neutral-500">{notice}</p>} | |
| 107 | + </div> | |
| 108 | + ); | |
| 109 | +} | |
| 110 | + | |
| 10 | 111 | /** 部署级配置:注册开关 + worker 并发。 */ |
| 11 | 112 | function DeploymentAdmin() { |
| 12 | 113 | const queryClient = useQueryClient(); |
| @@ -452,7 +553,9 @@ | ||
| 452 | 553 | checked={on} |
| 453 | 554 | onChange={() => toggle(p.id)} |
| 454 | 555 | /> |
| 455 | - <span className="block text-xs text-neutral-200">{p.name}</span> | |
| 556 | + <span className="block text-xs text-neutral-200"> | |
| 557 | + {p.name} | |
| 558 | + </span> | |
| 456 | 559 | <span className="block text-[11px] leading-snug text-neutral-500"> |
| 457 | 560 | {p.summary} |
| 458 | 561 | </span> |
| @@ -533,42 +636,45 @@ | ||
| 533 | 636 | |
| 534 | 637 | <div className="glass rounded-xl divide-y divide-white/5"> |
| 535 | 638 | {(list.data?.data_sources ?? []).map((d) => ( |
| 536 | - <div key={d.id} className="px-4 py-3 flex items-center gap-3"> | |
| 537 | - <div className="min-w-0 flex-1"> | |
| 538 | - <div className="text-sm text-neutral-200">{d.name}</div> | |
| 539 | - <div className="text-xs text-neutral-500 font-mono truncate"> | |
| 540 | - {d.summary} | |
| 639 | + <div key={d.id} className="px-4 py-3 space-y-3"> | |
| 640 | + <div className="flex items-center gap-3"> | |
| 641 | + <div className="min-w-0 flex-1"> | |
| 642 | + <div className="text-sm text-neutral-200">{d.name}</div> | |
| 643 | + <div className="text-xs text-neutral-500 font-mono truncate"> | |
| 644 | + {d.summary} | |
| 645 | + </div> | |
| 541 | 646 | </div> |
| 542 | - </div> | |
| 543 | - <span | |
| 544 | - className={`u-chip shrink-0 ${ | |
| 545 | - d.last_test_ok === true | |
| 546 | - ? "u-chip-success" | |
| 647 | + <span | |
| 648 | + className={`u-chip shrink-0 ${ | |
| 649 | + d.last_test_ok === true | |
| 650 | + ? "u-chip-success" | |
| 651 | + : d.last_test_ok === false | |
| 652 | + ? "u-chip-danger" | |
| 653 | + : "u-chip-neutral" | |
| 654 | + }`} | |
| 655 | + > | |
| 656 | + {d.last_test_ok === true | |
| 657 | + ? S.settings.datasources.testOk | |
| 547 | 658 | : d.last_test_ok === false |
| 548 | - ? "u-chip-danger" | |
| 549 | - : "u-chip-neutral" | |
| 550 | - }`} | |
| 551 | - > | |
| 552 | - {d.last_test_ok === true | |
| 553 | - ? S.settings.datasources.testOk | |
| 554 | - : d.last_test_ok === false | |
| 555 | - ? S.settings.datasources.testFail | |
| 556 | - : S.settings.datasources.neverTested} | |
| 557 | - </span> | |
| 558 | - <button | |
| 559 | - className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0" | |
| 560 | - disabled={test.isPending} | |
| 561 | - onClick={() => test.mutate(d.id)} | |
| 562 | - > | |
| 563 | - {S.settings.datasources.test} | |
| 564 | - </button> | |
| 565 | - <button | |
| 566 | - className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0" | |
| 567 | - disabled={remove.isPending} | |
| 568 | - onClick={() => remove.mutate(d.id)} | |
| 569 | - > | |
| 570 | - {S.settings.datasources.remove} | |
| 571 | - </button> | |
| 659 | + ? S.settings.datasources.testFail | |
| 660 | + : S.settings.datasources.neverTested} | |
| 661 | + </span> | |
| 662 | + <button | |
| 663 | + className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0" | |
| 664 | + disabled={test.isPending} | |
| 665 | + onClick={() => test.mutate(d.id)} | |
| 666 | + > | |
| 667 | + {S.settings.datasources.test} | |
| 668 | + </button> | |
| 669 | + <button | |
| 670 | + className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0" | |
| 671 | + disabled={remove.isPending} | |
| 672 | + onClick={() => remove.mutate(d.id)} | |
| 673 | + > | |
| 674 | + {S.settings.datasources.remove} | |
| 675 | + </button> | |
| 676 | + </div> | |
| 677 | + <SourceGrants sourceId={d.id} /> | |
| 572 | 678 | </div> |
| 573 | 679 | ))} |
| 574 | 680 | {list.data?.data_sources.length === 0 && ( |