World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
An app with a trusted client id can swap its user's fresh ID token for a Utopia session (#1049)
WaylandYangb58d2195ace1
diff --git a/.env.example b/.env.exampleindex e675efc8..3bb75859 100644--- a/.env.example+++ b/.env.example@@ -24,6 +24,11 @@ UTOPIA_OPEN_REGISTRATION=true# UTOPIA_OIDC_CLIENT_ID=# UTOPIA_OIDC_CLIENT_SECRET=# UTOPIA_OIDC_REDIRECT_URI=https://your-deployment/api/v1/auth/oidc/callback+# 受信的另一个应用可以拿它用户在同一个身份提供方刚登录到的 ID token,到+# POST /api/v1/auth/oidc/exchange 换一个 Utopia 会话(0066)。这里列它的 client id,逗号分隔;+# 与 Utopia 共用一个 client 的就写 Utopia 自己的 client id。留空 = 不开放这个端点。+# 只认本人绑定过的身份,不建号、不自动绑定;每个 ID token 只能换一次。+# UTOPIA_OIDC_EXCHANGE_AUDIENCES=# 数据库连接池上限。缺省 32,与 worker 并发的缺省对齐。# 池子小于并发时症状是请求变慢、而不是任何一处说"池子不够"——调高 worker# 并发时一并考虑这里,也别超过 Postgres 自己的 max_connections(默认 100)。diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rsindex 7fa00290..28ac45de 100644--- a/crates/utopia-cli/src/main.rs+++ b/crates/utopia-cli/src/main.rs@@ -82,7 +82,7 @@ struct ManifestDataDir {/// not a side effect of a code change.// 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current`// 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71-const CURRENT_SCHEMA_VERSION: u32 = 93;+const CURRENT_SCHEMA_VERSION: u32 = 94;fn main() -> anyhow::Result<()> {dotenvy::dotenv().ok();diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex b75830e1..3e22eb0d 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -118,6 +118,8 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {.route("/auth/oidc/status", get(oidc_routes::status)).route("/auth/oidc/start", get(oidc_routes::start)).route("/auth/oidc/callback", get(oidc_routes::callback))+ // 受信的另一个应用拿它用户刚到手的 ID token 换一个会话(0066)+ .route("/auth/oidc/exchange", post(oidc_routes::exchange))// 我自己的绑定:看、解绑。绑定走 `/auth/oidc/start?link=1`,由本人完成.route("/auth/oidc/me",@@ -668,5 +670,8 @@ async fn jobs_noop(#[cfg(test)]mod rule_metadata_tests;+#[cfg(test)]+mod oidc_exchange_tests;+#[cfg(test)]mod rule_expression_tests;diff --git a/crates/utopia-server/src/api/oidc_exchange_tests.rs b/crates/utopia-server/src/api/oidc_exchange_tests.rsnew file mode 100644index 00000000..fdcad262--- /dev/null+++ b/crates/utopia-server/src/api/oidc_exchange_tests.rs@@ -0,0 +1,152 @@+//! 换会话走完整条路由:发现文档与 JWKS 来自本机的假身份提供方,映射与一次性走真库。+use crate::state::AppState;+use axum::{+ body::Body,+ http::{Request, StatusCode},+ routing::get,+ Json, Router,+};+use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};+use serde_json::{json, Value};+use std::sync::Arc;+use tower::ServiceExt;+use uuid::Uuid;++// 这把钥匙只为测试生成,应用从不使用+#[tokio::test]+async fn exchange_maps_only_linked_active_people_and_spends_each_token_once() -> 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 listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;+ let issuer = format!("http://{}", listener.local_addr()?);+ let discovery = json!({"issuer": issuer, "jwks_uri": format!("{issuer}/jwks")});+ let jwks: Value = serde_json::from_str(include_str!(+ "../../tests/fixtures/oidc_test_only_jwks.json"+ ))?;+ let provider = Router::new()+ .route(+ "/.well-known/openid-configuration",+ get(move || async move { Json(discovery) }),+ )+ .route("/jwks", get(move || async move { Json(jwks) }));+ let server = tokio::spawn(async move { axum::serve(listener, provider).await.unwrap() });+ // 只有这个测试读写这几个变量+ std::env::set_var("UTOPIA_OIDC_ISSUER", &issuer);+ std::env::set_var("UTOPIA_OIDC_CLIENT_ID", "utopia-test");+ std::env::set_var(+ "UTOPIA_OIDC_REDIRECT_URI",+ "http://localhost/api/v1/auth/oidc/callback",+ );+ std::env::set_var("UTOPIA_OIDC_ALLOW_LOOPBACK_HTTP", "1");+ std::env::remove_var("UTOPIA_OIDC_EXCHANGE_AUDIENCES");++ let (org, user) = (Uuid::now_v7(), Uuid::now_v7());+ let subject = format!("person-{user}");+ 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}','exchange-test');+ INSERT INTO users(id,org_id,email,password_hash,display_name) VALUES('{user}','{org}','{user}@example.test','unused','Test');+ INSERT INTO oidc_identities(issuer,subject,user_id) VALUES('{issuer}','{subject}','{user}');"+ ))+ .execute(&pool)+ .await?;+ let key = EncodingKey::from_rsa_pem(include_bytes!(+ "../../tests/fixtures/oidc_test_only_key.pem"+ ))?;+ let mut header = Header::new(Algorithm::RS256);+ header.kid = Some("fixture".into());+ // `jti` 只为让每次签出来的令牌不同;Utopia 不读它+ let sign_at = |sub: &str, issued_ago: i64, expires_in: i64| {+ let now = chrono::Utc::now().timestamp();+ encode(+ &header,+ &json!({"iss": issuer, "aud": "sibling-app", "sub": sub, "iat": now - issued_ago, "exp": now + expires_in, "jti": Uuid::now_v7()}),+ &key,+ )+ };+ let sign = |sub: &str| sign_at(sub, 0, 300);+ let exchange = |id_token: String| {+ let state = state.clone();+ async move {+ let request = Request::builder()+ .method("POST")+ .uri("/api/v1/auth/oidc/exchange")+ .header("content-type", "application/json")+ .body(Body::from(json!({"id_token": id_token}).to_string()))?;+ let response = super::router(state, &Default::default())+ .oneshot(request)+ .await?;+ let status = response.status();+ let body = axum::body::to_bytes(response.into_body(), 65536).await?;+ anyhow::Ok((status, serde_json::from_slice::<Value>(&body).unwrap_or(Value::Null)))+ }+ };++ // 没配受信 audience:端点不存在+ let (status, _) = exchange(sign(&subject)?).await?;+ anyhow::ensure!(status == StatusCode::NOT_FOUND, "closed: {status}");+ std::env::set_var("UTOPIA_OIDC_EXCHANGE_AUDIENCES", "other-app, sibling-app");++ let token = sign(&subject)?;+ let (status, body) = exchange(token.clone()).await?;+ anyhow::ensure!(status == StatusCode::OK, "linked: {status} {body}");+ anyhow::ensure!(crate::auth::decode_user_id(&state, body["token"].as_str().unwrap())? == user);+ let expires_at: chrono::DateTime<chrono::Utc> =+ serde_json::from_value(body["expires_at"].clone())?;+ anyhow::ensure!(expires_at > chrono::Utc::now() + chrono::Duration::days(6));+ let audited: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM audit_events WHERE actor_id = $1 AND action = 'auth.oidc_exchange'",+ )+ .bind(user)+ .fetch_one(&pool)+ .await?;+ anyhow::ensure!(audited == 1);++ let (status, body) = exchange(token).await?;+ anyhow::ensure!(body["code"] == "oidc_replayed", "replay: {status} {body}");++ // 刚过 `exp` 的令牌还在校验的宽限里、验得过:换过一次的记录不能先于它失效,+ // 否则这一分钟里它能再换一次+ let late = sign_at(&subject, 100, -30)?;+ let (status, body) = exchange(late.clone()).await?;+ anyhow::ensure!(status == StatusCode::OK, "within leeway: {status} {body}");+ let (status, body) = exchange(late).await?;+ anyhow::ensure!(body["code"] == "oidc_replayed", "replay within leeway: {status} {body}");++ let (status, body) = exchange(sign("nobody-linked-this")?).await?;+ anyhow::ensure!(body["code"] == "oidc_unlinked", "unlinked: {status} {body}");++ sqlx::query("UPDATE users SET deactivated_at = now() WHERE id = $1")+ .bind(user)+ .execute(&pool)+ .await?;+ let (status, body) = exchange(sign(&subject)?).await?;+ anyhow::ensure!(body["code"] == "oidc_unlinked", "deactivated: {status} {body}");+ anyhow::Ok(())+ }+ .await;+ server.abort();+ sqlx::query("DELETE FROM organizations WHERE id=$1")+ .bind(org)+ .execute(&pool)+ .await?;+ result+}diff --git a/crates/utopia-server/src/api/oidc_routes.rs b/crates/utopia-server/src/api/oidc_routes.rsindex af37cb7e..8fb4c0a9 100644--- a/crates/utopia-server/src/api/oidc_routes.rs+++ b/crates/utopia-server/src/api/oidc_routes.rs@@ -8,6 +8,9 @@//! 操作在台账上记成被冒充的人(0014:身份来自本人)。管理员现在只能看与解绑。//!//! 绝不按身份提供方的 email 这类可变声明自动关联,首次登录也绝不自动开账号。+//!+//! **另一个应用可以拿它刚登录到的 ID token 换一个会话**(`exchange`,0066):同一个+//! 身份提供方、受信的 audience 列表、十分钟内签发、只换一次,映射规则与登录相同。use crate::{auth::{self, AuthUser},@@ -46,12 +49,18 @@ const DOC_LIMIT: usize = 256 * 1024;const TOKEN_LIMIT: usize = 64 * 1024;/// 发现文档与 JWKS 的缓存时长。轮换密钥时 `kid` 找不到会强制刷新一次const CACHE_TTL: Duration = Duration::from_secs(600);+/// 同一地址两次强制刷新之间至少隔这么久。`kid` 由请求方写,`exchange` 又不需要登录:+/// 不设冷却的话,编一个 `kid` 就能让服务器每次都去问一遍身份提供方+const FORCE_COOLDOWN: Duration = Duration::from_secs(60);struct Config {issuer: String,client_id: String,secret: Option<String>,redirect: String,+ /// `exchange` 收哪些 client 的 ID token。空 = 不开放换会话。与 Utopia 共用一个+ /// client 的部署把 Utopia 自己的 client id 写进来+ exchange_audiences: Vec<String>,/// 本地开发:允许 issuer 与各端点走回环地址上的明文 HTTP。只认 localhost //// 127.0.0.1 / ::1,公网地址照旧只能 HTTPSloopback_http: bool,@@ -71,6 +80,13 @@ fn config() -> Result<Config, AppError> {.ok().filter(|s| !s.is_empty()),redirect: get("UTOPIA_OIDC_REDIRECT_URI")?,+ exchange_audiences: std::env::var("UTOPIA_OIDC_EXCHANGE_AUDIENCES")+ .unwrap_or_default()+ .split(',')+ .map(str::trim)+ .filter(|a| !a.is_empty())+ .map(String::from)+ .collect(),loopback_http: std::env::var("UTOPIA_OIDC_ALLOW_LOOPBACK_HTTP").is_ok_and(|v| matches!(v.trim(), "1" | "true")),};@@ -153,6 +169,7 @@ fn cache() -> &'static Cache {/// 都会让服务器去问一次身份提供方async fn cached_json(url: &reqwest::Url, force: bool) -> Result<Value, Refusal> {let key = url.to_string();+ let force = force && force_allowed(&key).await;if !force {if let Some((at, v)) = cache().lock().await.get(&key) {if at.elapsed() < CACHE_TTL {@@ -175,6 +192,22 @@ async fn cached_json(url: &reqwest::Url, force: bool) -> Result<Value, Refusal>Ok(v)}+/// 这一次强制刷新放不放行:冷却期内的一律退回读缓存。先记下时刻再去取,+/// 同时到的一批请求里只有一个真去问身份提供方+async fn force_allowed(key: &str) -> bool {+ static LAST: std::sync::OnceLock<tokio::sync::Mutex<HashMap<String, Instant>>> =+ std::sync::OnceLock::new();+ let mut last = LAST.get_or_init(Default::default).lock().await;+ if last+ .get(key)+ .is_some_and(|at| at.elapsed() < FORCE_COOLDOWN)+ {+ return false;+ }+ last.insert(key.to_string(), Instant::now());+ true+}+async fn metadata(c: &Config) -> Result<Value, Refusal> {let url = secure_url(&format!(@@ -342,7 +375,9 @@ pub struct Callback {#[derive(Clone, Deserialize)]struct Claims {sub: String,- nonce: String,+ /// 登录拿到的令牌带着本次流程的 nonce;换会话的令牌是别人的流程签的,未必有+ #[serde(default)]+ nonce: Option<String>,iat: i64,#[serde(default)]azp: Option<String>,@@ -371,6 +406,21 @@ fn verify_token(id_token: &str,keys: &JwkSet,nonce: &str,+) -> Result<Claims, AppError> {+ let claims = verify_for(c, id_token, keys, &[c.client_id.as_str()])?;+ if claims.nonce.as_deref() != Some(nonce) {+ return Err(AppError::Unauthorized);+ }+ Ok(claims)+}++/// 签名、issuer、有效期与 audience:令牌得是配置的 issuer 签给 `audiences` 之一的。+/// `azp` 出现时(或 audience 不止一个时)也必须在其中+fn verify_for(+ c: &Config,+ id_token: &str,+ keys: &JwkSet,+ audiences: &[&str],) -> Result<Claims, AppError> {let header = decode_header(id_token).map_err(|_| AppError::Unauthorized)?;if header.alg != Algorithm::RS256 {@@ -380,7 +430,7 @@ fn verify_token(let mut validation = Validation::new(Algorithm::RS256);validation.validate_nbf = true;validation.set_issuer(&[&c.issuer]);- validation.set_audience(&[&c.client_id]);+ validation.set_audience(audiences);validation.set_required_spec_claims(&["exp", "iss", "aud", "sub", "iat"]);let claims = decode::<Claims>(id_token,@@ -389,18 +439,119 @@ fn verify_token().map_err(|_| AppError::Unauthorized)?.claims;- if claims.nonce != nonce- || claims.sub.is_empty()+ let trusted = |a: &String| audiences.contains(&a.as_str());+ if claims.sub.is_empty()|| claims.iat > chrono::Utc::now().timestamp() + 60- || claims.azp.as_ref().is_some_and(|a| a != &c.client_id)+ || claims.azp.as_ref().is_some_and(|a| !trusted(a))|| (claims.aud.as_array().is_some_and(|a| a.len() > 1)- && claims.azp.as_deref() != Some(c.client_id.as_str()))+ && !claims.azp.as_ref().is_some_and(trusted)){return Err(AppError::Unauthorized);}Ok(claims)}+/// 换会话的 ID token 最多多旧:它是登录一完成就拿来换的+const EXCHANGE_MAX_AGE_SECS: i64 = 600;++/// 一个刚签发的、签给受信 audience 之一的 ID token+fn verify_exchange_token(c: &Config, id_token: &str, keys: &JwkSet) -> Result<Claims, AppError> {+ let audiences: Vec<&str> = c.exchange_audiences.iter().map(String::as_str).collect();+ let claims = verify_for(c, id_token, keys, &audiences)?;+ if claims.iat < chrono::Utc::now().timestamp() - EXCHANGE_MAX_AGE_SECS {+ return Err(AppError::Unauthorized);+ }+ Ok(claims)+}++#[derive(Deserialize)]+pub struct Exchange {+ id_token: String,+}++/// 另一个应用(client id 在 `UTOPIA_OIDC_EXCHANGE_AUDIENCES` 里)让它的用户在同一个+/// 身份提供方登录,再拿刚到手的 ID token 换一个 Utopia 会话,以那个人的身份调这里的+/// API。映射与 SSO 登录一样只认本人绑定过的身份;这里不开账号,也不绑定。+/// 没配 SSO 或没配受信 audience 时就当这个端点不存在+pub async fn exchange(+ State(s): State<AppState>,+ Json(body): Json<Exchange>,+) -> ApiResult<Json<Value>> {+ let Some(c) = config().ok().filter(|c| !c.exchange_audiences.is_empty()) else {+ return Err(AppError::NotFound.into());+ };+ let unavailable = |r: Refusal| {+ tracing::warn!(reason = %r.reason, "SSO exchange: identity provider unavailable");+ AppError::invalid("oidc_unavailable", "The identity provider is unavailable")+ };+ let meta = metadata(&c).await.map_err(unavailable)?;+ let jwks_url = endpoint(&c, &meta, "jwks_uri").map_err(unavailable)?;+ 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.map_err(unavailable)?).map_err(unavailable)?;+ let kid = decode_header(&body.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.map_err(unavailable)?).map_err(unavailable)?;+ }+ let claims = verify_exchange_token(&c, &body.id_token, &keys)?;++ // 一次性:令牌的哈希落一行,活过令牌还能被接受的每一刻;插不进去就是换过了。+ // 只按 `iat` 算:十分钟的新鲜度没有宽限,而 `exp` 的校验有 60 秒宽限——按 `exp` 记的话,+ // 过期后的那一分钟里行已经扫掉、令牌却还验得过,能再换一次。多留的一分钟给应用和库的钟差+ sqlx::query("DELETE FROM oidc_exchanges WHERE expires_at < now()")+ .execute(&s.pool)+ .await?;+ let until = claims.iat + EXCHANGE_MAX_AGE_SECS + 60;+ let spent = sqlx::query(+ "INSERT INTO oidc_exchanges (token_hash, expires_at) VALUES ($1, to_timestamp($2))+ ON CONFLICT DO NOTHING",+ )+ .bind(+ Sha256::digest(body.id_token.as_bytes())+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect::<String>(),+ )+ .bind(until as f64)+ .execute(&s.pool)+ .await?;+ if spent.rows_affected() == 0 {+ return Err(+ AppError::invalid("oidc_replayed", "This ID token has already been exchanged").into(),+ );+ }++ 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(|| {+ AppError::invalid(+ "oidc_unlinked",+ "This SSO identity is not linked to a Utopia account",+ )+ })?;+ let (token, expires_at) = auth::issue_session(&s, user_id)?;+ let _ = utopia_store::audit::record(+ &s.pool,+ None,+ user_id,+ "auth.oidc_exchange",+ "user",+ Some(user_id),+ json!({"issuer": c.issuer, "client": claims.azp.or_else(|| claims.aud.as_str().map(String::from))}),+ )+ .await;+ Ok(Json(json!({"token": token, "expires_at": expires_at})))+}+/// 回调办成的是哪一件事enum Done {SignedIn(Uuid),@@ -741,12 +892,21 @@ mod tests {);}+ #[tokio::test]+ async fn a_forced_refresh_waits_out_its_cooldown() {+ let key = "https://id.example.test/cooldown-test";+ assert!(super::force_allowed(key).await);+ assert!(!super::force_allowed(key).await);+ assert!(super::force_allowed("https://id.example.test/another").await);+ }+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(),+ exchange_audiences: vec!["sibling-app".into(), "utopia-test".into()],loopback_http: false,}}@@ -814,4 +974,59 @@ mod tests {two.keys.push(second);assert!(super::verify_token(&c, &no_kid, &two, "expected").is_err());}++ #[test]+ fn exchange_accepts_only_fresh_tokens_of_a_trusted_client() {+ 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":"theirs","iat":now,"exp":now+300});+ let mut header = Header::new(Algorithm::RS256);+ header.kid = Some("fixture".into());+ let sign = |claims: &serde_json::Value| encode(&header, claims, &key).unwrap();+ assert_eq!(+ super::verify_exchange_token(&c, &sign(&valid), &keys)+ .unwrap()+ .sub,+ "person-123"+ );+ for (field, value) in [+ ("aud", json!("other-client")),+ ("aud", json!([c.client_id, "other-client"])),+ ("azp", json!("other-client")),+ ("iat", json!(now - 3600)),+ ("exp", json!(now - 3600)),+ ("iss", json!("https://other.example.test")),+ ] {+ let mut invalid = valid.clone();+ invalid[field] = value;+ assert!(+ super::verify_exchange_token(&c, &sign(&invalid), &keys).is_err(),+ "accepted invalid {field}"+ );+ }+ let mut multi = valid.clone();+ multi["aud"] = json!([c.client_id, "other-client"]);+ multi["azp"] = json!(c.client_id);+ assert!(super::verify_exchange_token(&c, &sign(&multi), &keys).is_ok());++ // 另一个应用用它自己的 client id;不在受信列表里的照样不认+ let mut sibling = valid.clone();+ sibling["aud"] = json!("sibling-app");+ assert!(super::verify_exchange_token(&c, &sign(&sibling), &keys).is_ok());+ let closed = super::Config {+ exchange_audiences: Vec::new(),+ ..config()+ };+ assert!(super::verify_exchange_token(&closed, &sign(&valid), &keys).is_err());+ }}diff --git a/crates/utopia-server/src/auth.rs b/crates/utopia-server/src/auth.rsindex 3d6974cb..bc150f3b 100644--- a/crates/utopia-server/src/auth.rs+++ b/crates/utopia-server/src/auth.rs@@ -61,16 +61,27 @@ pub fn dummy_password_hash() -> &'static str {}pub fn issue_token(state: &AppState, user_id: Uuid) -> Result<String, AppError> {+ issue_session(state, user_id).map(|(token, _)| token)+}++/// 签发会话并给出它的过期时刻:要把过期时间告诉调用方的地方用这个,+/// 免得在别处再按 TTL 算一遍、和 JWT 里的 `exp` 对不上+pub fn issue_session(+ state: &AppState,+ user_id: Uuid,+) -> Result<(String, chrono::DateTime<Utc>), AppError> {+ let expires_at = Utc::now() + chrono::Duration::days(TOKEN_TTL_DAYS);let claims = Claims {sub: user_id,- exp: (Utc::now() + chrono::Duration::days(TOKEN_TTL_DAYS)).timestamp(),+ exp: expires_at.timestamp(),};- encode(+ let token = encode(&Header::default(),&claims,&EncodingKey::from_secret(state.jwt_secret.as_bytes()),)- .map_err(|e| AppError::Other(anyhow::anyhow!("Token issuance failed: {e}")))+ .map_err(|e| AppError::Other(anyhow::anyhow!("Token issuance failed: {e}")))?;+ Ok((token, expires_at))}/// 外层是否在跑 TLS。反代都会带 `X-Forwarded-Proto`;没有这个头(本地直连、diff --git a/docs/decisions/0066-another-app-may-trade-a-fresh-id-token-for-a-session.md b/docs/decisions/0066-another-app-may-trade-a-fresh-id-token-for-a-session.mdnew file mode 100644index 00000000..170c3789--- /dev/null+++ b/docs/decisions/0066-another-app-may-trade-a-fresh-id-token-for-a-session.md@@ -0,0 +1,36 @@+# 0066 · Another app may trade a fresh ID token for a session++- **Status**: Implemented · 2026-10-02 · #1010, migration 0103 · open: no per-app scope; the session is a full seven-day JWT+- **Written**: 2026-10-02 (conventions in the [README](README.md))+- **Related**: [0014](0014-identity-from-the-person-scope-from-the-token.md) (identity comes from the person); migration `0056` (an identity is linked by its owner); [#1010](https://github.com/deeplethe/utopia/pull/1010)++## Problem++A second application signs its users in with the same identity provider as Utopia and needs to call Utopia's API as them: list their knowledge bases, or issue them a personal token for MCP. The only way to a Utopia session is the browser login on Utopia's own origin, which a server-side app cannot drive. Without another way, it would ask people for their Utopia password or keep a shared admin credential, and both break the rule of 0014 that what a caller does is attributed to a real person.++## Decisions++1. **`POST /api/v1/auth/oidc/exchange` takes `{ "id_token" }` and returns `{ token, expires_at }`**, the same session JWT as SSO login. The token must be signed by the configured issuer (JWKS), carry an audience from `UTOPIA_OIDC_EXCHANGE_AUDIENCES`, carry an `azp` from that list when it has one (or when it has several audiences), and have been issued in the last ten minutes.++2. **Trusted audiences, not a shared client.** The calling app uses its own client id, and Utopia lists the ids it trusts. A deployment where the app shares Utopia's client may put Utopia's own client id in the list; that is a choice the operator makes, not a default. When the list is empty, the endpoint answers 404, as it does when SSO is not configured.++3. **The mapping is the login's mapping.** Only an identity the person linked themselves (`oidc_identities`) maps to an account, and only while the account is active; otherwise `oidc_unlinked`. The exchange never creates an account and never links one. An app that can exchange tokens therefore reaches no one who has not, at some point, signed in to Utopia with a password and linked their identity.++4. **Each token is spent once.** Login makes its `state` single-use through `oidc_flows`; the exchange has no state of its own, so it records the token. `oidc_exchanges` holds the SHA-256 of the whole ID token until the token can no longer be accepted, and a second exchange gets `oidc_replayed`. The row lives until `iat` plus eleven minutes: the ten-minute freshness check has no leeway, and one more minute covers a clock difference between the server and the database. It does not follow `exp`, because `exp` is validated with a 60-second leeway, and a row that ended at `exp` would be swept while the token still verified. The hash of the whole token rather than `jti`: not every provider sends `jti`, and every token has a hash. Expired rows are swept on each exchange.++5. **A forced JWKS refresh has a cooldown.** An unknown `kid` forces a fetch from the provider, so that key rotation does not lock people out. In the login callback that fetch sits behind a validated flow; the exchange is unauthenticated, so a made-up `kid` would cost the provider a request each time. Forced refreshes of one URL are at most one per minute (`FORCE_COOLDOWN`), for login and exchange alike; a refused force falls back to the cache. The moment is recorded before the fetch, so a burst of requests sends one.++6. **No nonce.** The token was minted for the other app's flow, and Utopia never saw its nonce. The audience list, the ten-minute window and single use are what limit replay.++7. **Audited** as `auth.oidc_exchange`, with the issuer and the client (`azp`, or the single audience).++## Dead ends++- **Shared client only** (the first version of #1010). The calling app had to hold Utopia's client secret, and Utopia could not tell the app's sign-ins from its own.+- **Token exchange per RFC 8693** at the identity provider. It depends on the provider supporting it and being configured for it, and Utopia's sessions are not tokens the provider issues.+- **Creating or linking an account on first exchange.** The same reason login does not: an identity provider's claim would decide which account a person is (0056).++## Open questions++- **Scope.** The session is the person's full session for seven days. An app that only needs to list bases or mint a personal token gets everything the person can do. A narrower, shorter session for exchanged tokens would follow 0014's "scope from the token".+- **Revocation.** Sessions are stateless JWTs; unlinking the identity stops new exchanges but not sessions already issued. Deactivating the account is still the way to cut access at once.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex 692a786d..b4d4490d 100644--- a/docs/decisions/README.md+++ b/docs/decisions/README.md@@ -129,6 +129,7 @@ By domain; the domains are the files of [../design/](../design/README.md). **Sta|---|---|---|---|| 0014 | [Identity from the person, scope from the token](0014-identity-from-the-person-scope-from-the-token.md) | Implemented | || 0020 | [An auditor reads it without us](0020-an-auditor-reads-it-without-us.md) | Implemented | |+| 0066 | [Another app may trade a fresh ID token for a session](0066-another-app-may-trade-a-fresh-id-token-for-a-session.md) | Implemented | |### [interface](../design/interface.md)diff --git a/docs/design/access-and-audit.md b/docs/design/access-and-audit.mdindex d825b256..cdef5117 100644--- a/docs/design/access-and-audit.md+++ b/docs/design/access-and-audit.md@@ -2,7 +2,7 @@Records: [0014] (tokens and MCP scope), [0020] (the export and the read contract), [0026] (why onevery decision), [0025] d1 (only people write precedent), [0005] d3 and d4 (visibility), [0013]-(credentials), [0034] d5 and d6 (roles for actions), [0016] E.+(credentials), [0034] d5 and d6 (roles for actions), [0016] E, [0066] (exchanging an ID token).## What it does today@@ -18,6 +18,13 @@ intersected with the token's scope; every MCP call re-runs authentication, scopewrites an audit row `mcp.tool_called`; the tokens page shows the plaintext once beside a clientsnippet [0014]. `ingest_token` on a source is a different kind: plaintext, push-only [0014].+**Another app can trade its user's fresh ID token for a session.** `POST /auth/oidc/exchange`+accepts an ID token from the configured issuer whose audience is in+`UTOPIA_OIDC_EXCHANGE_AUDIENCES` and that was issued in the last ten minutes, maps it only to an+identity the person linked themselves, spends it once (`oidc_exchanges`) and audits+`auth.oidc_exchange`; with no trusted audience the endpoint is a 404. Forced JWKS refreshes are at+most one a minute per URL [0066].+**The audit ledger.** `audit_events` records what people did, with an actor and an `actor_label`snapshot, kept forever, never a notification: entity retypes and renames with before and after,review decisions with both names and the `why` a person wrote, merges and reverts, nods, mapping@@ -49,6 +56,8 @@ removed or renamed only with a record [0020 revised].- **Base-level machine tokens were refused** because attribution would become synthetic and a thirdauthorisation model fails towards giving too much [0014].- **Every call checks scope** because list filtering guards only what is visible [0014].+- **The calling app has its own client id** rather than Utopia's secret, and each ID token is spent+ once because the exchange has no `state` of its own [0066].- **The ledger records what people did; alerts record what the system did**, with differentretention and readers [0005].- **Reification and standard terms** so the export opens in what the reader already runs, and@@ -70,5 +79,6 @@ removed or renamed only with a record [0020 revised].## Open questions- What evidence an external agent's fact carries and how its SQL runs are audited [0014].+- Whether an exchanged session should be narrower and shorter than a login's [0066].- Whether 0014's status line still holds: it says `can_write` is hard-coded false, while #735exercises `remember` over MCP with a write token; check the code before relying on either.diff --git a/migrations/0103_an_exchanged_id_token_is_spent_once.sql b/migrations/0103_an_exchanged_id_token_is_spent_once.sqlnew file mode 100644index 00000000..6dd3cbd6--- /dev/null+++ b/migrations/0103_an_exchanged_id_token_is_spent_once.sql@@ -0,0 +1,12 @@+-- 换会话用过的 ID token(0066)。+--+-- `POST /auth/oidc/exchange` 拿别的应用刚登录到的 ID token 换一个 Utopia 会话。+-- 同一个令牌在有效窗口里只能换一次:记下它的 SHA-256,再来一次就拒。+-- 不记 `jti`——不是每个身份提供方都发;整个令牌的哈希一定有。+-- 行只活到令牌本身不再被接受的那一刻,之后每次换会话时顺手扫掉。+CREATE TABLE oidc_exchanges (+ token_hash TEXT PRIMARY KEY,+ expires_at TIMESTAMPTZ NOT NULL+);++CREATE INDEX oidc_exchanges_expiry_idx ON oidc_exchanges (expires_at);