diff --git a/sdk/rust/README.md b/sdk/rust/README.md index 94f84ed5dbc..81790778992 100644 --- a/sdk/rust/README.md +++ b/sdk/rust/README.md @@ -71,7 +71,6 @@ use clickhouse_loom::{Client, SearchRequest, SetRequest}; async fn main() -> Result<(), Box> { let bot = Client::builder("dev", "local", "my-agent") .base_url("http://localhost:7777") - .api_key("") .build()?; let mut write = SetRequest::new("deploy_window", "Deploy Tue/Thu, never Friday"); write.memory_type = Some("semantic".into()); @@ -109,13 +108,68 @@ 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`, `retry`, `pacing`, `ratelimit_max_wait`, +`profile`, `credential_provider` and `consumer`. 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, -requests carry no Authorization header. -Explicit settings override the environment. `.api_key("")` disables authorization. -Empty environment values are treated as unset. +and response body. An explicit `.base_url(...)` selects the server. Otherwise, +the SDK uses the profile or provider's server when it has one, then +`LOOM_BASE_URL`, then `http://localhost:7777`. An explicit server must match a +profile or provider's server binding. + +### Authentication + +A nonempty `.api_key(...)` uses that token. Alternatively, select +`.profile(...)` or `.credential_provider(...)`; configure only one of these +credential sources. An explicit profile or provider takes precedence over +`LOOM_API_KEY`. + +Without an explicit credential source, the SDK checks: + +1. A nonempty `LOOM_API_KEY`. +2. The profile selected by `LOOM_PROFILE` (default `default`) in + `.loom/credentials` in the user's home directory, if its server matches the + selected server. +3. The first line of `.loom/token` in the user's home directory. + +`.api_key("")` and empty environment values are treated as unset; they do not +disable credential discovery. Requests carry no Authorization header only when +no credential is found, or an explicit provider returns an empty token. For an +unauthenticated local connection, check that no matching stored login or legacy +token is present. + +Sign in with the Loom CLI, then select that profile: + +```bash +loom login --profile team +``` + +```rust +use clickhouse_loom::Client; + +let bot = Client::builder("my-org", "my-namespace", "rust-agent") + .profile("team") + .build()?; +let memory = bot.get("preference").await?; +``` + +The profile supplies its server and tokens. `StoredLogin::from_file(path, profile)` +reads a profile from an application-selected credentials file; pass it to +`.credential_provider(...)`. Applications can also implement +`CredentialProvider` to supply and replace tokens themselves. + +Stored login refreshes an access token when it has at most 60 seconds left. +Concurrent refreshes share a credentials-file lock and save rotated tokens before +returning them. If renewal is temporarily unavailable, an unexpired token that +has not been rejected can still be used. Otherwise, the call returns a +retryable `Error::Credentials`. A revoked refresh token requires `loom login` +again. + +On HTTP 401, the SDK asks the provider to replace the rejected token and resends +only if it changed. An unchanged token or a second rejection ends authentication +retries. Fixed API keys are not refreshed. These rules apply to the async and +blocking clients and to routes outside the op registry. + +### Identity and request defaults Builder identity values apply to declared caller and authorship fields. `knowledge_add` and `knowledge_upsert` receive agent and session identity; @@ -513,9 +567,10 @@ a route takes the org, namespace and other fields it needs from them. `request` returns the whole response of a status below 400 with its status and headers; a redirect is returned, not followed. `request_json` decodes the body as the requested type; an empty body decodes as an empty object and an invalid -one is `Error::Protocol`. A status of 400 or higher is `Error::Api`. The SDK -resends only on a 429, after the server's hint and within the client's pacing -budget. The HTTP transport does not retry requests. A refused HTTP/2 stream +one is `Error::Protocol`. A status of 400 or higher is `Error::Api`. On a 429, +the SDK resends after the server's hint and within the client's pacing budget. +On a 401, it can resend once with a changed token as described in +[Authentication](#authentication). The HTTP transport does not retry requests. A refused HTTP/2 stream returns `Error::Transport`. `request_with_options` and `request_json_with_options` accept `CallOptions` diff --git a/sdk/rust/examples/README.md b/sdk/rust/examples/README.md index d1bb38738a0..8d745abb9d7 100644 --- a/sdk/rust/examples/README.md +++ b/sdk/rust/examples/README.md @@ -33,13 +33,17 @@ cargo run --manifest-path sdk/rust/Cargo.toml --example operations cargo run --manifest-path sdk/rust/Cargo.toml --features blocking --example blocking ``` -The empty token is for a local server that permits unauthenticated requests. -For a team deployment, set `LOOM_API_KEY` to your token before running Cargo. +An empty `LOOM_API_KEY` leaves credential discovery enabled. For unauthenticated +local requests, no matching stored login or legacy token may be present. +For a team deployment, set `LOOM_API_KEY` to your token or sign in with +`loom login` and select a matching profile through `LOOM_PROFILE`. +See the [authentication contract](../README.md#authentication). | Variable | Default | Purpose | | ------------------- | ----------------------- | ------------------------------------------------------------------ | | `LOOM_BASE_URL` | `http://localhost:7777` | Server address, read by the SDK | -| `LOOM_API_KEY` | Unset | Bearer token; empty means no Authorization header | +| `LOOM_API_KEY` | Unset | Bearer token; empty continues stored credential discovery | +| `LOOM_PROFILE` | `default` | Stored login profile, used when its server matches `LOOM_BASE_URL` | | `LOOM_ORG` | `dev` | Organization, read by each example | | `LOOM_NAMESPACE` | `local` | Namespace, read by each example | | `LOOM_CHECK_HEALTH` | Unset | `1` adds an `ops.health` call in `operations.rs` and `blocking.rs` | @@ -53,6 +57,20 @@ Writes use the server's configured embedding provider. Indexing may still be pending when a search runs. `operations.rs` and `blocking.rs` print search results without requiring an immediate hit; `memory.rs` requires its saved key to appear. +## renew_login.rs + +The [renew_login.rs](renew_login.rs) example uses a stored login profile to read +the `preference` memory key. Select a namespace that the login can access: + +```bash +loom login --profile team +LOOM_NAMESPACE=my-namespace cargo run --manifest-path sdk/rust/Cargo.toml --example renew_login -- team +``` + +The profile supplies the server and tokens. The profile argument defaults to +`default`; `LOOM_NAMESPACE` has no default and must be nonblank. The example +prints `found: true` or `found: false`. + ## memory.rs The [memory.rs](memory.rs) example saves a value under an agent identity, reads diff --git a/sdk/rust/examples/renew_login.rs b/sdk/rust/examples/renew_login.rs index e20e0b7b861..9aeac3007b1 100644 --- a/sdk/rust/examples/renew_login.rs +++ b/sdk/rust/examples/renew_login.rs @@ -3,10 +3,29 @@ use clickhouse_loom::{Client, StoredLogin}; #[tokio::main] async fn main() -> Result<(), Box> { let profile = std::env::args().nth(1).unwrap_or_else(|| "default".into()); - let client = Client::builder("", "", "profile-example") - .credential_provider(StoredLogin::profile(profile)?) + let namespace = required_namespace(std::env::var("LOOM_NAMESPACE").ok())?; + let found = read_preference(StoredLogin::profile(profile)?, namespace).await?; + println!("found: {found}"); + Ok(()) +} + +fn required_namespace(namespace: Option) -> Result { + namespace + .filter(|value| !value.trim().is_empty()) + .ok_or("set LOOM_NAMESPACE to a namespace your login can access") +} + +async fn read_preference( + login: StoredLogin, + namespace: String, +) -> Result> { + let client = Client::builder("", namespace, "profile-example") + .credential_provider(login) .build()?; let memory = client.get("preference").await?; - println!("found: {}", memory.found); - Ok(()) + Ok(memory.found) } + +#[cfg(test)] +#[path = "../tests/renew_login_example/mod.rs"] +mod tests; diff --git a/sdk/rust/tests/renew_login_example/mod.rs b/sdk/rust/tests/renew_login_example/mod.rs new file mode 100644 index 00000000000..95454ef35a5 --- /dev/null +++ b/sdk/rust/tests/renew_login_example/mod.rs @@ -0,0 +1,119 @@ +use super::*; +use std::{ + io::{BufRead, BufReader, Read, Write}, + net::TcpListener, + thread, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; + +#[tokio::test] +async fn stored_login_read_sends_the_selected_namespace() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let server = format!("http://{}", listener.local_addr().unwrap()); + listener.set_nonblocking(true).unwrap(); + let worker = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(5); + let mut stream = loop { + assert!(Instant::now() < deadline, "example did not send a request"); + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::park_timeout(Duration::from_millis(5)); + } + Err(error) => panic!("accept: {error}"), + } + }; + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(&mut stream); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert!(line.starts_with("POST /v1/memory.get ")); + let mut length = 0; + let mut authorized = false; + loop { + line.clear(); + assert!(reader.read_line(&mut line).unwrap() > 0); + if line == "\r\n" { + break; + } + let (name, value) = line.split_once(':').unwrap(); + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse().unwrap(); + } + if name.eq_ignore_ascii_case("authorization") { + authorized = value.trim() == "Bearer stored-token"; + } + } + let mut bytes = vec![0; length]; + reader.read_exact(&mut bytes).unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let (status, response) = if body.get("namespace").is_some() { + ("200 OK", r#"{"found":false}"#) + } else { + ( + "422 Unprocessable Entity", + r#"{"detail":"namespace is required"}"#, + ) + }; + write!( + stream, + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}", + response.len() + ) + .unwrap(); + (authorized, body) + }); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("credentials"); + let expires = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() + + 3600; + std::fs::write( + &path, + serde_json::json!({ + "profiles": { + "team": { + "server": server, + "access_token": "stored-token", + "refresh_token": "refresh-token", + "expires_at": expires, + "session": "example-test", + "marked": true + } + } + }) + .to_string(), + ) + .unwrap(); + let login = StoredLogin::from_file(path, "team").unwrap(); + let result = read_preference(login, "team-memory".into()).await; + let (authorized, body) = worker.join().unwrap(); + assert!(!result.unwrap()); + assert!(authorized); + assert_eq!(body["namespace"], "team-memory"); + assert_eq!(body["memory_key"], "preference"); + assert_eq!(body["org"], ""); +} + +#[test] +fn missing_or_blank_namespace_is_rejected() { + for namespace in [None, Some(String::new()), Some(" \t ".into())] { + let error = required_namespace(namespace).unwrap_err(); + assert_eq!( + error, + "set LOOM_NAMESPACE to a namespace your login can access" + ); + } + assert_eq!( + required_namespace(Some("team-memory".into())).unwrap(), + "team-memory" + ); +}