Skip to content

World's first open-source enterprise world model.

A system admin can make another user a system admin (#1234)

Szabo Bogdan70bf7a7f3459
diff --git a/crates/utopia-server/src/api/admin_routes.rs b/crates/utopia-server/src/api/admin_routes.rs
index 0c123401..ebbf2843 100644
--- a/crates/utopia-server/src/api/admin_routes.rs
+++ b/crates/utopia-server/src/api/admin_routes.rs
@@ -198,3 +198,35 @@ pub async fn reactivate_user(
.await;
Ok(Json(serde_json::json!({ "ok": true })))
}
+
+#[derive(Deserialize)]
+pub struct SetSystemAdminReq {
+ pub is_admin: bool,
+}
+
+/// 授予或收回系统管理员。首个注册的人之外,这是唯一能拿到它的路(#1233)。
+pub async fn set_system_admin(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(target): Path<Uuid>,
+ Json(req): Json<SetSystemAdminReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ utopia_store::accounts::set_system_admin(&state.pool, target, user.id, req.is_admin).await?;
+ let action = if req.is_admin {
+ "user.admin_granted"
+ } else {
+ "user.admin_revoked"
+ };
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ None,
+ user.id,
+ action,
+ "user",
+ Some(target),
+ serde_json::json!({}),
+ )
+ .await;
+ Ok(Json(serde_json::json!({ "ok": true })))
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index a0211913..9955b2e7 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -196,7 +196,8 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
.route(
"/admin/users/{id}",
axum::routing::delete(admin_routes::deactivate_user)
- .post(admin_routes::reactivate_user),
+ .post(admin_routes::reactivate_user)
+ .put(admin_routes::set_system_admin),
)
// 管理员看得见谁绑了哪个 subject,也能解绑;**不能替人绑定**(0056)
.route("/admin/oidc/identities", get(oidc_routes::identities))
@@ -651,6 +652,9 @@ async fn jobs_noop(
#[cfg(test)]
mod rule_metadata_tests;
+#[cfg(test)]
+mod system_admin_tests;
+
#[cfg(test)]
mod oidc_exchange_tests;
diff --git a/crates/utopia-server/src/api/system_admin_tests.rs b/crates/utopia-server/src/api/system_admin_tests.rs
new file mode 100644
index 00000000..c273f95c
--- /dev/null
+++ b/crates/utopia-server/src/api/system_admin_tests.rs
@@ -0,0 +1,83 @@
+//! 授予系统管理员走的那条接口:只有系统管理员能调,调了留审计。
+use crate::state::AppState;
+use axum::{
+ body::Body,
+ http::{Request, StatusCode},
+};
+use serde_json::json;
+use std::sync::Arc;
+use tower::ServiceExt;
+use uuid::Uuid;
+
+#[tokio::test]
+async fn only_a_system_admin_grants_the_flag_and_the_grant_is_audited() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = sqlx::PgPool::connect(&url).await?;
+ utopia_store::db::migrate(&pool).await?;
+ let (org, admin, member) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let dir = tempfile::tempdir()?;
+ let cfg = utopia_core::config::AppConfig {
+ data_dir: dir.path().to_string_lossy().into_owned(),
+ ..Default::default()
+ };
+ let state = AppState::new(
+ pool.clone(),
+ &cfg,
+ Arc::new(utopia_search::SearchIndex::open(
+ &dir.path().join("search"),
+ )?),
+ "test-only".into(),
+ );
+ let result = async {
+ sqlx::raw_sql(&format!(
+ "INSERT INTO organizations(id,name) VALUES('{org}','sysadmin-route-test');
+ INSERT INTO users(id,org_id,email,password_hash,display_name,is_admin) VALUES
+ ('{admin}','{org}','{admin}@example.test','unused','Admin',TRUE),
+ ('{member}','{org}','{member}@example.test','unused','Member',FALSE);"
+ ))
+ .execute(&pool)
+ .await?;
+ let grant = |caller: Uuid| {
+ let state = state.clone();
+ async move {
+ let token = crate::auth::issue_token(&state, caller)?;
+ let request = Request::builder()
+ .method("PUT")
+ .uri(format!("/api/v1/admin/users/{member}"))
+ .header("authorization", format!("Bearer {token}"))
+ .header("content-type", "application/json")
+ .body(Body::from(json!({ "is_admin": true }).to_string()))?;
+ let response = super::router(state, &Default::default())
+ .oneshot(request)
+ .await?;
+ anyhow::Ok(response.status())
+ }
+ };
+
+ anyhow::ensure!(grant(member).await? == StatusCode::FORBIDDEN);
+ anyhow::ensure!(grant(admin).await? == StatusCode::OK);
+
+ let flag: bool = sqlx::query_scalar("SELECT is_admin FROM users WHERE id = $1")
+ .bind(member)
+ .fetch_one(&pool)
+ .await?;
+ let audited: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM audit_events
+ WHERE actor_id = $1 AND action = 'user.admin_granted' AND target_id = $2",
+ )
+ .bind(admin)
+ .bind(member)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(flag && audited == 1, "flag={flag} audited={audited}");
+ anyhow::Ok(())
+ }
+ .await;
+ sqlx::query("DELETE FROM organizations WHERE id=$1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ result
+}
diff --git a/crates/utopia-store/src/accounts.rs b/crates/utopia-store/src/accounts.rs
index 308c9c4e..0e8a5f65 100644
--- a/crates/utopia-store/src/accounts.rs
+++ b/crates/utopia-store/src/accounts.rs
@@ -332,3 +332,25 @@ pub async fn reactivate_user(pool: &PgPool, target: Uuid) -> AppResult<()> {
}
Ok(())
}
+
+/// 授予或收回系统管理员(`users.is_admin`)。
+pub async fn set_system_admin(
+ pool: &PgPool,
+ target: Uuid,
+ actor: Uuid,
+ value: bool,
+) -> AppResult<()> {
+ if target == actor && !value {
+ return Err(AppError::Validation("不能收回自己的系统管理员".into()));
+ }
+ let res =
+ sqlx::query("UPDATE users SET is_admin = $2 WHERE id = $1 AND deactivated_at IS NULL")
+ .bind(target)
+ .bind(value)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
diff --git a/crates/utopia-store/tests/store/an_admin_grants_system_admin.rs b/crates/utopia-store/tests/store/an_admin_grants_system_admin.rs
new file mode 100644
index 00000000..c1b73364
--- /dev/null
+++ b/crates/utopia-store/tests/store/an_admin_grants_system_admin.rs
@@ -0,0 +1,107 @@
+//! 授予、收回系统管理员——打在真库上。
+
+use sqlx::PgPool;
+use uuid::Uuid;
+
+async fn org_with_admin_and_member(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {
+ let (org, admin, member) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'sysadmin-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ for (id, mail, is_admin) in [(admin, "admin", true), (member, "member", false)] {
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, display_name, password_hash, is_admin)
+ VALUES ($1, $2, $3, 'u', 'x', $4)",
+ )
+ .bind(id)
+ .bind(org)
+ .bind(format!("{}-{mail}@sysadmin.test", id.simple()))
+ .bind(is_admin)
+ .execute(pool)
+ .await?;
+ }
+ Ok((org, admin, member))
+}
+
+async fn is_admin(pool: &PgPool, id: Uuid) -> anyhow::Result<bool> {
+ Ok(
+ sqlx::query_scalar("SELECT is_admin FROM users WHERE id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?,
+ )
+}
+
+#[tokio::test]
+async fn granting_a_member_makes_them_admin() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let (org, admin, member) = org_with_admin_and_member(&pool).await?;
+
+ let run = async {
+ utopia_store::accounts::set_system_admin(&pool, member, admin, true).await?;
+ assert!(is_admin(&pool, member).await?);
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+#[tokio::test]
+async fn revoking_your_own_flag_is_refused_and_you_stay_admin() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let (org, admin, member) = org_with_admin_and_member(&pool).await?;
+
+ let run = async {
+ utopia_store::accounts::set_system_admin(&pool, member, admin, true).await?;
+ let refused = utopia_store::accounts::set_system_admin(&pool, admin, admin, false).await;
+ assert!(matches!(refused, Err(utopia_core::AppError::Validation(_))));
+ assert!(is_admin(&pool, admin).await?);
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+#[tokio::test]
+async fn granting_a_deactivated_or_unknown_user_is_not_found() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let (org, admin, member) = org_with_admin_and_member(&pool).await?;
+
+ let run = async {
+ utopia_store::accounts::deactivate_user(&pool, member, admin).await?;
+ for target in [member, Uuid::now_v7()] {
+ let missing =
+ utopia_store::accounts::set_system_admin(&pool, target, admin, true).await;
+ assert!(matches!(missing, Err(utopia_core::AppError::NotFound)));
+ }
+ assert!(!is_admin(&pool, member).await?);
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs
index 138065ca..551594d2 100644
--- a/crates/utopia-store/tests/store/main.rs
+++ b/crates/utopia-store/tests/store/main.rs
@@ -101,6 +101,7 @@ mod a_trimmed_description_is_not_stale;
mod a_viewer_never_sees_a_credential;
mod a_wrong_time_can_be_corrected;
mod adopting_an_iri_adopts_the_shape;
+mod an_admin_grants_system_admin;
mod an_agent_can_record;
mod an_automatic_merge_is_gated_by_what_it_can_undo;
mod an_axiom_that_moved_closes_its_findings;
diff --git a/web/src/api.ts b/web/src/api.ts
index a821a443..fcc73836 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1840,6 +1840,12 @@ export const api = {
request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
method: "DELETE",
}),
+ /** 授予或收回系统管理员(#1233) */
+ adminSetSystemAdmin: (userId: string, isAdmin: boolean) =>
+ request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
+ method: "PUT",
+ body: JSON.stringify({ is_admin: isAdmin }),
+ }),
adminDataSources: () =>
request<{ data_sources: DataSourceView[] }>("/api/v1/admin/data-sources"),
adminCreateDataSource: (body: { name: string; conn_string: string }) =>
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 07b4fe95..8d1b8509 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -2462,6 +2462,7 @@ export const en = {
members: {
title: "Deployment users",
systemAdmin: "System admin",
+ systemAdminHint: "Opens Administration: deployment settings, accounts, data sources. You can't remove your own.",
remove: "Remove",
deactivate: "Deactivate",
cancel: "Cancel",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 47232a6f..960239d1 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -2157,6 +2157,7 @@ export const zh: Strings = {
members: {
title: "部署用户",
systemAdmin: "系统管理员",
+ systemAdminHint: "可进入系统管理:部署配置、账号、数据源。不能收回自己的。",
remove: "移除",
deactivate: "停用账号",
cancel: "取消",
diff --git a/web/src/pages/Members.tsx b/web/src/pages/Members.tsx
index cad8fe84..6edd7d05 100644
--- a/web/src/pages/Members.tsx
+++ b/web/src/pages/Members.tsx
@@ -3,8 +3,10 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Pencil, Plus, Search } from "lucide-react";
import { api } from "../api";
import { S } from "../i18n";
+import { memberChanges } from "./memberChanges";
import {
Button,
+ Checkbox,
Chip,
DangerConfirm,
Dialog,
@@ -48,21 +50,27 @@ type Person = {
function MemberDialog({
member,
canDeactivate,
+ canSetAdmin,
+ isSelf,
busy,
- onSaveRole,
+ onSave,
onDeactivate,
onRemove,
onClose,
}: {
member: Person;
canDeactivate: boolean;
+ canSetAdmin: boolean;
+ isSelf: boolean;
busy: boolean;
- onSaveRole: (role: string) => void;
+ onSave: (changes: ReturnType<typeof memberChanges>) => void;
onDeactivate: () => void;
onRemove: () => void;
onClose: () => void;
}) {
const [role, setRole] = useState(member.role);
+ const [isAdmin, setIsAdmin] = useState(member.is_admin);
+ const changes = memberChanges(member, { role, is_admin: isAdmin });
return (
<FormDialog
title={member.display_name}
@@ -71,9 +79,9 @@ function MemberDialog({
closeLabel={S.members.close}
saveLabel={S.members.save}
cancelLabel={S.members.cancel}
- canSave={role !== member.role}
+ canSave={Object.keys(changes).length > 0}
busy={busy}
- onSave={() => onSaveRole(role)}
+ onSave={() => onSave(changes)}
onCancel={onClose}
danger={[
...(canDeactivate
@@ -96,6 +104,15 @@ function MemberDialog({
options={ROLE_OPTIONS}
/>
</Field>
+ {canSetAdmin && (
+ <Checkbox
+ label={S.members.systemAdmin}
+ hint={S.members.systemAdminHint}
+ checked={isAdmin}
+ disabled={isSelf && member.is_admin}
+ onChange={setIsAdmin}
+ />
+ )}
</FormDialog>
);
}
@@ -142,6 +159,12 @@ export function Members({ workspaceId }: { workspaceId: string }) {
onSuccess: refresh,
onError,
});
+ const setSystemAdmin = useMutation({
+ mutationFn: ({ userId, isAdmin }: { userId: string; isAdmin: boolean }) =>
+ api.adminSetSystemAdmin(userId, isAdmin),
+ onSuccess: refresh,
+ onError,
+ });
const remove = useMutation({
mutationFn: (userId: string) => api.removeMember(workspaceId, userId),
onSuccess: refresh,
@@ -400,10 +423,13 @@ export function Members({ workspaceId }: { workspaceId: string }) {
<MemberDialog
member={editing}
canDeactivate={!!me.data?.is_admin && me.data.id !== editing.user_id}
- busy={setRole_.isPending || remove.isPending}
- onSaveRole={(role) => {
- if (role !== editing.role)
- setRole_.mutate({ userId: editing.user_id, role });
+ canSetAdmin={!!me.data?.is_admin}
+ isSelf={me.data?.id === editing.user_id}
+ busy={setRole_.isPending || setSystemAdmin.isPending || remove.isPending}
+ onSave={({ role, is_admin }) => {
+ if (role !== undefined) setRole_.mutate({ userId: editing.user_id, role });
+ if (is_admin !== undefined)
+ setSystemAdmin.mutate({ userId: editing.user_id, isAdmin: is_admin });
setEditing(null);
}}
onDeactivate={() => {
diff --git a/web/src/pages/memberChanges.test.ts b/web/src/pages/memberChanges.test.ts
new file mode 100644
index 00000000..0f629089
--- /dev/null
+++ b/web/src/pages/memberChanges.test.ts
@@ -0,0 +1,16 @@
+import { expect, it } from "vitest";
+import { memberChanges } from "./memberChanges";
+
+const member = { role: "editor", is_admin: false };
+
+it("returns nothing when neither role nor system admin changed", () => {
+ expect(memberChanges(member, { role: "editor", is_admin: false })).toEqual({});
+});
+
+it("returns is_admin true when only system admin was switched on", () => {
+ expect(memberChanges(member, { role: "editor", is_admin: true })).toEqual({ is_admin: true });
+});
+
+it("returns role and is_admin when both changed", () => {
+ expect(memberChanges(member, { role: "owner", is_admin: true })).toEqual({ role: "owner", is_admin: true });
+});
diff --git a/web/src/pages/memberChanges.ts b/web/src/pages/memberChanges.ts
new file mode 100644
index 00000000..c7acf7dd
--- /dev/null
+++ b/web/src/pages/memberChanges.ts
@@ -0,0 +1,9 @@
+type MemberAccess = { role: string; is_admin: boolean };
+
+/** 弹窗保存时真正要发出去的改动:没变的字段不发 */
+export function memberChanges(member: MemberAccess, draft: MemberAccess): Partial<MemberAccess> {
+ return {
+ ...(draft.role !== member.role && { role: draft.role }),
+ ...(draft.is_admin !== member.is_admin && { is_admin: draft.is_admin }),
+ };
+}