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-profiles

Steven Enamakel954c1d6db710
diff --cc crates/openhuman-core/src/core/runtime/saas.rs
index 16a8cfc2ac,dd0f4fe04b..84b408a68f
--- a/crates/openhuman-core/src/core/runtime/saas.rs
+++ b/crates/openhuman-core/src/core/runtime/saas.rs
@@@ -288,17 -286,10 +294,10 @@@ pub async fn build
builder = builder.port(port);
}
let runtime = builder.build().await?;
- // Built-in agent definitions only. The registry is process-wide and the
- // first initialiser wins, so seeding it here also stops a lazy init from
- // loading one user's workspace definitions for everyone.
- crate::agent::harness::AgentDefinitionRegistry::init_global_builtins()?;
- log::info!(
- "[saas] agent definitions: {} built-in(s), no workspace or home overrides",
- crate::agent::harness::AgentDefinitionRegistry::global()
- .map(|r| r.len())
- .unwrap_or(0)
- );
+ // 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())?;
- let host = Arc::new(crate::user_agents::AgentHost::new(
+ let host = Arc::new(crate::profiles::ProfileHost::new(
config,
runtime.context().clone(),
));
diff --cc crates/openhuman-core/src/profiles/credentials_tests.rs
index be66fae0cc,5a2a5ddb7a..c137a2afff
--- a/crates/openhuman-core/src/profiles/credentials_tests.rs
+++ b/crates/openhuman-core/src/profiles/credentials_tests.rs
@@@ -114,3 -110,40 +114,40 @@@ fn every_profile_of_the_other_kind_is_r
assert!(clear(&alice).unwrap());
assert!(!has(&alice));
}
+
+ #[test]
+ fn concurrent_stores_of_different_kinds_leave_exactly_one_kind() {
+ let tmp = tempfile::tempdir().unwrap();
+ for round in 0..8 {
- let user = agent(&tmp, &format!("race{round}"));
++ let user = profile(&tmp, &format!("race{round}"));
+ let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));
+ let spawn = |kind, token: &'static str| {
+ let (user, barrier) = (user.clone(), barrier.clone());
+ std::thread::spawn(move || {
+ barrier.wait();
+ store(&user, kind, token, None).unwrap();
+ })
+ };
+ let session = spawn(UserCredentialKind::Session, "race-jwt");
+ let key = spawn(UserCredentialKind::ApiKey, "race-key");
+ session.join().unwrap();
+ key.join().unwrap();
+
- // Whichever store ran last owns the agent; the other kind is gone.
++ // Whichever store ran last owns the profile; the other kind is gone.
+ let provider_present = |provider: &str| {
+ let auth = AuthService::from_config(&user);
+ let id = crate::security::credentials::normalize_provider(provider).unwrap();
+ auth.load_profiles()
+ .unwrap()
+ .profiles
+ .values()
+ .any(|profile| profile.provider == id)
+ };
+ let has_key = provider_present(api_key::API_KEY_PROVIDER);
+ let has_session = provider_present(APP_SESSION_PROVIDER);
+ assert!(
+ has_key != has_session,
+ "round {round}: exactly one kind must remain (key={has_key}, session={has_session})"
+ );
+ }
+ }
diff --cc crates/openhuman-core/src/security/approval/gate_forced_tests.rs
index 4dc4ce70a2,ace1892917..c0f32e828e
--- a/crates/openhuman-core/src/security/approval/gate_forced_tests.rs
+++ b/crates/openhuman-core/src/security/approval/gate_forced_tests.rs
@@@ -136,3 -136,29 +136,29 @@@ async fn forced_approval_still_denies_a
}
assert!(gate.list_pending().unwrap().is_empty());
}
+
+ #[test]
+ fn saas_outcome_is_absent_outside_saas() {
+ assert!(saas_outcome_with(false, "shell").is_none());
+ }
+
+ #[test]
+ fn saas_outcome_never_parks_and_denies_without_an_allowlisted_group() {
+ // No agent host is installed here, so no tool group is allowlisted.
+ match saas_outcome_with(true, "shell") {
+ Some(GateOutcome::Deny { reason }) => {
+ assert!(reason.starts_with(POLICY_DENIED_MARKER), "{reason}");
+ assert!(reason.contains("no approval surface"), "{reason}");
+ }
+ other => panic!("expected an immediate deny, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn saas_outcome_maps_an_allowlisted_verdict_to_allow() {
- use crate::user_agents::tools::{gate_verdict_with, SaasToolGroup};
++ use crate::profiles::tools::{gate_verdict_with, SaasToolGroup};
+ let verdict = gate_verdict_with("shell", &[SaasToolGroup::HostShell]);
+ assert!(matches!(saas_outcome(verdict), GateOutcome::Allow));
+ let verdict = gate_verdict_with("shell", &[SaasToolGroup::HostFiles]);
+ assert!(matches!(saas_outcome(verdict), GateOutcome::Deny { .. }));
+ }
diff --cc crates/openhuman-core/src/security/approval/gate_intercept.rs
index 9de37c44b7,5d07530977..f41fb32837
--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs
+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs
@@@ -653,3 -647,25 +647,25 @@@ impl ApprovalGate
outcome
}
}
+
+ /// The gate's outcome in SaaS, `None` outside it. SaaS has no per-user approval
+ /// surface, so the gate never parks there; the verdict comes from the
+ /// deployment's allowlisted tool groups.
+ pub(crate) fn saas_outcome_with(saas: bool, tool_name: &str) -> Option<GateOutcome> {
+ if !saas {
+ return None;
+ }
- Some(saas_outcome(crate::user_agents::tools::gate_verdict(
++ Some(saas_outcome(crate::profiles::tools::gate_verdict(
+ tool_name,
+ )))
+ }
+
+ /// Maps a SaaS gate verdict to a [`GateOutcome`].
+ pub(crate) fn saas_outcome(verdict: Result<(), String>) -> GateOutcome {
+ match verdict {
+ Ok(()) => GateOutcome::Allow,
+ Err(why) => GateOutcome::Deny {
+ reason: format!("{POLICY_DENIED_MARKER} {why}"),
+ },
+ }
+ }
diff --cc crates/openhuman-core/src/security/credentials/bus.rs
index 3ce17baba4,652cb8ecba..f622181e03
--- a/crates/openhuman-core/src/security/credentials/bus.rs
+++ b/crates/openhuman-core/src/security/credentials/bus.rs
@@@ -60,9 -69,9 +69,9 @@@ impl SessionExpiredSubscriber
};
// SaaS: the credential belongs to one user and the gateway owns its
- // refresh (`user_agents.set_credential`). Nothing process-wide is torn
+ // refresh (`profiles.set_credential`). Nothing process-wide is torn
// down; the failing call already reports the 401 to that user.
- if crate::core::runtime::is_saas() {
+ if saas {
tracing::warn!(
source = %source,
reason = %reason,
diff --cc crates/openhuman-core/src/storage/README.md
index 14e34a43d4,165916b360..d33d63ab37
--- a/crates/openhuman-core/src/storage/README.md
+++ b/crates/openhuman-core/src/storage/README.md
@@@ -71,6 -71,41 +71,41 @@@ on `storage-mongodb`
master key they fail closed. The config encryption key stays on the
process keyring, because `config.toml` is loaded before any agent acts.
+ ## Background work and agent scopes
+
+ Work done inside an agent's turn runs under that agent's `CoreContext`
-(`session_agent`, set for embed agents and SaaS user agents), so with a
++(`session_agent`, set for embed agents and SaaS profiles), so with a
+ backend installed its records land in that agent's scope. Background work
+ runs under the process default context and on its own would only see
+ `local`. `storage::agents` closes the gap:
+
+ - Known agents: the live ones are `core::runtime::AgentContextRegistry`'s
+ (embed registers each agent it builds and deregisters it on drop).
+ `AgentContextRegistry::register` also records the agent id in the
+ backend's `local` scope (`storage_agents`, `agents::record`), so a
+ restarted process still knows it; `agents::contexts()` lists both.
+ - `for_each_scope(label, step)`: runs `step` for `local`, then under each
+ known agent's context — its live one, or the default context acting for it
+ (`CoreContext::for_agent`). `for_each_agent` skips `local`.
+ - `within_agent(agent, fut)` / `context_for(agent)`: re-enter an agent's
+ scope when background work learned whose record it is handling.
+ - `find_owner(label, probe)`: the scope (`local` first, then each agent)
+ where a record named only by id lives — for event subscribers, whose
+ events carry ids but no agent.
+
+ Users: the task-source poller, the flows boot sweep and schedule-trigger reconcile, the run reaper,
+ the device tunnel (a paired device's frames run as the agent that paired
+ it, `security::devices::owner`), and the event subscribers: a flow's
+ schedule tick, run digest and dedup settlement run as the flow's owner
+ (`flows::bus::owner`); Composio app-event triggers and new connections are
+ matched in every scope; a cron job's completion notification is stored with
+ the job's owner. Without a backend these run once, as
+ before. The cron scheduler visits live agents only
+ (`cron::scheduler::tick_live_agents`): an agent's jobs need its live
+ context (host tools, prompt) to run, so a recorded agent's jobs wait until
+ it is live again; with a backend it no longer needs the agent's `jobs.db`. In SaaS mode agent ids are not recorded and `local` is skipped;
-per-user background work there is `user_agents::background`.
++per-user background work there is `profiles::background`.
+
## Boundaries
The ports, drivers, scopes and conformance suites are tinystoragedrivers';
diff --cc crates/openhuman-core/src/storage/agents.rs
index 0000000000,80cb1a5e4f..289f5292ab
mode 000000,100644..100644
--- a/crates/openhuman-core/src/storage/agents.rs
+++ b/crates/openhuman-core/src/storage/agents.rs
@@@ -1,0 -1,282 +1,282 @@@
+ //! The agents that keep records in their own storage scope, and a way for
+ //! background work to visit each of them.
+ //!
+ //! Work done inside an agent's turn runs under that agent's `CoreContext`
+ //! (`session_agent`), so with a storage backend installed its cron jobs,
+ //! flows, approvals and the rest land in that agent's scope. Background work
+ //! — the cron scheduler, pollers, boot sweeps — runs under the process
+ //! default context, which names no agent, and on its own would only ever see
+ //! the `local` scope. [`for_each_scope`] closes that gap: it runs a step once
+ //! for `local` and once under each known agent's context.
+ //!
+ //! An agent is known when it is live in this process
+ //! (`core::runtime::AgentContextRegistry`, which embed agents register on
+ //! build) — its own context is used, with its configuration, policy and
+ //! tools — or when an earlier process recorded its id in the backend's
+ //! `local` scope (`storage_agents`, written by [`record`] when the agent
+ //! registers), so a restart still visits agents the host has not re-created
+ //! yet; those are visited under the default context acting for them
+ //! (`CoreContext::for_agent`).
+ //!
+ //! Without a backend [`for_each_agent`] visits nothing: the SQLite stores
+ //! these loops read do not split by agent. In SaaS mode the process has no
+ //! `local` scope and per-user background work is driven by
-//! `user_agents::background`, so agent ids are not recorded and
++//! `profiles::background`, so agent ids are not recorded and
+ //! [`for_each_scope`] skips `local`.
+
+ use std::collections::{BTreeMap, HashSet};
+ use std::future::Future;
+ use std::sync::{Arc, LazyLock, Mutex};
+
+ use serde_json::json;
+ use tinystoragedrivers::{CollectionSpec, Precondition, Query, Scope};
+
+ use super::{block_on, installed, DocumentStoreExt, StorageBackend};
+ use crate::core::runtime::{AgentContextRegistry, CoreContext};
+
+ /// The `local`-scope collection recording which agents have their own scope.
+ const AGENTS: &str = "storage_agents";
+
+ /// `(backend, agent id)` pairs this process has already recorded, the
+ /// backend identified by its address (see [`backend_key`]).
+ static RECORDED: LazyLock<Mutex<HashSet<(usize, String)>>> = LazyLock::new(Default::default);
+
+ /// Identifies `backend` within this process. [`reset_recorded`] runs on every
+ /// install and clear, so an address reused by a later backend never inherits
+ /// an earlier one's records.
+ fn backend_key(backend: &Arc<dyn StorageBackend>) -> usize {
+ Arc::as_ptr(backend).cast::<()>() as usize
+ }
+
+ /// Forgets which agents were recorded, so the next [`record`] writes them to
+ /// the backend now installed (or removed). Called by [`super::install`] and
+ /// [`super::clear`]: the record cache describes one backend, not the process.
+ pub(super) fn reset_recorded() {
+ RECORDED
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clear();
+ }
+
+ /// Records every live agent in the backend — for agents registered before
+ /// the host installed its backend. Called by [`super::install`].
+ pub(super) fn record_live() {
+ for (agent, _) in AgentContextRegistry::live() {
+ record(&agent);
+ }
+ }
+
+ /// Writes `agent` to the backend's `storage_agents` collection, once per
+ /// process. `AgentContextRegistry::register` calls it for every agent. Best
+ /// effort: a failure is logged and retried on the next registration, and
+ /// only costs a restarted process its visits to that agent until the agent
+ /// registers again.
+ pub fn record(agent: &str) {
+ if crate::core::runtime::mode::is_saas() {
+ return;
+ }
+ let Some(backend) = installed() else {
+ return;
+ };
+ record_in(backend, agent);
+ }
+
+ /// [`record`] against an explicit `backend`.
+ fn record_in(backend: Arc<dyn StorageBackend>, agent: &str) {
+ let key = (backend_key(&backend), agent.to_string());
+ if RECORDED
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .contains(&key)
+ {
+ return;
+ }
+ let id = agent.to_string();
+ let result = block_on(async move {
+ let docs = Arc::clone(backend.for_scope(&Scope::local())?.documents());
+ docs.ensure_collection(&CollectionSpec::new(AGENTS)).await?;
+ docs.put(AGENTS, &id, json!({}), Precondition::None).await?;
+ Ok(())
+ });
+ match result {
+ Ok(()) => {
+ RECORDED
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(key);
+ tracing::debug!(%agent, "[storage::agents] recorded agent scope");
+ }
+ Err(error) => {
+ tracing::warn!(%agent, %error, "[storage::agents] could not record agent scope");
+ }
+ }
+ }
+
+ /// Agent ids recorded in the backend by this or an earlier process.
+ fn recorded(backend: Arc<dyn StorageBackend>) -> Vec<String> {
+ let result = block_on(async move {
+ let docs = Arc::clone(backend.for_scope(&Scope::local())?.documents());
+ docs.ensure_collection(&CollectionSpec::new(AGENTS)).await?;
+ let stored = docs.query_all(AGENTS, &Query::all()).await?;
+ Ok(stored.into_iter().map(|doc| doc.id).collect::<Vec<_>>())
+ });
+ result.unwrap_or_else(|error| {
+ tracing::warn!(%error, "[storage::agents] could not list recorded agent scopes");
+ Vec::new()
+ })
+ }
+
+ /// Every agent background work should visit, each with the context to visit
+ /// it under: the live ones (`AgentContextRegistry`), then — with a storage
+ /// backend installed, outside SaaS mode — every agent recorded by this or an
+ /// earlier process, under the current context acting for it.
+ pub fn contexts() -> Vec<(String, Arc<CoreContext>)> {
+ let backend = if crate::core::runtime::mode::is_saas() {
+ None
+ } else {
+ installed()
+ };
+ contexts_in(backend, CoreContext::current().as_ref())
+ }
+
+ /// [`contexts`] with the backend whose recorded agents are visited, and the
+ /// context that acts for an agent with no live one, made explicit (`None`
+ /// visits live contexts only).
+ fn contexts_in(
+ backend: Option<Arc<dyn StorageBackend>>,
+ fallback: Option<&Arc<CoreContext>>,
+ ) -> Vec<(String, Arc<CoreContext>)> {
+ let mut contexts: BTreeMap<String, Arc<CoreContext>> =
+ AgentContextRegistry::live().into_iter().collect();
+ if let (Some(backend), Some(fallback)) = (backend, fallback) {
+ for agent in recorded(backend) {
+ contexts
+ .entry(agent.clone())
+ .or_insert_with(|| fallback.for_agent(&agent));
+ }
+ }
+ contexts.into_iter().collect()
+ }
+
+ /// The context to act for `agent` under: its live context when one exists,
+ /// else — outside SaaS mode — the current context acting for it
+ /// (`CoreContext::for_agent`).
+ pub fn context_for(agent: &str) -> Option<Arc<CoreContext>> {
+ AgentContextRegistry::get(agent).or_else(|| {
+ // SaaS acts only through a user's own live context: a copy of the
+ // operator's would carry the wrong configuration.
+ if crate::core::runtime::mode::is_saas() {
+ return None;
+ }
+ CoreContext::current().map(|current| current.for_agent(agent))
+ })
+ }
+
+ /// Runs `fut` acting for `agent` when there is one — background work that
+ /// learned whose record it is handling (a device's pairing agent, an event's
+ /// publisher) re-enters that agent's scope — and as-is otherwise.
+ pub async fn within_agent<F: Future>(agent: Option<&str>, fut: F) -> F::Output {
+ match agent.and_then(context_for) {
+ Some(context) => CoreContext::scope(context, fut).await,
+ None => fut.await,
+ }
+ }
+
+ /// The scope a record lives in, for background work that holds only its id
+ /// (an event naming a flow, a job, a device): the first scope — `local`
+ /// first, then each known agent ([`for_each_scope`]) — where `probe` finds
+ /// it. `Some(None)` is `local`, `Some(Some(agent))` an agent, `None` nowhere.
+ pub async fn find_owner<F, Fut>(label: &str, probe: F) -> Option<Option<String>>
+ where
+ F: Fn() -> Fut,
+ Fut: Future<Output = bool>,
+ {
+ for_each_scope(label, probe)
+ .await
+ .into_iter()
+ .find_map(|(agent, found)| found.then_some(agent))
+ }
+
+ /// Runs `step` for every storage scope background work must cover: once
+ /// under the current context (the `local` scope, outside SaaS mode), then
+ /// once per known agent ([`for_each_agent`]). Each result is returned with
+ /// the agent it ran for (`None` for `local`).
+ ///
+ /// `label` names the caller in logs.
+ pub async fn for_each_scope<T, F, Fut>(label: &str, step: F) -> Vec<(Option<String>, T)>
+ where
+ F: Fn() -> Fut,
+ Fut: Future<Output = T>,
+ {
+ let mut results = Vec::new();
+ if !crate::core::runtime::mode::is_saas() {
+ results.push((None, step().await));
+ }
+ for (agent, value) in for_each_agent(label, step).await {
+ results.push((Some(agent), value));
+ }
+ results
+ }
+
+ /// Runs `step` once under each known agent's context, one after another —
+ /// only when a storage backend is installed, since without one the stores do
+ /// not split by agent and the `local` pass already covers everything.
+ ///
+ /// For a loop that handles the `local` scope itself (the cron scheduler keeps
+ /// its process-wide health tracking there) and needs the agents on top.
+ pub async fn for_each_agent<T, F, Fut>(label: &str, step: F) -> Vec<(String, T)>
+ where
+ F: Fn() -> Fut,
+ Fut: Future<Output = T>,
+ {
+ if installed().is_none() {
+ return Vec::new();
+ }
+ visit(label, contexts(), step).await
+ }
+
+ /// [`for_each_scope`], visiting only live agents (`AgentContextRegistry`):
+ /// for work that acts as the agent — runs its flows, fetches with its
+ /// connections — and so needs the agent's own configuration and tools, which
+ /// a recorded agent's stand-in context (`CoreContext::for_agent`) lacks.
+ pub async fn for_each_live_scope<T, F, Fut>(label: &str, step: F) -> Vec<(Option<String>, T)>
+ where
+ F: Fn() -> Fut,
+ Fut: Future<Output = T>,
+ {
+ let mut results = Vec::new();
+ if !crate::core::runtime::mode::is_saas() {
+ results.push((None, step().await));
+ }
+ if installed().is_none() {
+ return results;
+ }
+ for (agent, value) in visit(label, AgentContextRegistry::live(), step).await {
+ results.push((Some(agent), value));
+ }
+ results
+ }
+
+ /// Runs `step` under each of `contexts`, building each step inside its
+ /// agent's scope, so anything it reads while being set up is the agent's.
+ async fn visit<T, F, Fut>(
+ label: &str,
+ contexts: Vec<(String, Arc<CoreContext>)>,
+ step: F,
+ ) -> Vec<(String, T)>
+ where
+ F: Fn() -> Fut,
+ Fut: Future<Output = T>,
+ {
+ let mut results = Vec::new();
+ for (agent, context) in contexts {
+ tracing::trace!(%agent, label, "[storage::agents] visiting agent scope");
+ let value = CoreContext::scope(context, async { step().await }).await;
+ results.push((agent, value));
+ }
+ results
+ }
+
+ #[cfg(test)]
+ #[path = "agents_tests.rs"]
+ mod tests;
diff --cc crates/openhuman-core/src/tools/impl/system/shell.rs
index 162084ddb5,4fc56f5c4f..c9ace8a1d3
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@@ -364,12 -364,17 +364,17 @@@ impl ShellTool
// SaaS: every command runs in the user's container, whatever the
// agent's sandbox mode says, and never on the host.
- if crate::core::runtime::is_saas() {
- let action_dir = self.effective_action_dir_for_context(context);
- return match crate::profiles::tools::sandbox_policy(
- &action_dir,
- &self.security.workspace_dir,
- ) {
+ let saas_action_dir = self.effective_action_dir_for_context(context);
+ if let Some(resolved) =
+ super::shell_saas::saas_sandbox_with(crate::core::runtime::is_saas(), || {
- crate::user_agents::tools::sandbox_policy(
++ crate::profiles::tools::sandbox_policy(
+ &saas_action_dir,
+ &self.security.workspace_dir,
+ )
+ })
+ {
+ let action_dir = saas_action_dir;
+ return match resolved {
Ok(policy) => {
self.run_in_policy(policy, command, requested_timeout, &action_dir)
.await
diff --cc crates/openhuman-rpc/src/server/saas_gateway.rs
index 49aa6de6ec,d211872e95..973a2924d2
--- a/crates/openhuman-rpc/src/server/saas_gateway.rs
+++ b/crates/openhuman-rpc/src/server/saas_gateway.rs
@@@ -19,8 -19,8 +19,8 @@@ use std::sync::Arc
use std::time::{SystemTime, UNIX_EPOCH};
use crate::core_host::core::runtime::CoreContext;
-use crate::core_host::user_agents::gateway::{
+use crate::core_host::profiles::gateway::{
- resolve_scope, GatewayScope, USER_HEADER, USER_SIG_HEADER,
+ resolve_scope, GatewayRefusal, GatewayScope, USER_HEADER, USER_SIG_HEADER,
};
use axum::extract::Request;
use axum::http::{header, StatusCode};
@@@ -69,6 -69,37 +69,37 @@@ fn bearer(req: &Request) -> Option<&str
/// The SaaS request layer; `operator` is the runtime's own context.
pub(crate) async fn saas_gateway(operator: Arc<CoreContext>, req: Request, next: Next) -> Response {
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or_default();
+ let secret = crate::core_host::core::auth::get_rpc_token();
+ match decide(&req, secret, now, resolve_scope) {
+ Err(response) => response,
- Ok(GatewayScope::User(agent)) => {
- let ctx = Arc::clone(agent.context());
- // Holding the state for the request keeps the agent from being
++ Ok(GatewayScope::User(profile)) => {
++ let ctx = Arc::clone(profile.context());
++ // Holding the state for the request keeps the profile from being
+ // evicted under it.
+ let response = CoreContext::scope(ctx, next.run(req)).await;
- drop(agent);
++ drop(profile);
+ response
+ }
+ Ok(GatewayScope::Operator) => CoreContext::scope(operator, next.run(req)).await,
+ }
+ }
+
+ /// Which scope a request runs under, or the response that refuses it.
+ ///
+ /// `secret` is the service bearer (`None` before the core has one), `now` is
+ /// unix seconds and `resolve` maps the checked headers to a scope
+ /// ([`resolve_scope`] in production). Taking them as arguments keeps the
+ /// decision free of process-wide state.
+ pub(crate) fn decide(
+ req: &Request,
+ secret: Option<&str>,
+ now: u64,
+ resolve: impl FnOnce(Option<&str>, Option<&str>, &str, u64) -> Result<GatewayScope, GatewayRefusal>,
+ ) -> Result<GatewayScope, Response> {
let path = req.uri().path();
if is_closed_in_saas(path) {
log::debug!("[rpc:saas] {path} is not served in SaaS mode");
diff --cc crates/openhuman-rpc/src/server/saas_gateway_tests.rs
index 0155a407bf,9ed79de79f..120b3a0685
--- a/crates/openhuman-rpc/src/server/saas_gateway_tests.rs
+++ b/crates/openhuman-rpc/src/server/saas_gateway_tests.rs
@@@ -32,3 -32,222 +32,222 @@@ fn the_gateway_surfaces_stay_open()
assert!(!is_closed_in_saas(path), "{path}");
}
}
+
+ mod decision {
+ use super::*;
- use crate::core_host::user_agents::gateway::sign;
++ use crate::core_host::profiles::gateway::sign;
+ use axum::body::Body;
+ use axum::routing::get;
+ use axum::Router;
+ use tower::ServiceExt;
+
+ const SECRET: &str = "service-token";
+ const NOW: u64 = 1_700_000_000;
+
- /// Stands in for `resolve_scope`, which reads the process's agent host: a
++ /// Stands in for `resolve_scope`, which reads the process's profile host: a
+ /// user needs a valid signature, and only `alice` is provisioned.
+ fn resolve(
+ user: Option<&str>,
+ sig: Option<&str>,
+ secret: &str,
+ now: u64,
+ ) -> Result<GatewayScope, GatewayRefusal> {
+ let refuse = |status, message: &str| GatewayRefusal {
+ status,
+ message: message.to_string(),
+ };
+ let Some(user) = user else {
+ return Ok(GatewayScope::Operator);
+ };
+ let sig = sig.ok_or_else(|| refuse(401, "missing signature"))?;
- crate::core_host::user_agents::gateway::verify(secret, user, sig, now)
++ crate::core_host::profiles::gateway::verify(secret, user, sig, now)
+ .map_err(|e| refuse(401, &e))?;
+ if user == "alice" {
- // The real resolver returns the user's agent state, which needs a
++ // The real resolver returns the user's profile, which needs a
+ // booted host; the operator scope stands in for "accepted".
+ Ok(GatewayScope::Operator)
+ } else {
+ Err(refuse(403, "not provisioned"))
+ }
+ }
+
+ fn app(secret: Option<&'static str>) -> Router {
+ Router::new()
+ .route("/rpc", get(|| async { "ok" }))
+ .route("/events", get(|| async { "ok" }))
+ .route("/v1/models", get(|| async { "ok" }))
+ .layer(axum::middleware::from_fn(
+ move |req: Request, next: Next| async move {
+ match decide(&req, secret, NOW, resolve) {
+ Ok(_) => next.run(req).await,
+ Err(response) => response,
+ }
+ },
+ ))
+ }
+
+ async fn status(app: Router, path: &str, headers: &[(&str, String)]) -> StatusCode {
+ let mut req = Request::builder().uri(path);
+ for (name, value) in headers {
+ req = req.header(*name, value);
+ }
+ app.oneshot(req.body(Body::empty()).unwrap())
+ .await
+ .unwrap()
+ .status()
+ }
+
+ fn bearer_header() -> (&'static str, String) {
+ ("authorization", format!("Bearer {SECRET}"))
+ }
+
+ fn user(id: &str) -> (&'static str, String) {
+ (USER_HEADER, id.to_string())
+ }
+
+ fn sig(id: &str, ts: u64) -> (&'static str, String) {
+ (USER_SIG_HEADER, sign(SECRET, id, ts))
+ }
+
+ #[tokio::test]
+ async fn closed_routes_are_404_even_for_a_valid_caller() {
+ let headers = [bearer_header(), user("alice"), sig("alice", NOW)];
+ assert_eq!(
+ status(app(Some(SECRET)), "/v1/models", &headers).await,
+ StatusCode::NOT_FOUND
+ );
+ }
+
+ #[tokio::test]
+ async fn no_user_header_runs_on_the_operator_plane() {
+ assert_eq!(status(app(Some(SECRET)), "/rpc", &[]).await, StatusCode::OK);
+ }
+
+ #[tokio::test]
+ async fn the_chat_event_stream_is_not_the_operators() {
+ assert_eq!(
+ status(app(Some(SECRET)), "/events", &[bearer_header()]).await,
+ StatusCode::NOT_FOUND
+ );
+ }
+
+ #[tokio::test]
+ async fn a_user_request_without_the_bearer_is_401_before_anything_else() {
+ let app = app(Some(SECRET));
+ assert_eq!(
+ status(app.clone(), "/rpc", &[user("alice"), sig("alice", NOW)]).await,
+ StatusCode::UNAUTHORIZED
+ );
+ let wrong = ("authorization", "Bearer nope".to_string());
+ assert_eq!(
+ status(app, "/rpc", &[wrong, user("nobody"), sig("nobody", NOW)]).await,
+ StatusCode::UNAUTHORIZED,
+ "an unauthenticated caller must not learn who is provisioned"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_user_request_before_the_core_has_a_token_is_503() {
+ assert_eq!(
+ status(app(None), "/rpc", &[bearer_header(), user("alice")]).await,
+ StatusCode::SERVICE_UNAVAILABLE
+ );
+ }
+
+ #[tokio::test]
+ async fn a_valid_signed_user_is_admitted() {
+ let headers = [bearer_header(), user("alice"), sig("alice", NOW)];
+ assert_eq!(
+ status(app(Some(SECRET)), "/rpc", &headers).await,
+ StatusCode::OK
+ );
+ }
+
+ #[tokio::test]
+ async fn the_signature_window_is_plus_or_minus_sixty_seconds() {
+ for ts in [NOW - 60, NOW + 60] {
+ let headers = [bearer_header(), user("alice"), sig("alice", ts)];
+ assert_eq!(
+ status(app(Some(SECRET)), "/rpc", &headers).await,
+ StatusCode::OK,
+ "t={ts}"
+ );
+ }
+ for ts in [NOW - 61, NOW + 61] {
+ let headers = [bearer_header(), user("alice"), sig("alice", ts)];
+ assert_eq!(
+ status(app(Some(SECRET)), "/rpc", &headers).await,
+ StatusCode::UNAUTHORIZED,
+ "t={ts}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn a_missing_or_forged_signature_is_refused() {
+ let app = app(Some(SECRET));
+ assert_eq!(
+ status(app.clone(), "/rpc", &[bearer_header(), user("alice")]).await,
+ StatusCode::UNAUTHORIZED
+ );
+ // Signed for another user.
+ let headers = [bearer_header(), user("alice"), sig("mallory", NOW)];
+ assert_eq!(
+ status(app.clone(), "/rpc", &headers).await,
+ StatusCode::UNAUTHORIZED
+ );
+ // Signed with another key.
+ let forged = (USER_SIG_HEADER, sign("other-key", "alice", NOW));
+ assert_eq!(
+ status(app, "/rpc", &[bearer_header(), user("alice"), forged]).await,
+ StatusCode::UNAUTHORIZED
+ );
+ }
+
+ #[tokio::test]
+ async fn an_unprovisioned_user_is_403() {
+ let headers = [bearer_header(), user("bob"), sig("bob", NOW)];
+ assert_eq!(
+ status(app(Some(SECRET)), "/rpc", &headers).await,
+ StatusCode::FORBIDDEN
+ );
+ }
+
+ #[tokio::test]
+ async fn a_repeated_user_header_is_400() {
+ let headers = [
+ bearer_header(),
+ user("alice"),
+ user("bob"),
+ sig("alice", NOW),
+ ];
+ assert_eq!(
+ status(app(Some(SECRET)), "/rpc", &headers).await,
+ StatusCode::BAD_REQUEST
+ );
+ }
+
+ #[tokio::test]
+ async fn a_repeated_signature_header_is_400_not_first_wins() {
+ // The first signature is valid; the second must not be ignored.
+ let headers = [
+ bearer_header(),
+ user("alice"),
+ sig("alice", NOW),
+ sig("alice", NOW + 1),
+ ];
+ assert_eq!(
+ status(app(Some(SECRET)), "/rpc", &headers).await,
+ StatusCode::BAD_REQUEST
+ );
+ }
+
+ #[tokio::test]
+ async fn a_repeated_signature_header_does_not_leak_to_an_unauthenticated_caller() {
+ let headers = [user("alice"), sig("alice", NOW), sig("alice", NOW)];
+ assert_eq!(
+ status(app(Some(SECRET)), "/rpc", &headers).await,
+ StatusCode::UNAUTHORIZED
+ );
+ }
+ }