From f5bf95aeeaf55e5e8f31b9ac6e9226fab9ec5efa Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Sun, 29 Nov 2026 22:10:26 +0800 Subject: [PATCH 1/5] Add onboarding helpers to the Rust SDK Let applications label operation calls, inspect token claims and operation roles, and request the Loom guide or Mentor brief without installing a plugin. Signed-off-by: zhangxiaoyu.york --- sdk/rust/Cargo.toml | 1 + sdk/rust/README.md | 64 ++++++- sdk/rust/src/blocking.rs | 65 ++++++- sdk/rust/src/capabilities.rs | 84 ++++++++- sdk/rust/src/client.rs | 252 +++++++++++++++++++++++++-- sdk/rust/src/lib.rs | 42 ++++- sdk/rust/src/token.rs | 248 ++++++++++++++++++++++++++ sdk/rust/tests/blocking_cases/mod.rs | 41 ++++- sdk/rust/tests/client.rs | 186 +++++++++++++++++++- sdk/rust/tests/probe/mod.rs | 162 +++++++++++++++++ 10 files changed, 1118 insertions(+), 27 deletions(-) create mode 100644 sdk/rust/src/token.rs diff --git a/sdk/rust/Cargo.toml b/sdk/rust/Cargo.toml index 5685f8d132a..4adba4140f4 100644 --- a/sdk/rust/Cargo.toml +++ b/sdk/rust/Cargo.toml @@ -17,6 +17,7 @@ name = "blocking" required-features = ["blocking"] [dependencies] +base64 = "0.22" reqwest = { version = "0.12.28", default-features = false, features = [ "json", "rustls-tls", diff --git a/sdk/rust/README.md b/sdk/rust/README.md index 3b0bc6c3e0d..af99a340bad 100644 --- a/sdk/rust/README.md +++ b/sdk/rust/README.md @@ -47,7 +47,7 @@ application's dependencies. The crate name is `clickhouse-loom`; Rust imports it as `clickhouse_loom`. The repository build uses reqwest with Rustls and HTTP/2. It also depends on -serde, serde_json, Tokio, rand, uuid, httpdate, log and derive_more. +serde, serde_json, Tokio, rand, uuid, httpdate, log, derive_more and base64. ## Use @@ -108,7 +108,8 @@ Server setup is covered in the ## Configuration `Client::builder(org, namespace, agent)` accepts `base_url`, `api_key`, `timeout`, -`user_id`, `session_id`, `run_id`, `retry`, `pacing` and `ratelimit_max_wait`. +`user_id`, `session_id`, `run_id`, `consumer`, `retry`, `pacing` and +`ratelimit_max_wait`. The default timeout is 60 seconds per attempt. It covers the whole HTTP request and response body. The server address comes from `LOOM_BASE_URL`, defaulting to `http://localhost:7777`. The token comes from `LOOM_API_KEY`; without a token, @@ -116,6 +117,20 @@ requests carry no Authorization header. Explicit settings override the environment. `.api_key("")` disables authorization. Empty environment values are treated as unset. +An empty org lets Loom resolve it from the configured plane, token, or local +installation. On a tokenless single-user server, an empty namespace lets Loom +fill the namespace for supported memory and search operations. Empty builder +values leave an org or namespace named in a request intact. Supply a namespace +when the operation requires an explicit target. + +A blank agent name uses `sdk-rust:`, based on the executable's name. +Explicit `"-"` and `"*"` retain their operation-specific meanings. + +`.consumer(label)` names the product this process speaks for. The label is +stamped on every operation body that names none (absent, null, empty or `-`); +a body that names its own takes precedence. A consumer claim in the verified +token takes precedence on the server. An empty builder label stamps nothing. + Builder identity values apply to declared caller and authorship fields. `knowledge_add` and `knowledge_upsert` receive agent and session identity; `observe_record` receives user, session and run identity. `conversation_create` @@ -560,6 +575,51 @@ An empty request returns `ok = true`. with the capability response's metadata. The blocking client provides the same methods without `.await`. +## What the token may call + +`token_claims` decodes the bearer token's payload without verifying it. +`permissions(max_age)` returns the deployment's served +operations paired with those claims, reusing a snapshot at most `max_age` old; +a zero age fetches again. `can_call(op)` compares the declared minimum role +with the token's claimed role and write scope for the client's explicit org and +namespace. It returns `None` if the SDK cannot make that comparison. The server +checks live grants, revocation and other policies on every call. + +```rust +# async fn example(bot: clickhouse_loom::Client) -> Result<(), clickhouse_loom::Error> { +let write_hint = bot.can_call("memory.set").await?; +let caps = bot.permissions(std::time::Duration::ZERO).await?; +println!("write role hint: {write_hint:?}; build: {}", caps.build_commit); +# Ok(()) +# } +``` + +## Guide and mentor + +`guide(part)` returns `mentor.guide` as Markdown for the system prompt of an +agent that has no plugin to carry it: `MentorGuideInputPart::Skill` is the loop, +where each kind of state goes and how to read answers; `Reference` is every +plane with its operations; `All` is both. + +`mentor()` returns `mentor.brief` for this identity over the server's default +window: the planes it never uses, the hints with the counts behind them, and +whether past hints were followed. `mentor_with_window(seconds)` requests a +lookback window. + +```rust +use clickhouse_loom::{Client, MentorGuideInputPart}; + +# async fn example(bot: Client) -> Result<(), clickhouse_loom::Error> { +let _skill = bot.guide(MentorGuideInputPart::All).await?; +let brief = bot.mentor_with_window(7 * 24 * 3600).await?; +println!("{} sessions, {} hints", brief.sessions, brief.hints.len()); +# Ok(()) +# } +``` + +Guide and mentor calls use a ten second timeout per attempt. They run only +when called. The blocking client provides the same methods without `.await`. + ## Blocking calls Enable the feature in the consuming application's `Cargo.toml`: diff --git a/sdk/rust/src/blocking.rs b/sdk/rust/src/blocking.rs index bf65fab184f..09d8097c2a0 100644 --- a/sdk/rust/src/blocking.rs +++ b/sdk/rust/src/blocking.rs @@ -9,7 +9,8 @@ use serde::{de::DeserializeOwned, Serialize}; use tokio::sync::mpsc; use crate::{ - CallFailure, CallOptions, CallResult, Error, RetryPolicy, RouteRequest, RouteResponse, + CallFailure, CallOptions, CallResult, Capabilities, Error, RetryPolicy, RouteRequest, + RouteResponse, TokenClaims, }; type Job = Box Pin + Send>> + Send>; @@ -34,6 +35,7 @@ impl Drop for Worker { pub struct Client { worker: Arc, retry: Option, + claims: Option>, } /// Endpoint, identity and retry settings for a synchronous client. @@ -126,6 +128,43 @@ impl Client { }) } + /// The deployment's served operations with this token's claims; see + /// [`crate::Client::permissions`]. + pub fn permissions(&self, max_age: Duration) -> Result { + self.onboarding(move |client| async move { client.permissions(max_age).await }) + } + + /// Whether this client's token may call `op`; see [`crate::Client::can_call`]. + pub fn can_call(&self, op: &str) -> Result, Error> { + let op = op.to_owned(); + self.onboarding(|client| async move { client.can_call(&op).await }) + } + + /// The unverified bearer token payload; see [`crate::Client::token_claims`]. + pub fn token_claims(&self) -> Option<&TokenClaims> { + self.claims.as_deref() + } + + /// How to use Loom, as Markdown; see [`crate::Client::guide`]. + pub fn guide(&self, part: crate::MentorGuideInputPart) -> Result { + self.onboarding(move |client| async move { client.guide(part).await }) + } + + /// The store's advice to this agent; see [`crate::Client::mentor`]. + pub fn mentor(&self) -> Result { + self.onboarding(|client| async move { client.mentor().await }) + } + + /// [`crate::Client::mentor`] over the last `window_seconds`. + pub fn mentor_with_window( + &self, + window_seconds: i64, + ) -> Result { + self.onboarding( + move |client| async move { client.mentor_with_window(window_seconds).await }, + ) + } + pub fn get_with_options( &self, memory_key: &str, @@ -245,6 +284,22 @@ impl Client { .map_err(|_| worker_error())?; receiver.recv().map_err(|_| worker_error())? } + + fn onboarding(&self, job: F) -> Result + where + F: FnOnce(crate::Client) -> Fut + Send + 'static, + Fut: Future> + Send + 'static, + { + let retry = self.retry.clone(); + self.submit(move |client| async move { + let client = match retry { + Some(retry) => client.with_retry(retry)?, + None => client, + }; + Ok(job(client).await?) + }) + .map_err(|failure| failure.error) + } } fn worker_error() -> CallFailure { @@ -275,6 +330,7 @@ impl ClientBuilder { setting!(user_id, impl Into); setting!(session_id, impl Into); setting!(run_id, impl Into); + setting!(consumer, impl Into); setting!(timeout, Duration); setting!(retry, RetryPolicy); setting!(pacing, bool); @@ -306,7 +362,7 @@ impl ClientBuilder { return; } }; - if ready.send(Ok(())).is_err() { + if ready.send(Ok(client.token_claims().cloned())).is_err() { return; } while let Some(job) = receiver.recv().await { @@ -318,12 +374,13 @@ impl ClientBuilder { Error::Configuration(format!("cannot start blocking worker: {error}")) })?; match startup.recv() { - Ok(Ok(())) => Ok(Client { + Ok(Ok(claims)) => Ok(Client { worker: Arc::new(Worker { sender: Some(sender), thread: Some(worker), }), retry: None, + claims: claims.map(Arc::new), }), result => { drop(sender); @@ -333,7 +390,7 @@ impl ClientBuilder { Err(_) => Err(Error::Configuration( "blocking client worker stopped during startup".into(), )), - Ok(Ok(())) => unreachable!("success handled above"), + Ok(Ok(_)) => unreachable!("success handled above"), } } } diff --git a/sdk/rust/src/capabilities.rs b/sdk/rust/src/capabilities.rs index 3afc1d7a995..1194379c232 100644 --- a/sdk/rust/src/capabilities.rs +++ b/sdk/rust/src/capabilities.rs @@ -1,6 +1,12 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::{ + collections::{BTreeMap, BTreeSet}, + time::{Duration, Instant}, +}; -use crate::OpsCapabilitiesOutput; +use crate::{ + token::{claim_allows, role_on}, + OpCapability, OpsCapabilitiesOutput, TokenClaims, +}; /// Operations and request fields an application needs from the server. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -32,6 +38,80 @@ impl ProbeRequest { } } +/// What the deployment serves and what this token may call. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub struct Capabilities { + served: BTreeMap, + pub build_commit: String, + pub schema_version: String, + /// The bearer token's payload; `None` when it is not a decodable JWT. + pub claims: Option, + fetched_at: Instant, +} + +impl Capabilities { + pub(crate) fn new(output: OpsCapabilitiesOutput, claims: Option) -> Self { + let served = output + .ops + .into_iter() + .filter(|op| !op.name.is_empty()) + .map(|mut op| { + op.required_role = op.required_role.to_lowercase(); + (op.name.clone(), op) + }) + .collect(); + Self { + served, + build_commit: output.build_commit, + schema_version: output.schema_version, + claims, + fetched_at: Instant::now(), + } + } + + /// The served operations by name, each with its lowercased required role. + pub fn ops(&self) -> &BTreeMap { + &self.served + } + + /// The deployment serves this op. + pub fn has(&self, op: &str) -> bool { + self.served.contains_key(op) + } + + /// The op's minimum role, lowercased, when served and declared. + pub fn required_role(&self, op: &str) -> Option<&str> { + let role = self.served.get(op)?.required_role.trim(); + (!role.is_empty()).then_some(role) + } + + /// The token's role on `namespace`; `None` when unknown. + pub fn role(&self, namespace: Option<&str>) -> Option<&str> { + role_on(self.claims.as_ref(), namespace) + } + + /// Compare the named namespace's token role with the operation's declared + /// role. `None` means the comparison is unavailable. Live authorization + /// can differ from this hint. + pub fn can_call(&self, op: &str, namespace: Option<&str>) -> Option { + claim_allows(self.claims.as_ref()?, namespace?, self.required_role(op)?) + } + + /// Served ops whose declared role the token matches, sorted by name. + pub fn callable(&self, namespace: Option<&str>) -> Vec { + self.served + .keys() + .filter(|op| self.can_call(op, namespace) == Some(true)) + .cloned() + .collect() + } + + pub(crate) fn age(&self) -> Duration { + self.fetched_at.elapsed() + } +} + /// A capability comparison. Missing capabilities do not produce an error. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] diff --git a/sdk/rust/src/client.rs b/sdk/rust/src/client.rs index 8f6bd51781d..69c39e3ae3e 100644 --- a/sdk/rust/src/client.rs +++ b/sdk/rust/src/client.rs @@ -1,6 +1,7 @@ use std::{ collections::HashMap, env, fmt, + path::Path, sync::Arc, time::{Duration, Instant}, }; @@ -14,12 +15,22 @@ use serde::{de::DeserializeOwned, Serialize}; use serde_json::{json, Value}; use crate::{ - ApiError, CallFailure, CallMetadata, CallOptions, CallResult, DeleteResponse, Error, - GetResponse, RetryPolicy, SearchRequest, SearchResponse, SetRequest, SetResponse, + token::decode_token_claims, ApiError, CallFailure, CallMetadata, CallOptions, CallResult, + Capabilities, DeleteResponse, Error, GetResponse, RetryPolicy, SearchRequest, SearchResponse, + SetRequest, SetResponse, TokenClaims, }; use tokio::sync::Mutex; const DEFAULT_URL: &str = "http://localhost:7777"; +/// How long a capabilities snapshot answers `can_call` before it is fetched again. +const CAPS_MAX_AGE: Duration = Duration::from_secs(60); +/// The guide and the mentor's advice are fetched under a short timeout, so a +/// call at startup does not stall on them. +const ADVICE_TIMEOUT: Duration = Duration::from_secs(10); + +fn advice_options() -> CallOptions { + CallOptions::default().timeout(ADVICE_TIMEOUT) +} macro_rules! typed_call { ($method:ident, $with_options:ident, $request:ty, $response:ty, $op:literal) => { @@ -50,10 +61,13 @@ pub struct Client { pub(crate) base_url: Url, authorization: Option, identity: Value, + consumer: String, + claims: Option, retry: RetryPolicy, pub(crate) pacing: bool, pub(crate) ratelimit_max_wait: Duration, rate_state: Arc>>, + capabilities: Arc>>, } /// Explicit endpoint and token options override LOOM_BASE_URL and LOOM_API_KEY. @@ -61,6 +75,7 @@ pub struct ClientBuilder { base_url: Option, api_key: Option, identity: Value, + consumer: String, timeout: Duration, retry: RetryPolicy, pacing: bool, @@ -92,6 +107,7 @@ impl Client { base_url: None, api_key: None, identity: json!({"org": org.into(), "namespace": namespace.into(), "agent": agent.into()}), + consumer: String::new(), timeout: Duration::from_secs(60), retry: RetryPolicy::default(), pacing: true, @@ -124,6 +140,100 @@ impl Client { }) } + /// The bearer token's payload, decoded and not verified; `None` without a JWT. + /// + /// The server verifies every call. The SDK uses the claims for role hints. + pub fn token_claims(&self) -> Option<&TokenClaims> { + self.claims.as_ref() + } + + /// The deployment's served operations with this token's claims. + /// + /// A snapshot at most `max_age` old is reused; a zero age fetches again. A + /// failed fetch is an error and is not cached. + pub async fn permissions(&self, max_age: Duration) -> Result { + let mut cache = self.capabilities.lock().await; + if let Some(caps) = cache + .as_ref() + .filter(|caps| !max_age.is_zero() && caps.age() <= max_age) + { + return Ok(caps.clone()); + } + let output = self + .capabilities(crate::OpsCapabilitiesInput::new()) + .await?; + let caps = Capabilities::new(output, self.claims.clone()); + *cache = Some(caps.clone()); + Ok(caps) + } + + /// Compare the token's claimed role and write scope with the requirement + /// for `op` on this client's explicit org and namespace. `None` means the + /// comparison is unavailable. The server checks live grants and policies. + pub async fn can_call(&self, op: &str) -> Result, Error> { + let org = self.identity["org"].as_str().unwrap_or_default().trim(); + let namespace = self.identity["namespace"] + .as_str() + .unwrap_or_default() + .trim(); + let Some(token_org) = self.token_claims().and_then(|claims| claims.org.as_deref()) else { + return Ok(None); + }; + // A blank org uses server resolution; a plane default can differ from + // the token's org. Explicit target operations are not this bound scope. + if org != token_org || crate::token::role_on(self.token_claims(), Some(namespace)).is_none() + { + return Ok(None); + } + let binds_namespace = crate::wire_models::OP_POLICIES + .iter() + .any(|(name, _, _, keys, _)| *name == op && keys.contains(&"namespace")); + if !binds_namespace { + return Ok(None); + } + let caps = self.permissions(CAPS_MAX_AGE).await?; + Ok(caps.can_call(op, Some(namespace))) + } + + /// How to use Loom, as Markdown: `Skill` is the loop, where each kind of + /// state goes and how to read answers; `Reference` is every plane with its + /// operations; `All` is both. Put it in the system prompt of an agent that + /// has no plugin to carry it. + pub async fn guide(&self, part: crate::MentorGuideInputPart) -> Result { + self.mentor_guide_with_options(crate::MentorGuideInput::new().part(part), advice_options()) + .await + .map(|result| result.data.text) + .map_err(|failure| failure.error) + } + + /// The store's advice to this agent: `mentor.brief` for this identity over + /// the server's default window, the planes it never uses, the hints with + /// the counts behind them, and whether past hints were followed. + pub async fn mentor(&self) -> Result { + self.brief(None).await + } + + /// [`Client::mentor`] with a requested lookback of `window_seconds`. + pub async fn mentor_with_window( + &self, + window_seconds: i64, + ) -> Result { + self.brief(Some(window_seconds)).await + } + + async fn brief(&self, window_seconds: Option) -> Result { + let agent = self.identity["agent"].as_str().unwrap_or_default(); + let request = crate::MentorBriefInput::new().agent(agent); + let request = match window_seconds { + Some(seconds) => request.window_seconds(seconds), + None => request, + }; + self.mentor_brief_with_options(request, advice_options()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + pub async fn set(&self, request: SetRequest) -> Result { self.set_with_options(request, CallOptions::default()) .await @@ -252,24 +362,39 @@ impl Client { if op == "memory.search" { // Search identity fields are filters; write authorship must not narrow recall. fields.entry("agent").or_insert_with(|| json!("*")); - for key in ["org", "namespace"] { - fields.insert(key.into(), self.identity[key].clone()); - } } // Only declared identity fields are stamped; optional reader filters survive. let identity_fields = policy.map_or(&["org", "namespace"][..], |(_, _, _, keys, _)| *keys); - for key in identity_fields { - if let Some(value) = self.identity.get(*key) { - fields.insert((*key).into(), value.clone()); + for &key in identity_fields { + if let Some(value) = self.identity.get(key) { + if matches!(key, "org" | "namespace") && value == "" { + // Keep the server's blank sentinel for known operations. + if key != "namespace" || policy.is_some() { + fields.entry(key).or_insert_with(|| value.clone()); + } + } else { + fields.insert(key.into(), value.clone()); + } } } if let Some((_, _, _, _, defaults)) = policy { for key in *defaults { if let Some(value) = self.identity.get(*key) { + if *key == "namespace" && value == "" { + continue; + } fields.entry(*key).or_insert_with(|| value.clone()); } } } + // A body that names its own consumer wins. + if !self.consumer.is_empty() + && fields + .get("consumer") + .is_none_or(|value| consumer_value(value).is_empty()) + { + fields.insert("consumer".into(), json!(self.consumer)); + } let url = self .base_url .join(&format!("v1/{op}")) @@ -487,6 +612,13 @@ impl ClientBuilder { self } + /// The product this process speaks for: stamped on every operation body + /// that names none and stored on the ledgers. An empty label stamps nothing. + pub fn consumer(mut self, consumer: impl Into) -> Self { + self.consumer = consumer_label(&consumer.into()); + self + } + pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = timeout; self @@ -511,15 +643,21 @@ impl ClientBuilder { pub fn build(self) -> Result { self.retry.validate()?; - for key in ["org", "namespace", "agent"] { - if self.identity[key].as_str().unwrap_or("").trim().is_empty() { - return Err(Error::Configuration(format!("{key} must not be empty"))); - } - } if self.timeout.is_zero() { return Err(Error::Configuration("timeout must be positive".into())); } - if let Some(run_id) = self.identity.get("run_id").and_then(Value::as_str) { + let mut identity = self.identity; + for key in ["org", "namespace"] { + if identity[key].as_str().unwrap_or("").trim().is_empty() { + identity[key] = json!(""); + } + } + if identity["agent"].as_str().unwrap_or("").trim().is_empty() { + let agent = default_agent_name(); + log::warn!(target: "clickhouse_loom", "agent name is blank; using {agent:?}"); + identity["agent"] = json!(agent); + } + if let Some(run_id) = identity.get("run_id").and_then(Value::as_str) { HeaderValue::from_str(run_id) .map_err(|_| Error::Configuration("invalid run ID header".into()))?; } @@ -554,6 +692,11 @@ impl ClientBuilder { Ok(header) }) .transpose()?; + let claims = authorization + .as_ref() + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.strip_prefix("Bearer ")) + .and_then(|value| decode_token_claims(Some(value))); let http = HttpClient::builder() .redirect(Policy::none()) .retry(reqwest::retry::never()) @@ -564,12 +707,63 @@ impl ClientBuilder { http, base_url, authorization, - identity: self.identity, + identity, + consumer: self.consumer, + claims, retry: self.retry, pacing: self.pacing, ratelimit_max_wait: self.ratelimit_max_wait, rate_state: Arc::new(Mutex::new(HashMap::new())), + capabilities: Arc::new(Mutex::new(None)), + }) + } +} + +/// A real name for an anonymous agent: the program under an `sdk-rust:` +/// prefix, so profiles, costs and provenance are per bot. +fn default_agent_name() -> String { + let program = env::args_os() + .next() + .and_then(|arg| { + Path::new(&arg) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) }) + .unwrap_or_default(); + let program = program + .strip_suffix(env::consts::EXE_EXTENSION) + .unwrap_or(&program); + format!( + "sdk-rust:{}", + if program.is_empty() { "bot" } else { program } + ) +} + +/// The server bounds the ledger's `consumer` column to this many characters. +const CONSUMER_MAX_CHARS: usize = 64; + +/// The `consumer` label as the server stores it: without control characters, +/// stripped, at most 64 characters; empty for a blank or the wire's `-`. +fn consumer_label(value: &str) -> String { + let text: String = value + .chars() + .filter(|c| *c == ' ' || (!c.is_control() && !c.is_whitespace())) + .collect(); + let text = text.trim(); + if text.is_empty() || text == "-" { + return String::new(); + } + text.chars().take(CONSUMER_MAX_CHARS).collect() +} + +/// The consumer a body names, read by the label rule; empty when it names none. +fn consumer_value(value: &Value) -> String { + match value { + Value::String(text) => consumer_label(text), + Value::Number(number) if !number.as_str().contains(['.', 'e', 'E']) => { + consumer_label(number.as_str()) + } + _ => String::new(), } } @@ -612,6 +806,7 @@ impl fmt::Debug for ClientBuilder { // An unvalidated URL can contain credentials, so omit it along with the token. f.debug_struct("ClientBuilder") .field("identity", &self.identity) + .field("consumer", &self.consumer) .field("timeout", &self.timeout) .finish_non_exhaustive() } @@ -631,6 +826,33 @@ mod tests { ); } + #[test] + fn consumer_labels_drop_control_characters_and_are_bounded() { + assert_eq!(consumer_label(" crm\u{b}\n "), "crm"); + assert_eq!(consumer_label(&"x".repeat(80)), "x".repeat(64)); + assert_eq!(consumer_label("a\u{a0}\u{2028}b"), "ab"); + assert_eq!(consumer_label("a b"), "a b"); + for blank in ["", " \t ", "-"] { + assert_eq!(consumer_label(blank), ""); + } + assert_eq!(consumer_value(&json!(7)), "7"); + assert_eq!(consumer_value(&json!(null)), ""); + assert_eq!(consumer_value(&json!(true)), ""); + } + + #[test] + fn a_blank_agent_is_named_after_the_program() { + let named = Client::builder(" ", " ", " \t").build().unwrap(); + let agent = named.identity["agent"].as_str().unwrap(); + assert!(agent.starts_with("sdk-rust:")); + assert_ne!(agent, "sdk-rust:"); + assert_eq!(named.identity["org"], ""); + assert_eq!(named.identity["namespace"], ""); + let client = Client::builder("org", "ns", "").build().unwrap(); + assert_eq!(client.identity["agent"], agent); + assert_eq!(client.identity["org"], "org"); + } + #[tokio::test] async fn rate_state_updates_capacity_and_ignores_incomplete_readings() { let client = Client::builder("org", "ns", "bot") diff --git a/sdk/rust/src/lib.rs b/sdk/rust/src/lib.rs index 6dd97831793..779bd527a4e 100644 --- a/sdk/rust/src/lib.rs +++ b/sdk/rust/src/lib.rs @@ -11,6 +11,9 @@ //! answers [`Error::category`] and [`Error::retryable`] with the server's //! declaration or the SDK's own class; an API error also has a typed //! [`ApiError::kind`]. +//! An empty org or namespace is left to the server, and a blank agent name +//! is replaced with `sdk-rust:`. [`ClientBuilder::consumer`] names the +//! product behind the calls and is stamped on every body that names none. //! Search defaults to all agents with no user or session filter. Set filters on //! [`SearchRequest`] explicitly. Builder identity values apply to declared identity //! fields; optional reader filters keep the values in the request. @@ -55,6 +58,41 @@ //! # } //! ``` //! +//! # What the token may call +//! +//! [`Client::token_claims`] decodes the bearer token's payload without +//! verifying it; the server verifies every call. [`Client::permissions`] pairs +//! the served operations with those claims. [`Client::can_call`] compares +//! the token's claimed role and write scope with the operation's requirement. +//! `None` means the comparison is unavailable. +//! +//! ``` +//! # async fn example(client: clickhouse_loom::Client) -> Result<(), clickhouse_loom::Error> { +//! let write_hint = client.can_call("memory.set").await?; +//! let caps = client.permissions(std::time::Duration::ZERO).await?; +//! println!("{} operations, build {}", caps.ops().len(), caps.build_commit); +//! println!("memory.set role hint: {write_hint:?}"); +//! # Ok(()) +//! # } +//! ``` +//! +//! # Guide and mentor +//! +//! [`Client::guide`] returns how to use Loom as Markdown, for the system +//! prompt of an agent that has no plugin to carry it. [`Client::mentor`] +//! returns the store's advice for the bound scope. +//! +//! ``` +//! use clickhouse_loom::{Client, MentorGuideInputPart}; +//! +//! # async fn example(client: Client) -> Result<(), clickhouse_loom::Error> { +//! let _skill = client.guide(MentorGuideInputPart::All).await?; +//! let brief = client.mentor_with_window(7 * 24 * 3600).await?; +//! println!("{} sessions, {} hints", brief.sessions, brief.hints.len()); +//! # Ok(()) +//! # } +//! ``` +//! //! # Per-call options and metadata //! //! [`CallOptions`] overrides timeout, retry policy and request identifiers for @@ -202,6 +240,7 @@ mod models; mod operations; mod retry; mod routes; +mod token; mod wire_models; #[cfg(feature = "blocking")] @@ -210,10 +249,11 @@ pub mod blocking; mod blocking_operations; pub use call::{CallFailure, CallMetadata, CallOptions, CallResult, RateLimit}; -pub use capabilities::{ProbeReport, ProbeRequest}; +pub use capabilities::{Capabilities, ProbeReport, ProbeRequest}; pub use client::{Client, ClientBuilder}; pub use error::{ApiError, Error, ErrorCategory, ErrorKind}; pub use models::*; pub use retry::{RetryPolicy, RetryTimeouts}; pub use routes::{Method, RouteRequest, RouteResponse}; +pub use token::TokenClaims; pub use wire_models::*; diff --git a/sdk/rust/src/token.rs b/sdk/rust/src/token.rs new file mode 100644 index 00000000000..4dc697b3b1e --- /dev/null +++ b/sdk/rust/src/token.rs @@ -0,0 +1,248 @@ +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use serde_json::Value; + +/// Ascending privilege, mirroring the server's role order. +const ROLE_RANK: [(&str, u8); 5] = [ + ("viewer", 10), + ("writer", 20), + ("admin", 30), + ("org_admin", 40), + ("platform_admin", 50), +]; + +/// What the bearer token says about its holder. +/// +/// The payload is decoded without verifying the signature. The server verifies +/// every call. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct TokenClaims { + pub subject: Option, + pub org: Option, + pub namespaces: Vec, + /// The `ns_write` claim; an empty list does not narrow writes. + pub write_namespaces: Vec, + /// Flat roles of unscoped and wildcard tokens, lowercased. + pub roles: Vec, + /// Per-namespace role of a scoped token, authoritative where present. + pub ns_roles: Vec<(String, String)>, + pub exp: Option, +} + +/// The token's payload, or `None` when it is not a decodable JWT. +pub(crate) fn decode_token_claims(token: Option<&str>) -> Option { + let token = token.filter(|token| !token.is_empty())?; + let mut segments = token.split('.'); + segments.next()?; // the header is not read + let payload = segments.next()?; + let payload: Value = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload).ok()?).ok()?; + segments.next()?; // the signature is not verified + if segments.next().is_some() || !payload.is_object() { + return None; + } + let text = |key: &str| payload.get(key).and_then(Value::as_str).map(str::to_owned); + let strings = |key: &str| -> Vec { + payload + .get(key) + .and_then(Value::as_array) + .map(|values| { + values + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default() + }; + let mut ns_roles = Vec::new(); + match payload.get("ns_roles") { + Some(Value::Object(map)) => ns_roles.extend(map.iter().filter_map(|(namespace, role)| { + Some((namespace.clone(), role.as_str()?.to_ascii_lowercase())) + })), + None | Some(Value::Null) => {} + _ => return None, + } + Some(TokenClaims { + subject: text("sub"), + org: text("org"), + namespaces: strings("namespaces"), + write_namespaces: strings("ns_write"), + roles: strings("roles") + .into_iter() + .map(|role| role.to_ascii_lowercase()) + .collect(), + ns_roles, + exp: payload.get("exp").and_then(Value::as_i64), + }) +} + +fn rank(role: &str) -> Option { + ROLE_RANK + .iter() + .find(|(known, _)| *known == role) + .map(|(_, rank)| *rank) +} + +fn best<'a>(roles: impl Iterator) -> Option<&'a str> { + let mut top: Option<(&str, u8)> = None; + for role in roles { + if let Some(rank) = rank(role) { + if top.is_none_or(|(_, top_rank)| rank > top_rank) { + top = Some((role, rank)); + } + } + } + top.map(|(role, _)| role) +} + +/// The role a token holds on `namespace`: the scoped entry when the token has +/// a map, else its highest flat role. `None` when the token says nothing. +pub(crate) fn role_on<'a>( + claims: Option<&'a TokenClaims>, + namespace: Option<&str>, +) -> Option<&'a str> { + let claims = claims?; + let namespace = namespace.filter(|ns| !matches!(*ns, "" | "-" | "*" | "@me"))?; + if namespace.starts_with("col-") || namespace.starts_with("me-") { + return None; + } + if !claims.ns_roles.is_empty() { + return claims.ns_roles.iter().find_map(|(known, role)| { + (known == namespace && matches!(role.as_str(), "viewer" | "writer" | "admin")) + .then_some(role.as_str()) + }); + } + if !claims + .namespaces + .iter() + .any(|ns| ns == namespace || ns == "*") + { + return None; + } + best(claims.roles.iter().map(String::as_str)) +} + +pub(crate) fn claim_allows(claims: &TokenClaims, namespace: &str, required: &str) -> Option { + let required = rank(required)?; + let role = rank(role_on(Some(claims), Some(namespace))?)?; + let in_write_scope = required < 20 + || claims.write_namespaces.is_empty() + || claims + .write_namespaces + .iter() + .any(|ns| ns == namespace || ns == "*"); + Some(role >= required && in_write_scope) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_payload_is_decoded_from_url_safe_base64() { + let payload = br#"{"sub":"sa:bot","org":"acme","namespaces":["eng","ops"],"ns_write":["ops"],"roles":["WRITER"],"ns_roles":{"eng":"Viewer"},"exp":1900000000}"#; + let claims_segment = URL_SAFE_NO_PAD.encode(payload); + let claims = + decode_token_claims(Some(&format!("header.{claims_segment}.signature"))).unwrap(); + assert_eq!(claims.subject.as_deref(), Some("sa:bot")); + assert_eq!(claims.org.as_deref(), Some("acme")); + assert_eq!(claims.namespaces, ["eng", "ops"]); + assert_eq!(claims.write_namespaces, ["ops"]); + assert_eq!(claims.roles, ["writer"]); + assert_eq!(claims.ns_roles, [("eng".to_owned(), "viewer".to_owned())]); + assert_eq!(claims.exp, Some(1900000000)); + + let claims = + decode_token_claims(Some("h.eyJvcmciOiJhP2J-YyIsInJvbGVzIjpbIkFETUlOIl19.s")).unwrap(); + assert_eq!(claims.org.as_deref(), Some("a?b~c")); + assert_eq!(claims.roles, ["admin"]); + assert_eq!(claims.ns_roles, []); + assert_eq!(claims.exp, None); + } + + #[test] + fn a_map_lists_its_roles_and_only_strings_are_kept() { + let claims = decode_token_claims(Some( + "h.eyJuc19yb2xlcyI6eyJlbmciOiJ3cml0ZXIiLCJvcHMiOiJ2aWV3ZXIifSwicm9sZXMiOltdfQ.s", + )) + .unwrap(); + assert_eq!( + claims.ns_roles, + [ + ("eng".to_owned(), "writer".to_owned()), + ("ops".to_owned(), "viewer".to_owned()) + ] + ); + } + + #[test] + fn what_is_not_a_jwt_has_no_claims() { + for token in [ + None, + Some(""), + Some("secret-opaque-token"), + Some("a.b"), + Some("a.b.c.d"), + Some("h.!!!.s"), + Some("h.W10.s"), + Some("h.e30-.s"), + ] { + assert_eq!(decode_token_claims(token), None, "{token:?}"); + } + // An empty payload object is a decodable JWT that says nothing. + assert_eq!( + decode_token_claims(Some("h.e30.s")), + Some(TokenClaims::default()) + ); + } + + #[test] + fn a_role_is_read_from_its_map_then_its_flat_roles() { + let unscoped = TokenClaims { + roles: ["writer".into(), "editor".into(), "admin".into()].into(), + namespaces: vec!["eng".into()], + ..TokenClaims::default() + }; + assert_eq!(role_on(Some(&unscoped), Some("eng")), Some("admin")); + assert_eq!(role_on(Some(&unscoped), None), None); + assert_eq!(role_on(Some(&unscoped), Some("other")), None); + let scoped = TokenClaims { + roles: ["platform_admin".into()].into(), + ns_roles: [ + ("eng".into(), "viewer".into()), + ("ops".into(), "writer".into()), + ] + .into(), + ..TokenClaims::default() + }; + assert_eq!(role_on(Some(&scoped), Some("eng")), Some("viewer")); + assert_eq!(role_on(Some(&scoped), Some("other")), None); + assert_eq!(role_on(Some(&scoped), None), None); + let unknown = TokenClaims { + roles: ["editor".into()].into(), + ..TokenClaims::default() + }; + assert_eq!(role_on(Some(&unknown), None), None); + assert_eq!(role_on(None, Some("eng")), None); + + assert_eq!(claim_allows(&scoped, "eng", "writer"), Some(false)); + assert_eq!(claim_allows(&scoped, "ops", "writer"), Some(true)); + assert_eq!(claim_allows(&scoped, "ops", "owner"), None); + } + + #[test] + fn write_scope_only_narrows_writes() { + let mut claims = TokenClaims { + namespaces: vec!["eng".into(), "ops".into()], + write_namespaces: vec!["ops".into()], + roles: vec!["writer".into()], + ..TokenClaims::default() + }; + assert_eq!(claim_allows(&claims, "eng", "viewer"), Some(true)); + assert_eq!(claim_allows(&claims, "eng", "writer"), Some(false)); + assert_eq!(claim_allows(&claims, "ops", "writer"), Some(true)); + claims.ns_roles = vec![("eng".into(), "writer".into())]; + assert_eq!(claim_allows(&claims, "eng", "viewer"), Some(true)); + assert_eq!(claim_allows(&claims, "eng", "writer"), Some(false)); + } +} diff --git a/sdk/rust/tests/blocking_cases/mod.rs b/sdk/rust/tests/blocking_cases/mod.rs index 6177562f70a..45afca70d08 100644 --- a/sdk/rust/tests/blocking_cases/mod.rs +++ b/sdk/rust/tests/blocking_cases/mod.rs @@ -194,6 +194,36 @@ fn synchronous_facades_preserve_wire_contracts_and_metadata() { } } +#[test] +fn blocking_guide_and_mentor_follow_the_async_rules() { + let server = Server::new(vec![ + response( + 200, + json!({"version": "1", "part": "all", "text": "# Loom"}), + "", + ), + response(200, brief(), ""), + response(200, "{}", ""), + ]); + let client = blocking::Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .build() + .unwrap(); + assert_eq!( + client + .guide(clickhouse_loom::MentorGuideInputPart::All) + .unwrap(), + "# Loom" + ); + assert_eq!(client.mentor_with_window(3600).unwrap().hints.len(), 4); + assert_eq!(request(&server).body, json!({"org": "org", "part": "all"})); + assert_eq!( + request(&server).body, + json!({"org": "org", "namespace": "ns", "agent": "bot", "window_seconds": 3600}) + ); +} + #[test] fn blocking_generic_call_propagates_retries_and_failure_metadata() { let server = Server::new(vec![ @@ -237,10 +267,17 @@ fn blocking_generic_call_propagates_retries_and_failure_metadata() { .unwrap_err() .metadata .is_none()); - assert!(blocking::Client::builder("", "ns", "bot") + let server = Server::new(vec![response(200, "{}", "")]); + let client = blocking::Client::builder("", "", "bot") + .base_url(&server.url) .api_key("") + .consumer(" crm ") .build() - .is_err()); + .unwrap(); + client + .call::("future.op", &json!({}), CallOptions::default()) + .unwrap(); + assert_eq!(request(&server).body, json!({"org": "", "consumer": "crm"})); } #[test] diff --git a/sdk/rust/tests/client.rs b/sdk/rust/tests/client.rs index 4665c4f118c..c400c2ad67d 100644 --- a/sdk/rust/tests/client.rs +++ b/sdk/rust/tests/client.rs @@ -372,6 +372,191 @@ async fn values_preserve_all_supported_json_shapes() { )); } +fn brief() -> Value { + json!({ + "org": "org", + "namespace": "ns", + "agent": "bot", + "window_seconds": 604800, + "computed_at": "2026-01-01T00:00:00Z", + "sessions": 12, + "hints": (0..4) + .map(|n| { + json!({"code": format!("hint-{n}"), "severity": "info", "text": format!("hint {n}")}) + }) + .collect::>(), + }) +} + +#[tokio::test] +async fn guide_and_mentor_ask_their_operations_for_this_identity() { + let server = Server::new(vec![ + response( + 200, + json!({"version": "1", "part": "skill", "text": "# Loom"}), + "", + ), + response(200, brief(), ""), + response(200, brief(), ""), + response(200, "{}", ""), + ]); + let client = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .build() + .unwrap(); + assert_eq!( + client + .guide(clickhouse_loom::MentorGuideInputPart::Skill) + .await + .unwrap(), + "# Loom" + ); + let mentor = client.mentor().await.unwrap(); + assert_eq!(mentor.hints.len(), 4); + assert_eq!(mentor.hints[3].text, "hint 3"); + assert_eq!( + client.mentor_with_window(3600).await.unwrap().hints.len(), + 4 + ); + let guide = server.request().await; + assert_eq!(guide.body, json!({"org": "org", "part": "skill"})); + let default = server.request().await; + assert_eq!( + default.body, + json!({"org": "org", "namespace": "ns", "agent": "bot"}) + ); + let window = server.request().await; + assert_eq!( + window.body, + json!({"org": "org", "namespace": "ns", "agent": "bot", "window_seconds": 3600}) + ); + assert!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_err() + ); +} + +#[tokio::test] +async fn an_empty_org_and_namespace_are_left_to_the_server() { + let server = Server::new(vec![ + response(200, json!({"found": false}), ""), + response(200, json!({"version": 1}), ""), + response(200, json!({"version": 1}), ""), + response(200, "{}", ""), + response(200, "{}", ""), + ]); + let client = Client::builder(" ", "", "bot") + .base_url(&server.url) + .api_key("") + .build() + .unwrap(); + client.get("key").await.unwrap(); + client.set(SetRequest::new("key", "fact")).await.unwrap(); + client + .memory_set( + clickhouse_loom::MemorySetInput::new("key", "fact") + .org("mine") + .namespace("other"), + ) + .await + .unwrap(); + for body in [json!({"org": "mine"}), json!({"namespace": "other"})] { + client + .call::("future.op", &body, clickhouse_loom::CallOptions::default()) + .await + .unwrap(); + } + for _ in 0..2 { + let request = server.request().await; + assert_eq!(request.body["org"], ""); + assert_eq!(request.body["namespace"], ""); + } + let explicit = server.request().await.body; + assert_eq!(explicit["org"], "mine"); + assert_eq!(explicit["namespace"], "other"); + assert_eq!(server.request().await.body, json!({"org": "mine"})); + assert_eq!( + server.request().await.body, + json!({"org": "", "namespace": "other"}) + ); +} + +#[tokio::test] +async fn explicit_builder_agents_keep_their_memory_list_scope() { + let agents = ["*", "-", " bot "]; + let server = Server::new( + agents + .iter() + .map(|_| response(200, json!({"entries": [], "truncated": false}), "")) + .collect(), + ); + let mut sent = Vec::new(); + for agent in agents { + let client = Client::builder("org", "ns", agent) + .base_url(&server.url) + .api_key("") + .build() + .unwrap(); + client + .memory_list(clickhouse_loom::MemoryListInput::new()) + .await + .unwrap(); + sent.push(server.request().await.body["agent"].clone()); + } + assert_eq!(sent, agents.map(|agent| json!(agent))); +} + +#[tokio::test] +async fn a_consumer_label_is_stamped_on_bodies_that_name_none() { + let bodies = [ + (json!({"q": 1}), json!("crm")), + (json!({"q": 1, "consumer": null}), json!("crm")), + (json!({"q": 1, "consumer": ""}), json!("crm")), + (json!({"q": 1, "consumer": " - "}), json!("crm")), + (json!({"q": 1, "consumer": "own"}), json!("own")), + (json!({"q": 1, "consumer": 7}), json!(7)), + ]; + let server = Server::new(bodies.iter().map(|_| response(200, "{}", "")).collect()); + let client = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .consumer(" crm\u{b}\n ") + .build() + .unwrap(); + for (body, _) in &bodies { + client + .call::("future.op", body, clickhouse_loom::CallOptions::default()) + .await + .unwrap(); + } + for (_, expected) in bodies { + assert_eq!(server.request().await.body["consumer"], expected); + } + + // With no label, the body goes out as given. + let server = Server::new(vec![response(200, "{}", "")]); + let client = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .consumer(" - ") + .build() + .unwrap(); + client + .call::( + "future.op", + &json!({"q": 1, "consumer": null}), + clickhouse_loom::CallOptions::default(), + ) + .await + .unwrap(); + assert_eq!( + server.request().await.body, + json!({"org": "org", "namespace": "ns", "q": 1, "consumer": null}) + ); +} + #[tokio::test] async fn get_then_set_preserves_arbitrary_precision_json_integers() { let integers = [ @@ -685,7 +870,6 @@ fn invalid_configuration_and_debug_never_expose_credentials() { assert!(matches!(error, Error::Configuration(_))); assert!(!format!("{error:?} {error}").contains("secret")); } - assert!(Client::builder("", "ns", "bot").build().is_err()); assert!(Client::builder("org", "ns", "bot") .timeout(Duration::ZERO) .build() diff --git a/sdk/rust/tests/probe/mod.rs b/sdk/rust/tests/probe/mod.rs index 65a6862212a..e2fa4fdfaf8 100644 --- a/sdk/rust/tests/probe/mod.rs +++ b/sdk/rust/tests/probe/mod.rs @@ -257,3 +257,165 @@ async fn blocking_probe_refuses_calls_inside_tokio() { assert!(matches!(failure.error, Error::Configuration(_))); assert!(failure.metadata.is_none()); } + +fn served(role: &str, name: &str) -> Value { + let mut op = capability(name, &[]); + op["required_role"] = json!(role); + op +} + +fn served_roles() -> Value { + json!({ + "build_commit": "build", + "schema_version": "schema", + "ops": [ + served("writer", "memory.set"), + served("Viewer", "memory.get"), + served("org_admin", "namespace.delete"), + served("Reader", "future.op"), + served("", "future.blank") + ] + }) +} + +/// A JWT whose payload names org `acme` and one scoped role, `viewer` on `eng`. +const TOKEN: &str = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzYTpib3QiLCJvcmciOiJhY21lIiwibmFtZXNwYWNlcyI6WyJlbmciLCJvcHMiXSwicm9sZXMiOlsiV1JJVEVSIiwiV3JpdGVyIl0sIm5zX3JvbGVzIjp7ImVuZyI6IlZpZXdlciJ9LCJleHAiOjQxMDI0NDQ4MDB9.c2lnbmF0dXJl"; + +fn with_token(server: &Server, token: &str) -> Client { + Client::builder("acme", "eng", "bot") + .base_url(&server.url) + .api_key(token) + .build() + .unwrap() +} + +#[tokio::test] +async fn can_call_compares_the_served_role_with_the_token() { + let server = Server::new(vec![ + response(200, served_roles(), ""), + response(200, served_roles(), ""), + response(200, "{}", ""), + ]); + let client = with_token(&server, TOKEN); + assert_eq!( + client.token_claims().map(|claims| claims.org.as_deref()), + Some(Some("acme")) + ); + let clone = client.clone(); + let (write, read) = tokio::join!(client.can_call("memory.set"), clone.can_call("memory.get")); + assert_eq!(write.unwrap(), Some(false)); + assert_eq!(read.unwrap(), Some(true)); + assert_eq!(client.can_call("namespace.delete").await.unwrap(), None); + for unknown in ["future.op", "future.blank", "memory.search"] { + assert_eq!(client.can_call(unknown).await.unwrap(), None, "{unknown}"); + } + // One fetch answered every question for a minute. + assert!(server.request().await.line.contains("ops.capabilities")); + assert!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_err() + ); + + // A zero age fetches again; the snapshot keeps what the server said. + let caps = client.permissions(Duration::ZERO).await.unwrap(); + assert!(server.request().await.line.contains("ops.capabilities")); + assert_eq!(caps.build_commit, "build"); + assert_eq!(caps.schema_version, "schema"); + assert!(caps.has("memory.set") && !caps.has("memory.search")); + assert_eq!(caps.ops()["memory.set"].required_role, "writer"); + assert_eq!(caps.required_role("future.op"), Some("reader")); + assert_eq!(caps.required_role("future.blank"), None); + assert_eq!(caps.required_role("memory.search"), None); + assert_eq!(caps.role(Some("eng")), Some("viewer")); + assert_eq!(caps.role(Some("ops")), None); + assert_eq!(caps.role(None), None); + assert_eq!(caps.callable(Some("eng")), ["memory.get"]); + assert_eq!(caps.can_call("memory.set", None), None); +} + +#[tokio::test] +async fn can_call_does_not_apply_claims_to_another_org_or_namespace() { + let server = Server::new(vec![response(200, served_roles(), "")]); + for (org, namespace) in [("other", "eng"), ("", "eng"), ("acme", "ops")] { + let client = Client::builder(org, namespace, "bot") + .base_url(&server.url) + .api_key(TOKEN) + .build() + .unwrap(); + assert_eq!(client.can_call("memory.get").await.unwrap(), None); + } + assert!( + tokio::time::timeout(Duration::from_millis(300), server.request()) + .await + .is_err() + ); +} + +#[tokio::test] +async fn a_token_that_is_not_a_jwt_cannot_tell() { + let server = Server::new(vec![ + response(200, served_roles(), ""), + response(200, served_roles(), ""), + response(200, "{}", ""), + ]); + let client = with_token(&server, "opaque-secret"); + assert!(client.token_claims().is_none()); + assert_eq!(client.can_call("memory.set").await.unwrap(), None); + let caps = client.permissions(Duration::ZERO).await.unwrap(); + assert!(caps.claims.is_none()); + assert_eq!(caps.callable(None), Vec::::new()); + assert!(caps.has("memory.set")); + + let server = Server::new(vec![response(200, served_roles(), "")]); + let client = Client::builder("org", "eng", "bot") + .base_url(&server.url) + .api_key("") + .build() + .unwrap(); + assert!(client.token_claims().is_none()); + assert_eq!(client.can_call("memory.get").await.unwrap(), None); +} + +#[tokio::test] +async fn a_failed_fetch_is_an_error_and_is_not_cached() { + let server = Server::new(vec![ + response(503, json!({"detail": {"code": "OVERLOADED"}}), ""), + response(200, served_roles(), ""), + response(200, "{}", ""), + ]); + let client = Client::builder("acme", "eng", "bot") + .base_url(&server.url) + .api_key(TOKEN) + .retry(RetryPolicy::disabled()) + .build() + .unwrap(); + assert!(matches!( + client.permissions(Duration::ZERO).await.unwrap_err(), + Error::Api(ref error) if error.status == 503 + )); + assert_eq!(client.can_call("memory.get").await.unwrap(), Some(true)); +} + +#[cfg(feature = "blocking")] +#[test] +fn blocking_permissions_follow_the_async_rules() { + let server = Server::new(vec![ + response(200, served_roles(), ""), + response(200, served_roles(), ""), + response(200, "{}", ""), + ]); + let client = clickhouse_loom::blocking::Client::builder("acme", "eng", "bot") + .base_url(&server.url) + .api_key(TOKEN) + .build() + .unwrap(); + assert_eq!( + client.token_claims().and_then(|c| c.org.as_deref()), + Some("acme") + ); + assert_eq!(client.can_call("memory.set").unwrap(), Some(false)); + let caps = client.permissions(Duration::ZERO).unwrap(); + assert_eq!(caps.callable(Some("eng")), ["memory.get"]); + assert_eq!(client.can_call("memory.get").unwrap(), Some(true)); +} From d8f72ec3cafb7cc1c015969bbb879a4db4184a06 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Mon, 30 Nov 2026 14:27:08 +0800 Subject: [PATCH 2/5] Rust onboarding hints follow operation authorization scope Namespace role hints exclude operations authorized on other scopes. Consumer defaults survive labels the server removes, and Mentor helpers preserve the server's reported window. Published documentation waits for the crate release. Signed-off-by: zhangxiaoyu.york --- scripts/codegen/sdk_rust_gen.py | 15 +++++++ sdk/rust/Cargo.toml | 1 + sdk/rust/README.md | 64 +--------------------------- sdk/rust/src/blocking.rs | 2 +- sdk/rust/src/capabilities.rs | 16 ++++++- sdk/rust/src/client.rs | 41 ++++++++++++------ sdk/rust/src/wire_models.rs | 8 ++++ sdk/rust/tests/blocking_cases/mod.rs | 4 +- sdk/rust/tests/client.rs | 13 ++++-- sdk/rust/tests/probe/mod.rs | 37 ++++++++++++++++ 10 files changed, 118 insertions(+), 83 deletions(-) diff --git a/scripts/codegen/sdk_rust_gen.py b/scripts/codegen/sdk_rust_gen.py index f3f9b23bb85..8fe0b1f32e7 100644 --- a/scripts/codegen/sdk_rust_gen.py +++ b/scripts/codegen/sdk_rust_gen.py @@ -714,6 +714,18 @@ def operation_facts() -> str: return "\n".join(facts) +def namespace_hint_exclusions() -> str: + from server.operations.registry import ALL_OPERATIONS + + names = [ + op.name + for op in ALL_OPERATIONS + if (op.skip_namespace_authz or op.deployment_scoped or op.row_scoped) + and "namespace" in operation_identity_fields(op)[0] + ] + return "\n".join(f"{rust_string(name)}," for name in sorted(names)) + + def selected_operations(selected: tuple[str, ...] | None = None) -> list[Any]: from server.operations.registry import ALL_OPERATIONS @@ -781,6 +793,9 @@ def build(selected: tuple[str, ...] | None = None) -> str: + "\npub(crate) const OP_POLICIES: &[OperationPolicy] = &[\n" + operation_facts() + "\n];\n" + + "\npub(crate) const NAMESPACE_HINT_EXCLUSIONS: &[&str] = &[\n" + + namespace_hint_exclusions() + + "\n];\n" + "\n\n".join(em.declarations.values()) + "\n" + "\n".join(em.defaults) diff --git a/sdk/rust/Cargo.toml b/sdk/rust/Cargo.toml index 4adba4140f4..f0cb4dea899 100644 --- a/sdk/rust/Cargo.toml +++ b/sdk/rust/Cargo.toml @@ -31,6 +31,7 @@ derive_more = { version = "2", features = ["display"] } log = "0.4" httpdate = "1" tokio = { version = "1", features = ["sync", "time"] } +unicode-general-category = "0.6" [dev-dependencies] sha2 = "0.10" diff --git a/sdk/rust/README.md b/sdk/rust/README.md index af99a340bad..3b0bc6c3e0d 100644 --- a/sdk/rust/README.md +++ b/sdk/rust/README.md @@ -47,7 +47,7 @@ application's dependencies. The crate name is `clickhouse-loom`; Rust imports it as `clickhouse_loom`. The repository build uses reqwest with Rustls and HTTP/2. It also depends on -serde, serde_json, Tokio, rand, uuid, httpdate, log, derive_more and base64. +serde, serde_json, Tokio, rand, uuid, httpdate, log and derive_more. ## Use @@ -108,8 +108,7 @@ Server setup is covered in the ## Configuration `Client::builder(org, namespace, agent)` accepts `base_url`, `api_key`, `timeout`, -`user_id`, `session_id`, `run_id`, `consumer`, `retry`, `pacing` and -`ratelimit_max_wait`. +`user_id`, `session_id`, `run_id`, `retry`, `pacing` and `ratelimit_max_wait`. The default timeout is 60 seconds per attempt. It covers the whole HTTP request and response body. The server address comes from `LOOM_BASE_URL`, defaulting to `http://localhost:7777`. The token comes from `LOOM_API_KEY`; without a token, @@ -117,20 +116,6 @@ requests carry no Authorization header. Explicit settings override the environment. `.api_key("")` disables authorization. Empty environment values are treated as unset. -An empty org lets Loom resolve it from the configured plane, token, or local -installation. On a tokenless single-user server, an empty namespace lets Loom -fill the namespace for supported memory and search operations. Empty builder -values leave an org or namespace named in a request intact. Supply a namespace -when the operation requires an explicit target. - -A blank agent name uses `sdk-rust:`, based on the executable's name. -Explicit `"-"` and `"*"` retain their operation-specific meanings. - -`.consumer(label)` names the product this process speaks for. The label is -stamped on every operation body that names none (absent, null, empty or `-`); -a body that names its own takes precedence. A consumer claim in the verified -token takes precedence on the server. An empty builder label stamps nothing. - Builder identity values apply to declared caller and authorship fields. `knowledge_add` and `knowledge_upsert` receive agent and session identity; `observe_record` receives user, session and run identity. `conversation_create` @@ -575,51 +560,6 @@ An empty request returns `ok = true`. with the capability response's metadata. The blocking client provides the same methods without `.await`. -## What the token may call - -`token_claims` decodes the bearer token's payload without verifying it. -`permissions(max_age)` returns the deployment's served -operations paired with those claims, reusing a snapshot at most `max_age` old; -a zero age fetches again. `can_call(op)` compares the declared minimum role -with the token's claimed role and write scope for the client's explicit org and -namespace. It returns `None` if the SDK cannot make that comparison. The server -checks live grants, revocation and other policies on every call. - -```rust -# async fn example(bot: clickhouse_loom::Client) -> Result<(), clickhouse_loom::Error> { -let write_hint = bot.can_call("memory.set").await?; -let caps = bot.permissions(std::time::Duration::ZERO).await?; -println!("write role hint: {write_hint:?}; build: {}", caps.build_commit); -# Ok(()) -# } -``` - -## Guide and mentor - -`guide(part)` returns `mentor.guide` as Markdown for the system prompt of an -agent that has no plugin to carry it: `MentorGuideInputPart::Skill` is the loop, -where each kind of state goes and how to read answers; `Reference` is every -plane with its operations; `All` is both. - -`mentor()` returns `mentor.brief` for this identity over the server's default -window: the planes it never uses, the hints with the counts behind them, and -whether past hints were followed. `mentor_with_window(seconds)` requests a -lookback window. - -```rust -use clickhouse_loom::{Client, MentorGuideInputPart}; - -# async fn example(bot: Client) -> Result<(), clickhouse_loom::Error> { -let _skill = bot.guide(MentorGuideInputPart::All).await?; -let brief = bot.mentor_with_window(7 * 24 * 3600).await?; -println!("{} sessions, {} hints", brief.sessions, brief.hints.len()); -# Ok(()) -# } -``` - -Guide and mentor calls use a ten second timeout per attempt. They run only -when called. The blocking client provides the same methods without `.await`. - ## Blocking calls Enable the feature in the consuming application's `Cargo.toml`: diff --git a/sdk/rust/src/blocking.rs b/sdk/rust/src/blocking.rs index 09d8097c2a0..71e71525131 100644 --- a/sdk/rust/src/blocking.rs +++ b/sdk/rust/src/blocking.rs @@ -155,7 +155,7 @@ impl Client { self.onboarding(|client| async move { client.mentor().await }) } - /// [`crate::Client::mentor`] over the last `window_seconds`. + /// See [`crate::Client::mentor_with_window`]; the response reports the window used. pub fn mentor_with_window( &self, window_seconds: i64, diff --git a/sdk/rust/src/capabilities.rs b/sdk/rust/src/capabilities.rs index 1194379c232..b4403087100 100644 --- a/sdk/rust/src/capabilities.rs +++ b/sdk/rust/src/capabilities.rs @@ -5,9 +5,18 @@ use std::{ use crate::{ token::{claim_allows, role_on}, + wire_models::{NAMESPACE_HINT_EXCLUSIONS, OP_POLICIES}, OpCapability, OpsCapabilitiesOutput, TokenClaims, }; +pub(crate) fn supports_namespace_hint(op: &str) -> bool { + // Some ops take a namespace without authorizing the request on it. + NAMESPACE_HINT_EXCLUSIONS.binary_search(&op).is_err() + && OP_POLICIES + .iter() + .any(|(name, _, _, keys, _)| *name == op && keys.contains(&"namespace")) +} + /// Operations and request fields an application needs from the server. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] @@ -92,9 +101,12 @@ impl Capabilities { } /// Compare the named namespace's token role with the operation's declared - /// role. `None` means the comparison is unavailable. Live authorization - /// can differ from this hint. + /// role for operations with a bound namespace. `None` means the comparison + /// is unavailable. Live authorization can differ from this hint. pub fn can_call(&self, op: &str, namespace: Option<&str>) -> Option { + if !supports_namespace_hint(op) { + return None; + } claim_allows(self.claims.as_ref()?, namespace?, self.required_role(op)?) } diff --git a/sdk/rust/src/client.rs b/sdk/rust/src/client.rs index 69c39e3ae3e..6535b292eca 100644 --- a/sdk/rust/src/client.rs +++ b/sdk/rust/src/client.rs @@ -15,11 +15,12 @@ use serde::{de::DeserializeOwned, Serialize}; use serde_json::{json, Value}; use crate::{ - token::decode_token_claims, ApiError, CallFailure, CallMetadata, CallOptions, CallResult, - Capabilities, DeleteResponse, Error, GetResponse, RetryPolicy, SearchRequest, SearchResponse, - SetRequest, SetResponse, TokenClaims, + capabilities::supports_namespace_hint, token::decode_token_claims, ApiError, CallFailure, + CallMetadata, CallOptions, CallResult, Capabilities, DeleteResponse, Error, GetResponse, + RetryPolicy, SearchRequest, SearchResponse, SetRequest, SetResponse, TokenClaims, }; use tokio::sync::Mutex; +use unicode_general_category::{get_general_category, GeneralCategory}; const DEFAULT_URL: &str = "http://localhost:7777"; /// How long a capabilities snapshot answers `can_call` before it is fetched again. @@ -185,10 +186,7 @@ impl Client { { return Ok(None); } - let binds_namespace = crate::wire_models::OP_POLICIES - .iter() - .any(|(name, _, _, keys, _)| *name == op && keys.contains(&"namespace")); - if !binds_namespace { + if !supports_namespace_hint(op) { return Ok(None); } let caps = self.permissions(CAPS_MAX_AGE).await?; @@ -206,14 +204,14 @@ impl Client { .map_err(|failure| failure.error) } - /// The store's advice to this agent: `mentor.brief` for this identity over - /// the server's default window, the planes it never uses, the hints with - /// the counts behind them, and whether past hints were followed. + /// Request `mentor.brief` for this agent using the server's default lookback. + /// The response's `window_seconds` reports the window the server used. pub async fn mentor(&self) -> Result { self.brief(None).await } /// [`Client::mentor`] with a requested lookback of `window_seconds`. + /// Read the response's `window_seconds` for the window the server used. pub async fn mentor_with_window( &self, window_seconds: i64, @@ -742,12 +740,29 @@ fn default_agent_name() -> String { /// The server bounds the ledger's `consumer` column to this many characters. const CONSUMER_MAX_CHARS: usize = 64; -/// The `consumer` label as the server stores it: without control characters, -/// stripped, at most 64 characters; empty for a blank or the wire's `-`. +/// The server keeps printable Unicode characters and ASCII space. fn consumer_label(value: &str) -> String { + use GeneralCategory::{ + Control, Format, LineSeparator, ParagraphSeparator, PrivateUse, SpaceSeparator, Surrogate, + Unassigned, + }; + let text: String = value .chars() - .filter(|c| *c == ' ' || (!c.is_control() && !c.is_whitespace())) + .filter(|&c| { + c == ' ' + || !matches!( + get_general_category(c), + Control + | Format + | LineSeparator + | ParagraphSeparator + | PrivateUse + | SpaceSeparator + | Surrogate + | Unassigned + ) + }) .collect(); let text = text.trim(); if text.is_empty() || text == "-" { diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index c13078b6211..d142a63c3a3 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -1967,6 +1967,14 @@ pub(crate) const OP_POLICIES: &[OperationPolicy] = &[ ), ("ui.vitals", true, false, &["namespace", "org"], &[]), ]; + +pub(crate) const NAMESPACE_HINT_EXCLUSIONS: &[&str] = &[ + "code.repos", + "extraction_policy.clear", + "extraction_policy.get", + "extraction_policy.set", + "memory.verify", +]; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ContextBlock { diff --git a/sdk/rust/tests/blocking_cases/mod.rs b/sdk/rust/tests/blocking_cases/mod.rs index 45afca70d08..0e445c74405 100644 --- a/sdk/rust/tests/blocking_cases/mod.rs +++ b/sdk/rust/tests/blocking_cases/mod.rs @@ -216,7 +216,9 @@ fn blocking_guide_and_mentor_follow_the_async_rules() { .unwrap(), "# Loom" ); - assert_eq!(client.mentor_with_window(3600).unwrap().hints.len(), 4); + let brief = client.mentor_with_window(3600).unwrap(); + assert_eq!(brief.window_seconds, 604800_i64.into()); + assert_eq!(brief.hints.len(), 4); assert_eq!(request(&server).body, json!({"org": "org", "part": "all"})); assert_eq!( request(&server).body, diff --git a/sdk/rust/tests/client.rs b/sdk/rust/tests/client.rs index c400c2ad67d..44be088b045 100644 --- a/sdk/rust/tests/client.rs +++ b/sdk/rust/tests/client.rs @@ -415,10 +415,9 @@ async fn guide_and_mentor_ask_their_operations_for_this_identity() { let mentor = client.mentor().await.unwrap(); assert_eq!(mentor.hints.len(), 4); assert_eq!(mentor.hints[3].text, "hint 3"); - assert_eq!( - client.mentor_with_window(3600).await.unwrap().hints.len(), - 4 - ); + let brief = client.mentor_with_window(3600).await.unwrap(); + assert_eq!(brief.window_seconds, 604800_i64.into()); + assert_eq!(brief.hints.len(), 4); let guide = server.request().await; assert_eq!(guide.body, json!({"org": "org", "part": "skill"})); let default = server.request().await; @@ -515,6 +514,12 @@ async fn a_consumer_label_is_stamped_on_bodies_that_name_none() { (json!({"q": 1, "consumer": null}), json!("crm")), (json!({"q": 1, "consumer": ""}), json!("crm")), (json!({"q": 1, "consumer": " - "}), json!("crm")), + (json!({"q": 1, "consumer": "\u{200b}"}), json!("crm")), + (json!({"q": 1, "consumer": "\u{e000}"}), json!("crm")), + ( + json!({"q": 1, "consumer": "\u{200b}東京"}), + json!("\u{200b}東京"), + ), (json!({"q": 1, "consumer": "own"}), json!("own")), (json!({"q": 1, "consumer": 7}), json!(7)), ]; diff --git a/sdk/rust/tests/probe/mod.rs b/sdk/rust/tests/probe/mod.rs index e2fa4fdfaf8..02679f929ef 100644 --- a/sdk/rust/tests/probe/mod.rs +++ b/sdk/rust/tests/probe/mod.rs @@ -334,6 +334,43 @@ async fn can_call_compares_the_served_role_with_the_token() { assert_eq!(caps.can_call("memory.set", None), None); } +#[tokio::test] +async fn namespace_write_scope_is_not_used_for_org_authorized_operations() { + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; + + let payload = + br#"{"org":"acme","namespaces":["eng","ops"],"roles":["org_admin"],"ns_write":["ops"]}"#; + let token = format!("header.{}.signature", URL_SAFE_NO_PAD.encode(payload)); + let server = Server::new(vec![ + response( + 200, + json!({ + "ops": [ + served("org_admin", "extraction_policy.get"), + served("viewer", "mentor.guide"), + served("viewer", "future.op"), + served("writer", "memory.set"), + served("viewer", "memory.get") + ] + }), + "", + ), + response(200, "{}", ""), + ]); + let client = with_token(&server, &token); + assert_eq!( + client.can_call("extraction_policy.get").await.unwrap(), + None + ); + assert_eq!(client.can_call("memory.set").await.unwrap(), Some(false)); + assert_eq!(client.can_call("memory.get").await.unwrap(), Some(true)); + let caps = client.permissions(Duration::from_secs(60)).await.unwrap(); + assert_eq!(caps.can_call("extraction_policy.get", Some("eng")), None); + assert_eq!(caps.can_call("extraction_policy.get", Some("ops")), None); + assert_eq!(caps.callable(Some("eng")), ["memory.get"]); + assert_eq!(caps.callable(Some("ops")), ["memory.get", "memory.set"]); +} + #[tokio::test] async fn can_call_does_not_apply_claims_to_another_org_or_namespace() { let server = Server::new(vec![response(200, served_roles(), "")]); From e018f70ef1ff99c3cc0cf1b23bc6df07488cb757 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Mon, 30 Nov 2026 15:02:40 +0800 Subject: [PATCH 3/5] Rust defaults preserve namespace validation and executable names An empty namespace passes memory model validation and can reach a write handler. Omitting it permits tokenless defaults and rejects authenticated writes that need an explicit namespace. Explicit targets are preserved. Executable suffix removal includes the dot and leaves suffix-free platforms unchanged. Signed-off-by: zhangxiaoyu.york --- sdk/rust/src/client.rs | 35 ++++++++++++++++++++++++---- sdk/rust/tests/blocking_cases/mod.rs | 14 +++++++++++ sdk/rust/tests/client.rs | 31 +++++++++++++++++++++++- 3 files changed, 74 insertions(+), 6 deletions(-) diff --git a/sdk/rust/src/client.rs b/sdk/rust/src/client.rs index 6535b292eca..65504623868 100644 --- a/sdk/rust/src/client.rs +++ b/sdk/rust/src/client.rs @@ -366,8 +366,7 @@ impl Client { for &key in identity_fields { if let Some(value) = self.identity.get(key) { if matches!(key, "org" | "namespace") && value == "" { - // Keep the server's blank sentinel for known operations. - if key != "namespace" || policy.is_some() { + if key == "org" { fields.entry(key).or_insert_with(|| value.clone()); } } else { @@ -385,6 +384,11 @@ impl Client { } } } + // Missing namespaces get tokenless defaults or required-field validation. + // An empty string can instead reach a write handler as a real target. + if fields.get("namespace").is_some_and(|value| value == "") { + fields.remove("namespace"); + } // A body that names its own consumer wins. if !self.consumer.is_empty() && fields @@ -728,9 +732,17 @@ fn default_agent_name() -> String { .map(|name| name.to_string_lossy().into_owned()) }) .unwrap_or_default(); - let program = program - .strip_suffix(env::consts::EXE_EXTENSION) - .unwrap_or(&program); + agent_name_for(&program, env::consts::EXE_EXTENSION) +} + +fn agent_name_for(program: &str, executable_extension: &str) -> String { + let program = if executable_extension.is_empty() { + program + } else { + program + .strip_suffix(&format!(".{executable_extension}")) + .unwrap_or(program) + }; format!( "sdk-rust:{}", if program.is_empty() { "bot" } else { program } @@ -855,6 +867,19 @@ mod tests { assert_eq!(consumer_value(&json!(true)), ""); } + #[test] + fn executable_names_strip_only_the_platform_suffix() { + for (program, extension, expected) in [ + ("myapp.exe", "exe", "sdk-rust:myapp"), + ("myapp", "exe", "sdk-rust:myapp"), + ("myapp.", "", "sdk-rust:myapp."), + ("myapp.exe", "", "sdk-rust:myapp.exe"), + ("", "", "sdk-rust:bot"), + ] { + assert_eq!(agent_name_for(program, extension), expected); + } + } + #[test] fn a_blank_agent_is_named_after_the_program() { let named = Client::builder(" ", " ", " \t").build().unwrap(); diff --git a/sdk/rust/tests/blocking_cases/mod.rs b/sdk/rust/tests/blocking_cases/mod.rs index 0e445c74405..e176c7c539c 100644 --- a/sdk/rust/tests/blocking_cases/mod.rs +++ b/sdk/rust/tests/blocking_cases/mod.rs @@ -12,6 +12,20 @@ fn request(server: &Server) -> Request { .block_on(server.request()) } +#[test] +fn authenticated_empty_namespaces_are_omitted_in_blocking_calls() { + let server = Server::new(vec![response(200, json!({"version": 1}), "")]); + let client = blocking::Client::builder("acme", "", "bot") + .base_url(&server.url) + .api_key("writer-token") + .build() + .unwrap(); + client.set(SetRequest::new("key", "fact")).unwrap(); + let sent = request(&server); + assert_eq!(sent.headers["authorization"], "Bearer writer-token"); + assert!(!sent.body.as_object().unwrap().contains_key("namespace")); +} + #[test] fn bound_run_ids_are_validated_before_calls() { for run_id in ["private\nrun", "private\rrun", "private\0run"] { diff --git a/sdk/rust/tests/client.rs b/sdk/rust/tests/client.rs index 44be088b045..18006fb2593 100644 --- a/sdk/rust/tests/client.rs +++ b/sdk/rust/tests/client.rs @@ -437,6 +437,35 @@ async fn guide_and_mentor_ask_their_operations_for_this_identity() { ); } +#[tokio::test] +async fn authenticated_calls_omit_empty_namespaces_and_keep_explicit_targets() { + let server = Server::new( + (0..3) + .map(|_| response(200, json!({"version": 1}), "")) + .collect(), + ); + let client = Client::builder("acme", "", "bot") + .base_url(&server.url) + .api_key("writer-token") + .build() + .unwrap(); + client.set(SetRequest::new("key", "fact")).await.unwrap(); + client + .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace("")) + .await + .unwrap(); + client + .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace("target")) + .await + .unwrap(); + for _ in 0..2 { + let request = server.request().await; + assert_eq!(request.headers["authorization"], "Bearer writer-token"); + assert!(!request.body.as_object().unwrap().contains_key("namespace")); + } + assert_eq!(server.request().await.body["namespace"], "target"); +} + #[tokio::test] async fn an_empty_org_and_namespace_are_left_to_the_server() { let server = Server::new(vec![ @@ -470,7 +499,7 @@ async fn an_empty_org_and_namespace_are_left_to_the_server() { for _ in 0..2 { let request = server.request().await; assert_eq!(request.body["org"], ""); - assert_eq!(request.body["namespace"], ""); + assert!(!request.body.as_object().unwrap().contains_key("namespace")); } let explicit = server.request().await.body; assert_eq!(explicit["org"], "mine"); From 9a145a9bdf78d63c255c09ab38aa6b5488d17595 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Mon, 30 Nov 2026 15:21:51 +0800 Subject: [PATCH 4/5] Rust defaults omit blank namespaces and match executable suffix casing Whitespace-only namespaces can reach write handlers without a namespace authorization target. Omit them so required-field validation refuses the write. Windows executable suffixes are case-insensitive; strip them without changing the program name's casing. Signed-off-by: zhangxiaoyu.york --- sdk/rust/src/client.rs | 17 +++++++++++++---- sdk/rust/tests/blocking_cases/mod.rs | 23 +++++++++++++++++++---- sdk/rust/tests/client.rs | 15 +++++++++++---- 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/sdk/rust/src/client.rs b/sdk/rust/src/client.rs index 65504623868..94263abb1b8 100644 --- a/sdk/rust/src/client.rs +++ b/sdk/rust/src/client.rs @@ -385,8 +385,12 @@ impl Client { } } // Missing namespaces get tokenless defaults or required-field validation. - // An empty string can instead reach a write handler as a real target. - if fields.get("namespace").is_some_and(|value| value == "") { + // A blank string can instead reach a write handler as a real target. + if fields + .get("namespace") + .and_then(Value::as_str) + .is_some_and(|namespace| namespace.trim().is_empty()) + { fields.remove("namespace"); } // A body that names its own consumer wins. @@ -740,8 +744,9 @@ fn agent_name_for(program: &str, executable_extension: &str) -> String { program } else { program - .strip_suffix(&format!(".{executable_extension}")) - .unwrap_or(program) + .rsplit_once('.') + .filter(|(_, suffix)| suffix.eq_ignore_ascii_case(executable_extension)) + .map_or(program, |(stem, _)| stem) }; format!( "sdk-rust:{}", @@ -871,9 +876,13 @@ mod tests { fn executable_names_strip_only_the_platform_suffix() { for (program, extension, expected) in [ ("myapp.exe", "exe", "sdk-rust:myapp"), + ("APP.EXE", "exe", "sdk-rust:APP"), + ("myapp.ExE", "exe", "sdk-rust:myapp"), + ("机器人.EXE", "exe", "sdk-rust:机器人"), ("myapp", "exe", "sdk-rust:myapp"), ("myapp.", "", "sdk-rust:myapp."), ("myapp.exe", "", "sdk-rust:myapp.exe"), + ("APP.EXE", "", "sdk-rust:APP.EXE"), ("", "", "sdk-rust:bot"), ] { assert_eq!(agent_name_for(program, extension), expected); diff --git a/sdk/rust/tests/blocking_cases/mod.rs b/sdk/rust/tests/blocking_cases/mod.rs index e176c7c539c..12f8a9167a9 100644 --- a/sdk/rust/tests/blocking_cases/mod.rs +++ b/sdk/rust/tests/blocking_cases/mod.rs @@ -14,16 +14,31 @@ fn request(server: &Server) -> Request { #[test] fn authenticated_empty_namespaces_are_omitted_in_blocking_calls() { - let server = Server::new(vec![response(200, json!({"version": 1}), "")]); + let server = Server::new( + (0..4) + .map(|_| response(200, json!({"version": 1}), "")) + .collect(), + ); let client = blocking::Client::builder("acme", "", "bot") .base_url(&server.url) .api_key("writer-token") .build() .unwrap(); client.set(SetRequest::new("key", "fact")).unwrap(); - let sent = request(&server); - assert_eq!(sent.headers["authorization"], "Bearer writer-token"); - assert!(!sent.body.as_object().unwrap().contains_key("namespace")); + for namespace in [" \t ", "\u{2003}"] { + client + .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace(namespace)) + .unwrap(); + } + client + .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace("target")) + .unwrap(); + for _ in 0..3 { + let sent = request(&server); + assert_eq!(sent.headers["authorization"], "Bearer writer-token"); + assert!(!sent.body.as_object().unwrap().contains_key("namespace")); + } + assert_eq!(request(&server).body["namespace"], "target"); } #[test] diff --git a/sdk/rust/tests/client.rs b/sdk/rust/tests/client.rs index 18006fb2593..3d76cfe6d3f 100644 --- a/sdk/rust/tests/client.rs +++ b/sdk/rust/tests/client.rs @@ -440,7 +440,7 @@ async fn guide_and_mentor_ask_their_operations_for_this_identity() { #[tokio::test] async fn authenticated_calls_omit_empty_namespaces_and_keep_explicit_targets() { let server = Server::new( - (0..3) + (0..6) .map(|_| response(200, json!({"version": 1}), "")) .collect(), ); @@ -450,20 +450,27 @@ async fn authenticated_calls_omit_empty_namespaces_and_keep_explicit_targets() { .build() .unwrap(); client.set(SetRequest::new("key", "fact")).await.unwrap(); + for namespace in ["", " \t ", "\u{2003}"] { + client + .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace(namespace)) + .await + .unwrap(); + } client - .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace("")) + .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace("target")) .await .unwrap(); client - .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace("target")) + .memory_set(clickhouse_loom::MemorySetInput::new("key", "fact").namespace(" target ")) .await .unwrap(); - for _ in 0..2 { + for _ in 0..4 { let request = server.request().await; assert_eq!(request.headers["authorization"], "Bearer writer-token"); assert!(!request.body.as_object().unwrap().contains_key("namespace")); } assert_eq!(server.request().await.body["namespace"], "target"); + assert_eq!(server.request().await.body["namespace"], " target "); } #[tokio::test] From 8a74384fe26360009494315f147f03079d256254 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Mon, 30 Nov 2026 20:37:56 +0800 Subject: [PATCH 5/5] Rust permission hints preserve scoped roles and bound advice calls Dropping malformed namespace roles lets flat writer claims produce a false permission hint. Retain each scoped entry so its map stays authoritative. Guide and Mentor calls have a ten-second deadline that includes retry and pacing waits. Return Error::Timeout when that deadline expires. Signed-off-by: zhangxiaoyu.york --- sdk/rust/src/client.rs | 26 ++-- sdk/rust/src/error.rs | 14 ++- sdk/rust/src/token.rs | 29 ++++- sdk/rust/tests/client.rs | 3 + sdk/rust/tests/onboarding_review/mod.rs | 152 ++++++++++++++++++++++++ 5 files changed, 210 insertions(+), 14 deletions(-) create mode 100644 sdk/rust/tests/onboarding_review/mod.rs diff --git a/sdk/rust/src/client.rs b/sdk/rust/src/client.rs index 94263abb1b8..a194652eda0 100644 --- a/sdk/rust/src/client.rs +++ b/sdk/rust/src/client.rs @@ -1,6 +1,7 @@ use std::{ collections::HashMap, env, fmt, + future::Future, path::Path, sync::Arc, time::{Duration, Instant}, @@ -33,6 +34,16 @@ fn advice_options() -> CallOptions { CallOptions::default().timeout(ADVICE_TIMEOUT) } +async fn advice( + call: impl Future, CallFailure>>, +) -> Result { + tokio::time::timeout(ADVICE_TIMEOUT, call) + .await + .map_err(|_| Error::Timeout)? + .map(|result| result.data) + .map_err(|failure| failure.error) +} + macro_rules! typed_call { ($method:ident, $with_options:ident, $request:ty, $response:ty, $op:literal) => { pub async fn $method(&self, request: $request) -> Result<$response, Error> { @@ -198,10 +209,12 @@ impl Client { /// operations; `All` is both. Put it in the system prompt of an agent that /// has no plugin to carry it. pub async fn guide(&self, part: crate::MentorGuideInputPart) -> Result { - self.mentor_guide_with_options(crate::MentorGuideInput::new().part(part), advice_options()) - .await - .map(|result| result.data.text) - .map_err(|failure| failure.error) + let guide = advice(self.mentor_guide_with_options( + crate::MentorGuideInput::new().part(part), + advice_options(), + )) + .await?; + Ok(guide.text) } /// Request `mentor.brief` for this agent using the server's default lookback. @@ -226,10 +239,7 @@ impl Client { Some(seconds) => request.window_seconds(seconds), None => request, }; - self.mentor_brief_with_options(request, advice_options()) - .await - .map(|result| result.data) - .map_err(|failure| failure.error) + advice(self.mentor_brief_with_options(request, advice_options())).await } pub async fn set(&self, request: SetRequest) -> Result { diff --git a/sdk/rust/src/error.rs b/sdk/rust/src/error.rs index 4ee78425a0f..7af0cc72bd1 100644 --- a/sdk/rust/src/error.rs +++ b/sdk/rust/src/error.rs @@ -327,6 +327,9 @@ pub enum Error { Input(String), #[display("HTTP transport failed: {_0}")] Transport(reqwest::Error), + /// The whole advice call exceeded its limit, including retries and waits. + #[display("advice call exceeded its time limit")] + Timeout, #[display("invalid JSON response (HTTP {status}): {source}")] #[non_exhaustive] Protocol { @@ -339,12 +342,13 @@ pub enum Error { impl Error { /// Whose move the error is, for every variant. An API error resolves as - /// [`ApiError::category`]. A transport failure is `Dependency`, an invalid - /// response `Internal`, and an invalid request or client configuration `Input`. + /// [`ApiError::category`]. A transport failure or advice timeout is + /// `Dependency`, an invalid response `Internal`, and an invalid request or + /// client configuration `Input`. pub fn category(&self) -> ErrorCategory { match self { Self::Api(error) => error.category(), - Self::Transport(_) => ErrorCategory::Dependency, + Self::Transport(_) | Self::Timeout => ErrorCategory::Dependency, Self::Protocol { .. } => ErrorCategory::Internal, _ => ErrorCategory::Input, } @@ -743,6 +747,10 @@ mod tests { #[tokio::test] async fn errors_the_sdk_raises_have_a_class() { + assert_eq!( + (Error::Timeout.category(), Error::Timeout.retryable()), + (ErrorCategory::Dependency, false) + ); let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); drop(listener); diff --git a/sdk/rust/src/token.rs b/sdk/rust/src/token.rs index 4dc697b3b1e..0ec2a84bd2b 100644 --- a/sdk/rust/src/token.rs +++ b/sdk/rust/src/token.rs @@ -25,6 +25,7 @@ pub struct TokenClaims { /// Flat roles of unscoped and wildcard tokens, lowercased. pub roles: Vec, /// Per-namespace role of a scoped token, authoritative where present. + /// Non-string values have an empty role and retain the map's authority. pub ns_roles: Vec<(String, String)>, pub exp: Option, } @@ -56,8 +57,11 @@ pub(crate) fn decode_token_claims(token: Option<&str>) -> Option { }; let mut ns_roles = Vec::new(); match payload.get("ns_roles") { - Some(Value::Object(map)) => ns_roles.extend(map.iter().filter_map(|(namespace, role)| { - Some((namespace.clone(), role.as_str()?.to_ascii_lowercase())) + Some(Value::Object(map)) => ns_roles.extend(map.iter().map(|(namespace, role)| { + ( + namespace.clone(), + role.as_str().unwrap_or_default().to_ascii_lowercase(), + ) })), None | Some(Value::Null) => {} _ => return None, @@ -161,7 +165,7 @@ mod tests { } #[test] - fn a_map_lists_its_roles_and_only_strings_are_kept() { + fn a_map_lists_its_roles() { let claims = decode_token_claims(Some( "h.eyJuc19yb2xlcyI6eyJlbmciOiJ3cml0ZXIiLCJvcHMiOiJ2aWV3ZXIifSwicm9sZXMiOltdfQ.s", )) @@ -175,6 +179,25 @@ mod tests { ); } + #[test] + fn non_string_scoped_roles_keep_the_map_authoritative() { + for role in [ + serde_json::json!(20), + serde_json::json!(null), + serde_json::json!(false), + serde_json::json!([]), + serde_json::json!({}), + ] { + let payload = serde_json::json!({ + "namespaces": ["eng"], "roles": ["writer"], "ns_roles": {"eng": role} + }); + let token = format!("h.{}.s", URL_SAFE_NO_PAD.encode(payload.to_string())); + let claims = decode_token_claims(Some(&token)).unwrap(); + assert_eq!(claims.ns_roles, [("eng".to_owned(), String::new())]); + assert_eq!(claim_allows(&claims, "eng", "writer"), None); + } + } + #[test] fn what_is_not_a_jwt_has_no_claims() { for token in [ diff --git a/sdk/rust/tests/client.rs b/sdk/rust/tests/client.rs index 3d76cfe6d3f..93ce467bf74 100644 --- a/sdk/rust/tests/client.rs +++ b/sdk/rust/tests/client.rs @@ -42,6 +42,9 @@ mod update_filters; #[path = "review_regressions/mod.rs"] mod review_regressions; +#[path = "onboarding_review/mod.rs"] +mod onboarding_review; + #[path = "routes/mod.rs"] mod routes; diff --git a/sdk/rust/tests/onboarding_review/mod.rs b/sdk/rust/tests/onboarding_review/mod.rs new file mode 100644 index 00000000000..aa00c4b109a --- /dev/null +++ b/sdk/rust/tests/onboarding_review/mod.rs @@ -0,0 +1,152 @@ +use super::*; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; + +fn capability(name: &str, role: &str) -> Value { + json!({ + "name": name, "path": format!("/v1/{name}"), "mcp_tool": name, + "mcp_tier": "core", "required_role": role, "budget_p99_ms": 100, + "idempotent": false, "audit": false + }) +} + +fn scoped_token(role: Value) -> String { + let payload = json!({ + "org": "acme", "namespaces": ["eng", "ops"], "roles": ["writer"], + "ns_roles": {"eng": role, "ops": "viewer"} + }); + format!( + "header.{}.signature", + URL_SAFE_NO_PAD.encode(payload.to_string()) + ) +} + +#[tokio::test] +async fn invalid_namespace_roles_never_fall_back_to_flat_writer() { + for role in [ + json!(20), + json!(null), + json!(false), + json!([]), + json!({}), + json!("editor"), + ] { + let server = Server::new(vec![response( + 200, + json!({"ops": [ + capability("memory.set", "writer"), + capability("memory.get", "viewer") + ]}), + "", + )]); + let token = scoped_token(role.clone()); + let client = Client::builder("acme", "eng", "bot") + .base_url(&server.url) + .api_key(&token) + .build() + .unwrap(); + assert_eq!(client.can_call("memory.set").await.unwrap(), None, "{role}"); + let caps = client.permissions(Duration::ZERO).await.unwrap(); + assert_eq!(caps.role(Some("eng")), None, "{role}"); + assert_eq!(caps.can_call("memory.set", Some("eng")), None, "{role}"); + assert!(caps.callable(Some("eng")).is_empty(), "{role}"); + assert_eq!(caps.role(Some("ops")), Some("viewer")); + assert_eq!(caps.can_call("memory.get", Some("ops")), Some(true)); + assert_eq!(caps.can_call("memory.set", Some("ops")), Some(false)); + } +} + +#[tokio::test] +async fn an_entirely_invalid_role_map_keeps_its_authority() { + let server = Server::new(vec![response( + 200, + json!({"ops": [capability("memory.set", "writer")]}), + "", + )]); + let payload = json!({ + "org": "acme", "namespaces": ["eng"], "roles": ["writer"], + "ns_roles": {"eng": 20} + }); + let token = format!( + "header.{}.signature", + URL_SAFE_NO_PAD.encode(payload.to_string()) + ); + let client = Client::builder("acme", "eng", "bot") + .base_url(&server.url) + .api_key(token) + .build() + .unwrap(); + assert_eq!(client.can_call("memory.set").await.unwrap(), None); +} + +enum Advice { + Guide, + Mentor, + Window, +} + +async fn bounded_advice(advice: Advice, status: u16) { + let server = Server::new(vec![response( + status, + json!({"detail": {"code": "OVERLOADED"}}), + if status == 429 { + "Retry-After: 12\r\n" + } else { + "Retry-After: 60\r\n" + }, + )]); + let client = server.client(); + let call = async { + match advice { + Advice::Guide => client + .guide(clickhouse_loom::MentorGuideInputPart::Skill) + .await + .map(|_| ()), + Advice::Mentor => client.mentor().await.map(|_| ()), + Advice::Window => client.mentor_with_window(3600).await.map(|_| ()), + } + }; + let result = tokio::time::timeout(Duration::from_secs(11), call).await; + assert!(result.is_ok(), "advice exceeded its whole-call time limit"); + assert!(matches!(result.unwrap(), Err(Error::Timeout))); + let sent = server.request().await; + assert!(sent.line.contains("mentor.")); +} + +#[tokio::test] +async fn guide_bounds_retry_waits() { + bounded_advice(Advice::Guide, 503).await; +} + +#[tokio::test] +async fn mentor_bounds_retry_waits() { + bounded_advice(Advice::Mentor, 503).await; +} + +#[tokio::test] +async fn mentor_window_bounds_pacing_waits() { + bounded_advice(Advice::Window, 429).await; +} + +#[cfg(feature = "blocking")] +#[test] +fn blocking_advice_bounds_retry_waits() { + let server = Server::new(vec![response(503, "{}", "")]); + let mut retry = RetryPolicy::default(); + retry.max_attempts = 2; + retry.backoff = Duration::from_secs(12); + retry.backoff_max = Duration::from_secs(12); + retry.backoff_jitter = 0.0; + retry.respect_retry_after = false; + let client = clickhouse_loom::blocking::Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("") + .retry(retry) + .build() + .unwrap(); + let started = Instant::now(); + assert!(matches!( + client.guide(clickhouse_loom::MentorGuideInputPart::Skill), + Err(Error::Timeout) + )); + assert!(started.elapsed() < Duration::from_secs(11)); +}