World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A write token may set up a base (#1244)
Szabo Bogdan15921f0f044e
diff --git a/crates/utopia-core/src/error.rs b/crates/utopia-core/src/error.rsindex edbb7e4c..fa8bf25b 100644--- a/crates/utopia-core/src/error.rs+++ b/crates/utopia-core/src/error.rs@@ -6,6 +6,10 @@ pub enum AppError {Unauthorized,#[error("You don't have permission to do that")]Forbidden,+ /// 带 code 的 403:人改得了的那种「不行」(换一枚令牌),要让客户端分得出来,+ /// 而不是和「你的角色不够」混成同一句+ #[error("{message}")]+ CodedForbidden { code: &'static str, message: String },#[error("{0}")]Conflict(String),/// Localizable conflict; legacy internal callers may still use Conflict.diff --git a/crates/utopia-server/src/api/documents_routes.rs b/crates/utopia-server/src/api/documents_routes.rsindex 3159c691..da196cc5 100644--- a/crates/utopia-server/src/api/documents_routes.rs+++ b/crates/utopia-server/src/api/documents_routes.rs@@ -1,21 +1,16 @@-use axum::extract::FromRequestParts;use axum::extract::{Multipart, Path, Query, State};-use axum::http::request::Parts;use axum::http::{header, HeaderMap, HeaderValue, StatusCode};use axum::response::{IntoResponse, Response};use axum::Json;-use axum_extra::extract::cookie::CookieJar;use percent_encoding::{percent_encode, AsciiSet, NON_ALPHANUMERIC};use serde::Deserialize;use serde_json::json;use sha2::{Digest, Sha256};use utopia_core::models::{Document, Role};use utopia_core::AppError;-use utopia_store::tokens::Authenticated;use uuid::Uuid;-use crate::auth::AuthUser;-use crate::error::ApiErr;+use crate::auth::{AuthUser, SessionOrToken};use crate::error::ApiResult;use crate::state::AppState;@@ -26,58 +21,6 @@ pub struct UploadQuery {pub source: Option<Uuid>,}-const PAT_PREFIX: &str = utopia_store::tokens::PREFIX;--/// Web session or personal access token, resolved far enough to enforce both-/// identity and token scope.-///-/// `AuthUser` cannot play this role: it interprets every bearer string as a-/// JWT, so the PAT designed for API clients would become a 401 before the-/// route could apply its Viewer check.-pub struct DocumentReader {- pub user: utopia_core::models::User,- pub pat: Option<Authenticated>,-}--impl FromRequestParts<AppState> for DocumentReader {- type Rejection = ApiErr;-- async fn from_request_parts(- parts: &mut Parts,- state: &AppState,- ) -> Result<Self, Self::Rejection> {- let raw = CookieJar::from_headers(&parts.headers)- .get(crate::auth::COOKIE_NAME)- .map(|cookie| cookie.value().to_string())- .or_else(|| {- parts- .headers- .get(header::AUTHORIZATION)- .and_then(|value| value.to_str().ok())- .and_then(|value| value.strip_prefix("Bearer "))- .map(str::to_owned)- })- .ok_or(AppError::Unauthorized)?;-- if raw.starts_with(PAT_PREFIX) {- let auth = utopia_store::tokens::authenticate(&state.pool, raw.trim()).await?;- let user = utopia_store::accounts::find_user_by_id(&state.pool, auth.user_id)- .await?- .ok_or(AppError::Unauthorized)?;- return Ok(Self {- user,- pat: Some(auth),- });- }-- let user_id = crate::auth::decode_user_id(state, &raw)?;- let user = utopia_store::accounts::find_user_by_id(&state.pool, user_id)- .await?- .ok_or(AppError::Unauthorized)?;- Ok(Self { user, pat: None })- }-}-#[derive(Deserialize)]pub struct ContentQuery {#[serde(default)]@@ -140,14 +83,12 @@ fn content_headers(async fn require_reader_kb(state: &AppState,- reader: &DocumentReader,+ reader: &SessionOrToken,kb_id: Uuid,) -> ApiResult<()> {utopia_store::access::require_kb(&state.pool, &reader.user, kb_id, Role::Viewer).await?;- if let Some(pat) = &reader.pat {- if !pat.covers(kb_id) {- return Err(AppError::NotFound.into());- }+ if !reader.reaches(kb_id) {+ return Err(AppError::NotFound.into());}Ok(())}@@ -155,7 +96,7 @@ async fn require_reader_kb(/// Serve the retained original named by the document ledger.pub async fn content(State(state): State<AppState>,- reader: DocumentReader,+ reader: SessionOrToken,Path(id): Path<Uuid>,Query(query): Query<ContentQuery>,) -> ApiResult<Response> {@@ -227,7 +168,7 @@ pub async fn content(/// Name the exact retained versions the content route can address.pub async fn versions(State(state): State<AppState>,- reader: DocumentReader,+ reader: SessionOrToken,Path(id): Path<Uuid>,) -> ApiResult<Response> {let document = utopia_store::documents::get(&state.pool, id).await?;diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rsindex df1339da..9937d507 100644--- a/crates/utopia-server/src/api/kbs.rs+++ b/crates/utopia-server/src/api/kbs.rs@@ -6,7 +6,7 @@ use utopia_core::models::{KnowledgeBase, Role, User};use utopia_core::AppError;use uuid::Uuid;-use crate::auth::AuthUser;+use crate::auth::{AuthUser, SessionOrToken};use crate::error::ApiResult;use crate::state::AppState;@@ -58,25 +58,35 @@ pub struct UpdateKbReq {}/// 用户可见的 KB 列表(restricted 库仅矩阵成员与系统管理员可见)。+///+/// 读令牌也能列(#1243):客户端建库之前先按名字找,免得每跑一次建一个同名库。+/// 限定过 `kb_ids` 的令牌只看得见它列着的那几个pub async fn list(State(state): State<AppState>,- AuthUser(user): AuthUser,+ caller: SessionOrToken,Path(workspace_id): Path<Uuid>,) -> ApiResult<Json<Vec<KnowledgeBase>>> {+ let user = &caller.user;utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Viewer).await?;- let list =+ let mut list =utopia_store::kbs::list_visible(&state.pool, workspace_id, user.id, user.is_admin).await?;+ list.retain(|kb| caller.reaches(kb.id));Ok(Json(list))}/// 建库:部署管理员(工作区 Admin+ 或系统管理员)。创建者自动进入矩阵为 admin。+///+/// 写令牌也能建(0014 决定 6):以发令牌的人的身份,角色要求一点没松pub async fn create(State(state): State<AppState>,- AuthUser(user): AuthUser,+ caller: SessionOrToken,Path(workspace_id): Path<Uuid>,Json(req): Json<CreateKbReq>,) -> ApiResult<Json<KnowledgeBase>> {+ caller.require_write(None)?;+ let token_id = caller.token_id();+ let user = caller.user;let name = req.name.trim();if name.is_empty() || name.chars().count() > 64 {return Err(AppError::invalid("bad_name", "Name must be 1-64 characters").into());@@ -120,7 +130,7 @@ pub async fn create(}utopia_store::access::set_kb_member(&state.pool, kb.id, user.id, "admin", Some(user.id)).await?;- install_packs(&state, kb.id, user.id, &req.ontology_packs).await?;+ install_packs(&state, kb.id, user.id, token_id, &req.ontology_packs).await?;let kb = utopia_store::kbs::get(&state.pool, kb.id).await?;Ok(Json(kb))}@@ -401,6 +411,7 @@ pub(super) async fn install_packs(state: &AppState,kb_id: Uuid,actor: Uuid,+ via_token: Option<Uuid>,pack_ids: &[String],) -> ApiResult<()> {if pack_ids.is_empty() {@@ -413,7 +424,7 @@ pub(super) async fn install_packs(packs.push((pack, crate::ontology_packs::bytes(pack)?));}for (pack, bytes) in &packs {- crate::owl_import::apply(state, kb_id, actor, pack.filename, bytes)+ crate::owl_import::apply(state, kb_id, actor, via_token, pack.filename, bytes).await.map_err(|e| AppError::Other(anyhow::anyhow!("装本体包 {} 失败:{e}", pack.id)))?;}diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 9955b2e7..b500ed79 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -658,5 +658,8 @@ mod system_admin_tests;#[cfg(test)]mod oidc_exchange_tests;+#[cfg(test)]+mod token_setup_tests;+#[cfg(test)]mod rule_expression_tests;diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rsindex a075ce68..2be1dd56 100644--- a/crates/utopia-server/src/api/ontology_routes.rs+++ b/crates/utopia-server/src/api/ontology_routes.rs@@ -9,7 +9,7 @@ use utopia_core::models::Role;use utopia_core::AppError;use uuid::Uuid;-use crate::auth::AuthUser;+use crate::auth::{AuthUser, SessionOrToken};use crate::error::ApiResult;use crate::state::AppState;@@ -605,12 +605,16 @@ pub async fn preview_import(Ok(Json(json!({ "filename": filename, "plan": plan })))}+/// 写令牌也能导(0014 决定 6):新库的本体与库一起由同一个客户端搭好pub async fn apply_import(State(state): State<AppState>,- AuthUser(user): AuthUser,+ caller: SessionOrToken,Path(kb_id): Path<Uuid>,multipart: axum::extract::Multipart,) -> ApiResult<Json<serde_json::Value>> {+ caller.require_write(Some(kb_id))?;+ let token_id = caller.token_id();+ let user = caller.user;require_kb(&state, &user, kb_id, Role::Editor).await?;let (filename, bytes) = read_upload(multipart).await?;// 导入会改判据(公理链、domain/range、父边):先把旧本体下会检出的违规@@ -622,7 +626,7 @@ pub async fn apply_import(let was_detected = utopia_store::reasoning::detection_keys(&mut baseline_tx, kb_id).await?;baseline_tx.commit().await?;let (import_id, plan) =- match crate::owl_import::apply(&state, kb_id, user.id, &filename, &bytes).await {+ match crate::owl_import::apply(&state, kb_id, user.id, token_id, &filename, &bytes).await {Ok(v) => v,Err(e) => {// apply 是多笔提交:中途失败时一部分判据已经落了。尽力对账——diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rsindex caf8f1f0..8f46a2fd 100644--- a/crates/utopia-server/src/api/review_routes.rs+++ b/crates/utopia-server/src/api/review_routes.rs@@ -8,7 +8,7 @@ use utopia_core::models::Role;use uuid::Uuid;use super::graph_routes::require_kb;-use crate::auth::AuthUser;+use crate::auth::{AuthUser, SessionOrToken};use crate::error::ApiResult;use crate::state::AppState;@@ -1395,12 +1395,17 @@ pub struct DecideAlignmentKindWordReq {/// 人定一个类别词绑到哪个类(#725 对齐队列)。绑上的类写到它名下的实体上;两端的类变了,/// 短语签名跟着变,所以再排一次短语对齐——与判定同一事务排下(`decide_and_apply_human`),/// 提交之后再排的话,进程在两步之间退出就只剩判定。+///+/// 写令牌也能定(0014 决定 6):判定记在发令牌的人名下,与网页上点的一样pub async fn decide_alignment_kind_word(State(state): State<AppState>,- AuthUser(user): AuthUser,+ caller: SessionOrToken,Path((kb_id, kind_word)): Path<(Uuid, String)>,Json(req): Json<DecideAlignmentKindWordReq>,) -> ApiResult<Json<serde_json::Value>> {+ caller.require_write(Some(kb_id))?;+ let token_id = caller.token_id();+ let user = caller.user;require_kb(&state, &user, kb_id, Role::Editor).await?;let class = match req.class@@ -1439,7 +1444,10 @@ pub async fn decide_alignment_kind_word("alignment.kind_word_decided","type_binding",None,- json!({ "kind_word": kind_word, "class": req.class }),+ utopia_store::audit::via_token(+ json!({ "kind_word": kind_word, "class": req.class }),+ token_id,+ ),).await;state.emit_review(kb_id);diff --git a/crates/utopia-server/src/api/sources_routes.rs b/crates/utopia-server/src/api/sources_routes.rsindex e0ea55bc..52db4125 100644--- a/crates/utopia-server/src/api/sources_routes.rs+++ b/crates/utopia-server/src/api/sources_routes.rs@@ -10,7 +10,7 @@ use utopia_core::models::{Role, SOURCE_SECRET_KEYS};use uuid::Uuid;use super::graph_routes::require_kb;-use crate::auth::AuthUser;+use crate::auth::{AuthUser, SessionOrToken};use crate::error::ApiResult;use crate::state::AppState;@@ -84,12 +84,27 @@ pub struct CreateBody {pub sync_cron: Option<String>,}+/// 写令牌也能建(0014 决定 6):给一个镜像仓库配 `statements` 来源,不该要人+/// 一个个手点。+///+/// 令牌只建 `statements`:`url`/`rss`/`custom` 一建好服务器就按时去拉(`custom`+/// 还带着存下的凭据),漏出去的 CI 令牌不该能让服务器定时去敲任意地址。会话照旧建什么都行pub async fn create(State(state): State<AppState>,- AuthUser(user): AuthUser,+ caller: SessionOrToken,Path(kb_id): Path<Uuid>,Json(body): Json<CreateBody>,) -> ApiResult<Json<serde_json::Value>> {+ caller.require_write(Some(kb_id))?;+ if caller.pat.is_some() && body.kind != "statements" {+ return Err(utopia_core::AppError::CodedForbidden {+ code: "token_source_kind",+ message: "A token creates only statements sources; other kinds take a session".into(),+ }+ .into());+ }+ let token_id = caller.token_id();+ let user = caller.user;require_kb(&state, &user, kb_id, Role::Editor).await?;validate_rss_config(&body.kind, &body.config)?;let source = utopia_store::sources::create(@@ -128,7 +143,10 @@ pub async fn create("source.created","source",Some(source.id),- json!({ "kind": source.kind, "name": source.name }),+ utopia_store::audit::via_token(+ json!({ "kind": source.kind, "name": source.name }),+ token_id,+ ),).await;Ok(Json(@@ -143,12 +161,15 @@ fn has_push_token(source: &utopia_core::models::Source) -> bool {}/// 查看推送密钥(Editor;列表响应从不携带,查看走这里)。+///+/// 令牌要 write:密钥能往库里推东西,读令牌拿到它就等于绕过了自己的 scopepub async fn get_token(State(state): State<AppState>,- AuthUser(user): AuthUser,+ caller: SessionOrToken,Path((kb_id, source_id)): Path<(Uuid, Uuid)>,) -> ApiResult<Json<serde_json::Value>> {- require_kb(&state, &user, kb_id, Role::Editor).await?;+ caller.require_write(Some(kb_id))?;+ require_kb(&state, &caller.user, kb_id, Role::Editor).await?;let source = source_in_kb(&state, kb_id, source_id).await?;if !has_push_token(&source) {return Err(utopia_core::AppError::NotFound.into());diff --git a/crates/utopia-server/src/api/token_setup_tests.rs b/crates/utopia-server/src/api/token_setup_tests.rsnew file mode 100644index 00000000..e08b9574--- /dev/null+++ b/crates/utopia-server/src/api/token_setup_tests.rs@@ -0,0 +1,383 @@+//! 写权限的个人令牌能把一个库从无到有搭起来(#1243):建库、建来源、读推送密钥、+//! 导入本体、定类别词。令牌照旧只收窄——人的角色是上限,scope 与 `kb_ids` 再往下压。+use crate::state::AppState;+use axum::body::{to_bytes, Body};+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use std::sync::Arc;+use tower::ServiceExt;+use uuid::Uuid;++struct Fixture {+ pool: sqlx::PgPool,+ app: axum::Router,+ org: Uuid,+ ws: Uuid,+ /// 工作区 admin:建得了库+ admin: Uuid,+ /// 工作区 viewer:令牌勾了 write 也建不了+ viewer: Uuid,+ _dir: tempfile::TempDir,+}++impl Fixture {+ async fn new() -> anyhow::Result<Option<Self>> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(None);+ };+ let pool = sqlx::PgPool::connect(&url).await?;+ utopia_store::db::migrate(&pool).await?;+ let (org, ws, admin, viewer) = (+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ );+ sqlx::raw_sql(&format!(+ "INSERT INTO organizations(id,name) VALUES ('{org}','token-setup-test');+ INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','token-setup-test');+ INSERT INTO users(id,org_id,email,display_name,password_hash) VALUES+ ('{admin}','{org}','{admin}@token-setup.test','Admin','unused'),+ ('{viewer}','{org}','{viewer}@token-setup.test','Viewer','unused');+ INSERT INTO memberships(user_id,workspace_id,role) VALUES+ ('{admin}','{ws}','admin'), ('{viewer}','{ws}','viewer');"+ ))+ .execute(&pool)+ .await?;+ let dir = tempfile::tempdir()?;+ let cfg = utopia_core::config::AppConfig {+ data_dir: dir.path().to_string_lossy().into_owned(),+ ..Default::default()+ };+ let search = Arc::new(utopia_search::SearchIndex::open(+ &dir.path().join("search"),+ )?);+ let state = AppState::new(pool.clone(), &cfg, search, "test-only".into());+ let app = super::router(state, &cfg);+ Ok(Some(Self {+ pool,+ app,+ org,+ ws,+ admin,+ viewer,+ _dir: dir,+ }))+ }++ async fn token(&self, user: Uuid, scope: &str, kb_ids: Option<&[Uuid]>) -> String {+ utopia_store::tokens::issue(&self.pool, user, "ci", scope, kb_ids, None)+ .await+ .expect("issuing a token")+ .1+ }++ async fn send(+ &self,+ method: &str,+ path: &str,+ token: &str,+ body: Option<Value>,+ ) -> anyhow::Result<(StatusCode, Value)> {+ let request = Request::builder()+ .method(method)+ .uri(format!("/api/v1{path}"))+ .header("authorization", format!("Bearer {token}"));+ let request = match body {+ Some(body) => request+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))?,+ None => request.body(Body::empty())?,+ };+ self.respond(request).await+ }++ /// 本体导入收 multipart。空表单在读上传那一步就会被拒(`no_files`),+ /// 够用来分辨「令牌被挡在门外」与「进了门、请求本身不对」+ async fn import_nothing(&self, kb: Uuid, token: &str) -> anyhow::Result<(StatusCode, Value)> {+ let request = Request::post(format!("/api/v1/kbs/{kb}/ontology/imports"))+ .header("authorization", format!("Bearer {token}"))+ .header("content-type", "multipart/form-data; boundary=x")+ .body(Body::from("--x--\r\n"))?;+ self.respond(request).await+ }++ async fn respond(&self, request: Request<Body>) -> anyhow::Result<(StatusCode, Value)> {+ let response = self.app.clone().oneshot(request).await?;+ let status = response.status();+ let bytes = to_bytes(response.into_body(), 1024 * 1024).await?;+ let body = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ Ok((status, body))+ }++ async fn create_kb(&self, token: &str, name: &str) -> anyhow::Result<(StatusCode, Value)> {+ let ws = self.ws;+ self.send(+ "POST",+ &format!("/workspaces/{ws}/kbs"),+ token,+ Some(json!({ "name": name })),+ )+ .await+ }++ async fn create_source(&self, kb: Uuid, token: &str) -> anyhow::Result<(StatusCode, Value)> {+ self.create_source_of_kind(kb, token, "statements").await+ }++ async fn create_source_of_kind(+ &self,+ kb: Uuid,+ token: &str,+ kind: &str,+ ) -> anyhow::Result<(StatusCode, Value)> {+ self.send(+ "POST",+ &format!("/kbs/{kb}/sources"),+ token,+ Some(json!({ "kind": kind, "name": "ci" })),+ )+ .await+ }++ async fn push_key(+ &self,+ kb: Uuid,+ source: Uuid,+ token: &str,+ ) -> anyhow::Result<(StatusCode, Value)> {+ let path = format!("/kbs/{kb}/sources/{source}/token");+ self.send("GET", &path, token, None).await+ }++ async fn decide_kind_word(&self, kb: Uuid, token: &str) -> anyhow::Result<(StatusCode, Value)> {+ let path = format!("/kbs/{kb}/review/alignment/kind-words/robot");+ self.send("POST", &path, token, Some(json!({}))).await+ }++ async fn list_kbs(&self, token: &str) -> anyhow::Result<(StatusCode, Value)> {+ let ws = self.ws;+ self.send("GET", &format!("/workspaces/{ws}/kbs"), token, None)+ .await+ }++ /// 直接写库建一个 admin 名下的库:只测令牌边界的用例不必先走一遍建库+ async fn seeded_kb(&self, name: &str) -> anyhow::Result<Uuid> {+ let kb = Uuid::now_v7();+ sqlx::query("INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ($1,$2,$3)")+ .bind(kb)+ .bind(self.ws)+ .bind(name)+ .execute(&self.pool)+ .await?;+ sqlx::query("INSERT INTO kb_members(kb_id,user_id,role) VALUES ($1,$2,'admin')")+ .bind(kb)+ .bind(self.admin)+ .execute(&self.pool)+ .await?;+ Ok(kb)+ }++ async fn cleanup(self) -> anyhow::Result<()> {+ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(self.org)+ .execute(&self.pool)+ .await?;+ Ok(())+ }+}++#[tokio::test]+async fn a_live_write_token_of_a_workspace_admin_sets_up_a_base_and_a_dead_one_does_not(+) -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ let result = async {+ let token = f.token(f.admin, "write", None).await;+ let token_id = utopia_store::tokens::authenticate(&f.pool, &token)+ .await?+ .token_id;++ let (status, kb) = f.create_kb(&token, "lore-mirror").await?;+ anyhow::ensure!(status == StatusCode::OK, "{status} {kb}");+ let kb: Uuid = serde_json::from_value(kb["id"].clone())?;++ let (status, created) = f.create_source(kb, &token).await?;+ anyhow::ensure!(status == StatusCode::OK, "{status} {created}");+ let source: Uuid = serde_json::from_value(created["source"]["id"].clone())?;++ let (status, key) = f.push_key(kb, source, &token).await?;+ anyhow::ensure!(status == StatusCode::OK, "{status} {key}");+ anyhow::ensure!(+ key["ingest_token"] == created["ingest_token"] && key["ingest_token"].is_string(),+ "{key} vs {created}"+ );++ // 进了门、请求本身不对:空上传过了令牌与角色,停在读上传那一步+ let (status, body) = f.import_nothing(kb, &token).await?;+ anyhow::ensure!(body["code"] == "no_files", "{status} {body}");+ let (status, body) = f.decide_kind_word(kb, &token).await?;+ anyhow::ensure!(status == StatusCode::OK, "{status} {body}");++ // 审计记的是发令牌的人,与会话一样+ let actors: Vec<(String, Option<Uuid>)> = sqlx::query_as(+ "SELECT action, actor_id FROM audit_events+ WHERE kb_id = $1 AND action IN ('source.created', 'alignment.kind_word_decided')+ ORDER BY action",+ )+ .bind(kb)+ .fetch_all(&f.pool)+ .await?;+ anyhow::ensure!(+ actors+ == [+ ("alignment.kind_word_decided".to_string(), Some(f.admin)),+ ("source.created".to_string(), Some(f.admin)),+ ],+ "{actors:?}"+ );+ // 哪一枚令牌代人做的(决定 5 靠它):记在 detail 里+ let detail: Value = sqlx::query_scalar(+ "SELECT detail FROM audit_events WHERE kb_id = $1 AND action = 'source.created'",+ )+ .bind(kb)+ .fetch_one(&f.pool)+ .await?;+ anyhow::ensure!(detail["token_id"] == json!(token_id), "{detail}");++ // 同一个人、同一条刚走通的路:过期的与撤销的令牌照旧挡在门外+ let (_, expired) = utopia_store::tokens::issue(+ &f.pool,+ f.admin,+ "expired",+ "write",+ None,+ Some(chrono::Utc::now() - chrono::Duration::minutes(1)),+ )+ .await?;+ let (revoked_view, revoked) =+ utopia_store::tokens::issue(&f.pool, f.admin, "revoked", "write", None, None).await?;+ utopia_store::tokens::revoke(&f.pool, f.admin, revoked_view.id).await?;+ for token in [expired, revoked] {+ let (status, body) = f.create_source(kb, &token).await?;+ anyhow::ensure!(status == StatusCode::UNAUTHORIZED, "{status} {body}");+ }+ anyhow::Ok(())+ }+ .await;+ f.cleanup().await?;+ result+}++#[tokio::test]+async fn a_write_token_creating_a_url_source_is_refused_with_token_source_kind(+) -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ let result = async {+ let kb = f.seeded_kb("pull").await?;+ let token = f.token(f.admin, "write", None).await;++ let (status, body) = f.create_source_of_kind(kb, &token, "url").await?;+ anyhow::ensure!(+ status == StatusCode::FORBIDDEN && body["code"] == "token_source_kind",+ "{status} {body}"+ );+ let sources: i64 = sqlx::query_scalar("SELECT count(*) FROM sources WHERE kb_id = $1")+ .bind(kb)+ .fetch_one(&f.pool)+ .await?;+ anyhow::ensure!(sources == 0, "{sources} sources");+ anyhow::Ok(())+ }+ .await;+ f.cleanup().await?;+ result+}++#[tokio::test]+async fn a_read_token_lists_bases_and_is_refused_on_every_setup_route() -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ let result = async {+ let kb = f.seeded_kb("existing").await?;+ let source = Uuid::now_v7();+ sqlx::query("INSERT INTO sources(id,kb_id,kind,name) VALUES ($1,$2,'statements','ci')")+ .bind(source)+ .bind(kb)+ .execute(&f.pool)+ .await?;+ let token = f.token(f.admin, "read", None).await;++ let (status, listed) = f.list_kbs(&token).await?;+ anyhow::ensure!(status == StatusCode::OK, "{status} {listed}");+ anyhow::ensure!(listed[0]["name"] == "existing", "{listed}");++ for (route, (status, body)) in [+ ("create base", f.create_kb(&token, "nope").await?),+ ("create source", f.create_source(kb, &token).await?),+ ("read push key", f.push_key(kb, source, &token).await?),+ ("import ontology", f.import_nothing(kb, &token).await?),+ ("decide kind word", f.decide_kind_word(kb, &token).await?),+ ] {+ anyhow::ensure!(+ status == StatusCode::FORBIDDEN && body["code"] == "token_read_only",+ "{route}: {status} {body}"+ );+ }+ anyhow::Ok(())+ }+ .await;+ f.cleanup().await?;+ result+}++#[tokio::test]+async fn a_write_token_reaches_no_further_than_its_owners_role_and_its_base_list(+) -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ let result = async {+ // 工作区 viewer:令牌勾了 write,建库照旧要工作区 admin+ let viewers = f.token(f.viewer, "write", None).await;+ let (status, body) = f.create_kb(&viewers, "nope").await?;+ anyhow::ensure!(status == StatusCode::FORBIDDEN, "viewer: {status} {body}");++ let (a, b) = (f.seeded_kb("a").await?, f.seeded_kb("b").await?);+ let token = f.token(f.admin, "write", Some(&[a])).await;++ let (status, body) = f.create_source(a, &token).await?;+ anyhow::ensure!(status == StatusCode::OK, "base a: {status} {body}");++ let (status, body) = f.create_source(b, &token).await?;+ anyhow::ensure!(+ status == StatusCode::FORBIDDEN && body["code"] == "token_kb_out_of_scope",+ "base b: {status} {body}"+ );+ let (status, body) = f.create_kb(&token, "new").await?;+ anyhow::ensure!(+ status == StatusCode::FORBIDDEN && body["code"] == "token_kb_out_of_scope",+ "new base: {status} {body}"+ );++ let (status, listed) = f.list_kbs(&token).await?;+ let names: Vec<&str> = listed+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|kb| kb["name"].as_str())+ .collect();+ anyhow::ensure!(+ status == StatusCode::OK && names == ["a"],+ "{status} {listed}"+ );+ anyhow::Ok(())+ }+ .await;+ f.cleanup().await?;+ result+}diff --git a/crates/utopia-server/src/auth.rs b/crates/utopia-server/src/auth.rsindex bc150f3b..fe061e70 100644--- a/crates/utopia-server/src/auth.rs+++ b/crates/utopia-server/src/auth.rs@@ -134,6 +134,22 @@ pub(crate) fn decode_user_id(state: &AppState, token: &str) -> Result<Uuid, AppEOk(data.claims.sub)}+/// 请求带来的凭据:Cookie `utopia_token` 优先,其次 `Authorization: Bearer`。+fn presented_credential(parts: &Parts) -> Result<String, AppError> {+ CookieJar::from_headers(&parts.headers)+ .get(COOKIE_NAME)+ .map(|c| c.value().to_string())+ .or_else(|| {+ parts+ .headers+ .get(axum::http::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("Bearer "))+ .map(|v| v.to_string())+ })+ .ok_or(AppError::Unauthorized)+}+/// 已登录用户提取器:Cookie `utopia_token` 或 `Authorization: Bearer`。pub struct AuthUser(pub User);@@ -144,20 +160,7 @@ impl FromRequestParts<AppState> for AuthUser {parts: &mut Parts,state: &AppState,) -> Result<Self, Self::Rejection> {- let jar = CookieJar::from_headers(&parts.headers);- let token = jar- .get(COOKIE_NAME)- .map(|c| c.value().to_string())- .or_else(|| {- parts- .headers- .get(axum::http::header::AUTHORIZATION)- .and_then(|v| v.to_str().ok())- .and_then(|v| v.strip_prefix("Bearer "))- .map(|v| v.to_string())- })- .ok_or(AppError::Unauthorized)?;-+ let token = presented_credential(parts)?;let user_id = decode_user_id(state, &token)?;let user = utopia_store::accounts::find_user_by_id(&state.pool, user_id).await?@@ -166,6 +169,81 @@ impl FromRequestParts<AppState> for AuthUser {}}+/// 会话或个人令牌,二者都落到同一个 `User` 上(0014 决定 6,#1243)。+///+/// **不替换 `AuthUser`。** `AuthUser` 把每个 Bearer 都当 JWT 解,令牌在那几百条+/// 路由上一律是 401——那是有意的:哪条路由准令牌进来,要在 0014 里说出理由。+/// 用这个提取器的只有文档原件(0052)和「把一个库搭起来」那几条。+///+/// 令牌只收窄:`pat` 在的时候,路由先问 [`Self::require_write`] 或+/// [`Self::reaches`],角色照旧由 `require_kb` 与工作区角色判。+pub struct SessionOrToken {+ pub user: User,+ /// None = 网页会话,不收窄任何东西+ pub pat: Option<utopia_store::tokens::Authenticated>,+}++impl FromRequestParts<AppState> for SessionOrToken {+ type Rejection = ApiErr;++ async fn from_request_parts(+ parts: &mut Parts,+ state: &AppState,+ ) -> Result<Self, Self::Rejection> {+ let raw = presented_credential(parts)?;+ // 过期与撤销在 `authenticate` 的 SQL 里判;停用的人 `find_user_by_id` 挡住+ let (user_id, pat) = if raw.starts_with(utopia_store::tokens::PREFIX) {+ let pat = utopia_store::tokens::authenticate(&state.pool, raw.trim()).await?;+ (pat.user_id, Some(pat))+ } else {+ (decode_user_id(state, &raw)?, None)+ };+ let user = utopia_store::accounts::find_user_by_id(&state.pool, user_id)+ .await?+ .ok_or(AppError::Unauthorized)?;+ Ok(Self { user, pat })+ }+}++impl SessionOrToken {+ /// 代人行事的那枚令牌;会话是 None。审计行靠它分得出是哪一枚(0014 决定 6)+ pub fn token_id(&self) -> Option<Uuid> {+ self.pat.as_ref().map(|pat| pat.token_id)+ }++ /// 令牌有没有把这个库排除掉。会话什么都不排除;这不是权限,权限归角色+ pub fn reaches(&self, kb_id: Uuid) -> bool {+ self.pat.as_ref().is_none_or(|pat| pat.covers(kb_id))+ }++ /// 令牌准不准往这个库里写。`None` 是一个还不存在的库:限定过 `kb_ids` 的令牌+ /// 列表里不可能有它,所以建库只给不限库的令牌。+ ///+ /// 两种拒绝各带 code:它们都是「换一枚令牌就行」,与角色不够的 403 不是一回事+ pub fn require_write(&self, kb_id: Option<Uuid>) -> Result<(), AppError> {+ let Some(pat) = &self.pat else {+ return Ok(());+ };+ if !pat.can_write() {+ return Err(AppError::CodedForbidden {+ code: "token_read_only",+ message: "This token is read-only; issue one with the write scope".into(),+ });+ }+ let in_scope = match kb_id {+ Some(kb_id) => pat.covers(kb_id),+ None => pat.kb_ids.is_none(),+ };+ if !in_scope {+ return Err(AppError::CodedForbidden {+ code: "token_kb_out_of_scope",+ message: "This token reaches only the knowledge bases it lists".into(),+ });+ }+ Ok(())+ }+}+/// 生成一条 JWT 签名密钥:32 字节 CSPRNG,hex 编码成 64 个字符。////// 长度取 32 字节是因为 HS256 的 HMAC 块就是 32 字节——再长会被先哈希一遍,diff --git a/crates/utopia-server/src/error.rs b/crates/utopia-server/src/error.rsindex 6afcb3ee..a11a2879 100644--- a/crates/utopia-server/src/error.rs+++ b/crates/utopia-server/src/error.rs@@ -33,6 +33,10 @@ impl IntoResponse for ApiErr {AppError::NotFound => (StatusCode::NOT_FOUND, self.0.to_string()),AppError::Unauthorized => (StatusCode::UNAUTHORIZED, self.0.to_string()),AppError::Forbidden => (StatusCode::FORBIDDEN, self.0.to_string()),+ AppError::CodedForbidden { code: c, message } => {+ code = Some(c);+ (StatusCode::FORBIDDEN, message.clone())+ }AppError::CodedConflict { code: c, message } => {code = Some(c);(StatusCode::CONFLICT, message.clone())@@ -90,6 +94,14 @@ mod tests {(AppError::Conflict("legacy".into()), 409, None),(AppError::Unauthorized, 401, None),(AppError::Forbidden, 403, None),+ (+ AppError::CodedForbidden {+ code: "token_read_only",+ message: "read-only".into(),+ },+ 403,+ Some("token_read_only"),+ ),(AppError::NotFound, 404, None),(AppError::invalid("bad_input", "invalid"),diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rsindex 09d69dc3..f5443ba0 100644--- a/crates/utopia-server/src/owl_import.rs+++ b/crates/utopia-server/src/owl_import.rs@@ -401,10 +401,13 @@ pub async fn relink_domains_ranges(/// 执行计划。属性在类之后落库——它们要挂在 domain 上,而 domain 要等/// 类先建好并解析 IRI → id(就是下面那个 `id_of`)。+///+/// `via_token`:代 `actor` 导入的那枚令牌,只进审计行(0014 决定 6);会话是 Nonepub async fn apply(state: &AppState,kb_id: Uuid,actor: Uuid,+ via_token: Option<Uuid>,filename: &str,bytes: &[u8],) -> AppResult<(Uuid, ImportPlan)> {@@ -771,7 +774,7 @@ pub async fn apply("ontology.imported","kb",Some(kb_id),- summary,+ utopia_store::audit::via_token(summary, via_token),).await;// 本体刚变过,向量都是陈的。**排任务而不是就地跑**:这一趟要嵌几千行,diff --git a/crates/utopia-store/src/audit.rs b/crates/utopia-store/src/audit.rsindex 64ae8c89..64e6532a 100644--- a/crates/utopia-store/src/audit.rs+++ b/crates/utopia-store/src/audit.rs@@ -27,6 +27,18 @@ pub async fn record(.await}+/// 令牌代人做的动作在 detail 里记下是哪一枚(0014 决定 6):撤销之前,管理员要查得出+/// 这枚令牌做过什么。会话来的(None)原样返回+pub fn via_token(mut detail: serde_json::Value, token_id: Option<Uuid>) -> serde_json::Value {+ if let (Some(token_id), Some(fields)) = (token_id, detail.as_object_mut()) {+ fields.insert(+ "token_id".into(),+ serde_json::Value::String(token_id.to_string()),+ );+ }+ detail+}+/// 请求的来源信息。由 HTTP 层在每个请求外层 scope 进 [`CLIENT`],`record_opt`/// 自行读取——否则 25 个调用点每一个都要多带两个与业务无关的参数。///diff --git a/docs/decisions/0014-identity-from-the-person-scope-from-the-token.md b/docs/decisions/0014-identity-from-the-person-scope-from-the-token.mdindex 898b5fb6..8c83b864 100644--- a/docs/decisions/0014-identity-from-the-person-scope-from-the-token.md+++ b/docs/decisions/0014-identity-from-the-person-scope-from-the-token.md@@ -1,6 +1,6 @@# 0014 · Identity from the person, scope from the token-- **Status**: Implemented (#180) · open: `can_write` is hard-coded false+- **Status**: Implemented · 2026-10-15 · #180, #318, #1243 · open: tokens across workspaces- **Written**: 2026-09-01 · condensed into English 2026-09-03- **Related**: migration `0014_data_source_grants` gave data sources a grant layer; this is the same question where a machine knocks. [0004](0004-language-and-localization.md) has the server speak English only, MCP error codes included. [0015](0015-recording-a-sentence-is-not-asserting-a-fact.md) removes the main objection to opening `remember` over MCP.@@ -54,6 +54,35 @@ push documents in.`require_kb`; a token revoked mid-session fails on its next call. Each call writes an auditrow (`mcp.tool_called`, target = the token), so attribution is real.+6. **A write token may set up a base** (added 2026-10-15, #1243). A repository mirrored into+ Utopia gets a base and a `statements` source; the push is the source key's job (0054), but+ creating the base and the source took a session, so a backend either held someone's seven-day+ JWT or a person did it by hand for each repository. Five routes now also take a personal+ token with `write` scope, acting as its owner: creating a base in a workspace, creating a+ source, reading a source's push key, importing an ontology, and deciding where a kind word+ binds. Listing a workspace's bases takes any token, so a client can find a base by name+ before it creates one. The reasons above hold unchanged. The actor is still the living person+ (`audit_events.actor_id` is theirs, as from a session); the person's role is still the+ ceiling, checked by the same `require_kb` and workspace role as before, so a token whose+ owner is not a workspace admin creates no base, and a system admin's write token acts as+ Owner in every base, as the admin does; writing must still be ticked, and a read-only token+ is refused with `token_read_only`; a token limited by `kb_ids` reaches only those bases, and+ it cannot create one, since a base that does not exist yet is in no list+ (`token_kb_out_of_scope`); revocation and expiry are judged in SQL on every request. Nothing+ here is a base-level machine token or a service account. A token creates only `statements`+ sources: a `url`, `rss` or `custom` source starts the server fetching on a schedule, with+ stored credentials for `custom`, which would turn a leaked CI token into a way to make the+ server call any address; other kinds from a token are refused with `token_source_kind`, and a+ session still creates every kind. The audit rows these routes write (`source.created`,+ `alignment.kind_word_decided`, `ontology.imported`) carry the acting token's id as+ `detail.token_id`, so before revoking a leaked token an admin can see what it did (decision+ 5). One extractor, `SessionOrToken`, takes either credential, and only these routes and+ document content (0052) use it; `AuthUser` still reads every bearer as a JWT, so the routes+ behind it stay session-only until someone has a reason to open one and says it here.++ Not done: rotating or deleting a source, changing a base's settings or members, and every+ other write still take a session. A token does not create workspaces or tokens.+## Dead ends- **Base-level machine tokens**, one per base and unrelated to a person. It would be a third@@ -72,6 +101,10 @@ push documents in.the server lives in `utopia-server/src/api/mcp.rs`. Deleted with `utopia-graph` and`utopia-connectors` ([0016](0016-close-the-open-seams-before-cutting-new-ones.md) A2).+- 2026-10-15: the status line still said `can_write` was hard-coded false. #318 had already+ computed it from the token's scope and the person's role, and `remember` has been reachable+ over MCP with a write token since then. The line now names what is open.+## Open questions- **`query_data` and `remember` over MCP.** The first version ships `search_chunks`,diff --git a/docs/design/access-and-audit.md b/docs/design/access-and-audit.mdindex cdef5117..4f83985d 100644--- a/docs/design/access-and-audit.md+++ b/docs/design/access-and-audit.md@@ -16,7 +16,11 @@ SHA-256 hash, `scope` read or write, `kb_ids` or every base, `expires_at` with 9default, `last_used_at`, `revoked_at` as a trace); effective permission is the person's roleintersected with the token's scope; every MCP call re-runs authentication, scope and role in SQL andwrites an audit row `mcp.tool_called`; the tokens page shows the plaintext once beside a client-snippet [0014]. `ingest_token` on a source is a different kind: plaintext, push-only [0014].+snippet [0014]. A `write` token also sets up a base as its owner: creating a base and a `statements` source,+reading the source's push key, importing an ontology and deciding a kind word, with the owner's+role unchanged as the ceiling; any token lists a workspace's bases; a token limited by `kb_ids`+creates no base. These routes and document content take `SessionOrToken`; apart from MCP, every+other route is session-only [0014 d6]. `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@@ -80,5 +84,3 @@ removed or renamed only with a record [0020 revised].- 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 #735- exercises `remember` over MCP with a write token; check the code before relying on either.