Skip to content

World's first open-source enterprise world model.

A source reaches only where it was granted (#142)

WaylandYang268fe3701c49
diff --git a/crates/utopia-server/src/api/datasource_routes.rs b/crates/utopia-server/src/api/datasource_routes.rs
index b44134b7..8c9e5507 100644
--- a/crates/utopia-server/src/api/datasource_routes.rs
+++ b/crates/utopia-server/src/api/datasource_routes.rs
@@ -103,15 +103,19 @@ pub async fn mounted(
Ok(Json(json!({ "data_sources": mounted })))
}
-/// 库 admin 从系统已注册的源里挑选挂载(列表给 name/summary,不含凭据)。
+/// 库 admin 能挂哪些(列表给 name/summary,不含凭据)。
+///
+/// **只列授权给本工作区的(0014)。** 从前这里返回 `datasources::list`——
+/// 全部署每一个源,于是任何库的管理员都看得见并挂得上任意生产库。
pub async fn mountable(
State(state): State<AppState>,
AuthUser(user): AuthUser,
Path(kb_id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
- require_kb(&state, &user, kb_id, Role::Admin).await?;
- let all = utopia_store::datasources::list(&state.pool).await?;
- Ok(Json(json!({ "data_sources": all })))
+ let kb = require_kb(&state, &user, kb_id, Role::Admin).await?;
+ let granted =
+ utopia_store::datasources::granted_to_workspace(&state.pool, kb.workspace_id).await?;
+ Ok(Json(json!({ "data_sources": granted })))
}
pub async fn mount(
@@ -120,6 +124,15 @@ pub async fn mount(
Path((kb_id, ds_id)): Path<(Uuid, Uuid)>,
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Admin).await?;
+ // **列表过滤不是守卫。** 那只挡「看得见」,而这个端点是照着 id 调的——
+ // 谁都能自己拼一个 uuid 打过来。授权在这里再查一次
+ if !utopia_store::datasources::is_granted(&state.pool, kb_id, ds_id).await? {
+ return Err(AppError::invalid(
+ "source_not_granted",
+ "This data source is not available to this workspace",
+ )
+ .into());
+ }
utopia_store::datasources::mount(&state.pool, kb_id, ds_id).await?;
// 挂载即摄取 schema:Chat 写 SQL 前能检索到表结构
let synced = sync_schema_doc(&state, kb_id, ds_id)
@@ -247,3 +260,70 @@ async fn sync_schema_doc(state: &AppState, kb_id: Uuid, ds_id: Uuid) -> anyhow::
state.emit_source(kb_id);
Ok(tables)
}
+
+// ---------------------------------------------------------------------------
+// 系统层:授权(0014)
+//
+// 授权与挂载是两层,各有各的主人:
+// 授权 = 系统管理员说「这个源可以给哪些工作区用」 ← 这里
+// 挂载 = KB 管理员说「我这个库挂哪几个」 ← 上面那组
+// 两层都是多对多。挂载只能在授权过的集合里挑。
+// ---------------------------------------------------------------------------
+
+/// 这个源授权给了哪些工作区。
+pub async fn grants(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ let rows = utopia_store::datasources::grants_for_source(&state.pool, id).await?;
+ let workspaces: Vec<serde_json::Value> = rows
+ .into_iter()
+ .map(|(id, name)| json!({ "id": id, "name": name }))
+ .collect();
+ Ok(Json(json!({ "workspaces": workspaces })))
+}
+
+pub async fn grant(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((id, workspace_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ utopia_store::datasources::grant(&state.pool, id, workspace_id, user.id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ None,
+ user.id,
+ "data_source.granted",
+ "data_source",
+ Some(id),
+ json!({ "workspace_id": workspace_id }),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 收回授权。**连同该工作区里已挂上的一起卸掉**——只删授权行的话,
+/// 问数读的还是 `kb_data_sources`,撤销就不生效。返回卸掉了几个,
+/// 好让界面说得出「顺带卸了 3 个库」而不是悄悄断人家的连接。
+pub async fn revoke(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((id, workspace_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ let unmounted = utopia_store::datasources::revoke(&state.pool, id, workspace_id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ None,
+ user.id,
+ "data_source.revoked",
+ "data_source",
+ Some(id),
+ json!({ "workspace_id": workspace_id, "unmounted": unmounted }),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true, "unmounted": unmounted })))
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 90bdc090..6ddd1527 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -111,6 +111,14 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/admin/data-sources/{id}/test",
post(datasource_routes::test),
)
+ .route(
+ "/admin/data-sources/{id}/grants",
+ get(datasource_routes::grants),
+ )
+ .route(
+ "/admin/data-sources/{id}/grants/{workspace_id}",
+ axum::routing::put(datasource_routes::grant).delete(datasource_routes::revoke),
+ )
.route("/kbs/{id}/mappings", get(mapping_routes::list))
.route(
"/kbs/{id}/mappings/{mapping_id}",
diff --git a/crates/utopia-store/src/datasources.rs b/crates/utopia-store/src/datasources.rs
index 57dfe84f..5fad6389 100644
--- a/crates/utopia-store/src/datasources.rs
+++ b/crates/utopia-store/src/datasources.rs
@@ -35,6 +35,25 @@ pub fn conn_summary(conn: &str) -> String {
.unwrap_or_else(|| "(unparsed)".into())
}
+/// 行 → 视图。**连接串在这里换成无凭据摘要**,是它不外流的那道关口;
+/// 四条查询共用一份,免得哪天新加一条忘了换
+fn row_to_view(
+ (id, name, engine, conn, created_at, last_test_at, last_test_ok): DataSourceRow,
+) -> DataSourceView {
+ DataSourceView {
+ id,
+ name,
+ engine,
+ summary: conn_summary(&conn),
+ created_at,
+ last_test_at,
+ last_test_ok,
+ }
+}
+
+/// 部署里全部的源。**只给系统管理员的注册台用。**
+/// 从前可挂载列表也走它,那是 0014 关掉的门——KB 侧现在走
+/// `granted_to_workspace`。
pub async fn list(pool: &PgPool) -> AppResult<Vec<DataSourceView>> {
let rows: Vec<DataSourceRow> = sqlx::query_as(
"SELECT id, name, engine, conn_string, created_at, last_test_at, last_test_ok
@@ -42,20 +61,7 @@ pub async fn list(pool: &PgPool) -> AppResult<Vec<DataSourceView>> {
)
.fetch_all(pool)
.await?;
- Ok(rows
- .into_iter()
- .map(
- |(id, name, engine, conn, created_at, last_test_at, last_test_ok)| DataSourceView {
- id,
- name,
- engine,
- summary: conn_summary(&conn),
- created_at,
- last_test_at,
- last_test_ok,
- },
- )
- .collect())
+ Ok(rows.into_iter().map(row_to_view).collect())
}
pub async fn create(
@@ -163,20 +169,7 @@ pub async fn mounted(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<DataSourceView
.bind(kb_id)
.fetch_all(pool)
.await?;
- Ok(rows
- .into_iter()
- .map(
- |(id, name, engine, conn, created_at, last_test_at, last_test_ok)| DataSourceView {
- id,
- name,
- engine,
- summary: conn_summary(&conn),
- created_at,
- last_test_at,
- last_test_ok,
- },
- )
- .collect())
+ Ok(rows.into_iter().map(row_to_view).collect())
}
/// (engine, conn_string):查询执行/测试/拉 schema 用(凭据不出服务端)。
@@ -188,3 +181,101 @@ pub async fn engine_and_conn(pool: &PgPool, id: Uuid) -> AppResult<(String, Stri
.await?;
row.ok_or(AppError::NotFound)
}
+
+/// 这个工作区被授权用哪些源(0014)。
+///
+/// **可挂载列表从此走这里,不再走 `list`。** 从前那条路给 KB 管理员看的是
+/// `datasources::list(pool)`——全部署每一个源,不过滤。于是任何库的管理员
+/// 都能把任意生产库挂进自己库,而挂上之后该库每个 Viewer 都能对它跑只读 SQL。
+pub async fn granted_to_workspace(
+ pool: &PgPool,
+ workspace_id: Uuid,
+) -> AppResult<Vec<DataSourceView>> {
+ let rows: Vec<DataSourceRow> = sqlx::query_as(
+ "SELECT d.id, d.name, d.engine, d.conn_string, d.created_at,
+ d.last_test_at, d.last_test_ok
+ FROM data_source_grants g JOIN data_sources d ON d.id = g.data_source_id
+ WHERE g.workspace_id = $1 ORDER BY d.name",
+ )
+ .bind(workspace_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().map(row_to_view).collect())
+}
+
+/// 这个源授权给了哪些工作区。管理台读它。
+pub async fn grants_for_source(
+ pool: &PgPool,
+ data_source_id: Uuid,
+) -> AppResult<Vec<(Uuid, String)>> {
+ Ok(sqlx::query_as(
+ "SELECT w.id, w.name FROM data_source_grants g
+ JOIN workspaces w ON w.id = g.workspace_id
+ WHERE g.data_source_id = $1 ORDER BY w.name",
+ )
+ .bind(data_source_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 授权一个工作区用这个源。幂等。
+pub async fn grant(
+ pool: &PgPool,
+ data_source_id: Uuid,
+ workspace_id: Uuid,
+ actor: Uuid,
+) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO data_source_grants (data_source_id, workspace_id, granted_by)
+ VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",
+ )
+ .bind(data_source_id)
+ .bind(workspace_id)
+ .bind(actor)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 收回授权,**连同该工作区里已经挂上的那些一起卸掉**。
+///
+/// 只删授权行不够:`mounted` 读的是 `kb_data_sources`,问数也读它。留着挂载
+/// 就等于收回了授权而访问照旧——一个不生效的权限撤销比没有还危险。
+///
+/// 一个事务里做完:两条 DELETE 之间如果崩了,留下的正是「无授权却挂着」那种
+/// 状态,而那恰恰是这条迁移要消灭的东西。
+pub async fn revoke(pool: &PgPool, data_source_id: Uuid, workspace_id: Uuid) -> AppResult<u64> {
+ let mut tx = pool.begin().await?;
+ let unmounted = sqlx::query(
+ "DELETE FROM kb_data_sources
+ WHERE data_source_id = $1
+ AND kb_id IN (SELECT id FROM knowledge_bases WHERE workspace_id = $2)",
+ )
+ .bind(data_source_id)
+ .bind(workspace_id)
+ .execute(&mut *tx)
+ .await?
+ .rows_affected();
+ sqlx::query("DELETE FROM data_source_grants WHERE data_source_id = $1 AND workspace_id = $2")
+ .bind(data_source_id)
+ .bind(workspace_id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(unmounted)
+}
+
+/// 这个源对这个知识库是不是授权过的。**挂载前必查**——守卫不能只在列表那一侧:
+/// 列表过滤挡的是「看得见」,而挂载端点是照着 id 调的,谁都能自己拼一个。
+pub async fn is_granted(pool: &PgPool, kb_id: Uuid, data_source_id: Uuid) -> AppResult<bool> {
+ let found: Option<(i32,)> = sqlx::query_as(
+ "SELECT 1 FROM data_source_grants g
+ JOIN knowledge_bases kb ON kb.workspace_id = g.workspace_id
+ WHERE kb.id = $1 AND g.data_source_id = $2",
+ )
+ .bind(kb_id)
+ .bind(data_source_id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(found.is_some())
+}
diff --git a/crates/utopia-store/tests/a_source_reaches_only_where_it_was_granted.rs b/crates/utopia-store/tests/a_source_reaches_only_where_it_was_granted.rs
new file mode 100644
index 00000000..400e0a9c
--- /dev/null
+++ b/crates/utopia-store/tests/a_source_reaches_only_where_it_was_granted.rs
@@ -0,0 +1,173 @@
+//! 数据源授权(0014)。
+//!
+//! 补的洞:注册是部署级动作,而挂载的守卫是 `require_kb(kb_id, Role::Admin)`
+//! ——请求者自己那个库的管理员。可挂载列表返回的又是全部署每一个源。于是任何
+//! 一个知识库的管理员,都能把任意生产库挂进自己库,而挂上之后该库每个 Viewer
+//! 都能通过 `query_data` 对它跑只读 SQL。
+//!
+//! 这里钉三件事:
+//!
+//! - **看不见**:没授权的源不进可挂载列表
+//! - **也挂不上**:列表过滤只挡「看得见」,而挂载端点是照着 id 调的——
+//! 守卫必须在两侧都有,这条测的是端点那一侧
+//! - **收回是真收回**:撤授权连同已挂上的一起卸掉。只删授权行的话,问数读的
+//! 还是 `kb_data_sources`,等于撤销不生效——一个不生效的权限撤销比没有还危险
+
+use sqlx::PgPool;
+use utopia_store::datasources;
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ /// 授权给它的工作区
+ ours: Uuid,
+ /// 没授权的工作区——它的库不该够得着这个源
+ theirs: Uuid,
+ our_kb: Uuid,
+ their_kb: Uuid,
+ source: Uuid,
+ actor: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let org = Uuid::now_v7();
+ let (ours, theirs) = (Uuid::now_v7(), Uuid::now_v7());
+ let (our_kb, their_kb) = (Uuid::now_v7(), Uuid::now_v7());
+ let (source, actor) = (Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'grant-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ for (id, name) in [(ours, "ours"), (theirs, "theirs")] {
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, $3)")
+ .bind(id)
+ .bind(org)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ for (kb, ws, name) in [(our_kb, ours, "our-kb"), (their_kb, theirs, "their-kb")] {
+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, $3)")
+ .bind(kb)
+ .bind(ws)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, password_hash, display_name, is_admin)
+ VALUES ($1, $2, $3, 'x', 'Grant Test', TRUE)",
+ )
+ .bind(actor)
+ .bind(org)
+ .bind(format!("{actor}@grant.test"))
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO data_sources (id, name, engine, conn_string, created_by)
+ VALUES ($1, $2, 'postgres', 'postgres://u:[email protected]:5432/w', $3)",
+ )
+ .bind(source)
+ .bind(format!("warehouse-{source}"))
+ .bind(actor)
+ .execute(pool)
+ .await?;
+
+ Ok(Fixture {
+ org,
+ ours,
+ theirs,
+ our_kb,
+ their_kb,
+ source,
+ actor,
+ })
+}
+
+#[tokio::test]
+async fn a_source_reaches_only_where_it_was_granted() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ // ---- 一、没授权 = 谁都够不着
+ assert!(
+ datasources::granted_to_workspace(&pool, f.ours)
+ .await?
+ .is_empty(),
+ "没授权过,可挂载列表就该是空的"
+ );
+ assert!(
+ !datasources::is_granted(&pool, f.our_kb, f.source).await?,
+ "没授权,挂载端点的守卫必须说不"
+ );
+
+ // ---- 二、授权一个工作区,另一个不受影响
+ datasources::grant(&pool, f.source, f.ours, f.actor).await?;
+ let ours = datasources::granted_to_workspace(&pool, f.ours).await?;
+ assert_eq!(ours.len(), 1, "授权过的工作区看得见它");
+ assert!(
+ !ours[0].summary.contains("p@"),
+ "列表里只能有 host:port/db 摘要,凭据不出服务端"
+ );
+ assert!(
+ datasources::granted_to_workspace(&pool, f.theirs)
+ .await?
+ .is_empty(),
+ "**授权是逐工作区的**:给了一个不等于给了全部署"
+ );
+
+ // ---- 三、端点侧的守卫:列表过滤只挡「看得见」
+ assert!(datasources::is_granted(&pool, f.our_kb, f.source).await?);
+ assert!(
+ !datasources::is_granted(&pool, f.their_kb, f.source).await?,
+ "没授权的工作区,就算自己拼一个 uuid 打过来也挂不上"
+ );
+
+ // ---- 四、一个源可授权给多个工作区(多对多,不是一对多)
+ datasources::grant(&pool, f.source, f.theirs, f.actor).await?;
+ assert_eq!(
+ datasources::grants_for_source(&pool, f.source).await?.len(),
+ 2,
+ "同一个数仓要能同时服务多个工作区"
+ );
+ datasources::grant(&pool, f.source, f.theirs, f.actor).await?;
+ assert_eq!(
+ datasources::grants_for_source(&pool, f.source).await?.len(),
+ 2,
+ "重复授权是幂等的"
+ );
+
+ // ---- 五、收回连同挂载一起收
+ datasources::mount(&pool, f.our_kb, f.source).await?;
+ datasources::mount(&pool, f.their_kb, f.source).await?;
+ let unmounted = datasources::revoke(&pool, f.source, f.theirs).await?;
+ assert_eq!(unmounted, 1, "撤授权要把那个工作区里已挂上的一起卸掉");
+ assert!(
+ datasources::mounted(&pool, f.their_kb).await?.is_empty(),
+ "**留着挂载 = 撤销不生效**:问数读的是 kb_data_sources"
+ );
+ assert_eq!(
+ datasources::mounted(&pool, f.our_kb).await?.len(),
+ 1,
+ "另一个工作区的挂载不受牵连"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM data_sources WHERE id = $1")
+ .bind(f.source)
+ .execute(&pool)
+ .await?;
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/migrations/0014_data_source_grants.sql b/migrations/0014_data_source_grants.sql
new file mode 100644
index 00000000..f56d2ea9
--- /dev/null
+++ b/migrations/0014_data_source_grants.sql
@@ -0,0 +1,44 @@
+-- 数据源授权:这个库可以给哪些工作区用。
+--
+-- **在此之前这一层不存在。** 注册是部署级动作(`require_admin`),而挂载的
+-- 守卫是 `require_kb(kb_id, Role::Admin)`——请求者自己那个库的管理员。可挂载
+-- 列表返回的又是 `datasources::list(pool)`:全部署每一个源,不过滤。
+--
+-- 于是任何一个知识库的管理员,都能列出部署里每一个已注册数据库,并把任意一个
+-- 挂进自己库。挂上之后该库的每个 Viewer 都能通过 `query_data` 对它跑只读 SQL
+-- (问数是读,viewer 亦可用)。多工作区部署下这是跨租户的。
+--
+-- **为什么是新表,而不是给 `data_sources` 加一列 `workspace_id`:**
+-- 那一列意味着每个数据源只属于一个工作区。公司只有一个数仓、几个部门各自一个
+-- 工作区时,这个数仓就只能给一个部门用——把一个本该多对多的关系退化成了一对多。
+-- 授权本身就是多对多的:一个源可授权给多个工作区,一个工作区可拿到多个源。
+--
+-- **与 `kb_data_sources` 的分工**(那张表一个字段都不动):
+--
+-- 授权 = 系统管理员说「这个库可以给哪些工作区用」 ← 本表
+-- 挂载 = KB 管理员说「我这个库挂哪几个」 ← kb_data_sources
+--
+-- 两层都是 M2M,各有各的主人。挂载不再能凭空发生:只能在授权过的集合里挑。
+CREATE TABLE data_source_grants (
+ data_source_id UUID NOT NULL REFERENCES data_sources(id) ON DELETE CASCADE,
+ workspace_id UUID NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ granted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- 授权的人。**裸外键**,与 entity_merges.merged_by 那几处一致:
+ -- 用户是软删除的,生产代码里没有 DELETE FROM users,所以归因保得住
+ granted_by UUID REFERENCES users(id),
+ PRIMARY KEY (data_source_id, workspace_id)
+);
+
+-- 「这个工作区能用哪些源」是热路径(每次开数据映射页都问一次);
+-- 主键已覆盖反向的「这个源给了谁」
+CREATE INDEX data_source_grants_workspace_idx ON data_source_grants (workspace_id);
+
+-- 存量授权:把已经挂着的补上,否则这条迁移一上线就把正在用的源全断掉。
+--
+-- **补的是既成事实,不是补一个宽松默认**:只授权给「确实已经挂载过它」的
+-- 那些工作区。没挂过的一个都不给——那正是这条迁移要关掉的门。
+INSERT INTO data_source_grants (data_source_id, workspace_id)
+SELECT DISTINCT kds.data_source_id, kb.workspace_id
+ FROM kb_data_sources kds
+ JOIN knowledge_bases kb ON kb.id = kds.kb_id
+ON CONFLICT DO NOTHING;
diff --git a/web/src/api.ts b/web/src/api.ts
index 5cd2c588..67db3b63 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1015,6 +1015,23 @@ export const api = {
request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {
method: "POST",
}),
+ /** 这个源授权给了哪些工作区(0014)。授权与挂载是两层:
+ * 授权由系统管理员写,挂载由 KB 管理员在授权过的集合里挑 */
+ dataSourceGrants: (id: string) =>
+ request<{ workspaces: { id: string; name: string }[] }>(
+ `/api/v1/admin/data-sources/${id}/grants`,
+ ),
+ grantDataSource: (id: string, workspaceId: string) =>
+ request<{ ok: boolean }>(
+ `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`,
+ { method: "PUT" },
+ ),
+ /** 收回授权。**连同该工作区里已挂上的一起卸掉**,返回卸了几个 */
+ revokeDataSource: (id: string, workspaceId: string) =>
+ request<{ ok: boolean; unmounted: number }>(
+ `/api/v1/admin/data-sources/${id}/grants/${workspaceId}`,
+ { method: "DELETE" },
+ ),
/** 一页口径。**Viewer 就能看**——问数的答案直接由口径决定,
* 看得见答案却看不见口径,等于要人信一个不给看的算法 */
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 8a711a5d..359ebfa7 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -56,6 +56,9 @@ export const en = {
"Pick the date this fact ended — the new one does not say when it started.",
empty_query: "Type something to search for.",
no_data_sources: "No databases are mounted on this knowledge base.",
+ // 授权是逐工作区的(0014):源没授权给本库所属的工作区
+ source_not_granted:
+ "This data source is not granted to this workspace. Ask a deployment admin to grant it in System settings → Data sources.",
memory_source_permanent:
"The Memory source is part of the knowledge base and stays.",
source_name_required: "Give this source a name.",
@@ -734,6 +737,18 @@ export const en = {
testFail: "Failed",
neverTested: "Untested",
remove: "Remove",
+ grants: "Available to",
+ grantsHint:
+ "Which workspaces may use this source. **Once granted, KB admins in those workspaces choose whether to mount it** — " +
+ "this controls what they can reach, not what they have mounted.",
+ grantsNone:
+ "Not granted to any workspace — no knowledge base can mount it.",
+ grantAdd: "Grant a workspace…",
+ grantRevoke: "Revoke",
+ grantRevoked: (n: number) =>
+ n === 0
+ ? "Revoked."
+ : `Revoked, and unmounted it from ${n} knowledge base(s).`,
},
kbs: {
hint:
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index b32b3558..9b1ef840 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -52,6 +52,9 @@ export const zh: Strings = {
close_at_required: "选一个这条事实结束的日期——新的那条没说自己何时开始。",
empty_query: "输入点什么再检索。",
no_data_sources: "这个知识库没有挂载任何数据库。",
+ // 授权是逐工作区的(0014):源没授权给本库所属的工作区
+ source_not_granted:
+ "这个数据源没有授权给本工作区。请部署管理员在「系统设置 → 数据源」里授权。",
memory_source_permanent: "「记忆」是知识库自带的来源,会一直在。",
source_name_required: "给这个来源起个名字。",
bad_cron: "这个 cron 表达式解析不了。",
@@ -670,6 +673,15 @@ export const zh: Strings = {
testFail: "失败",
neverTested: "未测试",
remove: "移除",
+ grants: "可用于",
+ grantsHint:
+ "授权哪些工作区可以用这个源。**授权之后,那些工作区的知识库管理员自己挑挂不挂**——" +
+ "这里管的是「能不能拿到」,不是「挂没挂」。",
+ grantsNone: "还没授权给任何工作区——现在没有知识库挂得上它。",
+ grantAdd: "授权工作区…",
+ grantRevoke: "收回",
+ grantRevoked: (n: number) =>
+ n === 0 ? "已收回。" : `已收回,顺带卸掉了 ${n} 个知识库上的挂载。`,
},
kbs: {
hint:
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index fae22804..acdb079f 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -5,8 +5,109 @@ import { Lock, Plus, X } from "lucide-react";
import { api } from "../api";
import { LANG_NAMES, S } from "../i18n";
import { useKb } from "../kb";
+import { toast } from "../toast";
+import { SearchSelect } from "../ui";
import { Members } from "./Members";
+/** 一个源授权给了哪些工作区(0014)。
+ *
+ * **授权与挂载是两层**:这里说「这个源可以给谁用」,KB 管理员再在授权过的
+ * 集合里挑挂不挂。从前没有这一层——可挂载列表返回全部署每一个源,于是任何
+ * 库的管理员都能把任意生产库挂进自己库。
+ *
+ * 两层都是多对多:一个源可授权给多个工作区,一个工作区可拿到多个源。 */
+function SourceGrants({ sourceId }: { sourceId: string }) {
+ const queryClient = useQueryClient();
+ const [picked, setPicked] = useState("");
+ const [notice, setNotice] = useState<string | null>(null);
+
+ const grants = useQuery({
+ queryKey: ["dataSourceGrants", sourceId],
+ queryFn: () => api.dataSourceGrants(sourceId),
+ });
+ const workspaces = useQuery({
+ queryKey: ["workspaces"],
+ queryFn: api.workspaces,
+ });
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ["dataSourceGrants", sourceId] });
+
+ const grant = useMutation({
+ mutationFn: (wsId: string) => api.grantDataSource(sourceId, wsId),
+ onSuccess: () => {
+ setPicked("");
+ setNotice(null);
+ invalidate();
+ },
+ onError: (e: unknown) => toast.error((e as Error).message),
+ });
+ const revoke = useMutation({
+ mutationFn: (wsId: string) => api.revokeDataSource(sourceId, wsId),
+ // 卸了几个要说出来:收回授权会顺带断掉正在用的挂载,
+ // 悄悄断比断本身更糟
+ onSuccess: (r) => {
+ setNotice(S.settings.datasources.grantRevoked(r.unmounted));
+ invalidate();
+ },
+ onError: (e: unknown) => toast.error((e as Error).message),
+ });
+
+ const granted = grants.data?.workspaces ?? [];
+ const grantedIds = new Set(granted.map((w) => w.id));
+ const grantable = (workspaces.data ?? []).filter(
+ (w) => !grantedIds.has(w.id),
+ );
+
+ return (
+ <div className="border-t border-white/5 pt-3 space-y-2">
+ <div className="flex items-baseline gap-2">
+ <span className="text-[11px] text-neutral-500">
+ {S.settings.datasources.grants}
+ </span>
+ {granted.length === 0 ? (
+ <span className="text-[11px] text-neutral-600">
+ {S.settings.datasources.grantsNone}
+ </span>
+ ) : (
+ <div className="flex flex-wrap gap-1.5">
+ {granted.map((w) => (
+ <span
+ key={w.id}
+ className="u-chip u-chip-neutral text-[11px] flex items-center gap-1"
+ >
+ {w.name}
+ <button
+ className="text-neutral-500 hover:text-[var(--u-danger)]"
+ title={S.settings.datasources.grantRevoke}
+ disabled={revoke.isPending}
+ onClick={() => revoke.mutate(w.id)}
+ >
+ <X size={10} />
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+ {grantable.length > 0 && (
+ <div className="flex items-center gap-2">
+ <SearchSelect
+ className="flex-1"
+ value={picked}
+ options={grantable.map((w) => ({ value: w.id, label: w.name }))}
+ onChange={(v) => {
+ setPicked(v);
+ if (v) grant.mutate(v);
+ }}
+ placeholder={S.settings.datasources.grantAdd}
+ />
+ </div>
+ )}
+ {notice && <p className="text-[11px] text-neutral-500">{notice}</p>}
+ </div>
+ );
+}
+
/** 部署级配置:注册开关 + worker 并发。 */
function DeploymentAdmin() {
const queryClient = useQueryClient();
@@ -452,7 +553,9 @@ function NewKbModal({
checked={on}
onChange={() => toggle(p.id)}
/>
- <span className="block text-xs text-neutral-200">{p.name}</span>
+ <span className="block text-xs text-neutral-200">
+ {p.name}
+ </span>
<span className="block text-[11px] leading-snug text-neutral-500">
{p.summary}
</span>
@@ -533,42 +636,45 @@ function DataSourcesAdmin() {
<div className="glass rounded-xl divide-y divide-white/5">
{(list.data?.data_sources ?? []).map((d) => (
- <div key={d.id} className="px-4 py-3 flex items-center gap-3">
- <div className="min-w-0 flex-1">
- <div className="text-sm text-neutral-200">{d.name}</div>
- <div className="text-xs text-neutral-500 font-mono truncate">
- {d.summary}
+ <div key={d.id} className="px-4 py-3 space-y-3">
+ <div className="flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-neutral-200">{d.name}</div>
+ <div className="text-xs text-neutral-500 font-mono truncate">
+ {d.summary}
+ </div>
</div>
- </div>
- <span
- className={`u-chip shrink-0 ${
- d.last_test_ok === true
- ? "u-chip-success"
+ <span
+ className={`u-chip shrink-0 ${
+ d.last_test_ok === true
+ ? "u-chip-success"
+ : d.last_test_ok === false
+ ? "u-chip-danger"
+ : "u-chip-neutral"
+ }`}
+ >
+ {d.last_test_ok === true
+ ? S.settings.datasources.testOk
: d.last_test_ok === false
- ? "u-chip-danger"
- : "u-chip-neutral"
- }`}
- >
- {d.last_test_ok === true
- ? S.settings.datasources.testOk
- : d.last_test_ok === false
- ? S.settings.datasources.testFail
- : S.settings.datasources.neverTested}
- </span>
- <button
- className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
- disabled={test.isPending}
- onClick={() => test.mutate(d.id)}
- >
- {S.settings.datasources.test}
- </button>
- <button
- className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"
- disabled={remove.isPending}
- onClick={() => remove.mutate(d.id)}
- >
- {S.settings.datasources.remove}
- </button>
+ ? S.settings.datasources.testFail
+ : S.settings.datasources.neverTested}
+ </span>
+ <button
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
+ disabled={test.isPending}
+ onClick={() => test.mutate(d.id)}
+ >
+ {S.settings.datasources.test}
+ </button>
+ <button
+ className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"
+ disabled={remove.isPending}
+ onClick={() => remove.mutate(d.id)}
+ >
+ {S.settings.datasources.remove}
+ </button>
+ </div>
+ <SourceGrants sourceId={d.id} />
</div>
))}
{list.data?.data_sources.length === 0 && (