Skip to content

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

Merge upstream/main into saas-isolation-e2e

Steven Enamakel6481bb4bdfd1
diff --cc crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index aaaa2c9f03,e7b06c40ad..1e2a680f3d
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@@ -124,42 -126,127 +126,158 @@@ impl EventHandler<DomainEvent> for Back
}
_ => {}
}
- if let Some((thread_id, delay)) = drain_schedule(event) {
- schedule_delivery(thread_id, delay);
+ let saas = crate::core::runtime::is_saas();
- for drain in drain_schedule_in(saas, event, completion_owners::context_for_profile) {
++ // Opening an owner (it may have been evicted) is async; the planner
++ // below resolves synchronously, so open the owners first.
++ let mut owners = std::collections::HashMap::new();
++ for profile in owning_profiles(event) {
++ if let Some(ctx) = completion_owners::context_for_profile(&profile).await {
++ owners.insert(profile, ctx);
++ }
++ }
++ for drain in drain_schedule_in(saas, event, |profile| owners.get(profile).cloned()) {
+ match drain.owner {
+ // Re-enter the owner's scope so the scheduled task inherits it.
+ Some(ctx) => {
+ CoreContext::sync_scope(ctx, || schedule_delivery(drain.thread_id, drain.delay))
+ }
+ None => schedule_delivery(drain.thread_id, drain.delay),
+ }
}
}
}
- /// Which thread to drain, and after how long, for an event. A session that maps
- /// to no thread (cron, voice, skills) has nothing to deliver into.
+ /// One drain an event asks for: the thread, how soon, and the context of the
+ /// profile that owns it (`None` on the desktop, where nothing is per profile).
+ pub(super) struct Drain {
+ pub(super) owner: Option<Arc<CoreContext>>,
+ pub(super) thread_id: String,
+ pub(super) delay: Duration,
+ }
+
+ /// Which thread to drain, and after how long, for an event, outside any
+ /// profile. A session that maps to no thread (cron, voice, skills) has nothing
+ /// to deliver into.
+ #[cfg(test)]
fn drain_schedule(event: &DomainEvent) -> Option<(String, Duration)> {
- let (session, delay) = match event {
+ let drain = drain_schedule_in(false, event, |_| None)
+ .into_iter()
+ .next()?;
+ Some((drain.thread_id, drain.delay))
+ }
+
+ /// The drains for `event`. This subscriber runs off-task, with no tenant scope,
+ /// but the thread tables are keyed per profile: the profiles that recorded the
+ /// completion (by task id) or ran the session are looked up in
+ /// [`completion_owners`] and each is resolved through `resolve` and drained in
+ /// its own scope, where it reaches only its own tables. In SaaS (`saas`) an id
+ /// with no owner is dropped; elsewhere it drains unscoped, as on the desktop.
+ pub(super) fn drain_schedule_in(
+ saas: bool,
+ event: &DomainEvent,
+ resolve: impl Fn(&str) -> Option<Arc<CoreContext>>,
+ ) -> Vec<Drain> {
- let (session, task, delay) = match event {
- // A user turn just ended (or failed) — drain anything that finished while
- // it ran.
- DomainEvent::AgentTurnCompleted { session_id, .. }
- | DomainEvent::AgentError { session_id, .. } => {
- (session_id, None, Duration::from_millis(300))
- }
- // Any subagent terminal state — completed, failed, or awaiting-user — can
- // arrive after the parent turn already went idle. Schedule a debounced
- // drain for all three so the pending result is delivered promptly instead
- // of sitting until some unrelated later turn. Only `SubagentCompleted`
- // used to trigger a drain, so a failure (or an awaiting-user pause) after
- // the parent turn went idle left the chat stuck on the original
- // "Accepted" response (#4896). Debounce so a burst batches into a single
- // turn.
- DomainEvent::SubagentCompleted {
- parent_session,
- task_id,
- ..
- }
- | DomainEvent::SubagentFailed {
- parent_session,
- task_id,
- ..
- }
- | DomainEvent::SubagentAwaitingUser {
- parent_session,
- task_id,
- ..
- } => (parent_session, Some(task_id), DEBOUNCE),
- _ => return Vec::new(),
++ let Some((session, task, delay)) = drain_trigger(event) else {
++ return Vec::new();
+ };
- // A task id is core-minted and unique, so it names its one owner; a
- // session id can be shared by profiles, so it may name several.
- let mut profiles = task
- .map(|t| completion_owners::profiles_of(t))
- .unwrap_or_default();
- if profiles.is_empty() {
- profiles = completion_owners::profiles_of(session);
- }
++ let profiles = owners_of(session, task);
+ let thread_in = |owner: Option<Arc<CoreContext>>| {
+ let thread_id = match &owner {
+ Some(ctx) => CoreContext::sync_scope(Arc::clone(ctx), || {
+ background_completions::thread_for_session(session)
+ }),
+ None => background_completions::thread_for_session(session),
+ };
+ if thread_id.is_none() {
+ log::trace!("[background_delivery] session has no delivery thread; not scheduling");
+ }
+ thread_id.map(|thread_id| Drain {
+ owner,
+ thread_id,
+ delay,
+ })
+ };
+ if profiles.is_empty() {
+ if saas {
+ log::debug!(
+ "[background_delivery] no owning profile for the session or task; dropping \
+ the drain (fails closed in SaaS)"
+ );
+ return Vec::new();
+ }
+ return thread_in(None).into_iter().collect();
+ }
+ profiles
+ .iter()
+ .filter_map(|profile| match resolve(profile) {
+ Some(ctx) => thread_in(Some(ctx)),
+ None => {
+ log::debug!("[background_delivery] owning profile has no live context; dropping");
+ None
+ }
+ })
+ .collect()
+ }
+
++/// The session (and sub-agent task) an event asks to drain, and after how
++/// long; `None` for events that drain nothing.
++fn drain_trigger(event: &DomainEvent) -> Option<(&String, Option<&String>, Duration)> {
++ let trigger = match event {
+ // A user turn just ended (or failed) — drain anything that finished while
+ // it ran.
+ DomainEvent::AgentTurnCompleted { session_id, .. }
- | DomainEvent::AgentError { session_id, .. } => (session_id, Duration::from_millis(300)),
++ | DomainEvent::AgentError { session_id, .. } => {
++ (session_id, None, Duration::from_millis(300))
++ }
+ // Any subagent terminal state — completed, failed, or awaiting-user — can
+ // arrive after the parent turn already went idle. Schedule a debounced
+ // drain for all three so the pending result is delivered promptly instead
+ // of sitting until some unrelated later turn. Only `SubagentCompleted`
+ // used to trigger a drain, so a failure (or an awaiting-user pause) after
+ // the parent turn went idle left the chat stuck on the original
+ // "Accepted" response (#4896). Debounce so a burst batches into a single
+ // turn.
- DomainEvent::SubagentCompleted { parent_session, .. }
- | DomainEvent::SubagentFailed { parent_session, .. }
- | DomainEvent::SubagentAwaitingUser { parent_session, .. } => (parent_session, DEBOUNCE),
++ DomainEvent::SubagentCompleted {
++ parent_session,
++ task_id,
++ ..
++ }
++ | DomainEvent::SubagentFailed {
++ parent_session,
++ task_id,
++ ..
++ }
++ | DomainEvent::SubagentAwaitingUser {
++ parent_session,
++ task_id,
++ ..
++ } => (parent_session, Some(task_id), DEBOUNCE),
+ _ => return None,
+ };
- match background_completions::thread_for_session(session) {
- Some(thread_id) => Some((thread_id, delay)),
- None => {
- log::trace!("[background_delivery] session has no delivery thread; not scheduling");
- None
- }
++ Some(trigger)
++}
++
++/// The profiles noted as owning `task` (core-minted and unique, so it names
++/// its one owner) or, failing that, `session` (shared by profiles, so it may
++/// name several).
++fn owners_of(session: &str, task: Option<&String>) -> Vec<String> {
++ let profiles = task
++ .map(|t| completion_owners::profiles_of(t))
++ .unwrap_or_default();
++ if profiles.is_empty() {
++ completion_owners::profiles_of(session)
++ } else {
++ profiles
+ }
+}
+
++/// The profiles whose contexts [`drain_schedule_in`] asks for on `event`.
++fn owning_profiles(event: &DomainEvent) -> Vec<String> {
++ drain_trigger(event)
++ .map(|(session, task, _)| owners_of(session, task))
++ .unwrap_or_default()
++}
++
/// Schedule a debounced delivery attempt for a thread.
fn schedule_delivery(thread_id: String, delay: Duration) {
#[cfg(test)]
diff --cc crates/openhuman-core/src/agent/orchestration/completion_owners.rs
index 0000000000,1015f4dc6c..d401d4e1ae
mode 000000,100644..100644
--- a/crates/openhuman-core/src/agent/orchestration/completion_owners.rs
+++ b/crates/openhuman-core/src/agent/orchestration/completion_owners.rs
@@@ -1,0 -1,93 +1,94 @@@
+ //! Which SaaS profile a detached sub-agent's completion belongs to, for the
+ //! bus subscriber that delivers it.
+ //!
+ //! The background-completion tables are keyed per profile
+ //! (`tenant::profile_key`), but the delivery subscriber
+ //! ([`super::background_delivery`]) runs off-task with no `CoreContext` scope,
+ //! so in SaaS it cannot read them. [`record_outcome`] runs inside the user's
+ //! scope: it notes the profile here under the sub-agent's task id (core-minted,
+ //! unique) and the parent session id, and the subscriber re-enters that
+ //! profile's context ([`context_for_profile`]) before it looks anything up.
+ //!
+ //! A session id is not unique across profiles (a web-chat one is
+ //! `{client_id, thread_id}`), so it can name several owners; each is drained in
+ //! its own scope, where it can only reach its own tables. Desktop contexts
+ //! carry no profile, so nothing is noted there and delivery stays unscoped.
+ //!
+ //! [`record_outcome`]: super::background_completions::record_outcome
+
+ use std::collections::{HashMap, VecDeque};
+ use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
+
+ use crate::core::runtime::CoreContext;
+
+ /// Bound on noted ids; the oldest is evicted first.
+ const OWNERS_CAP: usize = 4096;
+
+ /// Bound on the profiles one (session) id can name.
+ const PROFILES_PER_ID: usize = 16;
+
+ #[derive(Default)]
+ struct Owners {
+ by_id: HashMap<String, Vec<String>>,
+ order: VecDeque<String>,
+ }
+
+ fn owners() -> MutexGuard<'static, Owners> {
+ static OWNERS: OnceLock<Mutex<Owners>> = OnceLock::new();
+ OWNERS
+ .get_or_init(Mutex::default)
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
+
+ /// Note the calling task's profile as an owner of each id. A no-op outside a
+ /// profile (the desktop, embedded agents).
+ pub(crate) fn note(ids: &[&str]) {
+ let Ok(Some(profile)) = crate::core::runtime::current_tenant().map(|t| t.profile) else {
+ return;
+ };
+ note_profile(ids, &profile);
+ }
+
+ /// Note `profile` as an owner of each id.
+ pub(crate) fn note_profile(ids: &[&str], profile: &str) {
+ let mut st = owners();
+ for id in ids {
+ let fresh = !st.by_id.contains_key(*id);
+ let profiles = st.by_id.entry((*id).to_string()).or_default();
+ if !profiles.iter().any(|p| p == profile) {
+ if profiles.len() >= PROFILES_PER_ID {
+ profiles.remove(0);
+ }
+ profiles.push(profile.to_string());
+ }
+ if fresh {
+ st.order.push_back((*id).to_string());
+ }
+ }
+ while st.order.len() > OWNERS_CAP {
+ if let Some(oldest) = st.order.pop_front() {
+ st.by_id.remove(&oldest);
+ }
+ }
+ }
+
+ /// The profiles noted as owners of `id`, oldest first.
+ pub(crate) fn profiles_of(id: &str) -> Vec<String> {
+ owners().by_id.get(id).cloned().unwrap_or_default()
+ }
+
+ /// The context to act for `profile` under, off-task: the SaaS agent host's
+ /// agent for it, reopened if it was evicted. `None` outside SaaS or for a
+ /// profile the host does not know.
-pub(crate) fn context_for_profile(profile: &str) -> Option<Arc<CoreContext>> {
++pub(crate) async fn context_for_profile(profile: &str) -> Option<Arc<CoreContext>> {
+ let id = crate::profiles::ProfileId::parse(profile).ok()?;
- match crate::profiles::host::host()?.open(&id) {
++ let host = crate::profiles::host::host()?;
++ match host.open(&id).await {
+ Ok(state) => Some(Arc::clone(state.context())),
+ Err(error) => {
+ log::warn!("[completion_owners] cannot open the owning agent: {error}");
+ None
+ }
+ }
+ }
diff --cc crates/openhuman-core/src/core/runtime/saas_tests.rs
index 7c3fe4c6ea,1370f7e236..c13392124d
--- a/crates/openhuman-core/src/core/runtime/saas_tests.rs
+++ b/crates/openhuman-core/src/core/runtime/saas_tests.rs
@@@ -144,72 -144,10 +144,80 @@@ fn boot_refuses_a_registry_with_workspa
assert!(err.contains("built-ins only"), "{err}");
}
+#[test]
+fn cluster_settings_default_and_resolve() {
+ let mut config = SaasConfig::new("/srv/oh");
+ assert_eq!(config.lease_ttl_secs, 30);
+ assert_eq!(config.lease_ttl(), std::time::Duration::from_secs(30));
+ assert_eq!(config.operator_dir(), PathBuf::from("/srv/oh/operator"));
+ assert!(!config.is_clustered());
+ assert_eq!(config.storage_url_with(None), None);
+
+ config.storage_url = Some("sqlite:/srv/oh/a.db".into());
+ assert_eq!(
+ config.storage_url_with(None).as_deref(),
+ Some("sqlite:/srv/oh/a.db")
+ );
+ assert_eq!(
+ config.storage_url_with(Some("sqlite:/env.db")).as_deref(),
+ Some("sqlite:/env.db"),
+ "OPENHUMAN_STORAGE_URL wins"
+ );
+ assert_eq!(
+ config.storage_url_with(Some(" ")).as_deref(),
+ Some("sqlite:/srv/oh/a.db"),
+ "a blank environment value is unset"
+ );
+
+ assert_eq!(config.resolve_node_id(Some("node-env")), "node-env");
+ let mut fresh = SaasConfig::new("/srv/oh");
+ let random = fresh.resolve_node_id(None).to_owned();
+ assert!(random.starts_with("node-"), "{random}");
+ assert_eq!(
+ fresh.resolve_node_id(Some("ignored")),
+ random,
+ "resolved once"
+ );
+ let mut configured = SaasConfig::new("/srv/oh");
+ configured.node_id = Some("node-file".into());
+ assert_eq!(configured.resolve_node_id(Some("node-env")), "node-file");
+
+ config.operator_dir = Some("/srv/oh/operators/a".into());
+ assert_eq!(config.operator_dir(), PathBuf::from("/srv/oh/operators/a"));
+ config.advertise_url = Some("http://a:7788".into());
+ assert!(config.is_clustered());
+}
+
+#[test]
+fn reads_the_cluster_settings() {
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("operator.toml");
+ std::fs::write(
+ &path,
+ r#"
+root = "/srv/oh"
+storage_url = "sqlite:/srv/oh/shared.db"
+node_id = "node-a"
+advertise_url = "http://10.0.0.1:7788"
+lease_ttl_secs = 5
+operator_dir = "/srv/oh/operators/node-a"
+"#,
+ )
+ .unwrap();
+ let config = SaasConfig::load(&path).unwrap();
+ assert_eq!(config.node_id.as_deref(), Some("node-a"));
+ assert_eq!(config.lease_ttl_secs, 5);
+ assert!(config.is_clustered());
+ assert_eq!(
+ config.operator_config().workspace_dir,
+ PathBuf::from("/srv/oh/operators/node-a/workspace")
+ );
+}
++
+ #[test]
+ fn the_pre_rename_max_agents_open_key_still_sets_the_limit() {
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("operator.toml");
+ std::fs::write(&path, "root = \"/srv/openhuman\"\nmax_agents_open = 7\n").unwrap();
+ assert_eq!(SaasConfig::load(&path).unwrap().max_profiles_open, 7);
+ }
diff --cc crates/openhuman-core/src/flows/bus/owner.rs
index fc99e20694,84b6aea8fe..bfc76d442c
--- a/crates/openhuman-core/src/flows/bus/owner.rs
+++ b/crates/openhuman-core/src/flows/bus/owner.rs
@@@ -57,7 -75,39 +75,40 @@@ async fn resolve(config: &Config, flow_
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(flow_id.to_string(), owner.clone());
- owner
+ Ok(owner)
+ }
+
+ /// Runs `fut` as `flow_id`'s owner; logs and skips it when the owner is
+ /// unknown (a failed lookup) or no context can act for it.
+ pub(super) async fn as_owner<F: std::future::Future<Output = ()>>(
+ config: &Config,
+ flow_id: &str,
+ fut: F,
+ ) {
+ match flow_owner(config, flow_id).await {
+ Ok(owner) => {
+ within_agent(owner.as_deref(), fut).await;
+ }
+ Err(failed) => tracing::warn!(
+ target: "flows",
+ %flow_id,
+ "[flows] flow owner unknown ({failed}); event not handled"
+ ),
+ }
+ }
+
-/// The configuration to handle a flow event under: the acting agent's own
++/// The configuration to handle a flow event under: the acting agent's (or SaaS profile's) own
+ /// when the handler runs as one ([`as_owner`]) — its provider, access
+ /// policy, memory and action directory — else `registered`, the one the
+ /// subscriber was registered with.
+ pub(super) fn config_for_scope(registered: &std::sync::Arc<Config>) -> std::sync::Arc<Config> {
- let acting = crate::core::runtime::CoreContext::current()
- .is_some_and(|context| context.session_agent().is_some());
++ // A SaaS profile acts as its own tenant even with no agent inside it.
++ let acting = crate::core::runtime::current_tenant()
++ .is_ok_and(|tenant| tenant.agent.is_some() || tenant.profile.is_some());
+ match acting.then(crate::core::runtime::CoreContext::current_embedder_config) {
+ Some(Some(config)) => std::sync::Arc::new(config),
+ _ => std::sync::Arc::clone(registered),
+ }
}
/// Forgets a cached owner (a removed flow's id may be reused).
diff --cc crates/openhuman-core/src/profiles/README.md
index ce8ce51f7b,5fa79be79f..dd0a811308
--- a/crates/openhuman-core/src/profiles/README.md
+++ b/crates/openhuman-core/src/profiles/README.md
@@@ -40,12 -34,8 +40,12 @@@ The top-level `profile_ids` setting (`p
- Anything else, or every id under `"hashed"`, becomes `h-` + the first 32 hex
characters of `sha256(user_id)`.
+Provisioning also refuses a profile id equal to the file name of the node's
+`operator_dir`: keyring secrets are namespaced by their store's directory name,
+so such a profile would share the operator's credential slots.
+
Both forms fit the agent-id charset and can never contain a path separator.
- Changing the mode re-maps users onto different profiles.
+ Changing the mode may re-map users onto different profiles.
## Files
diff --cc crates/openhuman-core/src/profiles/gateway.rs
index 8ee05e4173,c763ccbcf4..c70fa3706e
--- a/crates/openhuman-core/src/profiles/gateway.rs
+++ b/crates/openhuman-core/src/profiles/gateway.rs
@@@ -26,8 -22,7 +26,8 @@@ use std::sync::Arc
use hmac::{Hmac, KeyInit, Mac};
use sha2_011::Sha256;
- use super::host::{self, Profile};
+ use super::host::{self, Profile, ProfileHost};
+use super::lease::OpenError;
use super::types::ProfileId;
/// The gateway's user header.
@@@ -157,6 -108,19 +157,21 @@@ pub async fn resolve_scope
return Ok(GatewayScope::Operator);
};
let host = host::host().ok_or_else(|| GatewayRefusal::new(503, "this core serves no users"))?;
- resolve_user_on(&host, user_id, signature, secret, now).map(GatewayScope::User)
++ resolve_user_on(&host, user_id, signature, secret, now)
++ .await
++ .map(GatewayScope::User)
+ }
+
+ /// [`resolve_scope`] for a request that names `user_id`, on an explicit
+ /// `host` rather than the process's: the profile that serves that user, or
+ /// the refusal.
-pub fn resolve_user_on(
++pub async fn resolve_user_on(
+ host: &ProfileHost,
+ user_id: &str,
+ signature: Option<&str>,
+ secret: &str,
+ now: u64,
+ ) -> Result<Arc<Profile>, GatewayRefusal> {
let profile = ProfileId::for_user(user_id, host.saas().profile_ids)
.map_err(|e| GatewayRefusal::new(400, e))?;
if host.saas().require_user_signature {
@@@ -167,16 -131,13 +182,16 @@@
GatewayRefusal::new(401, e)
})?;
}
- match host.open(&profile) {
+ match host.open(&profile).await {
Ok(state) => {
- log::debug!("[profiles][gateway] scoped request to profile={profile}");
- Ok(GatewayScope::User(state))
+ log::debug!("[profiles][gateway] scoped request to an open profile");
+ Ok(state)
}
- Err(e) if e.contains("not provisioned") => Err(GatewayRefusal::new(403, e)),
- Err(e) => Err(GatewayRefusal::new(503, e)),
+ Err(error) => Err(GatewayRefusal::from_open_error(
+ &profile,
+ error,
+ super::lease::now_ms(),
+ )),
}
}
diff --cc crates/openhuman-core/src/profiles/gateway_proptest_tests.rs
index 0000000000,fa06f74705..5e4c72a787
mode 000000,100644..100644
--- a/crates/openhuman-core/src/profiles/gateway_proptest_tests.rs
+++ b/crates/openhuman-core/src/profiles/gateway_proptest_tests.rs
@@@ -1,0 -1,242 +1,262 @@@
+ //! Property tests for the gateway's user header and its signature. Both
+ //! headers are attacker-shaped (a gateway may forward a client's headers by
+ //! mistake), so whatever arrives the outcome is a refusal (400, 401 or 403)
+ //! or the profile of exactly the user that was signed for — never another
+ //! user's profile, and never the operator plane.
+ //!
+ //! Case counts follow `PROPTEST_CASES` (default 256); CI pins the seed with
+ //! `PROPTEST_RNG_SEED`.
+
+ use super::*;
+ use crate::core::runtime::{CoreContext, DomainSet, SaasConfig};
+ use crate::profiles::ProfileIdMode;
+ use proptest::prelude::*;
+ use std::sync::OnceLock;
+
+ const SECRET: &str = "gateway-secret-0123456789abcdef0123456789";
+ const NOW: u64 = 1_700_000_000;
+
+ /// Users provisioned on the shared test host: two raw ids and one that hashes.
+ const PROVISIONED: &[&str] = &["alice", "bob", "[email protected]"];
+
++/// The runtime the async host calls run on: proptest cases are synchronous.
++fn rt() -> &'static tokio::runtime::Runtime {
++ static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
++ RT.get_or_init(|| {
++ tokio::runtime::Builder::new_current_thread()
++ .enable_all()
++ .build()
++ .expect("test runtime")
++ })
++}
++
++/// [`resolve_user_on`] driven to completion on [`rt`].
++fn resolve_user(
++ host: &ProfileHost,
++ user: &str,
++ header: Option<&str>,
++) -> Result<Arc<Profile>, GatewayRefusal> {
++ rt().block_on(resolve_user_on(host, user, header, SECRET, NOW))
++}
++
+ /// One host per mode, provisioned once and shared by every case (opening a
+ /// profile is the slow part).
+ fn host(mode: ProfileIdMode) -> &'static ProfileHost {
+ static RAW: OnceLock<(tempfile::TempDir, ProfileHost)> = OnceLock::new();
+ static HASHED: OnceLock<(tempfile::TempDir, ProfileHost)> = OnceLock::new();
+ let cell = match mode {
+ ProfileIdMode::Raw => &RAW,
+ ProfileIdMode::Hashed => &HASHED,
+ };
+ &cell
+ .get_or_init(|| {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut saas = SaasConfig::new(tmp.path());
+ saas.profile_ids = mode;
+ saas.require_user_signature = true;
+ saas.max_profiles_open = 16;
+ let host = ProfileHost::new(saas, CoreContext::for_test(DomainSet::full(), None));
+ for user in PROVISIONED {
- host.provision(&ProfileId::for_user(user, mode).unwrap())
++ rt().block_on(host.provision(&ProfileId::for_user(user, mode).unwrap()))
+ .unwrap();
+ }
+ (tmp, host)
+ })
+ .1
+ }
+
+ fn mode() -> impl Strategy<Value = ProfileIdMode> {
+ prop_oneof![Just(ProfileIdMode::Raw), Just(ProfileIdMode::Hashed)]
+ }
+
+ /// User header values: provisioned users and near-misses of them (case,
+ /// whitespace, duplicates joined with a comma, oversized), plus noise.
+ fn user_header() -> impl Strategy<Value = String> {
+ let known = prop::sample::select(PROVISIONED.to_vec()).prop_map(String::from);
+ prop_oneof![
+ 3 => known.clone(),
+ 1 => known.clone().prop_map(|u| u.to_uppercase()),
+ 1 => known.clone().prop_map(|u| format!(" {u}")),
+ 1 => known.clone().prop_map(|u| format!("{u} ")),
+ 1 => known.clone().prop_map(|u| format!("{u}\t")),
+ 1 => (known.clone(), known.clone()).prop_map(|(a, b)| format!("{a},{b}")),
+ 1 => known.prop_map(|u| format!("{u}{}", "x".repeat(300))),
+ 1 => Just("mallory".to_string()),
+ 1 => "[a-z0-9_-]{1,20}",
+ 1 => any::<String>(),
+ ]
+ }
+
+ /// How a signature header is built for a request claiming `user`.
+ #[derive(Debug, Clone)]
+ enum Sig {
+ Missing,
+ /// Signed for `signed_for` at `NOW + skew`.
+ Signed {
+ signed_for: SignedFor,
+ skew: i64,
+ },
+ /// A valid header with the tag cut to `keep` hex characters.
+ Truncated {
+ keep: usize,
+ },
+ /// A valid header with extra parts, duplicates or whitespace around it.
+ Decorated {
+ before: String,
+ after: String,
+ },
+ /// A valid tag paired with a different timestamp.
+ WrongT {
+ delta: u64,
+ },
+ Garbage(String),
+ }
+
+ #[derive(Debug, Clone)]
+ enum SignedFor {
+ /// The user the request claims.
+ Claimed,
+ /// Some other user: a replay of A's signature as B.
+ Other(String),
+ /// The claimed user under another secret.
+ OtherSecret,
+ }
+
+ fn sig() -> impl Strategy<Value = Sig> {
+ let signed_for = prop_oneof![
+ 3 => Just(SignedFor::Claimed),
+ 2 => prop::sample::select(PROVISIONED.to_vec()).prop_map(|u| SignedFor::Other(u.to_string())),
+ 1 => "[a-zA-Z0-9@. ]{0,12}".prop_map(SignedFor::Other),
+ 1 => Just(SignedFor::OtherSecret),
+ ];
+ let skew = prop_oneof![
+ 3 => -(SIGNATURE_WINDOW_SECS as i64)..=SIGNATURE_WINDOW_SECS as i64,
+ 1 => -100_000i64..100_000,
+ 1 => Just(SIGNATURE_WINDOW_SECS as i64 + 1),
+ 1 => Just(-(SIGNATURE_WINDOW_SECS as i64) - 1),
+ ];
+ prop_oneof![
+ 1 => Just(Sig::Missing),
+ 4 => (signed_for, skew).prop_map(|(signed_for, skew)| Sig::Signed { signed_for, skew }),
+ 1 => (0usize..64).prop_map(|keep| Sig::Truncated { keep }),
+ 1 => ("[ ,=tv1a-f0-9]{0,12}", "[ ,=tv1a-f0-9]{0,12}")
+ .prop_map(|(before, after)| Sig::Decorated { before, after }),
+ 1 => (1u64..10_000).prop_map(|delta| Sig::WrongT { delta }),
+ 1 => any::<String>().prop_map(Sig::Garbage),
+ ]
+ }
+
+ fn build_sig(sig: &Sig, claimed: &str) -> Option<String> {
+ let valid = || sign(SECRET, claimed, NOW);
+ match sig {
+ Sig::Missing => None,
+ Sig::Signed { signed_for, skew } => {
+ let ts = NOW.saturating_add_signed(*skew);
+ Some(match signed_for {
+ SignedFor::Claimed => sign(SECRET, claimed, ts),
+ SignedFor::Other(other) => sign(SECRET, other, ts),
+ SignedFor::OtherSecret => sign("another-secret", claimed, ts),
+ })
+ }
+ Sig::Truncated { keep } => {
+ let header = valid();
+ let (head, tag) = header.split_once("v1=").unwrap();
+ Some(format!("{head}v1={}", &tag[..(*keep).min(tag.len())]))
+ }
+ Sig::Decorated { before, after } => Some(format!("{before}{}{after}", valid())),
+ Sig::WrongT { delta } => {
+ let tag = valid().split_once("v1=").unwrap().1.to_string();
+ Some(format!("t={},v1={tag}", NOW + delta))
+ }
+ Sig::Garbage(s) => Some(s.clone()),
+ }
+ }
+
+ /// Whether `header` would verify for `user` at `NOW`, recomputed from first
+ /// principles: some `t` within the window, and a `v1` equal to the full tag.
+ fn is_valid_for(user: &str, header: &str) -> bool {
+ verify(SECRET, user, header, NOW).is_ok()
+ }
+
+ proptest! {
+ /// `verify` never panics, and accepts a header only when its `v1` is the
+ /// full HMAC of `<t>.<user>` for a `t` inside the window.
+ #[test]
+ fn verify_only_accepts_a_full_tag_for_this_user(user in user_header(), header in any::<String>()) {
+ if verify(SECRET, &user, &header, NOW).is_ok() {
+ let ts = header.split(',').filter_map(|p| p.trim().strip_prefix("t=")).next_back();
+ let ts: u64 = ts.and_then(|t| t.parse().ok()).expect("accepted without a t");
+ prop_assert!(ts.abs_diff(NOW) <= SIGNATURE_WINDOW_SECS);
+ prop_assert!(header.to_ascii_lowercase().contains(sign(SECRET, &user, ts).split_once("v1=").unwrap().1));
+ }
+ }
+
+ /// A signature for one user never verifies for another, at any skew.
+ #[test]
+ fn a_signature_never_transfers_between_users(
+ a in user_header(),
+ b in user_header(),
+ skew in -(SIGNATURE_WINDOW_SECS as i64)..=SIGNATURE_WINDOW_SECS as i64,
+ ) {
+ prop_assume!(a != b);
+ let header = sign(SECRET, &a, NOW.saturating_add_signed(skew));
+ prop_assert!(verify(SECRET, &a, &header, NOW).is_ok());
+ prop_assert!(verify(SECRET, &b, &header, NOW).is_err());
+ }
+
+ /// A truncated tag never verifies, down to an empty `v1=`.
+ #[test]
+ fn a_truncated_tag_never_verifies(user in user_header(), keep in 0usize..64) {
+ let header = sign(SECRET, &user, NOW);
+ let (head, tag) = header.split_once("v1=").unwrap();
+ let cut = format!("{head}v1={}", &tag[..keep]);
+ prop_assert!(verify(SECRET, &user, &cut, NOW).is_err(), "{cut}");
+ }
+
+ /// Whatever the headers, resolving a named user yields a refusal with a
+ /// client status, or exactly the profile of the claimed user — and only
+ /// when the signature is genuinely valid for that user.
+ #[test]
+ fn resolving_a_user_is_a_refusal_or_their_own_profile(
+ user in user_header(),
+ sig in sig(),
+ mode in mode(),
+ ) {
+ let host = host(mode);
+ let header = build_sig(&sig, &user);
- match resolve_user_on(host, &user, header.as_deref(), SECRET, NOW) {
++ match resolve_user(host, &user, header.as_deref()) {
+ Ok(profile) => {
+ let expected = ProfileId::for_user(&user, mode).unwrap();
+ prop_assert_eq!(&profile.id, &expected, "{:?} landed on another profile", user);
+ prop_assert_eq!(profile.context().session_agent(), Some(expected.as_str()));
+ prop_assert!(PROVISIONED.contains(&user.as_str()), "{:?} opened", user);
+ prop_assert!(is_valid_for(&user, header.as_deref().unwrap_or("")));
+ }
+ Err(refusal) => {
+ prop_assert!(matches!(refusal.status, 400 | 401 | 403), "{refusal:?}");
+ }
+ }
+ }
+
+ /// Without a valid signature a provisioned user and an unknown one get
+ /// the same refusal, so a caller with a bad signature cannot enumerate
+ /// profiles.
+ #[test]
+ fn bad_signatures_do_not_reveal_provisioning(sig in sig(), mode in mode(), known in prop::sample::select(PROVISIONED.to_vec())) {
+ let host = host(mode);
+ let unknown = "mallory";
+ let known_header = build_sig(&sig, known);
+ let unknown_header = build_sig(&sig, unknown);
+ // A genuinely valid signature is not a probe (and would push proptest
+ // past its global reject cap at high case counts if assumed away).
+ if is_valid_for(known, known_header.as_deref().unwrap_or(""))
+ || is_valid_for(unknown, unknown_header.as_deref().unwrap_or(""))
+ {
+ return Ok(());
+ }
- let a = resolve_user_on(host, known, known_header.as_deref(), SECRET, NOW).unwrap_err();
- let b = resolve_user_on(host, unknown, unknown_header.as_deref(), SECRET, NOW).unwrap_err();
++ let a = resolve_user(host, known, known_header.as_deref()).unwrap_err();
++ let b = resolve_user(host, unknown, unknown_header.as_deref()).unwrap_err();
+ prop_assert_eq!(a.status, 401);
+ prop_assert_eq!(a, b);
+ }
+ }
diff --cc crates/openhuman-core/src/profiles/host.rs
index 53ab2d87f8,20ea3f62e3..b1e34b747a
--- a/crates/openhuman-core/src/profiles/host.rs
+++ b/crates/openhuman-core/src/profiles/host.rs
@@@ -229,29 -149,24 +229,34 @@@ impl ProfileHost
// Credential secrets live in the process keyring under the profile id,
// not only in the profile's directory, so archiving the directory alone
// would let a re-provisioned profile pick the old credential back up.
- if let Err(e) = super::credentials::clear(&layout::profile_config(&layout, id)) {
+ let config = layout::profile_config(&layout, id);
+ let cleared = CoreContext::scope(self.records_context(id), async {
+ super::credentials::clear(&config)
+ })
+ .await;
+ if let Err(e) = cleared {
- log::warn!("[profiles] clearing credentials of profile={id} before archiving: {e}");
+ log::warn!("[profiles] clearing credentials before archiving failed: {e}");
+ // Keep the profile so cleanup can be retried; archiving now would
- // leave the secret for a re-provisioned profile to inherit.
++ // leave the secret for a re-provisioned profile to inherit. The
++ // profile is closed here already, so hand its lease back too.
++ profile_lease::release_all(self.leases(), vec![(id.clone(), grant)]).await;
+ return Err(format!("clearing credentials before archiving: {e}"));
}
- let archive = layout::archive_dir(&self.saas.root);
- std::fs::create_dir_all(&archive)
- .map_err(|e| format!("creating {}: {e}", archive.display()))?;
- // Unique even when one user is deprovisioned twice in a second.
- let dest = archive.join(format!(
- "{id}-{}-{}",
- unix_now(),
- uuid::Uuid::new_v4().simple()
- ));
- std::fs::rename(&layout.dir, &dest)
- .map_err(|e| format!("archiving {}: {e}", layout.dir.display()))?;
- drop(open);
+ if layout.dir.exists() {
+ let archive = layout::archive_dir(&self.saas.root);
+ std::fs::create_dir_all(&archive)
+ .map_err(|e| format!("creating {}: {e}", archive.display()))?;
+ // Unique even when one user is deprovisioned twice in a second.
+ let dest = archive.join(format!(
+ "{id}-{}-{}",
+ unix_now(),
+ uuid::Uuid::new_v4().simple()
+ ));
+ std::fs::rename(&layout.dir, &dest)
+ .map_err(|e| format!("archiving {}: {e}", layout.dir.display()))?;
+ }
+ self.registry.remove(id).await?;
+ profile_lease::release_all(self.leases(), vec![(id.clone(), grant)]).await;
log::info!("[profiles] deprovisioned profile={id} (archived)");
Ok(true)
}
diff --cc crates/openhuman-core/src/profiles/ops.rs
index 1af8cbaf78,374e4266c8..a3a17d9fa0
--- a/crates/openhuman-core/src/profiles/ops.rs
+++ b/crates/openhuman-core/src/profiles/ops.rs
@@@ -24,20 -27,11 +27,20 @@@ pub(crate) async fn provision_on
user_id: &str,
) -> Result<Outcome<ProvisionResult>, String> {
let profile_id = ProfileId::for_user(user_id, host.saas().profile_ids)?;
- let created = host.provision(&profile_id)?;
+ if names_operator_state(&profile_id, &host.saas().operator_dir()) {
+ log::warn!(
+ "[profiles] refusing to provision a profile named like the operator's state dir"
+ );
+ return Err(format!(
+ "profile id {profile_id} is reserved on this deployment: it is the name of the \
+ operator's state directory"
+ ));
+ }
+ let created = host.provision(&profile_id).await?;
let log = if created {
- format!("provisioned {profile_id}")
+ "profile provisioned"
} else {
- format!("{profile_id} was already provisioned")
+ "profile already provisioned"
};
Ok(Outcome::single_log(
ProvisionResult {
@@@ -70,11 -52,11 +73,11 @@@ pub(crate) async fn deprovision_on
profile_id: &str,
) -> Result<Outcome<DeprovisionResult>, String> {
let profile_id = ProfileId::parse(profile_id)?;
- let removed = host.deprovision(&profile_id)?;
+ let removed = host.deprovision(&profile_id).await?;
let log = if removed {
- format!("archived {profile_id}")
+ "profile archived"
} else {
- format!("{profile_id} was not provisioned")
+ "profile was not provisioned"
};
Ok(Outcome::single_log(
DeprovisionResult {
@@@ -103,13 -85,9 +106,10 @@@ pub(crate) async fn status_on
) -> Result<Outcome<ProfileSummary>, String> {
let profile_id = ProfileId::parse(profile_id)?;
let summary = host
- .summary(&profile_id)?
+ .summary(&profile_id)
+ .await?
- .ok_or_else(|| format!("profile {profile_id} is not provisioned"))?;
- Ok(Outcome::single_log(
- summary,
- format!("status of {profile_id}"),
- ))
+ .ok_or_else(|| "profile is not provisioned".to_string())?;
+ Ok(Outcome::single_log(summary, "profile status read"))
}
/// Install the backend credential the gateway holds for profile `profile_id`.
@@@ -132,14 -110,9 +132,14 @@@ pub(crate) async fn set_credential_on
let profile_id = ProfileId::parse(profile_id)?;
// From the layout, not `open`: installing or revoking a credential must
// work even when every profile slot is busy.
- let config = host.provisioned_config(&profile_id)?;
- credentials::store(&config, kind, token, expires_at)?;
+ let config = host.provisioned_config(&profile_id).await?;
+ // Under the profile's own scope, so a storage-backed secret store files
+ // the credential under that profile.
+ crate::core::runtime::CoreContext::scope(host.records_context(&profile_id), async {
+ credentials::store(&config, kind, token, expires_at)
+ })
+ .await?;
- log::info!("[profiles] credential installed for profile={profile_id} kind={kind:?}");
+ log::info!("[profiles] credential installed kind={kind:?}");
Ok(Outcome::single_log(
CredentialResult {
profile_id: profile_id.clone(),
@@@ -159,17 -132,13 +159,17 @@@ pub(crate) async fn clear_credential_on
profile_id: &str,
) -> Result<Outcome<CredentialResult>, String> {
let profile_id = ProfileId::parse(profile_id)?;
- let config = host.provisioned_config(&profile_id)?;
- let removed = credentials::clear(&config)?;
+ let config = host.provisioned_config(&profile_id).await?;
+ let removed =
+ crate::core::runtime::CoreContext::scope(host.records_context(&profile_id), async {
+ credentials::clear(&config)
+ })
+ .await?;
- log::info!("[profiles] credential cleared for profile={profile_id} removed={removed}");
+ log::info!("[profiles] credential cleared removed={removed}");
let log = if removed {
- format!("credential cleared for {profile_id}")
+ "credential cleared"
} else {
- format!("{profile_id} held no credential")
+ "profile held no credential"
};
Ok(Outcome::single_log(
CredentialResult {
@@@ -180,32 -149,6 +180,32 @@@
))
}
+/// Close profile `profile_id` on this node and release its lease, so another
+/// node can host it at once.
+pub async fn release(profile_id: &str) -> Result<Outcome<ReleaseResult>, String> {
+ release_on(&*require_host()?, profile_id).await
+}
+
+pub(crate) async fn release_on(
+ host: &ProfileHost,
+ profile_id: &str,
+) -> Result<Outcome<ReleaseResult>, String> {
+ let profile_id = ProfileId::parse(profile_id)?;
+ let released = host.release(&profile_id).await?;
+ let log = if released {
- format!("released {profile_id}")
++ "profile released"
+ } else {
- format!("{profile_id} was not open on this node")
++ "profile was not open on this node"
+ };
+ Ok(Outcome::single_log(
+ ReleaseResult {
+ profile_id,
+ released,
+ },
+ log,
+ ))
+}
+
#[cfg(test)]
#[path = "ops_tests.rs"]
mod tests;
diff --cc crates/openhuman-core/src/storage/lease_local.rs
index f704bc6de8,0a8f61c45c..18ea7f9f69
--- a/crates/openhuman-core/src/storage/lease_local.rs
+++ b/crates/openhuman-core/src/storage/lease_local.rs
@@@ -191,12 -182,30 +192,30 @@@ impl LeaseStore for LocalLeases
);
return Err(LeaseError::Held(record));
}
- let previous = self.read_record(key);
+ let previous = match self.read_record(key) {
+ Ok(previous) => previous,
+ Err(error) => {
+ let _ = FileExt::unlock(&file);
+ return Err(error.into());
+ }
+ };
let unclean = previous.as_ref().is_some_and(|record| !record.released);
- let epoch = previous.map_or(1, |record| record.epoch.saturating_add(1));
+ let epoch = match previous {
+ None => 1,
+ Some(record) => match record.epoch.checked_add(1) {
+ Some(next) => next,
+ None => {
+ let _ = FileExt::unlock(&file);
+ return Err(StorageError::conflict(format!(
+ "lease {key} epoch space exhausted"
+ ))
+ .into());
+ }
+ },
+ };
let record = LeaseRecord {
owner: self.node.clone(),
- endpoint: None,
+ endpoint: self.endpoint.clone(),
epoch,
expires_at_ms: u64::MAX,
released: false,
diff --cc crates/openhuman-embed/src/host_internals.rs
index 4ea9a5012d,159c4b75b2..d7115f8469
--- a/crates/openhuman-embed/src/host_internals.rs
+++ b/crates/openhuman-embed/src/host_internals.rs
@@@ -2,16 -2,339 +2,343 @@@
//! (`openhuman-tinyhumans`, `openhuman-rpc`), and nothing else.
//!
//! Those layers implement the backend transport, the hosted controllers and
- //! the JSON-RPC server, which reach deep into the core by nature. Routing
- //! them through this module keeps the dependency chain strict (they need no
+ //! the JSON-RPC server, which reach into the core by nature. Routing them
+ //! through this module keeps the dependency chain strict (they need no
//! `openhuman-core` dependency of their own) without inventing a public API
- //! for every server internal. It is an explicit list of modules, not a glob:
- //! a new reach-in is added here on purpose. Hosts (app, CLI, TUI) use the
- //! curated facade at the crate root instead.
-
- pub use openhuman_core::{
- agent, backend, channels, config, core, desktop, inference, integrations, mcp, platform,
- profiles, security, storage, tools, util, voice, web3, web_chat,
- };
+ //! for every server internal.
+ //!
+ //! This is an explicit list of items, not a glob of modules: every entry is a
+ //! symbol one of the two consumers named in its group actually uses, and a new
+ //! reach-in is added here on purpose. The nested module layout mirrors the
+ //! core's paths so a consumer's `__host::a::b::item` reads like the core path.
+ //! Hosts (app, CLI, TUI) never see this module: the curated facade at the
+ //! crate root is theirs, and the layers above embed re-export no part of it
+ //! (`scripts/ci/check-crate-chain.mjs` enforces that).
pub use openhuman_core::run_core_from_args;
+
+ /// Shared by tinyhumans (hosted controllers) and rpc (`http_host`, `/health`).
+ pub mod core {
+ pub use openhuman_core::core::{
+ unwrap_rpc, ControllerSchema, FieldSchema, Outcome, StructuredRpcError, TypeSchema,
+ };
+
+ pub mod all {
+ // tinyhumans: hosted controller extension; rpc: http_host + `/health`.
+ pub use openhuman_core::core::all::{
+ all_controller_schemas, all_http_method_schemas, cli_handler_for_namespace,
+ namespace_description, register_controller_extension, rpc_method_from_parts,
+ schema_for_rpc_method, ControllerExtension, ControllerFuture, DomainGroup,
+ RegisteredController,
+ };
+ }
+
+ /// Error classification shared by the hosted client (tinyhumans) and the
+ /// RPC handler and classifier (rpc).
+ pub mod observability {
+ pub use openhuman_core::core::observability::{
+ contains_transient_transport_phrase, expected_error_kind, is_api_key_rejected_message,
+ is_session_expired_message, is_suppressed_usage_probe_backoff,
+ is_transient_http_status_code, is_transient_message_failure, report_error_or_expected,
+ report_warning_message, ExpectedErrorKind, API_KEY_REJECTED_PREFIX,
+ BACKEND_UNAVAILABLE_PREFIX, REPORT_ERROR_TRACING_TARGET,
+ };
+ }
+
+ // rpc server only, below.
+ pub mod auth {
+ pub use openhuman_core::core::auth::{
+ bearer_matches, get_rpc_token, init_rpc_token, init_rpc_token_with_value,
+ verify_bearer_token, CORE_TOKEN_ENV_VAR,
+ };
+ }
+ pub mod bus {
+ pub use openhuman_core::core::bus::{init, BUS};
+ }
+ pub mod cli {
+ pub use openhuman_core::core::cli::load_dotenv_for_cli;
+ }
+ pub mod dispatch {
+ pub use openhuman_core::core::dispatch::{
+ is_known_probe_method, unknown_method_name, UNKNOWN_METHOD_PREFIX,
+ };
+ }
+ pub mod event_bind_tokens {
+ pub use openhuman_core::core::event_bind_tokens::{consume, issue};
+ }
+ pub mod events {
+ // `DomainEvent` is matched variant by variant by the Socket.IO bridge.
+ pub use openhuman_core::core::events::DomainEvent;
+ }
+ pub mod invoke {
+ pub use openhuman_core::core::invoke::{default_state, invoke_method};
+ }
+ pub mod params {
+ pub use openhuman_core::core::params::{
+ is_param_validation_error, missing_required_param_message, unknown_param_message,
+ };
+ }
+ pub mod runtime {
+ pub use openhuman_core::core::runtime::{
+ current_tenant, is_saas, CoreContext, CoreRuntime, Mode, SaasConfig,
+ };
+ pub mod saas {
+ pub use openhuman_core::core::runtime::saas::build;
+ }
+ }
+ pub mod server_launcher {
+ pub use openhuman_core::core::server_launcher::{install_server_launcher, ServeRequest};
+ }
+ pub mod session_expiry {
+ pub use openhuman_core::core::session_expiry::is_session_expired_error;
+ }
+ pub mod shutdown {
+ pub use openhuman_core::core::shutdown::{register, signal};
+ }
+ pub mod types {
+ pub use openhuman_core::core::types::AppState;
+ }
+ }
+
+ /// tinyhumans (backend transport, hosted client, team ops) and rpc (`/health`).
+ pub mod backend {
+ pub use openhuman_core::backend::{
+ base_url, flatten_authed_error, BackendApiError, BackendClient,
+ };
+
+ pub mod transport {
+ pub use openhuman_core::backend::transport::{
+ clear_backend_transport, resolve_backend_transport, BackendTransport,
+ BackendTransportError, TransportProfile,
+ };
+ }
+ }
+
+ /// tinyhumans (every hosted controller loads its config) and rpc (server).
+ pub mod config {
+ pub use openhuman_core::config::{
+ active_workspace_dir, active_workspace_dir_cached, active_workspace_snapshot,
+ load_config_with_timeout, workspace_handle, Config,
+ };
+
+ pub mod app_env {
+ // tinyhumans: backend URL selection.
+ pub use openhuman_core::config::app_env::{
+ app_env_from_env, is_staging_app_env, APP_ENV_VAR, VITE_APP_ENV_VAR,
+ };
+ }
+ pub mod ops {
+ pub use openhuman_core::config::ops::load_config_with_timeout;
+ }
+ pub mod rpc {
+ pub use openhuman_core::config::rpc::load_config_with_timeout;
+ }
+ pub mod schema {
+ pub mod cloud_providers {
+ pub use openhuman_core::config::schema::cloud_providers::{
+ endpoint_host, host_is_builtin_cloud_provider,
+ };
+ }
+ }
+ }
+
+ /// tinyhumans: the Jev tool ranker and the jev route.
+ pub mod agent {
+ pub mod tinyagents {
+ pub mod discovery {
+ pub use openhuman_core::agent::tinyagents::discovery::{
+ embedding_provider_is_usable, embedding_tool_ranker, install_tool_ranker,
+ installed_tool_ranker,
+ };
+ }
+ // rpc: Socket.IO run-mode toggles.
+ pub mod run_mode {
+ pub use openhuman_core::agent::tinyagents::run_mode::{parse_mode_label, set_mode};
+ }
+ }
+ // rpc: shutdown, plan review over Socket.IO, and the session store install.
+ pub mod orchestration {
+ pub use openhuman_core::agent::orchestration::release_background_completion_stores;
+ }
+ pub mod plan_review {
+ pub mod gate {
+ pub use openhuman_core::agent::plan_review::gate::global;
+ }
+ }
+ pub mod session_store {
+ pub use openhuman_core::agent::session_store::{
+ context_workspace_dir, install, installed, restore,
+ };
+ }
+ }
+
+ /// tinyhumans: the channel-link controller schema.
+ pub mod channels {
+ pub mod contract_schema {
+ pub use openhuman_core::channels::contract_schema::contract_controller_schema;
+ }
+ }
+
+ /// tinyhumans: embeddings and provider-key lookup for the Jev ranker; rpc: the
+ /// OpenAI-compatible HTTP router.
+ pub mod inference {
+ pub mod embedding_host {
+ pub use openhuman_core::inference::embedding_host::default_embedding_provider_with_config;
+ }
+ pub mod provider {
+ pub mod factory {
+ pub use openhuman_core::inference::provider::factory::lookup_key_for_slug;
+ }
+ }
+ pub mod http {
+ #[cfg(feature = "http-server")]
+ pub use openhuman_core::inference::http::router;
+ pub use openhuman_core::inference::http::EXTERNAL_OPENAI_COMPAT_PROVIDER;
+ }
+ }
+
+ /// tinyhumans: the team ops budget gate.
+ pub mod integrations {
+ pub mod client {
+ pub use openhuman_core::integrations::client::budget_gate;
+ }
+ }
+
+ /// tinyhumans (credentials for the hosted client) and rpc (server auth,
+ /// Socket.IO approvals, bind policy).
+ pub mod security {
+ pub mod credentials {
+ pub use openhuman_core::security::credentials::{
+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
+ };
+ pub mod ops {
+ pub use openhuman_core::security::credentials::ops::{
+ list_provider_credentials, store_provider_credentials,
+ };
+ }
+ pub mod session_support {
+ pub use openhuman_core::security::credentials::session_support::{
+ build_session_state, current_session_is_local, resolve_backend_credential,
+ BackendCredential, LOCAL_SESSION_BACKEND_UNAVAILABLE,
+ };
+ }
+ }
+ pub mod approval {
+ pub use openhuman_core::security::approval::ApprovalGate;
+ }
+ pub mod pairing {
+ pub use openhuman_core::security::pairing::is_public_bind;
+ }
+ }
+
+ /// tinyhumans: TLS, URL and redaction helpers for the backend client.
+ pub mod util {
+ pub use openhuman_core::util::redact_url_for_log;
+
+ pub mod redact {
+ pub use openhuman_core::util::redact::redact_url_for_log;
+ }
+ pub mod tls {
+ pub use openhuman_core::util::tls::tls_client_builder;
+ }
+ pub mod url {
+ pub use openhuman_core::util::url::{
+ host_is_local, join_url, normalize_api_base_url, normalize_backend_api_base_url,
+ };
+ }
+ }
+
+ // The rest is the rpc server alone.
+
+ pub mod desktop {
+ pub mod notifications {
+ pub use openhuman_core::desktop::notifications::subscribe_core_notifications;
+ }
+ pub mod overlay {
+ pub use openhuman_core::desktop::overlay::subscribe_attention_events;
+ }
+ }
+
+ pub mod mcp {
+ pub mod registry {
+ pub mod oauth {
+ pub use openhuman_core::mcp::registry::oauth::complete;
+ }
+ }
+ }
+
+ pub mod platform {
+ pub mod connectivity {
+ pub mod rpc {
+ pub use openhuman_core::platform::connectivity::rpc::{
+ pick_listen_port_for_host_with, OccupiedByCore,
+ };
+ }
+ }
+ pub mod health {
+ pub use openhuman_core::platform::health::{snapshot, verdict};
+ }
+ }
+
+ pub mod storage {
+ pub use openhuman_core::storage::{
+ block_on_anyhow, clear, configured_url, driver_is_shared, install, installed, open,
+ url_from, StorageBackend, STORAGE_URL_VAR,
+ };
+ }
+
+ pub mod profiles {
+ pub mod gateway {
+ pub use openhuman_core::profiles::gateway::{
- resolve_scope, sign, verify, GatewayRefusal, GatewayScope, USER_HEADER, USER_SIG_HEADER,
++ resolve_scope, sign, verify, GatewayRefusal, GatewayScope, HeldBy, PROFILE_HELD,
++ PROFILE_OWNER_HEADER, USER_HEADER, USER_SIG_HEADER,
+ };
+ }
++ pub mod host {
++ pub use openhuman_core::profiles::host::host;
++ }
+ }
+
+ pub mod voice {
+ pub mod dictation_listener {
+ pub use openhuman_core::voice::dictation_listener::{
+ subscribe_dictation_events, subscribe_transcription_results,
+ };
+ }
+ // The core carries the live-voice and dictation sockets only with voice and
+ // the HTTP server compiled in. Where its features differ from embed's (a
+ // workspace build unifies them separately), rpc still names these paths, so
+ // embed supplies a socket-dropping stand-in rather than a missing item.
+ pub mod live {
+ pub mod ws {
+ #[cfg(all(feature = "voice", feature = "http-server"))]
+ pub use openhuman_core::voice::live::ws::handle_live_voice_ws;
+ #[cfg(not(all(feature = "voice", feature = "http-server")))]
+ pub async fn handle_live_voice_ws<S, C>(_socket: S, _config: C) {}
+ }
+ }
+ pub mod streaming {
+ #[cfg(all(feature = "voice", feature = "http-server"))]
+ pub use openhuman_core::voice::streaming::handle_dictation_ws;
+ #[cfg(not(all(feature = "voice", feature = "http-server")))]
+ pub async fn handle_dictation_ws<S, C>(_socket: S, _config: C) {}
+ }
+ }
+
+ pub mod web3 {
+ pub mod wallet {
+ pub use openhuman_core::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE;
+ }
+ }
+
+ pub mod web_chat {
+ pub use openhuman_core::web_chat::{
+ approval_request_event, cancel_chat_scoped, plan_review_request_event,
+ publish_web_channel_event, start_chat, subscribe_web_channel_events, unix_epoch_ms,
+ ChatRequestMetadata, GuardrailPayload, StartChatError, WebChannelEvent,
+ };
+ }
+
+ #[cfg(test)]
+ #[path = "host_internals_tests.rs"]
+ mod tests;
diff --cc crates/openhuman-rpc/src/server/saas_gateway_proptest_tests.rs
index 0000000000,648844cd62..5c5ed4370d
mode 000000,100644..100644
--- a/crates/openhuman-rpc/src/server/saas_gateway_proptest_tests.rs
+++ b/crates/openhuman-rpc/src/server/saas_gateway_proptest_tests.rs
@@@ -1,0 -1,201 +1,217 @@@
+ //! Property tests for the SaaS gateway layer's header handling. The user and
+ //! signature headers are attacker-shaped, so for any combination of them:
+ //!
+ //! - without the service bearer, every probe with one readable user header
+ //! gets the same `401`, whether that user is provisioned or not, and the
+ //! resolver is never consulted;
+ //! - with it, the answer is a 400/401/403 refusal, or the resolver receives
+ //! exactly the one user header and the one signature the request carried.
+ //!
+ //! Case counts follow `PROPTEST_CASES` (default 256); CI pins the seed with
+ //! `PROPTEST_RNG_SEED`.
+
+ use super::*;
+ use crate::core_host::profiles::gateway::{sign, verify};
+ use axum::body::Body;
+ use axum::http::HeaderValue;
+ use proptest::prelude::*;
+ use std::cell::RefCell;
+
+ const SECRET: &str = "service-token";
+ const NOW: u64 = 1_700_000_000;
+ const PROVISIONED: &str = "alice";
+
+ /// What reached the resolver, if anything.
+ type Seen = RefCell<Option<(Option<String>, Option<String>)>>;
+
+ /// Stands in for `resolve_scope`: records its inputs, then admits only a
+ /// correctly signed `alice` (the operator scope stands in for "her profile").
+ fn resolve_recording<'a>(
+ seen: &'a Seen,
+ ) -> impl FnOnce(Option<&str>, Option<&str>, &str, u64) -> Result<GatewayScope, GatewayRefusal> + 'a
+ {
+ move |user, sig, secret, now| {
+ *seen.borrow_mut() = Some((user.map(String::from), sig.map(String::from)));
- let refuse = |status, message: &str| GatewayRefusal {
- status,
- message: message.to_string(),
- };
++ let refuse = |status, message: &str| GatewayRefusal::new(status, message);
+ let user = user.ok_or_else(|| refuse(500, "resolver called without a user"))?;
+ let sig = sig.ok_or_else(|| refuse(401, "missing signature"))?;
+ verify(secret, user, sig, now).map_err(|e| refuse(401, &e))?;
+ if user == PROVISIONED {
+ Ok(GatewayScope::Operator)
+ } else {
+ Err(refuse(403, "not provisioned"))
+ }
+ }
+ }
+
++/// [`decide`] and then, for an admitted user, `resolve` — the order the
++/// layer runs them in, with the (async, process-wide) resolver swapped for
++/// a recording one.
++fn decide_then_resolve(
++ req: &Request,
++ secret: Option<&str>,
++ now: u64,
++ resolve: impl FnOnce(Option<&str>, Option<&str>, &str, u64) -> Result<GatewayScope, GatewayRefusal>,
++) -> Result<GatewayScope, GatewayRefusal> {
++ match decide(req, secret) {
++ Err(refused) => Err(GatewayRefusal::new(refused.status, refused.message)),
++ Ok(Admitted::Operator) => Ok(GatewayScope::Operator),
++ Ok(Admitted::User { user, signature }) => {
++ let secret = secret.expect("decide admits a user only once the core has a token");
++ resolve(Some(&user), signature.as_deref(), secret, now)
++ }
++ }
++}
++
+ /// Raw header bytes: real users, near-misses, signatures and noise. Values
+ /// `HeaderValue` cannot hold are dropped by the request builder below.
+ fn user_value() -> impl Strategy<Value = Vec<u8>> {
+ prop_oneof![
+ 3 => prop::sample::select(vec!["alice", "bob", "mallory", "ALICE", " alice", "alice ", "alice,bob", ""])
+ .prop_map(|s| s.as_bytes().to_vec()),
+ 1 => "[ -~]{0,40}".prop_map(String::into_bytes),
+ 1 => (0usize..9000).prop_map(|n| vec![b'a'; n]),
+ 1 => prop::collection::vec(any::<u8>(), 0..40),
+ ]
+ }
+
+ /// [`user_value`] restricted to values that are one readable header, so the
+ /// probe gets past the header checks to the bearer.
+ fn readable_user_value() -> impl Strategy<Value = Vec<u8>> {
+ prop_oneof![
+ 3 => prop::sample::select(vec!["bob", "mallory", "ALICE", " alice", "alice ", "alice,bob", ""])
+ .prop_map(|s| s.as_bytes().to_vec()),
+ 1 => "[\t -~]{0,40}".prop_map(String::into_bytes),
+ 1 => (0usize..9000).prop_map(|n| vec![b'a'; n]),
+ ]
+ }
+
+ fn sig_value() -> impl Strategy<Value = Vec<u8>> {
+ let user = prop::sample::select(vec!["alice", "bob", "mallory"]);
+ prop_oneof![
+ 3 => (user.clone(), -120i64..120).prop_map(|(u, skew)| {
+ sign(SECRET, u, NOW.saturating_add_signed(skew)).into_bytes()
+ }),
+ 1 => (user, 0usize..64).prop_map(|(u, keep)| {
+ let header = sign(SECRET, u, NOW);
+ let (head, tag) = header.split_once("v1=").unwrap();
+ format!("{head}v1={}", &tag[..keep]).into_bytes()
+ }),
+ 1 => "[ -~]{0,80}".prop_map(String::into_bytes),
+ 1 => prop::collection::vec(any::<u8>(), 0..80),
+ ]
+ }
+
+ fn authorization() -> impl Strategy<Value = Option<Vec<u8>>> {
+ prop_oneof![
+ Just(None),
+ Just(Some(b"Bearer nope".to_vec())),
+ Just(Some(b"Bearer ".to_vec())),
+ Just(Some(format!("bearer {SECRET}").into_bytes())),
+ Just(Some(format!("Basic {SECRET}").into_bytes())),
+ Just(Some(format!("Bearer {SECRET}x").into_bytes())),
+ "[ -~]{0,40}".prop_map(|s| Some(s.into_bytes())),
+ ]
+ }
+
+ fn request(auth: Option<&[u8]>, users: &[Vec<u8>], sigs: &[Vec<u8>]) -> Request {
+ let mut req = Request::builder().uri("/rpc");
+ let headers = req.headers_mut().unwrap();
+ if let Some(auth) = auth.and_then(|a| HeaderValue::from_bytes(a).ok()) {
+ headers.append(header::AUTHORIZATION, auth);
+ }
+ for value in users.iter().filter_map(|v| HeaderValue::from_bytes(v).ok()) {
+ headers.append(USER_HEADER, value);
+ }
+ for value in sigs.iter().filter_map(|v| HeaderValue::from_bytes(v).ok()) {
+ headers.append(USER_SIG_HEADER, value);
+ }
+ req.body(Body::empty()).unwrap()
+ }
+
+ /// A refusal's status and message, for comparing two of them exactly.
+ fn parts(refusal: GatewayRefusal) -> (u16, String) {
+ (refusal.status, refusal.message)
+ }
+
+ fn readable_single(values: &[Vec<u8>]) -> Option<String> {
+ let readable: Vec<_> = values
+ .iter()
+ .filter_map(|v| HeaderValue::from_bytes(v).ok())
+ .collect();
+ match readable.as_slice() {
+ [one] => one.to_str().ok().map(String::from),
+ _ => None,
+ }
+ }
+
+ proptest! {
+ /// Without the service bearer, a probe for a provisioned user and one for
+ /// an unknown user get identical `401`s, and the resolver (which
+ /// knows who is provisioned) is never reached.
+ #[test]
+ fn unauthenticated_probes_cannot_tell_users_apart(
+ auth in authorization(),
+ unknown in readable_user_value(),
+ sigs in prop::collection::vec(sig_value(), 0..3),
+ ) {
+ prop_assert!(readable_single(std::slice::from_ref(&unknown)).is_some());
+ let probe = |user: &[u8]| {
+ let seen = Seen::default();
+ let req = request(auth.as_deref(), &[user.to_vec()], &sigs);
- let outcome = decide(&req, Some(SECRET), NOW, resolve_recording(&seen));
++ let outcome = decide_then_resolve(&req, Some(SECRET), NOW, resolve_recording(&seen));
+ (outcome, seen.into_inner())
+ };
+ let (known, known_seen) = probe(PROVISIONED.as_bytes());
+ let (other, other_seen) = probe(&unknown);
+ let (Err(known), Err(other)) = (known, other) else {
+ return Err(TestCaseError::fail("an unauthenticated user request was admitted"));
+ };
+ prop_assert!(known_seen.is_none() && other_seen.is_none(), "resolver reached without the bearer");
+ let known = parts(known);
+ prop_assert_eq!(known.0, 401);
+ prop_assert_eq!(known, parts(other));
+ }
+
+ /// With the bearer, any header combination is refused with a client
+ /// status or reaches the resolver carrying exactly the request's single
+ /// user header and single signature, and only a correctly signed
+ /// provisioned user is admitted.
+ #[test]
+ fn authenticated_requests_resolve_only_what_they_carry(
+ users in prop::collection::vec(user_value(), 0..3),
+ sigs in prop::collection::vec(sig_value(), 0..3),
+ ) {
+ let bearer = format!("Bearer {SECRET}").into_bytes();
+ let req = request(Some(&bearer), &users, &sigs);
+ let user_count = req.headers().get_all(USER_HEADER).iter().count();
+ let sig_count = req.headers().get_all(USER_SIG_HEADER).iter().count();
+ let seen = Seen::default();
- let outcome = decide(&req, Some(SECRET), NOW, resolve_recording(&seen));
++ let outcome = decide_then_resolve(&req, Some(SECRET), NOW, resolve_recording(&seen));
+ let seen = seen.into_inner();
+ if user_count == 0 {
+ prop_assert!(matches!(outcome, Ok(GatewayScope::Operator)));
+ prop_assert!(seen.is_none());
+ return Ok(());
+ }
+ match outcome {
+ Ok(_) => {
+ let (user, sig) = seen.expect("admitted without resolving");
+ prop_assert_eq!(user_count, 1);
+ prop_assert!(sig_count <= 1);
+ prop_assert_eq!(user.as_deref(), Some(PROVISIONED));
+ prop_assert_eq!(user, readable_single(&users));
+ let sig = sig.expect("admitted without a signature");
+ prop_assert!(verify(SECRET, PROVISIONED, &sig, NOW).is_ok());
+ }
+ Err(refusal) => {
+ let status = refusal.status;
+ prop_assert!(matches!(status, 400 | 401 | 403), "status {}", status);
+ if user_count > 1 || sig_count > 1 {
+ prop_assert_eq!(status, 400);
+ prop_assert!(seen.is_none(), "resolver reached with duplicate headers");
+ }
+ }
+ }
+ }
+ }
diff --cc crates/openhuman-rpc/src/server/shims.rs
index aeb5c1b605,74fbdcfbbd..f0617762d2
--- a/crates/openhuman-rpc/src/server/shims.rs
+++ b/crates/openhuman-rpc/src/server/shims.rs
@@@ -77,72 -69,12 +76,25 @@@ pub async fn run_server_saas
saas_config: &std::path::Path,
) -> anyhow::Result<()> {
let config = crate::core_host::core::runtime::SaasConfig::load(saas_config)?;
- crate::session_store::install();
+ let storage_url = config.resolved_storage_url();
+ log::info!(
+ "[rpc:saas] session store: {}",
+ if storage_url.is_some() {
+ "storage backend"
+ } else {
+ "on-disk"
+ }
+ );
+ crate::session_store::install_for_saas(storage_url).await?;
let runtime =
crate::core_host::core::runtime::saas::build(config, host.map(str::to_owned), port).await?;
- super::serve::serve(&runtime, None, None).await
+ let served = super::serve::serve(&runtime, None, None).await;
+ if let Some(profiles) = crate::core_host::profiles::host::host() {
+ profiles.release_idle_on_shutdown().await;
+ }
+ served
}
- /// Like [`run_server`] but marks the instance as embedded.
- pub async fn run_server_embedded(
- host: Option<&str>,
- port: Option<u16>,
- socketio_enabled: bool,
- shutdown_token: CancellationToken,
- ) -> anyhow::Result<()> {
- run_server_inner(
- host,
- port,
- socketio_enabled,
- true,
- Some(shutdown_token),
- None,
- None,
- )
- .await
- }
-
- /// Embedded entrypoint with an explicit readiness callback.
- ///
- /// When the caller already holds the per-launch RPC bearer in memory (the
- /// Tauri shell now that the core runs in-process — PR #1061), it should
- /// pass `Some(token)` so the embedded server can seed its auth subsystem
- /// via `openhuman::core::auth::init_rpc_token_with_value` without ever
- /// reading `OPENHUMAN_CORE_TOKEN` from the process environment. Passing
- /// `None` preserves the env-as-config fallback (CLI / docker / cloud).
- pub async fn run_server_embedded_with_ready(
- host: Option<&str>,
- port: Option<u16>,
- socketio_enabled: bool,
- shutdown_token: CancellationToken,
- ready_tx: tokio::sync::oneshot::Sender<EmbeddedReadySignal>,
- rpc_token: Option<Arc<String>>,
- ) -> anyhow::Result<()> {
- run_server_inner(
- host,
- port,
- socketio_enabled,
- true,
- Some(shutdown_token),
- Some(ready_tx),
- rpc_token,
- )
- .await
- }
-
/// Internal server entrypoint.
async fn run_server_inner(
host: Option<&str>,
diff --cc scripts/ci/saas-ambient-baseline.json
index e01f346184,b9553e1f00..a73af53a90
--- a/scripts/ci/saas-ambient-baseline.json
+++ b/scripts/ci/saas-ambient-baseline.json
@@@ -79,14 -72,14 +72,14 @@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/agent/session_host/runtime_session.rs",
-- "line": 724,
++ "line": 723,
"text": "tokio::spawn(async move {",
"occurrence": 1
},
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/agent/session_host/runtime_session.rs",
-- "line": 726,
++ "line": 725,
"text": "let transcript = tokio::task::spawn_blocking(move || {",
"occurrence": 1
},
@@@ -191,7 -184,7 +184,7 @@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/channels/runtime/startup/start_channels.rs",
-- "line": 370,
++ "line": 225,
"text": "let provider_bridge = AbortOnDropHandle::new(tokio::spawn(async move {",
"occurrence": 1
},
@@@ -611,7 -632,7 +604,7 @@@
{
"rule": "ambient-config",
"path": "crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs",
-- "line": 49,
++ "line": 66,
"text": "let config = crate::config::Config::load_or_init()",
"occurrence": 1
},
@@@ -814,7 -849,7 +807,7 @@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/modules/ops.rs",
-- "line": 256,
++ "line": 274,
"text": "let found_on_search_path = tokio::task::spawn_blocking(move || {",
"occurrence": 1
},
@@@ -1059,7 -1129,7 +1059,7 @@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/threads/ops/edit.rs",
-- "line": 363,
++ "line": 379,
"text": "let result = tokio::task::spawn_blocking(move || {",
"occurrence": 1
},