The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge upstream/main into saas-profile-host
Steven Enamakel5add9c46b148
diff --cc crates/openhuman-core/src/agent/orchestration/background_delivery.rsindex 95d85305d6,e7b06c40ad..af60bb8c4f--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs@@@ -124,20 -126,56 +126,57 @@@ 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 a profile is async (it may take its lease), so resolve the++ // owning profiles' contexts first and hand the sync scheduler a lookup.++ let mut live = std::collections::HashMap::new();++ if saas {++ for profile in owning_profiles(event) {++ if let Some(ctx) = completion_owners::context_for_profile(&profile).await {++ live.insert(profile, ctx);++ }++ }++ }++ for drain in drain_schedule_in(saas, event, |p| live.get(p).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 {++/// The session, task and delay an event drains on, if it asks for a drain.++fn drain_target(event: &DomainEvent) -> Option<(&String, Option<&String>, Duration)> {++ 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))++ Some((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@@@ -146,18 -184,67 +185,96 @@@// 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 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.++ } => Some((parent_session, Some(task_id), DEBOUNCE)),+ _ => return None,++ }++}++++/// Profiles recorded as owning the task (else the session).++fn owners_of(session: &str, task: Option<&String>) -> Vec<String> {+ let mut profiles = task+ .map(|t| completion_owners::profiles_of(t))+ .unwrap_or_default();+ if profiles.is_empty() {+ profiles = completion_owners::profiles_of(session);+ }++ profiles++}++++/// The profiles whose contexts [`drain_schedule_in`] will ask for.++fn owning_profiles(event: &DomainEvent) -> Vec<String> {++ drain_target(event)++ .map(|(session, task, _)| owners_of(session, task))++ .unwrap_or_default()++}++++/// 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 Some((session, task, delay)) = drain_target(event) else {++ return Vec::new();+ };- match background_completions::thread_for_session(session) {- Some(thread_id) => Some((thread_id, delay)),- None => {++ // 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 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");- None}+ 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()}/// Schedule a debounced delivery attempt for a thread.diff --cc crates/openhuman-core/src/agent/orchestration/completion_owners.rsindex 0000000000,1015f4dc6c..474ce11dd7mode 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,93 @@@+ //! 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) {++ match crate::profiles::host::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.rsindex 35889feb70,c1b100e6cd..e98107aad5--- a/crates/openhuman-core/src/core/runtime/saas.rs+++ b/crates/openhuman-core/src/core/runtime/saas.rs@@@ -388,23 -297,19 +388,31 @@@ pub async fn build// Whoever initialised first won; refuse to serve users from a registry// that holds anything but the built-ins.verify_builtin_definitions(crate::agent::harness::AgentDefinitionRegistry::global())?;+ // A relayed platform message (`channel_relay_inbound`) runs through the+ // channel dispatch pipeline, which asks the native bus for an+ // `agent.run_turn`. The `Agent` family stays off in SaaS (no agent RPCs+ // on any surface), so its subscriber plan never registers that handler;+ // register it alone. The request carries the caller's own turn parts, and+ // the handler runs in the caller's (profile's) scope.+ crate::agent::bus::register_agent_handlers();+ log::debug!("[saas] registered the native agent.run_turn handler for relayed channel turns");- let host = Arc::new(crate::profiles::ProfileHost::new(- config,- runtime.context().clone(),- ));+ // With a storage backend installed (the host opened the configured URL+ // before boot), the profile registry and leases live in it and every node+ // sharing it contends for the same profiles; without one they are files+ // under the root.+ let backend = crate::storage::installed();+ if config.resolved_storage_url().is_some() && backend.is_none() {+ anyhow::bail!(+ "[saas] a storage URL is configured but no backend is installed; \+ the host must open it before boot"+ );+ }+ let host = Arc::new(+ crate::profiles::ProfileHost::with_backend(config, runtime.context().clone(), backend)+ .map_err(|e| anyhow::anyhow!("[saas] {e}"))?,+ );crate::profiles::host::install(Arc::clone(&host));+ crate::profiles::lease::heartbeat(Arc::clone(&host), runtime.context().clone());crate::profiles::background::spawn(host);Ok(runtime)}diff --cc crates/openhuman-core/src/profiles/gateway.rsindex b2cb1dfdc1,c763ccbcf4..4f57634077--- 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::Arcuse 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_scopereturn 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,15 -131,13 +182,15 @@@GatewayRefusal::new(401, e)})?;}- match host.open(&profile) {+ match host.open(&profile).await {Ok(state) => {log::debug!("[profiles][gateway] scoped request to an open profile");- Ok(GatewayScope::User(state))+ 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(+ error,+ super::lease::now_ms(),+ )),}}diff --cc crates/openhuman-core/src/profiles/gateway_proptest_tests.rsindex 0000000000,fa06f74705..982f470914mode 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,253 @@@+ //! 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;+++/// Runs an async host call to completion from a (synchronous) property body.++fn block<T>(future: impl std::future::Future<Output = T>) -> T {++ static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();++ RT.get_or_init(|| {++ tokio::runtime::Builder::new_current_thread()++ .enable_all()++ .build()++ .unwrap()++ })++ .block_on(future)++}+++ 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]"];++ /// 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())- .unwrap();++ block(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 block(resolve_user_on(host, &user, header.as_deref(), SECRET, NOW)) {+ 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 = block(resolve_user_on(host, known, known_header.as_deref(), SECRET, NOW)).unwrap_err();++ let b = block(resolve_user_on(host, unknown, unknown_header.as_deref(), SECRET, NOW)).unwrap_err();+ prop_assert_eq!(a.status, 401);+ prop_assert_eq!(a, b);+ }+ }diff --cc crates/openhuman-rpc/src/server/saas_gateway_proptest_tests.rsindex 0000000000,648844cd62..fa4baef184mode 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,158 @@@+ //! 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.++//! gets the same `401`, whether that user is provisioned or not;++//! - with it, the answer is a 400/401 refusal, or the one user header and the++//! one signature the request carried are handed on to be resolved.+ //!+ //! 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 crate::core_host::profiles::gateway::sign;+ 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 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"))- }- }-}++const KNOWN: &str = "alice";++ /// 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) {++fn parts(refusal: Refused) -> (u16, &'static str) {+ (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.++ /// Without the service bearer, a probe for a known user and one for an++ /// unknown user get identical `401`s.+ #[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));- (outcome, seen.into_inner())++ decide(&req, Some(SECRET))+ };- let (known, known_seen) = probe(PROVISIONED.as_bytes());- let (other, other_seen) = probe(&unknown);- let (Err(known), Err(other)) = (known, other) else {++ let (Err(known), Err(other)) = (probe(KNOWN.as_bytes()), probe(&unknown)) 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.++ /// status or admitted carrying exactly the request's single user header++ /// and single signature.+ #[test]- fn authenticated_requests_resolve_only_what_they_carry(++ fn authenticated_requests_carry_only_what_they_sent(+ 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 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");++ match decide(&req, Some(SECRET)) {++ Ok(Admitted::Operator) => prop_assert_eq!(user_count, 0),++ Ok(Admitted::User { user, signature }) => {+ 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());++ prop_assert_eq!(Some(user), readable_single(&users));++ if sig_count == 1 {++ prop_assert!(signature.is_none() || signature == readable_single(&sigs));++ } else {++ prop_assert!(signature.is_none());++ }+ }+ Err(refusal) => {- let status = refusal.status;- prop_assert!(matches!(status, 400 | 401 | 403), "status {}", status);++ prop_assert!(matches!(refusal.status, 400 | 401), "status {}", refusal.status);+ if user_count > 1 || sig_count > 1 {- prop_assert_eq!(status, 400);- prop_assert!(seen.is_none(), "resolver reached with duplicate headers");++ prop_assert_eq!(refusal.status, 400);+ }+ }+ }+ }+ }