Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Merge remote-tracking branch 'upstream/main' into saas-default-agent-tenant

Steven Enamakelac1b745f365e
diff --cc tests/saas_mode/memory.rs
index 0000000000,ef52da3b5f..24a7fc7094
mode 000000,100644..100644
--- a/tests/saas_mode/memory.rs
+++ b/tests/saas_mode/memory.rs
@@@ -1,0 -1,378 +1,367 @@@
+ //! Memory round trips across SaaS profiles, through the real binary and a
+ //! backend that actually serves `/memory/*` ([`MockMemory`]).
+ //!
+ //! Each profile runs the hosted `tinyhumans` engine with its own credential,
+ //! confined to `user:<id>` on the legacy layout (`profiles::layout`). The
+ //! mock keeps one store for every bearer, so nothing but the core's own
+ //! confinement keeps the profiles apart: the case `memory::user_scope`
+ //! defends, users sharing one engine.
+ //!
+ //! `ann` and `anna` are deliberate: one root is a string prefix of the
+ //! other, and a scope listing is a string-prefix match.
+
+ use std::path::PathBuf;
+
+ use super::mock_memory::{credential_id, MemoryRequest, MockMemory};
+ use super::*;
+
+ const USERS: [&str; 3] = ["ann", "anna", "bob"];
+
+ fn canary(user: &str) -> String {
+ format!("canary {user} keeps the secret word {user}-quince-7f3a")
+ }
+
+ /// The secret part of `user`'s canary, unique to that user.
+ fn secret(user: &str) -> String {
+ format!("{user}-quince-7f3a")
+ }
+
+ /// The legacy scope path of `user`'s memory root.
+ fn root_path(profile: &str) -> String {
+ format!("app:tinymemory/user:{profile}")
+ }
+
+ fn token(user: &str) -> String {
+ format!("{user}-memory-jwt")
+ }
+
+ /// Whether `scope` is `root` or lies below it (segment-wise).
+ fn inside(scope: &str, root: &str) -> bool {
+ scope == root || scope.starts_with(&format!("{root}/"))
+ }
+
+ struct Stack {
+ _server: Server,
+ base: String,
+ client: reqwest::blocking::Client,
+ mock: MockMemory,
+ log: PathBuf,
+ _d: Deployment,
+ }
+
+ impl Stack {
+ fn start() -> Self {
+ let d = deployment(true);
+ let mock = MockMemory::start();
- let port = free_port();
+ let log = d.tmp.path().join("core.log");
- let child = core_command(&d, &["--port", &port.to_string()])
- .env("BACKEND_URL", format!("http://127.0.0.1:{}", mock.port))
- .env("RUST_LOG", "info,openhuman::memory=debug")
- .stdout(std::fs::File::create(&log).unwrap())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn openhuman-core");
- let server = Server(child);
- let base = format!("http://127.0.0.1:{port}");
++ let (server, base) = spawn_core(|port| {
++ let mut cmd = core_command(&d, &["--port", &port.to_string()]);
++ cmd.env("BACKEND_URL", format!("http://127.0.0.1:{}", mock.port))
++ .env("RUST_LOG", "info,openhuman::memory=debug")
++ .stdout(std::fs::File::create(&log).unwrap())
++ .stderr(Stdio::null());
++ cmd
++ });
+ let client = reqwest::blocking::Client::builder()
+ .timeout(Duration::from_secs(60))
+ .build()
+ .unwrap();
- let deadline = Instant::now() + Duration::from_secs(120);
- while !client
- .get(format!("{base}/health"))
- .send()
- .is_ok_and(|r| r.status().is_success())
- {
- assert!(Instant::now() < deadline, "SaaS core never became healthy");
- std::thread::sleep(Duration::from_millis(250));
- }
+ Self {
+ _server: server,
+ base,
+ client,
+ mock,
+ log,
+ _d: d,
+ }
+ }
+
+ /// Provisions `user` with a session credential of their own; returns the
+ /// profile id.
+ fn provision(&self, user: &str) -> String {
+ let profile = provision(&self.client, &self.base, user);
+ let (_, body) = rpc_with(
+ &self.client,
+ &self.base,
+ Some(BEARER),
+ "openhuman.profiles_set_credential",
+ json!({ "profile_id": profile, "kind": "session", "token": token(user) }),
+ );
+ assert!(body.get("result").is_some(), "{body}");
+ profile
+ }
+
+ /// `method` as `user`; the whole JSON-RPC body.
+ fn call(&self, user: &str, method: &str, params: Value) -> Value {
+ let (status, body) =
+ user_rpc_with(&self.client, &self.base, BEARER, user, None, method, params);
+ assert_eq!(status, 200, "{user} {method}: {body}");
+ body
+ }
+
+ /// `method` as `user`, which must succeed; its result.
+ fn ok(&self, user: &str, method: &str, params: Value) -> Value {
+ let body = self.call(user, method, params);
+ let result = body.get("result").unwrap_or_else(|| {
+ panic!(
+ "{user} {method} failed: {body}\ncore log:\n{}",
+ self.log_tail()
+ )
+ });
+ result.get("result").unwrap_or(result).clone()
+ }
+
+ fn log_tail(&self) -> String {
+ let log = std::fs::read_to_string(&self.log).unwrap_or_default();
+ let lines: Vec<&str> = log.lines().collect();
+ lines[lines.len().saturating_sub(60)..].join("\n")
+ }
+ }
+
+ /// Asserts `body` holds none of the secrets of anyone but `user`.
+ fn holds_only_own(user: &str, what: &str, body: &Value) {
+ let text = body.to_string();
+ for other in USERS.iter().filter(|other| **other != user) {
+ assert!(
+ !text.contains(&secret(other)),
+ "{what} as {user} leaked {other}'s memory: {text}"
+ );
+ }
+ }
+
+ #[test]
+ fn profiles_round_trip_their_own_memory_and_never_anothers() {
+ let s = Stack::start();
+ let profiles: Vec<(String, String)> = USERS
+ .iter()
+ .map(|user| (user.to_string(), s.provision(user)))
+ .collect();
+
+ // Each profile stores its canary through the user surface.
+ let mut learned = std::collections::HashMap::new();
+ for (user, _) in &profiles {
+ let view = s.ok(
+ user,
+ "openhuman.memory_learn",
+ json!({ "text": canary(user), "kind": "fact" }),
+ );
+ let id = view["id"]
+ .as_str()
+ .expect("learn returns an id")
+ .to_string();
+ learned.insert(user.clone(), id);
+ }
+ for (user, profile) in &profiles {
+ let scopes = s.mock.scopes_holding(&secret(user));
+ assert!(!scopes.is_empty(), "{user}'s canary reached the backend");
+ for scope in scopes {
+ assert!(
+ inside(&scope, &root_path(profile)),
+ "{user}'s canary landed outside their root: {scope}"
+ );
+ }
+ }
+
+ // Each reads its own back, and only its own.
+ for (user, _) in &profiles {
+ let listed = s.ok(
+ user,
+ "openhuman.memory_items_list",
+ json!({ "filter": { "kinds": ["learning"] } }),
+ );
+ assert!(
+ listed.to_string().contains(&secret(user)),
+ "{user} lists their canary: {listed}"
+ );
+ holds_only_own(user, "items_list", &listed);
+
+ let fetched = s.ok(
+ user,
+ "openhuman.memory_fetch",
+ json!({ "query": "canary secret quince" }),
+ );
+ assert!(
+ fetched.to_string().contains(&secret(user)),
+ "{user} fetches their canary: {fetched}"
+ );
+ holds_only_own(user, "fetch", &fetched);
+
+ let recalled = s.ok(
+ user,
+ "openhuman.memory_recall",
+ json!({ "question": "what is the canary secret quince word?" }),
+ );
+ assert!(
+ recalled.to_string().contains(&secret(user)),
+ "{user} recalls their canary: {recalled}"
+ );
+ holds_only_own(user, "recall", &recalled);
+
+ for facet in ["namespace", "kind", "agent"] {
+ let explored = s.ok(user, "openhuman.memory_explore", json!({ "facet": facet }));
+ holds_only_own(user, &format!("explore by {facet}"), &explored);
+ let text = explored.to_string();
+ for (other, other_profile) in &profiles {
+ if other != user {
+ assert!(
+ !text.contains(&format!("user:{other_profile}\"")),
+ "explore by {facet} as {user} names {other}'s root: {text}"
+ );
+ }
+ }
+ }
+ }
+
+ // A malicious user aims every parameter they control at someone else.
+ let (attacker, attacker_profile) = (&profiles[0].0, &profiles[0].1);
+ for (victim, victim_profile) in profiles.iter().skip(1) {
+ let foreign = format!("user:{victim_profile}");
+ let reaches = [
+ json!({ "at": foreign, "descendants": true, "inherit": false }),
+ json!({ "at": foreign, "descendants": false, "inherit": true }),
+ json!({ "at": format!("{foreign}/agent:x"), "descendants": true }),
+ json!({ "at": "", "descendants": true }),
+ ];
+ for reach in &reaches {
+ let filter = json!({ "reach": reach });
+ for (method, params) in [
+ ("openhuman.memory_items_list", json!({ "filter": filter })),
+ (
+ "openhuman.memory_fetch",
+ json!({ "query": "canary quince", "filter": filter }),
+ ),
+ (
+ "openhuman.memory_recall",
+ json!({ "question": "canary quince", "filter": filter }),
+ ),
+ (
+ "openhuman.memory_explore",
+ json!({ "facet": "namespace", "filter": filter }),
+ ),
+ ] {
+ let body = s.call(attacker, method, params);
+ holds_only_own(attacker, &format!("{method} reaching {reach}"), &body);
+ }
+ let body = s.call(
+ attacker,
+ "openhuman.memory_forget",
+ json!({ "ids": [learned[victim]], "reach": reach }),
+ );
+ holds_only_own(attacker, "forget", &body);
+ }
+ for step in [foreign.clone(), String::new()] {
+ let body = s.call(
+ attacker,
+ "openhuman.memory_items_list",
+ json!({ "path": [{ "facet": "namespace", "value": step }] }),
+ );
+ holds_only_own(attacker, "items_list down a foreign path", &body);
+ }
+
+ // Forgetting the victim's id, with no reach at all, forgets nothing.
+ let body = s.call(
+ attacker,
+ "openhuman.memory_forget",
+ json!({ "ids": [learned[victim]] }),
+ );
+ if let Some(result) = body.get("result") {
+ let result = result.get("result").unwrap_or(result);
+ assert_eq!(result["forgotten"], json!(0), "{body}");
+ }
+
+ // Writing into the victim's tree lands in the attacker's, or not at all.
+ let planted = format!("planted by {attacker} into {victim}");
+ for namespace in [foreign.clone(), format!("{foreign}/agent:main")] {
+ let _ = s.call(
+ attacker,
+ "openhuman.memory_learn",
+ json!({ "text": planted, "meta": { "namespace": namespace } }),
+ );
+ }
+ for scope in s.mock.scopes_holding(&planted) {
+ assert!(
+ inside(&scope, &root_path(attacker_profile)),
+ "{attacker} planted into {scope}"
+ );
+ }
+ let listed = s.ok(
+ victim,
+ "openhuman.memory_items_list",
+ json!({ "filter": { "kinds": ["learning"] } }),
+ );
+ assert!(
+ !listed.to_string().contains(&planted),
+ "{victim} reads what {attacker} planted: {listed}"
+ );
+ assert!(
+ listed.to_string().contains(&secret(victim)),
+ "{victim} still holds their canary after {attacker}'s attempts: {listed}"
+ );
+ }
+
+ // A profile forgets its own memory; the others keep theirs.
+ let sweep_start = s.mock.requests().len();
+ let forgotten = s.ok(
+ attacker,
+ "openhuman.memory_forget",
+ json!({ "ids": [learned[attacker]] }),
+ );
+ let sweep = sweep_start..s.mock.requests().len();
+ assert_eq!(forgotten["forgotten"], json!(1), "{forgotten}");
+ for (user, _) in profiles.iter().skip(1) {
+ let listed = s.ok(
+ user,
+ "openhuman.memory_items_list",
+ json!({ "filter": { "kinds": ["learning"] } }),
+ );
+ assert!(
+ listed.to_string().contains(&secret(user)),
+ "{user} keeps their canary after {attacker} forgot theirs: {listed}"
+ );
+ }
+
+ // On the wire: every memory request carried one profile's credential,
+ // and named only scopes inside that profile's root.
+ //
+ // One known exception, read-only: forgetting by id. TinyMemory's
+ // `ForgetTarget::Ids` is unscoped by contract (ids are not namespaced;
+ // a confined caller reads them through `get` in its reach first, which
+ // `memory::ops::forget` does), so the engine then sweeps every scope
+ // from the tree's root looking for the ids' events. On a shared engine
+ // that sweep lists and reads other profiles' scopes with the caller's
+ // credential. Nothing read there reaches the caller, and nothing there
+ // is forgotten: an item id is a fingerprint of the item and its
+ // namespace, so no other tree holds it (checked above: everyone keeps
+ // their canary). Only the sweep's listings may leave the root; its
+ // forget, like every other write, must not.
+ let requests = s.mock.requests();
+ assert!(!requests.is_empty());
+ let owners: std::collections::HashMap<String, String> = profiles
+ .iter()
+ .map(|(user, profile)| (credential_id(&token(user)), root_path(profile)))
+ .collect();
+ let mut seen = std::collections::HashSet::new();
+ for (index, request) in requests.iter().enumerate() {
+ let MemoryRequest {
+ method,
+ path,
+ bearer,
+ scopes,
+ } = request;
+ let root = owners.get(bearer).unwrap_or_else(|| {
+ panic!("request {index}, {method} {path}, carried no profile's credential")
+ });
+ seen.insert(bearer.clone());
+ let sweeping = sweep.contains(&index)
+ && method == "GET"
+ && matches!(path.as_str(), "/memory/scopes" | "/memory/events")
+ && bearer == &credential_id(&token(attacker));
+ for scope in scopes {
+ assert!(
+ inside(scope, root) || (sweeping && inside(scope, "app:tinymemory")),
+ "request {index}, {method} {path} with {root}'s credential, named {scope}"
+ );
+ }
+ }
+ assert_eq!(seen.len(), USERS.len(), "every profile reached the backend");
+ }
diff --cc tests/saas_mode/node.rs
index 0000000000,b04cf6b7f3..6dc2334b18
mode 000000,100644..100644
--- a/tests/saas_mode/node.rs
+++ b/tests/saas_mode/node.rs
@@@ -1,0 -1,262 +1,252 @@@
+ //! One `openhuman-core` node of a deployment with its own operator file,
+ //! port and log, and signed calls against it (the cluster suites and the
+ //! isolation suite).
+
+ use std::path::PathBuf;
+ use std::process::{Command, Stdio};
+ use std::time::{Duration, Instant};
+
+ use serde_json::{json, Value};
+
+ use super::*;
+
++/// The last lines of a core's log, without the polling RPCs and without lines
++/// that may carry a credential.
++pub fn log_tail_of(path: &std::path::Path) -> String {
++ let log = std::fs::read_to_string(path).unwrap_or_default();
++ // The polling RPCs drown everything else out.
++ let lines: Vec<&str> = log
++ .lines()
++ .filter(|line| !line.contains("rpc_handler [rpc]"))
++ .collect();
++ // A failure trace is shared output: drop lines that may carry a
++ // credential and cap the rest.
++ lines[lines.len().saturating_sub(80)..]
++ .iter()
++ .map(|line| {
++ let lower = line.to_ascii_lowercase();
++ if [
++ "bearer",
++ "token",
++ "authorization",
++ "secret",
++ "password",
++ "canary",
++ ]
++ .iter()
++ .any(|k| lower.contains(k))
++ {
++ "[redacted log line]".to_string()
++ } else {
++ line.chars().take(300).collect()
++ }
++ })
++ .collect::<Vec<String>>()
++ .join("\n")
++}
++
+ /// One core of a deployment.
+ pub struct Node {
+ pub name: String,
+ pub server: Server,
+ pub base: String,
+ pub log: PathBuf,
+ }
+
+ impl Node {
+ pub fn log_tail(&self) -> String {
- let log = std::fs::read_to_string(&self.log).unwrap_or_default();
- // The polling RPCs drown everything else out.
- let lines: Vec<&str> = log
- .lines()
- .filter(|line| !line.contains("rpc_handler [rpc]"))
- .collect();
- // A failure trace is shared output: drop lines that may carry a
- // credential and cap the rest.
- lines[lines.len().saturating_sub(80)..]
- .iter()
- .map(|line| {
- let lower = line.to_ascii_lowercase();
- if [
- "bearer",
- "token",
- "authorization",
- "secret",
- "password",
- "canary",
- ]
- .iter()
- .any(|k| lower.contains(k))
- {
- "[redacted log line]".to_string()
- } else {
- line.chars().take(300).collect()
- }
- })
- .collect::<Vec<String>>()
- .join("\n")
++ log_tail_of(&self.log)
+ }
+
+ pub fn kill(&mut self) {
+ // SIGKILL on Unix: no shutdown hook runs, no lease is released.
+ self.server.0.kill().expect("kill core");
+ let _ = self.server.0.wait();
+ }
+ }
+
+ /// Write node `name`'s operator file on deployment `d` and start it.
+ pub fn start_node(
+ d: &Deployment,
+ name: &str,
+ storage_url: Option<&str>,
+ extra: &str,
+ backend: Option<u16>,
+ ) -> Node {
+ start_node_logging(
+ d,
+ name,
+ storage_url,
+ extra,
+ backend,
+ "info,openhuman_core::storage::lease=debug",
+ )
+ }
+
+ /// [`start_node`] with the child's `RUST_LOG`.
+ pub fn start_node_logging(
+ d: &Deployment,
+ name: &str,
+ storage_url: Option<&str>,
+ extra: &str,
+ backend: Option<u16>,
+ rust_log: &str,
+ ) -> Node {
- let port = free_port();
- let base = format!("http://127.0.0.1:{port}");
- let mut config = format!(
- "root = {:?}\nnode_id = \"core-{name}\"\noperator_dir = {:?}\nlease_ttl_secs = 3\n",
- d.root.display().to_string(),
- d.tmp
- .path()
- .join(format!("operator-{name}"))
- .display()
- .to_string(),
- );
- if let Some(url) = storage_url {
- config.push_str(&format!(
- "storage_url = {url:?}\nadvertise_url = {base:?}\n"
- ));
- }
- config.push_str(extra);
++ let log = d.tmp.path().join(format!("core-{name}.log"));
+ let config_path = d.tmp.path().join(format!("operator-{name}.toml"));
- std::fs::write(&config_path, config).unwrap();
++ let (server, base) = spawn_core_with(
++ |port| {
++ // The operator file names the port (`advertise_url`), so it is
++ // written again for each port tried.
++ let base = format!("http://127.0.0.1:{port}");
++ let mut config = format!(
++ "root = {:?}\nnode_id = \"core-{name}\"\noperator_dir = {:?}\nlease_ttl_secs = 3\n",
++ d.root.display().to_string(),
++ d.tmp
++ .path()
++ .join(format!("operator-{name}"))
++ .display()
++ .to_string(),
++ );
++ if let Some(url) = storage_url {
++ config.push_str(&format!(
++ "storage_url = {url:?}\nadvertise_url = {base:?}\n"
++ ));
++ }
++ config.push_str(extra);
++ std::fs::write(&config_path, config).unwrap();
+
- let log = d.tmp.path().join(format!("core-{name}.log"));
- let mut cmd = Command::new(env!("CARGO_BIN_EXE_openhuman-core"));
- cmd.args(["run", "--mode", "saas", "--saas-config"])
- .arg(&config_path)
- .args(["--port", &port.to_string()])
- .env("HOME", d.tmp.path())
- .env("USERPROFILE", d.tmp.path())
- .env("RUST_LOG", rust_log)
- .stdout(std::fs::File::create(&log).unwrap())
- .stderr(Stdio::null());
- for var in SCRUBBED_ENV {
- cmd.env_remove(var);
- }
- match backend {
- Some(port) => cmd.env("BACKEND_URL", format!("http://127.0.0.1:{port}")),
- None => cmd.env("BACKEND_URL", "http://127.0.0.1:9"),
- };
- let child: Child = cmd.spawn().expect("spawn openhuman-core");
- let mut node = Node {
++ let mut cmd = Command::new(env!("CARGO_BIN_EXE_openhuman-core"));
++ cmd.args(["run", "--mode", "saas", "--saas-config"])
++ .arg(&config_path)
++ .args(["--port", &port.to_string()])
++ .env("HOME", d.tmp.path())
++ .env("USERPROFILE", d.tmp.path())
++ .env("RUST_LOG", rust_log)
++ .stdout(std::fs::File::create(&log).unwrap())
++ .stderr(Stdio::null());
++ for var in SCRUBBED_ENV {
++ cmd.env_remove(var);
++ }
++ match backend {
++ Some(port) => cmd.env("BACKEND_URL", format!("http://127.0.0.1:{port}")),
++ None => cmd.env("BACKEND_URL", "http://127.0.0.1:9"),
++ };
++ cmd
++ },
++ || format!("core {name}:\n{}", log_tail_of(&log)),
++ );
++ Node {
+ name: name.to_string(),
- server: Server(child),
++ server,
+ base,
+ log,
- };
- let client = client();
- let deadline = Instant::now() + Duration::from_secs(120);
- while !client
- .get(format!("{}/health", node.base))
- .send()
- .is_ok_and(|r| r.status().is_success())
- {
- if let Ok(Some(status)) = node.server.0.try_wait() {
- panic!(
- "core {} exited before serving: {status}\n{}",
- node.name,
- node.log_tail()
- );
- }
- assert!(
- Instant::now() < deadline,
- "core {} never became healthy",
- name
- );
- std::thread::sleep(Duration::from_millis(250));
+ }
- node
+ }
+
+ pub fn client() -> reqwest::blocking::Client {
+ reqwest::blocking::Client::builder()
+ .timeout(Duration::from_secs(10))
+ .build()
+ .unwrap()
+ }
+
+ /// POST /rpc for `user` on `node`: status, `X-OpenHuman-Profile-Owner`, body.
+ pub fn call(node: &Node, user: &str, method: &str, params: Value) -> (u16, Option<String>, Value) {
+ use openhuman_core::profiles::gateway::{sign, USER_HEADER, USER_SIG_HEADER};
+ let response = client()
+ .post(format!("{}/rpc", node.base))
+ .bearer_auth(BEARER)
+ .header(USER_HEADER, user)
+ .header(USER_SIG_HEADER, sign(BEARER, user, now()))
+ .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": method, "params": params }))
+ .send()
+ .expect("POST /rpc");
+ let status = response.status().as_u16();
+ let owner = response
+ .headers()
+ .get("x-openhuman-profile-owner")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
+ (status, owner, response.json().unwrap_or(Value::Null))
+ }
+
+ pub fn operator(node: &Node, method: &str, params: Value) -> Value {
+ let (_, body) = rpc_with(&client(), &node.base, Some(BEARER), method, params);
+ body
+ }
+
+ /// Provision `user` (through `node`) with a session credential, so their
+ /// turns reach inference.
+ pub fn provision_with_credential(node: &Node, user: &str) -> String {
+ let profile = provision(&client(), &node.base, user);
+ let body = operator(
+ node,
+ "openhuman.profiles_set_credential",
+ json!({ "profile_id": profile, "kind": "session", "token": format!("{user}-jwt") }),
+ );
+ assert!(body.get("result").is_some(), "{body}");
+ profile
+ }
+
+ pub fn start_turn(node: &Node, user: &str, thread: &str) -> Value {
+ let (status, _, body) = call(
+ node,
+ user,
+ "openhuman.channel_web_chat",
+ json!({ "client_id": "c1", "thread_id": thread, "message": "hello" }),
+ );
+ assert_eq!(status, 200, "{user} starts a turn on {thread}: {body}");
+ assert!(body.get("result").is_some(), "{body}");
+ body
+ }
+
+ /// Whether `user`'s turn on `thread` is in flight on `node`.
+ pub fn active(node: &Node, user: &str, thread: &str) -> bool {
+ let (status, _, body) = call(
+ node,
+ user,
+ "openhuman.channel_web_queue_status",
+ json!({ "thread_id": thread }),
+ );
+ status == 200 && body.to_string().contains("\"active\":true")
+ }
+
+ pub fn wait_until(what: &str, node: &Node, timeout: Duration, mut done: impl FnMut() -> bool) {
+ let deadline = Instant::now() + timeout;
+ while !done() {
+ assert!(
+ Instant::now() < deadline,
+ "timed out waiting for {what}; core {} log:\n{}",
+ node.name,
+ node.log_tail()
+ );
+ std::thread::sleep(Duration::from_millis(200));
+ }
+ }
+
+ /// The lifecycle of `user`'s latest turn snapshot on `thread`, if any.
+ pub fn turn_state(node: &Node, user: &str, thread: &str) -> Option<String> {
+ let (status, _, body) = call(
+ node,
+ user,
+ "openhuman.threads_turn_state_get",
+ json!({ "thread_id": thread }),
+ );
+ assert_eq!(status, 200, "{body}");
+ body.pointer("/result/data/turnState/lifecycle")
+ .or_else(|| body.pointer("/result/result/data/turnState/lifecycle"))
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ }
+
+ /// The first value under `key` anywhere in `value`.
+ pub fn find_key<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
+ match value {
+ Value::Object(map) => map
+ .get(key)
+ .or_else(|| map.values().find_map(|v| find_key(v, key))),
+ Value::Array(items) => items.iter().find_map(|v| find_key(v, key)),
+ _ => None,
+ }
+ }
diff --cc tests/saas_mode/support.rs
index 0000000000,c181a5e619..9b9f5c198a
mode 000000,100644..100644
--- a/tests/saas_mode/support.rs
+++ b/tests/saas_mode/support.rs
@@@ -1,0 -1,341 +1,388 @@@
+ //! Helpers shared by the SaaS end-to-end suites (`saas_mode_e2e`,
+ //! `saas_profile_isolation_e2e`): a deployment on a temp root, a real
+ //! `openhuman-core run --mode saas` child, signed gateway calls for a user,
+ //! their `/events` stream, and fake backends.
+
+ #![allow(dead_code)]
+
+ use std::path::{Path, PathBuf};
+ use std::process::{Child, Command, Stdio};
+ use std::time::{Duration, Instant};
+
+ use serde_json::{json, Value};
+
+ pub const BEARER: &str = "saas-e2e-gateway-bearer-0123456789abcdef";
+
+ /// Environment a developer machine may carry that would point the child at a
+ /// single user, or that the boot guard refuses outright.
+ pub const SCRUBBED_ENV: &[&str] = &[
+ "OPENHUMAN_WORKSPACE",
+ "OPENHUMAN_DEV_CONNECT",
+ "OPENHUMAN_BACKEND_SESSION_TOKEN",
+ "OPENHUMAN_BACKEND_API_KEY",
+ "OPENHUMAN_CORE_TOKEN",
+ "OPENHUMAN_APPROVAL_GATE",
+ "OPENHUMAN_SANDBOX",
+ "OPENHUMAN_MODE",
+ "OPENHUMAN_STORAGE_URL",
+ "OPENHUMAN_NODE_ID",
+ "BACKEND_URL",
+ "VITE_BACKEND_URL",
+ ];
+
+ pub struct Deployment {
+ pub tmp: tempfile::TempDir,
+ pub root: PathBuf,
+ pub config: PathBuf,
+ }
+
+ pub fn deployment(write_token: bool) -> Deployment {
+ let tmp = tempfile::tempdir().expect("temp dir");
+ let root = tmp.path().join("saas");
+ std::fs::create_dir(&root).unwrap();
+ set_mode(&root, 0o700);
+ if write_token {
+ let token = root.join("service.token");
+ std::fs::write(&token, format!("{BEARER}\n")).unwrap();
+ set_mode(&token, 0o600);
+ }
+ let config = tmp.path().join("operator.toml");
+ std::fs::write(
+ &config,
+ format!("root = {:?}\n", root.display().to_string()),
+ )
+ .unwrap();
+ Deployment { tmp, root, config }
+ }
+
+ #[cfg(unix)]
+ pub fn set_mode(path: &Path, mode: u32) {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
+ }
+
+ #[cfg(not(unix))]
+ pub fn set_mode(_: &Path, _: u32) {}
+
+ pub fn core_command(d: &Deployment, extra: &[&str]) -> Command {
+ let mut cmd = Command::new(env!("CARGO_BIN_EXE_openhuman-core"));
+ cmd.args(["run", "--mode", "saas", "--saas-config"])
+ .arg(&d.config)
+ .args(extra)
+ // Keep the child away from the developer's real `~/.openhuman`.
+ .env("HOME", d.tmp.path())
+ .env("USERPROFILE", d.tmp.path());
+ for var in SCRUBBED_ENV {
+ cmd.env_remove(var);
+ }
+ cmd
+ }
+
+ pub struct Server(pub Child);
+
+ impl Drop for Server {
+ fn drop(&mut self) {
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+ }
+
+ pub fn free_port() -> u16 {
+ std::net::TcpListener::bind("127.0.0.1:0")
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port()
+ }
+
+ pub fn rpc(
+ client: &reqwest::blocking::Client,
+ base: &str,
+ bearer: Option<&str>,
+ method: &str,
+ ) -> (u16, Value) {
+ rpc_with(client, base, bearer, method, json!({}))
+ }
+
+ pub fn rpc_with(
+ client: &reqwest::blocking::Client,
+ base: &str,
+ bearer: Option<&str>,
+ method: &str,
+ params: Value,
+ ) -> (u16, Value) {
+ let mut request = client.post(format!("{base}/rpc")).json(&json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": method,
+ "params": params
+ }));
+ if let Some(bearer) = bearer {
+ request = request.bearer_auth(bearer);
+ }
+ let response = request.send().expect("POST /rpc");
+ let status = response.status().as_u16();
+ (status, response.json().unwrap_or(Value::Null))
+ }
+
-/// Start a SaaS core on deployment `d` and wait until it is healthy.
-pub fn start(d: &Deployment) -> (Server, String, reqwest::blocking::Client) {
- let port = free_port();
- let child = core_command(d, &["--port", &port.to_string()])
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn openhuman-core");
- let mut server = Server(child);
- let base = format!("http://127.0.0.1:{port}");
- let client = reqwest::blocking::Client::builder()
- .timeout(Duration::from_secs(10))
- .build()
- .unwrap();
++/// What answered `/health` on the port a core was told to listen on.
++#[derive(Debug, PartialEq, Eq)]
++pub enum Serving {
++ /// The core this harness spawned.
++ Ours,
++ /// Another process (pid) holds the port. `--port` is only a preference:
++ /// a core that finds it taken moves to a fallback port
++ /// (`OccupiedByCore::Fallback`), so talking to `base` would drive a
++ /// different deployment's core.
++ Taken(Option<u64>),
++}
+
- let deadline = Instant::now() + Duration::from_secs(120);
++/// Wait until `base` answers `/health`, and say whether the answer came from
++/// `server` (by the pid the health snapshot reports).
++pub fn wait_until_serving(
++ client: &reqwest::blocking::Client,
++ base: &str,
++ server: &mut Server,
++ deadline: Instant,
++) -> Result<Serving, String> {
++ let own = u64::from(server.0.id());
+ loop {
+ if let Ok(response) = client.get(format!("{base}/health")).send() {
+ if response.status().is_success() {
- break;
++ let body: Value = response.json().unwrap_or(Value::Null);
++ let pid = body.get("pid").and_then(Value::as_u64);
++ return Ok(if pid == Some(own) {
++ Serving::Ours
++ } else {
++ Serving::Taken(pid)
++ });
+ }
+ }
+ if let Ok(Some(status)) = server.0.try_wait() {
- panic!("SaaS core exited before serving: {status}");
++ return Err(format!("SaaS core exited before serving: {status}"));
+ }
- if let Ok(Some(status)) = server.0.try_wait() {
- panic!("SaaS core exited before serving: {status}");
++ if Instant::now() >= deadline {
++ return Err("SaaS core never became healthy".to_string());
+ }
- assert!(Instant::now() < deadline, "SaaS core never became healthy");
+ std::thread::sleep(Duration::from_millis(250));
+ }
++}
++
++/// Spawn a core with the command `command(port)` builds and wait until it
++/// serves on that port. [`free_port`] only finds a port that was free a moment
++/// ago: a parallel test's core (or any socket) can take it before this core
++/// binds, and the core then silently listens elsewhere. When another process
++/// answers, this core is killed and started again on a fresh port.
++pub fn spawn_core(command: impl FnMut(u16) -> Command) -> (Server, String) {
++ spawn_core_with(command, String::new)
++}
++
++/// [`spawn_core`], appending `context()` (a log tail) to a startup failure.
++pub fn spawn_core_with(
++ mut command: impl FnMut(u16) -> Command,
++ context: impl Fn() -> String,
++) -> (Server, String) {
++ const ATTEMPTS: usize = 5;
++ let client = reqwest::blocking::Client::builder()
++ .timeout(Duration::from_secs(10))
++ .build()
++ .unwrap();
++ for attempt in 1..=ATTEMPTS {
++ let port = free_port();
++ let child = command(port).spawn().expect("spawn openhuman-core");
++ let mut server = Server(child);
++ let base = format!("http://127.0.0.1:{port}");
++ let deadline = Instant::now() + Duration::from_secs(120);
++ match wait_until_serving(&client, &base, &mut server, deadline) {
++ Ok(Serving::Ours) => return (server, base),
++ Ok(Serving::Taken(pid)) => {
++ eprintln!(
++ "[saas-e2e] port {port} is held by pid {pid:?}, not our core; retrying ({attempt}/{ATTEMPTS})"
++ );
++ }
++ Err(error) => panic!("{error}\n{}", context()),
++ }
++ }
++ panic!("no free port held for a SaaS core after {ATTEMPTS} attempts");
++}
++
++/// Start a SaaS core on deployment `d` and wait until it is healthy.
++pub fn start(d: &Deployment) -> (Server, String, reqwest::blocking::Client) {
++ let (server, base) = spawn_core(|port| {
++ let mut cmd = core_command(d, &["--port", &port.to_string()]);
++ cmd.stdout(Stdio::null()).stderr(Stdio::null());
++ cmd
++ });
++ let client = reqwest::blocking::Client::builder()
++ .timeout(Duration::from_secs(10))
++ .build()
++ .unwrap();
+ (server, base, client)
+ }
+
+ pub fn now() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs()
+ }
+
+ /// POST /rpc for gateway user `user`, signed unless `sig` overrides it.
+ pub fn user_rpc(
+ client: &reqwest::blocking::Client,
+ base: &str,
+ bearer: &str,
+ user: &str,
+ sig: Option<&str>,
+ method: &str,
+ ) -> (u16, Value) {
+ user_rpc_with(client, base, bearer, user, sig, method, json!({}))
+ }
+
+ pub fn user_rpc_with(
+ client: &reqwest::blocking::Client,
+ base: &str,
+ bearer: &str,
+ user: &str,
+ sig: Option<&str>,
+ method: &str,
+ params: Value,
+ ) -> (u16, Value) {
+ use openhuman_core::profiles::gateway::{sign, USER_HEADER, USER_SIG_HEADER};
+ let signature = sig
+ .map(str::to_owned)
+ .unwrap_or_else(|| sign(BEARER, user, now()));
+ let response = client
+ .post(format!("{base}/rpc"))
+ .bearer_auth(bearer)
+ .header(USER_HEADER, user)
+ .header(USER_SIG_HEADER, signature)
+ .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": method, "params": params }))
+ .send()
+ .expect("POST /rpc");
+ let status = response.status().as_u16();
+ (status, response.json().unwrap_or(Value::Null))
+ }
+
+ pub fn provision(client: &reqwest::blocking::Client, base: &str, user: &str) -> String {
+ let (_, body) = rpc_with(
+ client,
+ base,
+ Some(BEARER),
+ "openhuman.profiles_provision",
+ json!({ "user_id": user }),
+ );
+ assert!(body.get("result").is_some(), "provision {user}: {body}");
+ openhuman_core::profiles::ProfileId::for_user(
+ user,
+ openhuman_core::profiles::ProfileIdMode::Raw,
+ )
+ .unwrap()
+ .to_string()
+ }
+
+ pub fn thread_ids(body: &Value) -> Vec<String> {
+ let text = body.to_string();
+ let mut ids = Vec::new();
+ for part in text.split("\"id\":\"").skip(1) {
+ if let Some(end) = part.find('"') {
+ ids.push(part[..end].to_string());
+ }
+ }
+ ids
+ }
+
+ /// Open `/events?client_id=` for `user` and forward each SSE `data:` line.
+ pub fn user_events(base: &str, user: &str, client_id: &str) -> std::sync::mpsc::Receiver<String> {
+ use openhuman_core::profiles::gateway::{sign, USER_HEADER, USER_SIG_HEADER};
+ use std::io::BufRead;
+ let (tx, rx) = std::sync::mpsc::channel();
+ let url = format!("{base}/events?client_id={client_id}");
+ let user = user.to_string();
+ std::thread::spawn(move || {
+ let client = reqwest::blocking::Client::builder()
+ .timeout(None)
+ .build()
+ .unwrap();
+ let Ok(response) = client
+ .get(&url)
+ .bearer_auth(BEARER)
+ .header(USER_HEADER, &user)
+ .header(USER_SIG_HEADER, sign(BEARER, &user, now()))
+ .send()
+ else {
+ return;
+ };
+ let _ = tx.send(format!("status:{}", response.status().as_u16()));
+ for line in std::io::BufReader::new(response).lines() {
+ let Ok(line) = line else { break };
+ if let Some(data) = line.strip_prefix("data:") {
+ if tx.send(data.trim().to_string()).is_err() {
+ break;
+ }
+ }
+ }
+ });
+ rx
+ }
+
+ /// A fake backend: answers every request `500` and reports each request's
+ /// path and `Authorization` header.
+ pub fn recording_backend() -> (u16, std::sync::mpsc::Receiver<(String, String)>) {
+ use std::io::{BufRead, BufReader, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ for stream in listener.incoming().flatten() {
+ let tx = tx.clone();
+ std::thread::spawn(move || {
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut line = String::new();
+ if reader.read_line(&mut line).is_err() {
+ return;
+ }
+ let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
+ let mut auth = String::new();
+ loop {
+ let mut header = String::new();
+ if reader.read_line(&mut header).unwrap_or(0) == 0 || header == "\r\n" {
+ break;
+ }
+ if let Some((name, value)) = header.split_once(':') {
+ if name.eq_ignore_ascii_case("authorization") {
+ auth = value.trim().to_string();
+ }
+ }
+ }
+ let _ = tx.send((path, auth));
+ let mut stream = stream;
+ let _ = stream.write_all(
+ b"HTTP/1.1 500 Internal Server Error\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
+ );
+ });
+ }
+ });
+ (port, rx)
+ }
+
+ /// Start a SaaS core whose backend is a closed port, so every turn fails fast
+ /// and its failure is itself the reply, without any real inference.
+ pub fn start_offline(d: &Deployment) -> (Server, String, reqwest::blocking::Client) {
- let port = free_port();
- let child = core_command(d, &["--port", &port.to_string()])
- .env("BACKEND_URL", "http://127.0.0.1:9")
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn openhuman-core");
- let mut server = Server(child);
- let base = format!("http://127.0.0.1:{port}");
++ let (server, base) = spawn_core(|port| {
++ let mut cmd = core_command(d, &["--port", &port.to_string()]);
++ cmd.env("BACKEND_URL", "http://127.0.0.1:9")
++ .stdout(Stdio::null())
++ .stderr(Stdio::null());
++ cmd
++ });
+ let client = reqwest::blocking::Client::builder()
+ .timeout(Duration::from_secs(30))
+ .build()
+ .unwrap();
- let deadline = Instant::now() + Duration::from_secs(120);
- while !client
- .get(format!("{base}/health"))
- .send()
- .is_ok_and(|r| r.status().is_success())
- {
- if let Ok(Some(status)) = server.0.try_wait() {
- panic!("SaaS core exited before serving: {status}");
- }
- assert!(Instant::now() < deadline, "SaaS core never became healthy");
- std::thread::sleep(Duration::from_millis(250));
- }
+ (server, base, client)
+ }
+
+ #[path = "node.rs"]
+ mod node;
+ pub use node::*;
diff --cc tests/saas_mode_e2e.rs
index a5cc0ba29b,94139c95a3..20bd5b8f94
--- a/tests/saas_mode_e2e.rs
+++ b/tests/saas_mode_e2e.rs
@@@ -1156,3 -784,3 +762,34 @@@ fn a_profile_holds_web_and_relayed_chan
);
drop(server);
}
++
++/// `--port` is a preference: a core that finds it taken listens elsewhere.
++/// The harness must notice that another core answers on the port, or the test
++/// drives that core's deployment and checks its own (an empty `users/`).
++#[test]
++fn a_core_on_a_taken_port_is_not_mistaken_for_ours() {
++ let first = deployment(true);
++ let (mut first_server, base, client) = start(&first);
++ let deadline = Instant::now() + Duration::from_secs(120);
++ assert_eq!(
++ wait_until_serving(&client, &base, &mut first_server, deadline),
++ Ok(Serving::Ours)
++ );
++
++ let second = deployment(true);
++ let port = base.rsplit(':').next().unwrap().to_string();
++ let child = core_command(&second, &["--port", &port])
++ .stdout(Stdio::null())
++ .stderr(Stdio::null())
++ .spawn()
++ .expect("spawn openhuman-core");
++ let mut second_server = Server(child);
++ let deadline = Instant::now() + Duration::from_secs(120);
++ assert_eq!(
++ wait_until_serving(&client, &base, &mut second_server, deadline),
++ Ok(Serving::Taken(Some(u64::from(first_server.0.id())))),
++ "the first core still answers on its port"
++ );
++ drop(second_server);
++ drop(first_server);
++}