World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Add single sign-on (OIDC) (#684)
naf r55448d341b1c
diff --git a/.env.example b/.env.exampleindex 61ee3c22..e675efc8 100644--- a/.env.example+++ b/.env.example@@ -16,6 +16,14 @@ UTOPIA_DATA_DIR=data# UTOPIA_COOKIE_SECURE=true# 开放注册;false 时仅首个用户可注册,其余由管理员开放UTOPIA_OPEN_REGISTRATION=true+# 单点登录(可选)。ISSUER、CLIENT_ID、REDIRECT_URI 三项都填才生效(CLIENT_SECRET 看身份+# 提供方要不要),留空即关闭——登录页不会露出那个按钮。账号由本人在账户页绑定自己的+# 身份(先用密码登录再走一遍 SSO),这几项只决定拿哪个身份提供方去核验令牌。+# 本地开发要用 http://localhost 上的身份提供方时,设 UTOPIA_OIDC_ALLOW_LOOPBACK_HTTP=1。+# UTOPIA_OIDC_ISSUER=https://id.example.com+# UTOPIA_OIDC_CLIENT_ID=+# UTOPIA_OIDC_CLIENT_SECRET=+# UTOPIA_OIDC_REDIRECT_URI=https://your-deployment/api/v1/auth/oidc/callback# 数据库连接池上限。缺省 32,与 worker 并发的缺省对齐。# 池子小于并发时症状是请求变慢、而不是任何一处说"池子不够"——调高 worker# 并发时一并考虑这里,也别超过 Postgres 自己的 max_connections(默认 100)。diff --git a/Cargo.lock b/Cargo.lockindex 161431d1..c3156a85 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3732,6 +3732,7 @@ dependencies = ["rustls-platform-verifier","serde","serde_json",+ "serde_urlencoded","sync_wrapper","tokio","tokio-rustls",diff --git a/Cargo.toml b/Cargo.tomlindex 5afaa522..5afe997b 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -70,7 +70,7 @@ pgvector = { version = "0.4", features = ["sqlx"] }# 21 字节而信息量只有 4 字节,一次响应 1.33 MB。实测同一条链路上不压缩 62 秒、# gzip 21 秒(429 KB)——服务端算完只用 1 秒,其余全在传。# `default-features = false` 把它一并关掉了,这里补回来。-reqwest = { version = "0.13", default-features = false, features = ["json", "stream", "http2", "rustls", "webpki-roots", "charset", "system-proxy", "gzip"] }+reqwest = { version = "0.13", default-features = false, features = ["json", "form", "stream", "http2", "rustls", "webpki-roots", "charset", "system-proxy", "gzip"] }feed-rs = "2"cron = "0.12"diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 3238b3fb..44899a3e 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -13,6 +13,7 @@ mod kbs;mod mapping_routes;mod mcp;mod members_routes;+mod oidc_routes;pub(crate) mod ontology_routes;mod review_routes;mod rig_model;@@ -110,6 +111,16 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {get(auth_routes::me).patch(auth_routes::update_me),).route("/auth/password", post(auth_routes::change_password))+ // 单点登录:窄范围 OIDC 授权码流程(0056)。未配置时 status 报 false,+ // 界面据此决定要不要露出登录页那个按钮+ .route("/auth/oidc/status", get(oidc_routes::status))+ .route("/auth/oidc/start", get(oidc_routes::start))+ .route("/auth/oidc/callback", get(oidc_routes::callback))+ // 我自己的绑定:看、解绑。绑定走 `/auth/oidc/start?link=1`,由本人完成+ .route(+ "/auth/oidc/me",+ get(oidc_routes::me).delete(oidc_routes::unlink_me),+ ).route("/workspaces",get(workspaces::list).post(workspaces::create),@@ -171,6 +182,12 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {axum::routing::delete(admin_routes::deactivate_user).post(admin_routes::reactivate_user),)+ // 管理员看得见谁绑了哪个 subject,也能解绑;**不能替人绑定**(0056)+ .route("/admin/oidc/identities", get(oidc_routes::identities))+ .route(+ "/admin/oidc/identities/{user_id}",+ axum::routing::delete(oidc_routes::unbind),+ ).route("/admin/data-sources",get(datasource_routes::list).post(datasource_routes::create),diff --git a/crates/utopia-server/src/api/oidc_routes.rs b/crates/utopia-server/src/api/oidc_routes.rsnew file mode 100644index 00000000..af37cb7e--- /dev/null+++ b/crates/utopia-server/src/api/oidc_routes.rs@@ -0,0 +1,817 @@+//! 单点登录:窄范围的 OIDC 授权码流程(PKCE、一次性 state、nonce、+//! issuer/audience 与 RS256 校验)。+//!+//! **身份提供方的一个 subject 由账号本人绑定。** 人先用密码登录,再在账户页走一遍+//! SSO;回调核对「完成这次流程的就是发起绑定的那个已登录的人」才写 `oidc_identities`。+//! 从前是管理员把任意 subject 填给任意账号——那等于给了管理员一条冒充任何人+//! (包括别的管理员)登录的路:绑定不经本人、本人看不见、改密码也断不掉,之后的+//! 操作在台账上记成被冒充的人(0014:身份来自本人)。管理员现在只能看与解绑。+//!+//! 绝不按身份提供方的 email 这类可变声明自动关联,首次登录也绝不自动开账号。++use crate::{+ auth::{self, AuthUser},+ error::ApiResult,+ state::AppState,+};+use axum::{+ extract::{Path, Query, State},+ http::HeaderMap,+ response::Redirect,+ Json,+};+use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};+use jsonwebtoken::{decode, decode_header, jwk::JwkSet, Algorithm, DecodingKey, Validation};+use serde::Deserialize;+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::collections::HashMap;+use std::time::{Duration, Instant};+use utopia_core::AppError;+use uuid::Uuid;++const FLOW_COOKIE: &str = "utopia_oidc_state";+/// HTTPS 下用 `__Host-` 前缀:浏览器只接受 Secure、Path=/、不带 Domain 的这个名字,+/// 同站点的兄弟子域名或明文链路就种不进来。否则攻击者先种一个自己的 state,+/// 再把受害者带到自己的回调地址上,受害者就登进了攻击者的账号(登录 CSRF)+const FLOW_COOKIE_HOST: &str = "__Host-utopia_oidc_state";+const FLOW_TTL_SECS: u64 = 600;+/// 同时在途的登录流程上限。`start` 不需要登录,每一次都会落一行、问一次身份提供方;+/// 没有上限的话,一个脚本就能把表撑大、把身份提供方对这个部署的限流打满+const MAX_PENDING_FLOWS: i64 = 1000;+/// 发现文档、JWKS、令牌响应的体积上限。它们来自身份提供方,但一个出了问题的+/// 身份提供方不该能把服务器的内存吃掉+const DOC_LIMIT: usize = 256 * 1024;+const TOKEN_LIMIT: usize = 64 * 1024;+/// 发现文档与 JWKS 的缓存时长。轮换密钥时 `kid` 找不到会强制刷新一次+const CACHE_TTL: Duration = Duration::from_secs(600);++struct Config {+ issuer: String,+ client_id: String,+ secret: Option<String>,+ redirect: String,+ /// 本地开发:允许 issuer 与各端点走回环地址上的明文 HTTP。只认 localhost /+ /// 127.0.0.1 / ::1,公网地址照旧只能 HTTPS+ loopback_http: bool,+}++fn config() -> Result<Config, AppError> {+ let get = |key: &str| {+ std::env::var(key)+ .ok()+ .filter(|v| !v.trim().is_empty())+ .ok_or_else(|| AppError::Validation("SSO is not configured".into()))+ };+ let c = Config {+ issuer: get("UTOPIA_OIDC_ISSUER")?,+ client_id: get("UTOPIA_OIDC_CLIENT_ID")?,+ secret: std::env::var("UTOPIA_OIDC_CLIENT_SECRET")+ .ok()+ .filter(|s| !s.is_empty()),+ redirect: get("UTOPIA_OIDC_REDIRECT_URI")?,+ loopback_http: std::env::var("UTOPIA_OIDC_ALLOW_LOOPBACK_HTTP")+ .is_ok_and(|v| matches!(v.trim(), "1" | "true")),+ };+ secure_url(&c.issuer, c.loopback_http)?;+ secure_url(&c.redirect, true)?;+ Ok(c)+}++fn secure_url(s: &str, loopback: bool) -> Result<reqwest::Url, AppError> {+ let url = reqwest::Url::parse(s).map_err(|_| AppError::Validation("Invalid SSO URL".into()))?;+ if !url.username().is_empty()+ || url.password().is_some()+ || url.fragment().is_some()+ || !(url.scheme() == "https"+ || (loopback+ && url.scheme() == "http"+ && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))))+ {+ return Err(AppError::Validation(+ "SSO endpoints require HTTPS (localhost callback may use HTTP)".into(),+ ));+ }+ Ok(url)+}++/// 一次拒绝:`code` 回给界面(登录页 / 账户页按它措辞),`reason` 只进日志与台账+struct Refusal {+ code: &'static str,+ reason: String,+}++fn refuse(code: &'static str, reason: impl Into<String>) -> Refusal {+ Refusal {+ code,+ reason: reason.into(),+ }+}++impl From<sqlx::Error> for Refusal {+ fn from(e: sqlx::Error) -> Self {+ refuse("unavailable", format!("database: {e}"))+ }+}++fn client() -> Result<reqwest::Client, Refusal> {+ reqwest::Client::builder()+ .timeout(Duration::from_secs(15))+ .redirect(reqwest::redirect::Policy::none())+ .build()+ .map_err(|e| refuse("unavailable", format!("http client: {e}")))+}++/// 读一个限了体积的 JSON 响应。先看 Content-Length,再边读边数——+/// 不报长度的响应一样截得住+async fn read_json(mut resp: reqwest::Response, limit: usize) -> Result<Value, String> {+ if !resp.status().is_success() {+ return Err(format!("status {}", resp.status()));+ }+ if resp.content_length().is_some_and(|n| n > limit as u64) {+ return Err(format!("response larger than {limit} bytes"));+ }+ let mut body = Vec::new();+ while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {+ body.extend_from_slice(&chunk);+ if body.len() > limit {+ return Err(format!("response larger than {limit} bytes"));+ }+ }+ serde_json::from_slice(&body).map_err(|e| format!("not JSON: {e}"))+}++type Cache = tokio::sync::Mutex<HashMap<String, (Instant, Value)>>;++fn cache() -> &'static Cache {+ static CACHE: std::sync::OnceLock<Cache> = std::sync::OnceLock::new();+ CACHE.get_or_init(Default::default)+}++/// 发现文档与 JWKS 按地址缓存。`start` 不需要登录,不缓存的话每一次匿名请求+/// 都会让服务器去问一次身份提供方+async fn cached_json(url: &reqwest::Url, force: bool) -> Result<Value, Refusal> {+ let key = url.to_string();+ if !force {+ if let Some((at, v)) = cache().lock().await.get(&key) {+ if at.elapsed() < CACHE_TTL {+ return Ok(v.clone());+ }+ }+ }+ let resp = client()?+ .get(url.clone())+ .send()+ .await+ .map_err(|e| refuse("unavailable", format!("fetch {key}: {e}")))?;+ let v = read_json(resp, DOC_LIMIT)+ .await+ .map_err(|e| refuse("unavailable", format!("fetch {key}: {e}")))?;+ cache()+ .lock()+ .await+ .insert(key, (Instant::now(), v.clone()));+ Ok(v)+}++async fn metadata(c: &Config) -> Result<Value, Refusal> {+ let url = secure_url(+ &format!(+ "{}/.well-known/openid-configuration",+ c.issuer.trim_end_matches('/')+ ),+ c.loopback_http,+ )+ .map_err(|_| refuse("unavailable", "issuer URL"))?;+ let meta = cached_json(&url, false).await?;+ if meta["issuer"] != c.issuer {+ return Err(refuse(+ "unavailable",+ "discovery document names a different issuer",+ ));+ }+ Ok(meta)+}++fn endpoint(c: &Config, meta: &Value, key: &str) -> Result<reqwest::Url, Refusal> {+ let raw = meta[key]+ .as_str()+ .ok_or_else(|| refuse("unavailable", format!("discovery has no {key}")))?;+ secure_url(raw, c.loopback_http)+ .map_err(|_| refuse("unavailable", format!("{key} is not HTTPS")))+}++fn flow_cookie(value: String, secure: bool) -> Cookie<'static> {+ let (name, path) = if secure {+ (FLOW_COOKIE_HOST, "/")+ } else {+ (FLOW_COOKIE, "/api/v1/auth/oidc")+ };+ Cookie::build((name, value))+ .path(path)+ .http_only(true)+ .same_site(SameSite::Lax)+ .secure(secure)+ .max_age(+ Duration::from_secs(FLOW_TTL_SECS)+ .try_into()+ .expect("ten minutes fits cookie duration"),+ )+ .build()+}++/// 当前请求带着的已登录会话(cookie),停用的账号不算+async fn session_user(s: &AppState, jar: &CookieJar) -> Option<Uuid> {+ let token = jar.get(auth::COOKIE_NAME)?.value().to_string();+ let id = auth::decode_user_id(s, &token).ok()?;+ utopia_store::accounts::find_user_by_id(&s.pool, id)+ .await+ .ok()+ .flatten()+ .map(|u| u.id)+}++/// RFC 6749 §2.3.1:client id 与 secret 先按表单编码,再放进 Basic 头。+/// 不编码的话含 `:`、`%`、`+` 的 secret 在严格的身份提供方那里认证失败+fn form_encode(s: &str) -> String {+ url::form_urlencoded::byte_serialize(s.as_bytes()).collect()+}++pub async fn status() -> Json<Value> {+ Json(json!({"enabled": config().is_ok()}))+}++#[derive(Deserialize)]+pub struct StartQuery {+ #[serde(default)]+ link: Option<String>,+}++/// 浏览器导航过来的:出错一律带着代码跳回页面,不给人看一段 JSON+fn back_to(page: &str, code: &str) -> Redirect {+ Redirect::to(&format!("{page}?sso_error={code}"))+}++pub async fn start(+ State(s): State<AppState>,+ headers: HeaderMap,+ jar: CookieJar,+ Query(q): Query<StartQuery>,+) -> (CookieJar, Redirect) {+ let linking = q.link.as_deref().is_some_and(|v| matches!(v, "1" | "true"));+ let page = if linking { "/account" } else { "/login" };+ match begin(&s, &jar, linking).await {+ Ok((state, url)) => {+ let secure = auth::behind_tls(&headers, s.cookie_secure);+ (+ jar.add(flow_cookie(state, secure)),+ Redirect::to(url.as_str()),+ )+ }+ Err(r) => {+ tracing::warn!(code = r.code, reason = %r.reason, "单点登录没能开始");+ (jar, back_to(page, r.code))+ }+ }+}++async fn begin(+ s: &AppState,+ jar: &CookieJar,+ linking: bool,+) -> Result<(String, reqwest::Url), Refusal> {+ let c = config().map_err(|_| refuse("unavailable", "not configured"))?;+ // 绑定只替已登录的本人发起:流程上记下是谁,回调时再核对一次+ let link_user = if linking {+ Some(+ session_user(s, jar)+ .await+ .ok_or_else(|| refuse("session", "link started without a session"))?,+ )+ } else {+ None+ };+ sqlx::query("DELETE FROM oidc_flows WHERE expires_at < now()")+ .execute(&s.pool)+ .await?;+ let pending: i64 = sqlx::query_scalar("SELECT count(*) FROM oidc_flows")+ .fetch_one(&s.pool)+ .await?;+ if pending >= MAX_PENDING_FLOWS {+ return Err(refuse("busy", format!("{pending} sign-ins in progress")));+ }+ let meta = metadata(&c).await?;+ let mut url = endpoint(&c, &meta, "authorization_endpoint")?;+ let state = auth::generate_jwt_secret();+ let nonce = auth::generate_jwt_secret();+ let verifier = auth::generate_jwt_secret();+ let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));+ sqlx::query(+ "INSERT INTO oidc_flows (state, nonce, verifier, link_user_id, expires_at)+ VALUES ($1, $2, $3, $4, now() + make_interval(secs => $5))",+ )+ .bind(&state)+ .bind(&nonce)+ .bind(&verifier)+ .bind(link_user)+ .bind(FLOW_TTL_SECS as f64)+ .execute(&s.pool)+ .await?;+ url.query_pairs_mut().extend_pairs([+ ("response_type", "code"),+ ("scope", "openid profile email"),+ ("client_id", &c.client_id),+ ("redirect_uri", &c.redirect),+ ("state", &state),+ ("nonce", &nonce),+ ("code_challenge", &challenge),+ ("code_challenge_method", "S256"),+ ]);+ Ok((state, url))+}++#[derive(Deserialize)]+pub struct Callback {+ code: Option<String>,+ state: Option<String>,+ /// 人在身份提供方那边点了取消,或者它拒绝了这次请求+ error: Option<String>,+}++#[derive(Clone, Deserialize)]+struct Claims {+ sub: String,+ nonce: String,+ iat: i64,+ #[serde(default)]+ azp: Option<String>,+ aud: Value,+}++/// 按 `kid` 找钥匙;令牌不带 `kid` 时,只有 JWKS 里恰好一把 RSA 钥匙才用它+fn pick_key<'a>(keys: &'a JwkSet, kid: Option<&str>) -> Option<&'a jsonwebtoken::jwk::Jwk> {+ match kid {+ Some(kid) => keys.find(kid),+ None => {+ let mut rsa = keys+ .keys+ .iter()+ .filter(|k| matches!(k.algorithm, jsonwebtoken::jwk::AlgorithmParameters::RSA(_)));+ match (rsa.next(), rsa.next()) {+ (Some(only), None) => Some(only),+ _ => None,+ }+ }+ }+}++fn verify_token(+ c: &Config,+ id_token: &str,+ keys: &JwkSet,+ nonce: &str,+) -> Result<Claims, AppError> {+ let header = decode_header(id_token).map_err(|_| AppError::Unauthorized)?;+ if header.alg != Algorithm::RS256 {+ return Err(AppError::Unauthorized);+ }+ let key = pick_key(keys, header.kid.as_deref()).ok_or(AppError::Unauthorized)?;+ let mut validation = Validation::new(Algorithm::RS256);+ validation.validate_nbf = true;+ validation.set_issuer(&[&c.issuer]);+ validation.set_audience(&[&c.client_id]);+ validation.set_required_spec_claims(&["exp", "iss", "aud", "sub", "iat"]);+ let claims = decode::<Claims>(+ id_token,+ &DecodingKey::from_jwk(key).map_err(|_| AppError::Unauthorized)?,+ &validation,+ )+ .map_err(|_| AppError::Unauthorized)?+ .claims;+ if claims.nonce != nonce+ || claims.sub.is_empty()+ || claims.iat > chrono::Utc::now().timestamp() + 60+ || claims.azp.as_ref().is_some_and(|a| a != &c.client_id)+ || (claims.aud.as_array().is_some_and(|a| a.len() > 1)+ && claims.azp.as_deref() != Some(c.client_id.as_str()))+ {+ return Err(AppError::Unauthorized);+ }+ Ok(claims)+}++/// 回调办成的是哪一件事+enum Done {+ SignedIn(Uuid),+ Linked,+}++pub async fn callback(+ State(s): State<AppState>,+ headers: HeaderMap,+ jar: CookieJar,+ Query(q): Query<Callback>,+) -> (CookieJar, Redirect) {+ let secure = auth::behind_tls(&headers, s.cookie_secure);+ let mut linking = false;+ // 先读后删:CookieJar 删掉的 cookie 再 `get` 就取不到了+ let outcome = finish(&s, &jar, q, &mut linking).await;+ let jar = jar+ .remove(flow_cookie(String::new(), true))+ .remove(flow_cookie(String::new(), false));+ match outcome {+ Ok(Done::SignedIn(user_id)) => match auth::issue_token(&s, user_id) {+ Ok(token) => (jar.add(auth::auth_cookie(token, secure)), Redirect::to("/")),+ Err(e) => {+ tracing::warn!(error = %e, "单点登录签发会话失败");+ (jar, back_to("/login", "unavailable"))+ }+ },+ Ok(Done::Linked) => (jar, Redirect::to("/account?sso=linked")),+ Err(r) => {+ tracing::warn!(code = r.code, reason = %r.reason, "单点登录被拒");+ // 失败也进台账,与密码登录的 `auth.login_failed` 同一个口径+ let _ = utopia_store::audit::record_opt(+ &s.pool,+ None,+ None,+ if linking {+ "auth.oidc_link_failed"+ } else {+ "auth.oidc_login_failed"+ },+ "user",+ None,+ json!({"reason": r.code, "detail": r.reason}),+ )+ .await;+ (+ jar,+ back_to(if linking { "/account" } else { "/login" }, r.code),+ )+ }+ }+}++async fn finish(+ s: &AppState,+ jar: &CookieJar,+ q: Callback,+ linking: &mut bool,+) -> Result<Done, Refusal> {+ if let Some(e) = q.error {+ return Err(refuse("cancelled", format!("provider returned {e}")));+ }+ let c = config().map_err(|_| refuse("unavailable", "not configured"))?;+ let (code, state) = match (q.code, q.state) {+ (Some(code), Some(state)) => (code, state),+ _ => return Err(refuse("invalid", "callback without code or state")),+ };+ let cookie = jar+ .get(FLOW_COOKIE_HOST)+ .or_else(|| jar.get(FLOW_COOKIE))+ .ok_or_else(|| refuse("session", "no state cookie in this browser"))?;+ use subtle::ConstantTimeEq;+ if !bool::from(cookie.value().as_bytes().ct_eq(state.as_bytes())) {+ return Err(refuse("session", "state does not match this browser"));+ }+ let flow: Option<(String, String, Option<Uuid>)> = sqlx::query_as(+ "DELETE FROM oidc_flows WHERE state = $1 AND expires_at > now()+ RETURNING nonce, verifier, link_user_id",+ )+ .bind(&state)+ .fetch_optional(&s.pool)+ .await?;+ let (nonce, verifier, link_user) =+ flow.ok_or_else(|| refuse("expired", "unknown or expired state"))?;+ *linking = link_user.is_some();++ let meta = metadata(&c).await?;+ let mut req = client()?+ .post(endpoint(&c, &meta, "token_endpoint")?)+ .form(&[+ ("grant_type", "authorization_code"),+ ("code", code.as_str()),+ ("redirect_uri", c.redirect.as_str()),+ ("client_id", c.client_id.as_str()),+ ("code_verifier", verifier.as_str()),+ ]);+ if let Some(secret) = &c.secret {+ req = req.basic_auth(form_encode(&c.client_id), Some(form_encode(secret)));+ }+ let resp = req+ .send()+ .await+ .map_err(|e| refuse("unavailable", format!("token endpoint: {e}")))?;+ let tokens = read_json(resp, TOKEN_LIMIT)+ .await+ .map_err(|e| refuse("denied", format!("token endpoint: {e}")))?;+ let id_token = tokens["id_token"]+ .as_str()+ .ok_or_else(|| refuse("denied", "token response has no id_token"))?;++ let jwks_url = endpoint(&c, &meta, "jwks_uri")?;+ let parse = |v: Value| {+ serde_json::from_value::<JwkSet>(v).map_err(|e| refuse("unavailable", format!("jwks: {e}")))+ };+ let mut keys = parse(cached_json(&jwks_url, false).await?)?;+ // 身份提供方轮换了密钥:缓存里没有这个 kid 就强制刷新一次,再不认就是真不认+ let kid = decode_header(id_token).ok().and_then(|h| h.kid);+ if pick_key(&keys, kid.as_deref()).is_none() {+ keys = parse(cached_json(&jwks_url, true).await?)?;+ }+ let claims = verify_token(&c, id_token, &keys, &nonce)+ .map_err(|_| refuse("denied", "id_token failed verification"))?;++ match link_user {+ Some(user_id) => {+ // 完成绑定的必须还是发起绑定的那个人:流程是在他登录着的时候开始的,+ // 回调时同一个浏览器里得还是他的会话+ if session_user(s, jar).await != Some(user_id) {+ return Err(refuse(+ "session",+ "link finished outside the starting session",+ ));+ }+ link(s, &c, user_id, &claims.sub).await?;+ Ok(Done::Linked)+ }+ None => {+ let user_id: Option<Uuid> = sqlx::query_scalar(+ "SELECT i.user_id FROM oidc_identities i JOIN users u ON u.id = i.user_id+ WHERE i.issuer = $1 AND i.subject = $2 AND u.deactivated_at IS NULL",+ )+ .bind(&c.issuer)+ .bind(&claims.sub)+ .fetch_optional(&s.pool)+ .await?;+ let user_id = user_id.ok_or_else(|| {+ refuse("unlinked", format!("subject {} is not linked", claims.sub))+ })?;+ let _ = utopia_store::audit::record(+ &s.pool,+ None,+ user_id,+ "auth.oidc_login",+ "user",+ Some(user_id),+ json!({"issuer": c.issuer}),+ )+ .await;+ Ok(Done::SignedIn(user_id))+ }+ }+}++async fn link(s: &AppState, c: &Config, user_id: Uuid, subject: &str) -> Result<(), Refusal> {+ let holder: Option<Uuid> = sqlx::query_scalar(+ "SELECT user_id FROM oidc_identities WHERE issuer = $1 AND subject = $2",+ )+ .bind(&c.issuer)+ .bind(subject)+ .fetch_optional(&s.pool)+ .await?;+ match holder {+ Some(h) if h == user_id => return Ok(()),+ Some(_) => return Err(refuse("taken", "subject already linked to another account")),+ None => {}+ }+ let inserted =+ sqlx::query("INSERT INTO oidc_identities (issuer, subject, user_id) VALUES ($1, $2, $3)")+ .bind(&c.issuer)+ .bind(subject)+ .bind(user_id)+ .execute(&s.pool)+ .await;+ match inserted {+ Ok(_) => {}+ // 两个约束各对应一种撞车:subject 被别人抢先绑了,或者这个账号已经有一个+ Err(sqlx::Error::Database(db)) if db.is_unique_violation() => {+ let code = if db.constraint().is_some_and(|n| n.contains("user")) {+ "already_linked"+ } else {+ "taken"+ };+ return Err(refuse(code, db.message().to_string()));+ }+ Err(e) => return Err(e.into()),+ }+ let _ = utopia_store::audit::record(+ &s.pool,+ None,+ user_id,+ "auth.oidc_link",+ "user",+ Some(user_id),+ json!({"issuer": c.issuer, "subject": subject}),+ )+ .await;+ Ok(())+}++/// 我自己的绑定:账户页用+pub async fn me(State(s): State<AppState>, AuthUser(u): AuthUser) -> ApiResult<Json<Value>> {+ let Ok(c) = config() else {+ return Ok(Json(json!({"enabled": false, "linked": false})));+ };+ let subject: Option<String> = sqlx::query_scalar(+ "SELECT subject FROM oidc_identities WHERE issuer = $1 AND user_id = $2",+ )+ .bind(&c.issuer)+ .bind(u.id)+ .fetch_optional(&s.pool)+ .await?;+ Ok(Json(+ json!({"enabled": true, "linked": subject.is_some(), "subject": subject}),+ ))+}++/// 解绑我自己的身份+pub async fn unlink_me(State(s): State<AppState>, AuthUser(u): AuthUser) -> ApiResult<Json<Value>> {+ let c = config()?;+ let done = sqlx::query("DELETE FROM oidc_identities WHERE issuer = $1 AND user_id = $2")+ .bind(&c.issuer)+ .bind(u.id)+ .execute(&s.pool)+ .await?;+ if done.rows_affected() == 0 {+ return Err(AppError::NotFound.into());+ }+ let _ = utopia_store::audit::record(+ &s.pool,+ None,+ u.id,+ "auth.oidc_unlink",+ "user",+ Some(u.id),+ json!({"issuer": c.issuer, "by": "self"}),+ )+ .await;+ Ok(Json(json!({"ok": true})))+}++pub async fn identities(+ State(s): State<AppState>,+ AuthUser(u): AuthUser,+) -> ApiResult<Json<Value>> {+ if !u.is_admin {+ return Err(AppError::Forbidden.into());+ };+ let c = config()?;+ let rows: Vec<Value> = sqlx::query_scalar(+ "SELECT jsonb_build_object('user_id', i.user_id, 'subject', i.subject, 'email', u.email)+ FROM oidc_identities i JOIN users u ON u.id = i.user_id+ WHERE i.issuer = $1 AND u.org_id = $2 ORDER BY u.email",+ )+ .bind(&c.issuer)+ .bind(u.org_id)+ .fetch_all(&s.pool)+ .await?;+ Ok(Json(+ json!({"issuer": c.issuer, "client_id": c.client_id, "redirect_uri": c.redirect, "identities": rows}),+ ))+}++/// 管理员解绑。**只有解绑,没有替人绑定**(见模块说明)。解绑不会让已签发的会话+/// 失效——会话是无状态的 JWT,要立刻切断访问得停用账号+pub async fn unbind(+ State(s): State<AppState>,+ AuthUser(u): AuthUser,+ Path(id): Path<Uuid>,+) -> ApiResult<Json<Value>> {+ if !u.is_admin {+ return Err(AppError::Forbidden.into());+ };+ let c = config()?;+ let done = sqlx::query(+ "DELETE FROM oidc_identities WHERE issuer = $1 AND user_id = $2+ AND user_id IN (SELECT id FROM users WHERE org_id = $3)",+ )+ .bind(&c.issuer)+ .bind(id)+ .bind(u.org_id)+ .execute(&s.pool)+ .await?;+ if done.rows_affected() == 0 {+ return Err(AppError::NotFound.into());+ }+ let _ = utopia_store::audit::record(+ &s.pool,+ None,+ u.id,+ "auth.oidc_unlink",+ "user",+ Some(id),+ json!({"issuer": c.issuer, "by": "admin"}),+ )+ .await;+ Ok(Json(json!({"ok": true})))+}++#[cfg(test)]+mod tests {+ #[test]+ fn only_local_callbacks_can_use_http() {+ assert!(super::secure_url("http://localhost:1516/callback", true).is_ok());+ assert!(super::secure_url("http://[::1]:1516/callback", true).is_ok());+ assert!(super::secure_url("http://example.org/callback", true).is_err());+ assert!(super::secure_url("http://localhost:1516", false).is_err());+ assert!(super::secure_url("https://user:[email protected]", false).is_err());+ }++ #[test]+ fn a_client_secret_is_form_encoded_before_basic_auth() {+ assert_eq!(super::form_encode("abc"), "abc");+ assert_eq!(super::form_encode("a:b%c+d e"), "a%3Ab%25c%2Bd+e");+ }++ #[tokio::test]+ async fn a_response_over_its_limit_is_refused() {+ let big = axum::http::Response::new(vec![b' '; 2048]);+ assert!(super::read_json(reqwest::Response::from(big), 1024)+ .await+ .is_err());+ let ok = axum::http::Response::new(br#"{"a":1}"#.to_vec());+ assert_eq!(+ super::read_json(reqwest::Response::from(ok), 1024)+ .await+ .unwrap()["a"],+ 1+ );+ }++ fn config() -> super::Config {+ super::Config {+ issuer: "https://id.example.test".into(),+ client_id: "utopia-test".into(),+ secret: None,+ redirect: "https://utopia.example.test/api/v1/auth/oidc/callback".into(),+ loopback_http: false,+ }+ }++ // This key is generated solely for these tests and is never used by the app.+ #[test]+ fn verifies_signature_issuer_audience_nonce_and_expiry() {+ use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};+ use serde_json::json;+ let c = config();+ let key = EncodingKey::from_rsa_pem(include_bytes!(+ "../../tests/fixtures/oidc_test_only_key.pem"+ ))+ .unwrap();+ let keys: jsonwebtoken::jwk::JwkSet = serde_json::from_str(include_str!(+ "../../tests/fixtures/oidc_test_only_jwks.json"+ ))+ .unwrap();+ let now = chrono::Utc::now().timestamp();+ let valid = json!({"iss":c.issuer,"aud":c.client_id,"sub":"person-123","nonce":"expected","iat":now,"exp":now+300});+ let mut header = Header::new(Algorithm::RS256);+ header.kid = Some("fixture".into());+ let token = encode(&header, &valid, &key).unwrap();+ assert!(super::verify_token(&c, &token, &keys, "expected").is_ok());+ assert!(super::verify_token(&c, &token, &keys, "wrong").is_err());+ for (field, value) in [+ ("iss", json!("https://other.example.test")),+ ("aud", json!("other-client")),+ ("exp", json!(now - 3600)),+ ("iat", json!(now + 3600)),+ ("azp", json!("other-client")),+ ("sub", json!("")),+ ] {+ let mut invalid = valid.clone();+ invalid[field] = value;+ let token = encode(&header, &invalid, &key).unwrap();+ assert!(+ super::verify_token(&c, &token, &keys, "expected").is_err(),+ "accepted invalid {field}"+ );+ }+ let fake = encode(+ &Header::default(),+ &valid,+ &EncodingKey::from_secret(b"not-an-rsa-key"),+ )+ .unwrap();+ assert!(super::verify_token(&c, &fake, &keys, "expected").is_err());+ header.kid = Some("unknown-key".into());+ assert!(super::verify_token(+ &c,+ &encode(&header, &valid, &key).unwrap(),+ &keys,+ "expected"+ )+ .is_err());++ // 不带 kid:JWKS 里只有一把 RSA 钥匙时用它,多于一把就不猜+ header.kid = None;+ let no_kid = encode(&header, &valid, &key).unwrap();+ assert!(super::verify_token(&c, &no_kid, &keys, "expected").is_ok());+ let mut two = keys.clone();+ let mut second = two.keys[0].clone();+ second.common.key_id = Some("other".into());+ two.keys.push(second);+ assert!(super::verify_token(&c, &no_kid, &two, "expected").is_err());+ }+}diff --git a/crates/utopia-server/tests/fixtures/oidc_test_only_jwks.json b/crates/utopia-server/tests/fixtures/oidc_test_only_jwks.jsonnew file mode 100644index 00000000..4219d807--- /dev/null+++ b/crates/utopia-server/tests/fixtures/oidc_test_only_jwks.json@@ -0,0 +1,12 @@+{+ "keys": [+ {+ "kty": "RSA",+ "use": "sig",+ "alg": "RS256",+ "kid": "fixture",+ "n": "qoxI0V6hhXQtaJuw3SFFCEd2_1_YjUCc81JdqsZXhEfaYd9WWV8rpnW3ffpM_Up3rzscUDR19TjyxMTattLnIXYlhoUP5fs4pxKKDKc0x-Cx_0XTTLtucaCJs0Ph8sT4RE7cHfyrqHi6VzxyG4GqOPrNztw_hAcu-TKwErVbBFO6M2jYCc1FLMLCrvYfO4c05yiVxjwZ-PY4FchfC5qw9rF3LlmlEHspEINiiHBjfs5wbVfGUttG-9DF3ApKdJjSZ_Vn0K2HMBumUPGFgYBHBh8GhO1-FbYmR8-cTJj8nGXQm4R7fGg1QC7n2-Y-iFqYkjZbttdn38puBxyDdArPGw",+ "e": "AQAB"+ }+ ]+}\ No newline at end of filediff --git a/crates/utopia-server/tests/fixtures/oidc_test_only_key.pem b/crates/utopia-server/tests/fixtures/oidc_test_only_key.pemnew file mode 100644index 00000000..9d2addff--- /dev/null+++ b/crates/utopia-server/tests/fixtures/oidc_test_only_key.pem@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCqjEjRXqGFdC1o+m7DdIUUIR3b/X9iNQJzzUl2qxleER9ph31ZZXyumdbd9+kz9SnevOxxQNHX1OPLE+xNq20uchdiWGhQ/l+zinEooMpzTH4LH/RdNMu25xoImzQ+HyxPhETtwd/KuoeLpX+PHIbgao4+s3O3D+EBy75MrAStVsEU7ozaNgJzUUswsKu9h87hzTnKJXGPBn49jgV+yF8LmrD2sXcuWaUQeykQg2KIcGN+znBtV8ZS20b70MXcCkp0mNJn9WfQrYcwG6ZQ+8YWBgEcGHwaE7X4VtiZHz5xMmPycZdCbhHt8aDVALufb5j6IWpiSNlu212ffym4H+HIN0Cs8bAgMBAAECggEAOrr5foQoekUSOBJZWyUQWTQHAhVXBPmJsu8by2nnDGoU+BZ075qXz6axjBnJyHc2Nnp3r96DBODOmwmUJ7mh9aJP/gy4CVg/np/0l5gqUjfpO+QZqhk6x98Yo3sTCAuDHlTtybR4ZR9L+yZ8UshFVoMZwI0KIfC0/P+MfgQ2kJkVjV+mkw6VxIa4/jTTE3QVM9aLxKx4Kb9btPCKkHkpezA8xPM0TuV6BO28+I29JxHwmZc+dneiN7p0vi3PJgynqozgA3pDQrh8kPatu4cG6A2u5Owx0TN5dautYPdPhWyZ3Jes+u8lXiT5nVZqTfkkg8jCZW+mUp7q5C9xniwCHoLS2/QKBgQDg7qytD9t/EBXXmrWs+warEGnn+PkpqIvJEms27AmUipPU2Nt4Y2Srs/7UXR6kd7bK85ax708pgBKLlWYTI+p8g2stmN3gj7gBOF1vPswJAT5CCg7KNqn5cOQNVMvHm/v9LKoa45trQXAlWuJMfw+PAaaRj+HkdUlhVxqtKxzJbcTnwKBgQDCGqXZNfqq2+cw7ekKT0JsEIhx9VEwucY1+vHC1PujDezb7sucHb5X74PgvtrBR9oPz8z9Rd+Um0iA7p4f0aO0BXJJXFjCOx3sq+9gU25QOzCbrCkiqXTWLlxPav0DuO/vAxa8X24KZv8mfXy9utvgVbEq/o80I81XQV+K/MFHPlzBQKBgQCxctl69kWdah0xKHYmwepsJs8TCiU+si8afF3NKMiMmkJw8Lwq+MjkxG1HL+darK7iUWUTHs3+2XDH+aa7dda/3pwUGbKH9dz7vmXJ51jhT2Ob8zXLm+TNyoe/FKRm5uHXC4NvDxyvcsJ8VcStwI4/H5h23bD+ttXFZaQArEFH7n1QKBgQC6+zmypJIMvpt3UwFNU4bz6RdsbWc6ex1wUYVxTgsz/PXlIOgCQrnq5Y+VX/kmpSEfs+I0HgBTSb7QSqhOyac9UNR2trtuZas289hHK2RygNSiLcmVG2NfslSS9lO1HmqELA+PYnTtJdaDACWthKhHs0GvnBgEKXB6GiE67xCQoVshQKBgQDgfmbuILkbTg6d5Iyg+1wRUE4wmQ6Yl3iRkoGCH5/vsD9UElOt+MHBL9J2/yaQQ8QVsb5a/sf9fvYeLz6NX+4Xzljon6HzUG5uTWatPxJhL8qSWoIn2iLlN7DHX7h/4ovzO36SAsSwltYwxNT0hU+qdzJqcB6asAkyKeFTapPjrkqKw==+-----END PRIVATE KEY-----diff --git a/migrations/0056_an_identity_can_be_linked_to_a_single_sign_on_subject.sql b/migrations/0056_an_identity_can_be_linked_to_a_single_sign_on_subject.sqlnew file mode 100644index 00000000..dd15654f--- /dev/null+++ b/migrations/0056_an_identity_can_be_linked_to_a_single_sign_on_subject.sql@@ -0,0 +1,26 @@+-- 单点登录:一个身份提供方的 subject 显式绑定到一个账号(0056)。+--+-- 绑定由账号本人建立:先用密码登录,再走一遍 SSO,回调核对是同一个人。+-- 绝不按 email 这类可变声明自动关联——那等于让身份提供方的一个字段直接决定+-- 「这是哪个账号」;也不让管理员替别人绑,那是一条冒充任何人登录的路。+CREATE TABLE oidc_identities (+ issuer TEXT NOT NULL,+ subject TEXT NOT NULL,+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (issuer, subject),+ UNIQUE (issuer, user_id)+);++-- 一次登录尝试的临时状态:授权码换令牌之前,state/nonce/PKCE verifier 都得先落着。+-- 短命、一次性——回调一到就删(成功)或者过期扫走(半途弃单)。+CREATE TABLE oidc_flows (+ state TEXT PRIMARY KEY,+ nonce TEXT NOT NULL,+ verifier TEXT NOT NULL,+ -- 绑定流程:发起它的已登录账号。回调时这个浏览器里的会话必须还是他。空 = 登录流程+ link_user_id UUID REFERENCES users(id) ON DELETE CASCADE,+ expires_at TIMESTAMPTZ NOT NULL+);++CREATE INDEX oidc_flows_expiry_idx ON oidc_flows (expires_at);diff --git a/web/src/api.ts b/web/src/api.tsindex 9a83bb3c..498b96dc 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -277,6 +277,13 @@ export interface OrgUser {is_admin: boolean;}+/** 一个身份提供方 subject 绑定到的账号(0056) */+export interface OidcIdentity {+ user_id: string;+ subject: string;+ email: string;+}+/** 问数数据源(凭据不下发,只有 host:port/db 摘要)。 */export interface DataSourceView {id: string;@@ -2335,6 +2342,30 @@ export const api = {chat: { ok: boolean; reply?: string; error?: string };embed: { ok: boolean; dim?: number; error?: string };}>(`/api/v1/workspaces/${workspaceId}/settings/test`, { method: "POST" }),++ /** 是否配置了单点登录(0056)。四项环境变量缺一个都是 false——+ * 登录页据此决定要不要露出那个按钮 */+ oidcStatus: () => request<{ enabled: boolean }>("/api/v1/auth/oidc/status"),+ /** 谁的哪个身份提供方 subject 绑定到了这个部署的哪个账号(只读 + 解绑) */+ oidcIdentities: () =>+ request<{+ issuer: string;+ client_id: string;+ redirect_uri: string;+ identities: OidcIdentity[];+ }>("/api/v1/admin/oidc/identities"),+ /** 我自己的绑定。绑定本身走 `/api/v1/auth/oidc/start?link=1`,由本人在身份提供方那边完成 */+ oidcMe: () =>+ request<{ enabled: boolean; linked: boolean; subject?: string | null }>(+ "/api/v1/auth/oidc/me",+ ),+ oidcUnlinkMe: () =>+ request<{ ok: boolean }>("/api/v1/auth/oidc/me", { method: "DELETE" }),+ /** 管理员解绑。没有替人绑定的接口——那是一条冒充别人登录的路 */+ oidcUnlink: (userId: string) =>+ request<{ ok: boolean }>(`/api/v1/admin/oidc/identities/${userId}`, {+ method: "DELETE",+ }),};/** RAG 对话:SSE 流式。返回中止函数。 */diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex d7958bf1..4868dff0 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -110,6 +110,21 @@ export const en = {newPassword: "New password (min. 8 characters)",changePassword: "Update password",passwordChanged: "Password updated",+ sso: {+ title: "Single sign-on",+ hint:+ "Link your identity provider account to sign in with SSO. You'll be sent to the provider " ++ "to confirm it's you.",+ linkedAs: (subject: string) => `Linked as ${subject}`,+ notLinked: "Not linked.",+ link: "Link identity",+ unlink: "Unlink",+ unlinkTitle: "Unlink single sign-on?",+ unlinkHint:+ "You won't be able to sign in with SSO until you link again. Sessions already open stay signed in.",+ linked: "Identity linked. You can now sign in with SSO.",+ unlinked: "Identity unlinked.",+ },avatarHint: "Avatars are generated from your name for now.",language: "Language",theme: "Theme",@@ -301,6 +316,22 @@ export const en = {submitting: "One moment…",createAccount: "Create account",networkError: "Network error, please try again",+ orDivider: "or",+ ssoButton: "Continue with SSO",+ ssoErrors: {+ unlinked:+ "This identity isn't linked to an account. Sign in with your password and link it from your account page.",+ cancelled: "Single sign-on was cancelled.",+ denied: "The identity provider's answer couldn't be verified.",+ session: "The sign-in started in a different browser session. Try again.",+ expired: "The sign-in took too long. Try again.",+ busy: "Too many sign-ins are in progress. Try again in a moment.",+ unavailable: "Single sign-on is unavailable right now.",+ invalid: "The sign-in request was incomplete. Try again.",+ taken: "That identity is already linked to another account.",+ already_linked: "Your account already has a linked identity. Unlink it first.",+ } as Record<string, string>,+ ssoErrorOther: "Single sign-on failed. Try again.",// 惯用同意句式:By continuing, you agree to the <Terms> and acknowledge the <Privacy>.agreePrefix: "By continuing, you agree to the ",agreeAnd: " and acknowledge the ",@@ -961,6 +992,7 @@ export const en = {tabMembers: "Users",tabKbs: "Knowledge bases",tabDeployment: "Deployment",+ tabSso: "Single sign-on",cardAccounts: "Accounts",newUser: "Create user",initialPassword: "Initial password (min. 8 characters)",@@ -1051,6 +1083,28 @@ export const en = {? "Revoked.": `Revoked, and unmounted it from ${n} knowledge base(s).`,},+ sso: {+ title: "Single sign-on",+ hint:+ "Sign-in through an identity provider (OIDC), configured with environment variables (see " ++ ".env.example). People link their own identity from their account page; an administrator " ++ "can see and remove links but can't create one for someone else.",+ disabled:+ "Not configured on this deployment. Set UTOPIA_OIDC_ISSUER, UTOPIA_OIDC_CLIENT_ID and " ++ "UTOPIA_OIDC_REDIRECT_URI (and, if the provider needs one, UTOPIA_OIDC_CLIENT_SECRET) " ++ "and restart.",+ issuer: "Issuer",+ clientId: "Client ID",+ redirectUri: "Redirect URI",+ colUser: "User",+ colSubject: "Subject",+ empty: "Nobody has linked an identity yet.",+ unlink: "Unlink",+ unlinkTitle: (email: string) => `Unlink ${email}?`,+ unlinkHint:+ "They won't be able to sign in with SSO until they link again. Sessions already open " ++ "stay signed in; deactivate the account to cut access immediately.",+ },kbs: {hint:"Every knowledge base in this deployment. Open ones are readable by all members; " +diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex 588ad863..8fa8fd8e 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -99,6 +99,18 @@ export const zh: Strings = {newPassword: "新密码(至少 8 位)",changePassword: "更新密码",passwordChanged: "密码已更新",+ sso: {+ title: "单点登录",+ hint: "绑定你在身份提供方的账号,之后可以用单点登录。会跳到身份提供方那边确认是你本人。",+ linkedAs: (subject: string) => `已绑定:${subject}`,+ notLinked: "尚未绑定。",+ link: "绑定身份",+ unlink: "解绑",+ unlinkTitle: "解绑单点登录?",+ unlinkHint: "重新绑定之前,没法再用单点登录。已经打开的会话仍保持登录。",+ linked: "身份已绑定,可以用单点登录了。",+ unlinked: "身份已解绑。",+ },avatarHint: "头像目前由你的名字生成。",language: "语言",theme: "主题",@@ -269,6 +281,21 @@ export const zh: Strings = {submitting: "稍候…",createAccount: "创建账户",networkError: "网络异常,请重试",+ orDivider: "或",+ ssoButton: "使用单点登录",+ ssoErrors: {+ unlinked: "这个身份还没绑定任何账号。先用密码登录,再到账户页绑定。",+ cancelled: "单点登录已取消。",+ denied: "身份提供方的应答没能通过校验。",+ session: "这次登录是在另一个浏览器会话里开始的,请重试。",+ expired: "登录耗时太久,请重试。",+ busy: "同时进行的登录太多,请稍后再试。",+ unavailable: "单点登录暂时不可用。",+ invalid: "登录请求不完整,请重试。",+ taken: "这个身份已经绑定到另一个账号。",+ already_linked: "你的账号已经绑定了一个身份,请先解绑。",+ } as Record<string, string>,+ ssoErrorOther: "单点登录失败,请重试。",agreePrefix: "继续即表示你同意",agreeAnd: ",并已知悉",agreeSuffix: "。",@@ -860,6 +887,7 @@ export const zh: Strings = {tabMembers: "用户",tabKbs: "知识库",tabDeployment: "部署",+ tabSso: "单点登录",cardAccounts: "账号",newUser: "创建用户",initialPassword: "初始密码(至少 8 位)",@@ -939,6 +967,25 @@ export const zh: Strings = {grantRevoked: (n: number) =>n === 0 ? "已收回。" : `已收回,顺带卸掉了 ${n} 个知识库上的挂载。`,},+ sso: {+ title: "单点登录",+ hint:+ "通过身份提供方(OIDC)登录,用环境变量配置(见 .env.example)。每个人在自己的账户页" ++ "绑定自己的身份;管理员能看到、能解绑,但不能替别人绑定。",+ disabled:+ "这个部署还没配置。设置 UTOPIA_OIDC_ISSUER、UTOPIA_OIDC_CLIENT_ID、" ++ "UTOPIA_OIDC_REDIRECT_URI(身份提供方要求的话还有 UTOPIA_OIDC_CLIENT_SECRET)后重启。",+ issuer: "Issuer",+ clientId: "Client ID",+ redirectUri: "Redirect URI",+ colUser: "用户",+ colSubject: "Subject",+ empty: "还没有人绑定身份。",+ unlink: "解绑",+ unlinkTitle: (email: string) => `解绑 ${email}?`,+ unlinkHint:+ "重新绑定之前,这个人没法再用单点登录。已经打开的会话仍保持登录;要立刻切断访问请停用账号。",+ },kbs: {hint:"本部署中的全部知识库。公开的对所有成员可读;受限的仅限受邀者。" +diff --git a/web/src/pages/Account.tsx b/web/src/pages/Account.tsxindex 95da302d..70d1ee7b 100644--- a/web/src/pages/Account.tsx+++ b/web/src/pages/Account.tsx@@ -11,6 +11,7 @@ import {} from "../ui";import { toast } from "../toast";import { Avatar } from "./UserMenu";+import { SsoAccount } from "./Sso";export function Account() {const queryClient = useQueryClient();@@ -120,6 +121,8 @@ export function Account() {</div></div></div>++ <SsoAccount /></div></div>);diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsxindex 6ee9cc09..b8638225 100644--- a/web/src/pages/Login.tsx+++ b/web/src/pages/Login.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { Link, useNavigate } from "@tanstack/react-router";/* lucide 已移除品牌图标,GitHub mark 内联(官方 mark 路径,fill=currentColor) */@@ -36,6 +36,9 @@ export function Login() {const [displayName, setDisplayName] = useState("");const [leaving, setLeaving] = useState(false);const queryClient = useQueryClient();+ const sso = useQuery({ queryKey: ["oidc-status"], queryFn: api.oidcStatus });+ // 单点登录回调失败时带着代码跳回这里(`?sso_error=`),措辞按代码查+ const ssoError = new URLSearchParams(window.location.search).get("sso_error");const mutation = useMutation({mutationFn: async () => {@@ -92,6 +95,12 @@ export function Login() {}))}/>+ {ssoError && (+ <p role="alert" className="mb-3 text-small text-danger">+ {S.login.ssoErrors[ssoError] ?? S.login.ssoErrorOther}+ </p>+ )}+<formclassName="space-y-3"onSubmit={(e) => {@@ -137,6 +146,24 @@ export function Login() {: S.login.createAccount}</Button></form>++ {mode === "login" && sso.data?.enabled && (+ <>+ <div className="my-4 flex items-center gap-3 text-fine text-ink-2">+ <span className="h-px flex-1 bg-line" />+ {S.login.orDivider}+ <span className="h-px flex-1 bg-line" />+ </div>+ <Button variant="secondary" size="md" className="w-full"+ disabled={leaving}+ onClick={() => {+ window.location.href = "/api/v1/auth/oidc/start";+ }}+ >+ {S.login.ssoButton}+ </Button>+ </>+ )}</div>{/* 页脚:惯用同意句式内嵌条款/隐私链接 + GitHub 入口 */}diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsxindex 75ff5d5f..4a8f75b0 100644--- a/web/src/pages/Settings.tsx+++ b/web/src/pages/Settings.tsx@@ -29,8 +29,9 @@ import {PageHeader,chipLike,} from "../ui";import { Members } from "./Members";+import { SsoAdmin } from "./Sso";-/** 管理页的五节。**它们是左栏的第二层,不是正文顶上的一条 tab 带**——+/** 管理页的六节。**它们是左栏的第二层,不是正文顶上的一条 tab 带**——与账户栏那四项是同一种东西(去哪儿),只是矮一级;地址里是 `?tab=`,刷新、回退、分享链接都落回同一节。左栏(AccountShell)与这一页的标题读的是同一份,名字只有一处。**label 是函数**:界面语言在运行时可切,@@ -39,6 +40,7 @@ export const ADMIN_TABS = [{ key: "models", label: () => S.settings.tabModels },{ key: "members", label: () => S.settings.tabMembers },{ key: "datasources", label: () => S.settings.datasources.tab },+ { key: "sso", label: () => S.settings.tabSso },{ key: "deployment", label: () => S.settings.tabDeployment },] as const;@@ -906,6 +908,7 @@ export function Settings() {{tab === "members" && <Members workspaceId={workspace.id} />}{tab === "datasources" && <DataSourcesAdmin />}+ {tab === "sso" && <SsoAdmin />}{tab === "deployment" && <DeploymentAdmin />}{tab === "models" && (diff --git a/web/src/pages/Sso.tsx b/web/src/pages/Sso.tsxnew file mode 100644index 00000000..d0d6958d--- /dev/null+++ b/web/src/pages/Sso.tsx@@ -0,0 +1,222 @@+/* 单点登录(0056)。++ **绑定由本人完成**:账户页上「绑定身份」跳到身份提供方,回来时服务端核对还是那个+ 已登录的人才写绑定。管理页只列出谁绑了哪个 subject、能解绑——没有替别人绑定的入口,+ 那是一条冒充任何人登录的路(见 crates/utopia-server/src/api/oidc_routes.rs 的模块说明)。 */+import { useEffect, useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import { S } from "../i18n";+import { toast } from "../toast";+import {+ Button,+ DangerConfirm,+ LinkButton,+ Table,+ TBody,+ Td,+ Th,+ THead,+ Tr,+} from "../ui";++/** 三行信息展示,只读——issuer/client_id/redirect_uri 由环境变量定,这里不能改。+ * 两列网格而不是一句话拼接:三个值长短不一,右列各自 truncate 更好读 */+function ConfigSummary({+ issuer,+ clientId,+ redirectUri,+}: {+ issuer: string;+ clientId: string;+ redirectUri: string;+}) {+ const D = S.settings.sso;+ return (+ <div className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 text-fine text-ink-2">+ <span>{D.issuer}</span>+ <span className="truncate font-mono" title={issuer}>+ {issuer}+ </span>+ <span>{D.clientId}</span>+ <span className="truncate font-mono" title={clientId}>+ {clientId}+ </span>+ <span>{D.redirectUri}</span>+ <span className="truncate font-mono" title={redirectUri}>+ {redirectUri}+ </span>+ </div>+ );+}++export function SsoAdmin() {+ const queryClient = useQueryClient();+ const status = useQuery({ queryKey: ["oidc-status"], queryFn: api.oidcStatus });+ const identities = useQuery({+ queryKey: ["oidc-identities"],+ queryFn: api.oidcIdentities,+ enabled: !!status.data?.enabled,+ });+ const [confirming, setConfirming] = useState<{ userId: string; email: string } | null>(+ null,+ );+ const unlink = useMutation({+ mutationFn: (userId: string) => api.oidcUnlink(userId),+ onSuccess: () => {+ setConfirming(null);+ queryClient.invalidateQueries({ queryKey: ["oidc-identities"] });+ },+ onError: (e) => toast.error((e as Error).message),+ });++ if (status.isPending) return null;++ if (!status.data?.enabled) {+ return (+ <div className="glass rounded-panel p-8 text-center text-body text-ink-2">+ {S.settings.sso.disabled}+ </div>+ );+ }++ const rows = identities.data?.identities ?? [];++ return (+ <div className="space-y-4">+ <p className="text-small text-ink-2">{S.settings.sso.hint}</p>++ {identities.data && (+ <ConfigSummary+ issuer={identities.data.issuer}+ clientId={identities.data.client_id}+ redirectUri={identities.data.redirect_uri}+ />+ )}++ {rows.length === 0 ? (+ <div className="glass rounded-panel p-8 text-center text-body text-ink-2">+ {S.settings.sso.empty}+ </div>+ ) : (+ <div className="glass rounded-panel overflow-hidden">+ <Table>+ <THead>+ <Tr>+ <Th>{S.settings.sso.colUser}</Th>+ <Th>{S.settings.sso.colSubject}</Th>+ <Th />+ </Tr>+ </THead>+ <TBody>+ {rows.map((r) => (+ <Tr key={r.user_id}>+ <Td className="text-ink">{r.email}</Td>+ <Td+ className="max-w-xs truncate font-mono text-small text-ink-2"+ title={r.subject}+ >+ {r.subject}+ </Td>+ <Td className="whitespace-nowrap text-right">+ <LinkButton+ tone="danger"+ onClick={() => setConfirming({ userId: r.user_id, email: r.email })}+ >+ {S.settings.sso.unlink}+ </LinkButton>+ </Td>+ </Tr>+ ))}+ </TBody>+ </Table>+ </div>+ )}++ {confirming && (+ <DangerConfirm+ title={S.settings.sso.unlinkTitle(confirming.email)}+ hint={S.settings.sso.unlinkHint}+ confirmLabel={S.settings.sso.unlink}+ cancelLabel={S.members.cancel}+ busy={unlink.isPending}+ onConfirm={() => unlink.mutate(confirming.userId)}+ onCancel={() => setConfirming(null)}+ />+ )}+ </div>+ );+}++/** 账户页上的一节:我自己的绑定。没配单点登录的部署上整节不出现 */+export function SsoAccount() {+ const queryClient = useQueryClient();+ const me = useQuery({ queryKey: ["oidc-me"], queryFn: api.oidcMe });+ const [confirming, setConfirming] = useState(false);+ const unlink = useMutation({+ mutationFn: api.oidcUnlinkMe,+ onSuccess: () => {+ setConfirming(false);+ queryClient.invalidateQueries({ queryKey: ["oidc-me"] });+ toast.success(S.account.sso.unlinked);+ },+ onError: (e) => toast.error((e as Error).message),+ });++ // 从身份提供方回来时带着结果(`?sso=linked` 或 `?sso_error=`):提示一次,再把地址洗干净,+ // 免得刷新一次又提示一次+ useEffect(() => {+ const params = new URLSearchParams(window.location.search);+ const linked = params.get("sso") === "linked";+ const error = params.get("sso_error");+ if (!linked && !error) return;+ if (linked) toast.success(S.account.sso.linked);+ if (error) toast.error(S.login.ssoErrors[error] ?? S.login.ssoErrorOther);+ params.delete("sso");+ params.delete("sso_error");+ const rest = params.toString();+ window.history.replaceState(null, "", window.location.pathname + (rest ? `?${rest}` : ""));+ }, []);++ if (!me.data?.enabled) return null;++ return (+ <div className="glass rounded-panel p-6 mt-4">+ <div className="max-w-xl">+ <h2 className="text-body font-medium text-ink mb-2">{S.account.sso.title}</h2>+ <p className="text-small text-ink-2 mb-4">{S.account.sso.hint}</p>+ <div className="flex items-center gap-3">+ <span className="min-w-0 flex-1 truncate text-body text-ink-2">+ {me.data.linked && me.data.subject+ ? S.account.sso.linkedAs(me.data.subject)+ : S.account.sso.notLinked}+ </span>+ {me.data.linked ? (+ <Button variant="secondary" size="sm" onClick={() => setConfirming(true)}>+ {S.account.sso.unlink}+ </Button>+ ) : (+ <Button variant="primary" size="sm"+ onClick={() => {+ window.location.href = "/api/v1/auth/oidc/start?link=1";+ }}+ >+ {S.account.sso.link}+ </Button>+ )}+ </div>+ </div>+ {confirming && (+ <DangerConfirm+ title={S.account.sso.unlinkTitle}+ hint={S.account.sso.unlinkHint}+ confirmLabel={S.account.sso.unlink}+ cancelLabel={S.account.cancel}+ busy={unlink.isPending}+ onConfirm={() => unlink.mutate()}+ onCancel={() => setConfirming(false)}+ />+ )}+ </div>+ );+}diff --git a/web/src/router.tsx b/web/src/router.tsxindex dfe5f21e..38609322 100644--- a/web/src/router.tsx+++ b/web/src/router.tsx@@ -209,11 +209,12 @@ const adminRoute = createRoute({// 深链指定页签(如 KB 数据节的"注册新连接"直达 Data sources)validateSearch: (search: Record<string, unknown>,- ): { tab?: "models" | "members" | "datasources" | "deployment" } => ({+ ): { tab?: "models" | "members" | "datasources" | "sso" | "deployment" } => ({tab:search.tab === "models" ||search.tab === "members" ||search.tab === "datasources" ||+ search.tab === "sso" ||search.tab === "deployment"? search.tab: undefined,