Elffuss BraidHub

kikocis/utopia public

An admin can retire an account without erasing what that person did (#129)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Changeset9130cb8620b60b4da4c2b6dc2f1f0f2400c54983047c55387388382d5f4187fe
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-08-31 04:10 +08:00
CommitterGitHub <noreply@github.com> · 2026-08-31 04:10 +08:00
Parentse879cb6b0d68

Browse the files at this changeset

11 files changed

modified crates/utopia-server/src/api/admin_routes.rs +56 −1
@@ -1,6 +1,6 @@
11 //! 系统管理 API(仅系统管理员):部署配置 + 代开账号。
22
3-use axum::extract::State;
3+use axum::extract::{Path, State};
44 use axum::Json;
55 use serde::Deserialize;
66 use serde_json::json;
@@ -10,6 +10,7 @@
1010 use crate::auth::{self, AuthUser};
1111 use crate::error::ApiResult;
1212 use crate::state::AppState;
13+use uuid::Uuid;
1314
1415 fn require_admin(user: &User) -> Result<(), AppError> {
1516 if user.is_admin {
@@ -143,3 +144,57 @@
143144 .await?;
144145 Ok(Json(json!({ "user": created })))
145146 }
147+
148+/// 停用一个账号(软删除,见迁移 0056)。
149+///
150+/// **不是 DELETE。** 审计事件、合并日志、改类账本、口径确认的 `actor_id` 都指着
151+/// 这个人,那些是审计材料——人走了仍然要能回答「当时是谁做的」。停用只断访问:
152+/// 登录查不到人,已签发的 token 下一次请求也查不到(会话校验走同一个函数),
153+/// 成员列表里不再出现,而所有归因照旧。
154+///
155+/// 两条护栏在 store 层而不是这里:不能停用自己、不能停用最后一个管理员。
156+/// 放在下面是因为界面挡得住误点,挡不住直接调接口。
157+pub async fn deactivate_user(
158+ State(state): State<AppState>,
159+ AuthUser(user): AuthUser,
160+ Path(target): Path<Uuid>,
161+) -> ApiResult<Json<serde_json::Value>> {
162+ require_admin(&user)?;
163+ utopia_store::accounts::deactivate_user(&state.pool, target, user.id).await?;
164+ let _ = utopia_store::audit::record(
165+ &state.pool,
166+ None,
167+ user.id,
168+ "user.deactivated",
169+ "user",
170+ Some(target),
171+ serde_json::json!({}),
172+ )
173+ .await;
174+ Ok(Json(serde_json::json!({ "ok": true })))
175+}
176+
177+/// 把停用的账号放回来。
178+///
179+/// **可能失败**:停用期间有人用同一个 email 建了新账号,那个部分唯一索引
180+/// (`users_email_active_idx`)会挡住恢复。让管理员看见冲突,好过悄悄让两个
181+/// 在职账号共用一个 email。
182+pub async fn reactivate_user(
183+ State(state): State<AppState>,
184+ AuthUser(user): AuthUser,
185+ Path(target): Path<Uuid>,
186+) -> ApiResult<Json<serde_json::Value>> {
187+ require_admin(&user)?;
188+ utopia_store::accounts::reactivate_user(&state.pool, target).await?;
189+ let _ = utopia_store::audit::record(
190+ &state.pool,
191+ None,
192+ user.id,
193+ "user.reactivated",
194+ "user",
195+ Some(target),
196+ serde_json::json!({}),
197+ )
198+ .await;
199+ Ok(Json(serde_json::json!({ "ok": true })))
200+}
modified crates/utopia-server/src/api/mod.rs +7 −0
@@ -89,6 +89,13 @@
8989 get(admin_routes::get_deployment).put(admin_routes::put_deployment),
9090 )
9191 .route("/admin/users", post(admin_routes::create_user))
92+ // 停用 / 恢复账号(0056)。DELETE 的语义是「这个人不再有访问权」,
93+ // 而不是「这一行没了」——归因照旧查得到
94+ .route(
95+ "/admin/users/{id}",
96+ axum::routing::delete(admin_routes::deactivate_user)
97+ .post(admin_routes::reactivate_user),
98+ )
9299 .route(
93100 "/admin/data-sources",
94101 get(datasource_routes::list).post(datasource_routes::create),
modified crates/utopia-store/src/access.rs +2 −1
@@ -102,7 +102,8 @@
102102 let rows: Vec<KbMemberView> = sqlx::query_as(
103103 "SELECT m.user_id, u.email, u.display_name, m.role
104104 FROM kb_members m JOIN users u ON u.id = m.user_id
105- WHERE m.kb_id = $1 ORDER BY u.display_name",
105+ -- 停用的人不出现在成员列表里(0056);成员关系那一行留着
106+ WHERE m.kb_id = $1 AND u.deactivated_at IS NULL ORDER BY u.display_name",
106107 )
107108 .bind(kb_id)
108109 .fetch_all(pool)
modified crates/utopia-store/src/accounts.rs +86 −2
@@ -197,16 +197,27 @@
197197 Ok(user)
198198 }
199199
200+/// 按 email 找账号——**只找在职的**。
201+///
202+/// 这一句 `deactivated_at IS NULL` 同时管两件事:停用的人登不进来,以及
203+/// 「一个 email 在停用账号里可能重复」时不会随机返回其中一条(唯一索引
204+/// 现在是部分的,只约束在职账号,见迁移 0056)。
200205 pub async fn find_user_by_email(pool: &PgPool, email: &str) -> AppResult<Option<User>> {
201- let user = sqlx::query_as("SELECT * FROM users WHERE email = $1")
206+ let user = sqlx::query_as("SELECT * FROM users WHERE email = $1 AND deactivated_at IS NULL")
202207 .bind(email)
203208 .fetch_optional(pool)
204209 .await?;
205210 Ok(user)
206211 }
207212
213+/// 按 id 找账号——**只找在职的**。
214+///
215+/// 会话校验走这里,所以停用**立即生效**,不必等 token 过期:已经签发出去的
216+/// token 下一次请求就查不到人。这是软删除唯一必须挡住的路径,其余读 users 的
217+/// 地方(审计、合并日志、改类账本)**要照旧查得到**——事情是他做的,人停用了
218+/// 不等于那件事没发生。
208219 pub async fn find_user_by_id(pool: &PgPool, id: Uuid) -> AppResult<Option<User>> {
209- let user = sqlx::query_as("SELECT * FROM users WHERE id = $1")
220+ let user = sqlx::query_as("SELECT * FROM users WHERE id = $1 AND deactivated_at IS NULL")
210221 .bind(id)
211222 .fetch_optional(pool)
212223 .await?;
@@ -232,3 +243,76 @@
232243 .await?;
233244 Ok(())
234245 }
246+
247+/// 停用一个账号(软删除,见迁移 0056)。
248+///
249+/// **不删行。** 审计事件、合并日志、改类账本、口径确认的 `actor_id` 都指着这个人,
250+/// 而那些是审计材料——人走了仍然要能回答「当时是谁做的」。停用只断访问。
251+///
252+/// **不能停用自己**:管理员把自己停掉之后就没人能把他放回来了(这个系统没有
253+/// 「超级管理员」这一层)。挡在这里而不是只挡在界面上——界面挡得住误点,
254+/// 挡不住直接调接口。
255+///
256+/// **最后一个管理员不能停用**:否则这个组织从此没人能管成员。同样的理由。
257+pub async fn deactivate_user(pool: &PgPool, target: Uuid, actor: Uuid) -> AppResult<()> {
258+ if target == actor {
259+ return Err(AppError::Validation("不能停用自己的账号".into()));
260+ }
261+ let mut tx = pool.begin().await?;
262+ let victim: Option<(bool, Uuid, Option<chrono::DateTime<chrono::Utc>>)> =
263+ sqlx::query_as("SELECT is_admin, org_id, deactivated_at FROM users WHERE id = $1")
264+ .bind(target)
265+ .fetch_optional(&mut *tx)
266+ .await?;
267+ let Some((is_admin, org_id, already)) = victim else {
268+ tx.rollback().await?;
269+ return Err(AppError::NotFound);
270+ };
271+ if already.is_some() {
272+ // 幂等:重复停用不是错误,也不该把 deactivated_by 改成第二个人
273+ tx.rollback().await?;
274+ return Ok(());
275+ }
276+ if is_admin {
277+ let (others,): (i64,) = sqlx::query_as(
278+ "SELECT count(*) FROM users
279+ WHERE org_id = $1 AND is_admin AND deactivated_at IS NULL AND id <> $2",
280+ )
281+ .bind(org_id)
282+ .bind(target)
283+ .fetch_one(&mut *tx)
284+ .await?;
285+ if others == 0 {
286+ tx.rollback().await?;
287+ return Err(AppError::Validation(
288+ "这是组织里最后一个管理员,停用之后没人能管成员".into(),
289+ ));
290+ }
291+ }
292+ sqlx::query("UPDATE users SET deactivated_at = now(), deactivated_by = $2 WHERE id = $1")
293+ .bind(target)
294+ .bind(actor)
295+ .execute(&mut *tx)
296+ .await?;
297+ tx.commit().await?;
298+ Ok(())
299+}
300+
301+/// 把停用的账号放回来。
302+///
303+/// **可能失败,而且失败得有道理**:停用期间有人用同一个 email 建了新账号,
304+/// 那个部分唯一索引会挡住这次恢复。这时该做的是让管理员看见冲突,而不是
305+/// 悄悄让两个在职账号共用一个 email。
306+pub async fn reactivate_user(pool: &PgPool, target: Uuid) -> AppResult<()> {
307+ let res = sqlx::query(
308+ "UPDATE users SET deactivated_at = NULL, deactivated_by = NULL
309+ WHERE id = $1 AND deactivated_at IS NOT NULL",
310+ )
311+ .bind(target)
312+ .execute(pool)
313+ .await?;
314+ if res.rows_affected() == 0 {
315+ return Err(AppError::NotFound);
316+ }
317+ Ok(())
318+}
modified crates/utopia-store/src/members.rs +12 −7
@@ -7,7 +7,9 @@
77 let rows = sqlx::query_as(
88 "SELECT m.user_id, u.email, u.display_name, m.role, u.is_admin
99 FROM memberships m JOIN users u ON u.id = m.user_id
10- WHERE m.workspace_id = $1
10+ -- 停用的人不再出现在成员列表里(0056)。成员关系那一行留着——
11+ -- 恢复账号时不必重新加回每一个工作区
12+ WHERE m.workspace_id = $1 AND u.deactivated_at IS NULL
1113 ORDER BY m.created_at",
1214 )
1315 .bind(workspace_id)
@@ -20,7 +22,7 @@
2022 pub async fn org_users(pool: &PgPool, org_id: Uuid) -> AppResult<Vec<OrgUser>> {
2123 let rows = sqlx::query_as(
2224 "SELECT id, email, display_name, is_admin FROM users
23- WHERE org_id = $1 ORDER BY created_at",
25+ WHERE org_id = $1 AND deactivated_at IS NULL ORDER BY created_at",
2426 )
2527 .bind(org_id)
2628 .fetch_all(pool)
@@ -53,11 +55,14 @@
5355 user_id: Uuid,
5456 role: Role,
5557 ) -> AppResult<()> {
56- // 目标用户必须存在于本组织
57- let exists: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM users WHERE id = $1")
58- .bind(user_id)
59- .fetch_optional(pool)
60- .await?;
58+ // 目标用户必须存在于本组织,**而且在职**——否则能把一个已停用的账号
59+ // 加进工作区,它在成员列表里又看不见(那条查询过滤了停用的),
60+ // 于是成了一条谁也发现不了的授权
61+ let exists: Option<(Uuid,)> =
62+ sqlx::query_as("SELECT id FROM users WHERE id = $1 AND deactivated_at IS NULL")
63+ .bind(user_id)
64+ .fetch_optional(pool)
65+ .await?;
6166 if exists.is_none() {
6267 return Err(AppError::NotFound);
6368 }
added crates/utopia-store/tests/a_retired_account.rs +134 −0
@@ -0,0 +1,134 @@
1+//! 停用账号的四条硬性质——打在真库上(见迁移 0056)。
2+//!
3+//! 软删除的风险全在「漏过滤一处」:只要有一条读 `users` 的路径忘了带
4+//! `deactivated_at IS NULL`,停用就成了摆设,而且**不会有任何报错**。
5+//! 所以这几条守的不是函数,是**路径**。
6+//!
7+//! 反过来,归因那几处必须**照旧查得到**:审计事件、合并日志、改类账本的
8+//! `actor_id` 指着这个人,而那些是审计材料——人走了不等于那件事没发生。
9+
10+use sqlx::PgPool;
11+use uuid::Uuid;
12+
13+async fn org_with_two_admins(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {
14+ let (org, a, b) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
15+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'retire-test')")
16+ .bind(org)
17+ .execute(pool)
18+ .await?;
19+ for (id, mail) in [(a, "a"), (b, "b")] {
20+ sqlx::query(
21+ "INSERT INTO users (id, org_id, email, display_name, password_hash, is_admin)
22+ VALUES ($1, $2, $3, 'u', 'x', TRUE)",
23+ )
24+ .bind(id)
25+ .bind(org)
26+ .bind(format!("{}-{mail}@retire.test", id.simple()))
27+ .execute(pool)
28+ .await?;
29+ }
30+ Ok((org, a, b))
31+}
32+
33+#[tokio::test]
34+async fn a_retired_account_cannot_get_back_in() -> anyhow::Result<()> {
35+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
36+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
37+ return Ok(());
38+ };
39+ let pool = PgPool::connect(&url).await?;
40+ let (org, a, b) = org_with_two_admins(&pool).await?;
41+
42+ let run = async {
43+ let email: String = sqlx::query_scalar("SELECT email FROM users WHERE id = $1")
44+ .bind(b)
45+ .fetch_one(&pool)
46+ .await?;
47+ assert!(
48+ utopia_store::accounts::find_user_by_email(&pool, &email)
49+ .await?
50+ .is_some(),
51+ "停用前该找得到"
52+ );
53+
54+ utopia_store::accounts::deactivate_user(&pool, b, a).await?;
55+
56+ // 登录这条路
57+ assert!(
58+ utopia_store::accounts::find_user_by_email(&pool, &email)
59+ .await?
60+ .is_none(),
61+ "停用的账号还能按 email 找到——登录挡不住"
62+ );
63+ // **已经签发出去的 token 那条路**。会话校验走 find_user_by_id,
64+ // 所以停用立即生效,不必等 token 过期
65+ assert!(
66+ utopia_store::accounts::find_user_by_id(&pool, b)
67+ .await?
68+ .is_none(),
69+ "停用的账号还能按 id 找到——已签发的 token 仍然有效"
70+ );
71+
72+ // 归因照旧:那一行还在,只是打了时间戳
73+ let still_there: i64 = sqlx::query_scalar("SELECT count(*) FROM users WHERE id = $1")
74+ .bind(b)
75+ .fetch_one(&pool)
76+ .await?;
77+ assert_eq!(still_there, 1, "软删除不该把行删掉——审计要靠它");
78+ Ok::<_, anyhow::Error>(())
79+ }
80+ .await;
81+
82+ sqlx::query("DELETE FROM organizations WHERE id = $1")
83+ .bind(org)
84+ .execute(&pool)
85+ .await?;
86+ run
87+}
88+
89+#[tokio::test]
90+async fn the_last_admin_and_oneself_are_protected() -> anyhow::Result<()> {
91+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
92+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
93+ return Ok(());
94+ };
95+ let pool = PgPool::connect(&url).await?;
96+ let (org, a, b) = org_with_two_admins(&pool).await?;
97+
98+ let run = async {
99+ assert!(
100+ utopia_store::accounts::deactivate_user(&pool, a, a)
101+ .await
102+ .is_err(),
103+ "不能停用自己——这个系统没有超级管理员那一层,停完就没人能放回来"
104+ );
105+
106+ utopia_store::accounts::deactivate_user(&pool, b, a).await?;
107+ assert!(
108+ utopia_store::accounts::deactivate_user(&pool, a, b)
109+ .await
110+ .is_err(),
111+ "最后一个管理员不能停用,否则组织从此没人能管成员"
112+ );
113+
114+ // 幂等:重复停用不是错误
115+ utopia_store::accounts::deactivate_user(&pool, b, a).await?;
116+
117+ // 恢复之后一切照旧
118+ utopia_store::accounts::reactivate_user(&pool, b).await?;
119+ assert!(
120+ utopia_store::accounts::find_user_by_id(&pool, b)
121+ .await?
122+ .is_some(),
123+ "恢复之后该能登录了"
124+ );
125+ Ok::<_, anyhow::Error>(())
126+ }
127+ .await;
128+
129+ sqlx::query("DELETE FROM organizations WHERE id = $1")
130+ .bind(org)
131+ .execute(&pool)
132+ .await?;
133+ run
134+}
added migrations/0056_users_can_be_retired.sql +24 −0
@@ -0,0 +1,24 @@
1+-- 管理员可以停用一个账号。**软删除,不是 DELETE。**
2+--
3+-- 硬删删不掉:审计事件、合并日志、改类账本、口径确认——它们的 `actor_id`
4+-- 指着这个人,而那些记录是审计材料,人走了仍然要能回答「当时是谁做的」。
5+-- 真去 DELETE 只有两个结果:要么被外键挡住(那些列是裸外键),要么级联把
6+-- 审计一起删掉。两个都不是我们要的。
7+--
8+-- 所以停用 = 打一个时间戳。**归因保住,访问断掉**。
9+ALTER TABLE users ADD COLUMN deactivated_at TIMESTAMPTZ;
10+
11+-- 谁停的。同样是裸外键——停用者自己也可能被停用,而那条记录还得在
12+ALTER TABLE users ADD COLUMN deactivated_by UUID REFERENCES users(id);
13+
14+-- **唯一的 email 约束要放停用的账号一马。**
15+--
16+-- 从前 email 是全表唯一。停用之后那个地址还占着位置,于是同一个人回来、
17+-- 或者同一个邮箱转给别人,都建不了新账号——而「停用」不该等于「这个邮箱
18+-- 永久报废」。改成部分唯一索引:只约束在职的。
19+--
20+-- 代价写在前面:停用过的账号里可以有重复 email,`find_user_by_email`
21+-- 因此必须带 `deactivated_at IS NULL`——它本来就要带(不然停用的人还能登录),
22+-- 这里只是让那一句同时也是正确性的保证,而不只是权限的。
23+ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key;
24+CREATE UNIQUE INDEX users_email_active_idx ON users (email) WHERE deactivated_at IS NULL;
modified web/src/api.ts +5 −0
@@ -789,6 +789,11 @@
789789 body: JSON.stringify(body),
790790 }),
791791
792+ /** 停用一个账号(软删除)。归因照旧查得到——审计、合并日志、改类账本都靠它 */
793+ adminDeactivateUser: (userId: string) =>
794+ request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
795+ method: "DELETE",
796+ }),
792797 adminDataSources: () =>
793798 request<{ data_sources: DataSourceView[] }>("/api/v1/admin/data-sources"),
794799 adminCreateDataSource: (body: { name: string; conn_string: string }) =>
modified web/src/i18n/en.ts +5 −0
@@ -1068,6 +1068,11 @@
10681068 title: "Deployment users",
10691069 systemAdmin: "System admin",
10701070 remove: "Remove",
1071+ deactivate: "Deactivate",
1072+ deactivateHint:
1073+ "Cuts off access everywhere — sign-in and any token already issued. What they did stays attributed to them.",
1074+ deactivateConfirm: (name: string) =>
1075+ `Deactivate ${name}? They lose access everywhere. Their past decisions stay on record.`,
10711076 pickUser: "Select a user to add…",
10721077 add: "Add",
10731078 roles: {
modified web/src/i18n/zh.ts +5 −0
@@ -957,6 +957,11 @@
957957 title: "部署用户",
958958 systemAdmin: "系统管理员",
959959 remove: "移除",
960+ deactivate: "停用账号",
961+ deactivateHint:
962+ "断掉整个系统的访问——登录与已签发的 token 都失效。他做过的事仍然记在他名下。",
963+ deactivateConfirm: (name: string) =>
964+ `停用 ${name}?他将无法再登录任何地方,但过往的决定仍然留痕。`,
960965 pickUser: "选择要添加的用户…",
961966 add: "添加",
962967 roles: {
modified web/src/pages/Members.tsx +21 −1
@@ -40,6 +40,11 @@
4040 onSuccess: refresh,
4141 onError,
4242 });
43+ const deactivate = useMutation({
44+ mutationFn: (userId: string) => api.adminDeactivateUser(userId),
45+ onSuccess: refresh,
46+ onError,
47+ });
4348
4449 const memberIds = new Set(members.data?.map((m) => m.user_id));
4550 const addable = orgUsers.data?.filter((u) => !memberIds.has(u.id)) ?? [];
@@ -91,13 +96,28 @@
9196 options={ROLE_OPTIONS}
9297 />
9398 </td>
94- <td className="py-2 text-right">
99+ <td className="py-2 text-right whitespace-nowrap">
95100 <button
96101 onClick={() => remove.mutate(m.user_id)}
97102 className="text-xs text-neutral-500 hover:text-rose-400"
98103 >
99104 {S.members.remove}
100105 </button>
106+ {/* 停用账号跟「移出工作区」是两件事:前者断掉整个系统的访问,
107+ 后者只是这个工作区不再有他。所以分开两个按钮,而且停用
108+ 只给管理员看——它的影响面大得多 */}
109+ {me.data?.is_admin && me.data.id !== m.user_id && (
110+ <button
111+ onClick={() => {
112+ if (confirm(S.members.deactivateConfirm(m.display_name)))
113+ deactivate.mutate(m.user_id);
114+ }}
115+ className="ml-3 text-xs text-neutral-600 hover:text-rose-400"
116+ title={S.members.deactivateHint}
117+ >
118+ {S.members.deactivate}
119+ </button>
120+ )}
101121 </td>
102122 </tr>
103123 ))}