Skip to content

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

feat(runtime): add boot guard and runtime mode detection

Steven Enamakel1d7b98338220
diff --git a/crates/openhuman-core/src/core/runtime/boot_guard.rs b/crates/openhuman-core/src/core/runtime/boot_guard.rs
index a81f85ae47..9dc3406be9 100644
--- a/crates/openhuman-core/src/core/runtime/boot_guard.rs
+++ b/crates/openhuman-core/src/core/runtime/boot_guard.rs
@@ -50,7 +50,7 @@ pub const FORBIDDEN_OFF_SWITCHES: &[(&str, &str)] = &[
fn is_off(value: &str) -> bool {
matches!(
value.trim().to_ascii_lowercase().as_str(),
- "0" | "false" | "off" | "no" | "disabled"
+ "0" | "false" | "off" | "no" | "none" | "disabled"
)
}
@@ -97,6 +97,14 @@ impl ServiceToken {
return Self::Invalid(format!("cannot read {display}: {e}"));
}
let token = raw.trim();
+ // It travels as `Authorization: Bearer <token>`: one line of visible
+ // ASCII, or no client could ever send it.
+ if !token.bytes().all(|b| b.is_ascii_graphic()) {
+ return Self::Invalid(format!(
+ "{display} must hold one token of visible ASCII characters (no spaces, \
+ line breaks or control characters)"
+ ));
+ }
if token.len() < MIN_SERVICE_TOKEN_LEN {
return Self::Invalid(format!(
"{display} holds {} bytes; at least {MIN_SERVICE_TOKEN_LEN} are required",
@@ -129,6 +137,7 @@ pub enum Violation {
RpcAllowlist(Vec<String>),
Root(String),
ServiceToken(String),
+ Platform(&'static str),
}
impl std::fmt::Display for Violation {
@@ -148,6 +157,7 @@ impl std::fmt::Display for Violation {
),
Self::Root(why) => write!(f, "root: {why}"),
Self::ServiceToken(why) => write!(f, "service token: {why}"),
+ Self::Platform(why) => write!(f, "platform: {why}"),
}
}
}
@@ -240,6 +250,11 @@ pub fn check(inputs: &BootInputs<'_>) -> Result<(), BootGuardError> {
if let Some(why) = root_problem(&inputs.config.root, inputs.home.as_deref()) {
violations.push(Violation::Root(why));
}
+ // Token and root permissions are verified only on Unix.
+ #[cfg(not(unix))]
+ violations.push(Violation::Platform(
+ "SaaS mode needs a Unix host, where token and root permissions can be verified",
+ ));
if let ServiceToken::Invalid(why) = inputs.token {
violations.push(Violation::ServiceToken(why.clone()));
}
@@ -274,8 +289,11 @@ fn root_problem(root: &Path, home: Option<&Path>) -> Option<String> {
#[cfg(not(unix))]
let _ = meta;
if let Some(home) = home {
- let desktop_root = home.join(".openhuman");
- if root.starts_with(&desktop_root) {
+ // Compare resolved paths, so neither a symlink nor `..` can alias the
+ // desktop directory.
+ let resolve = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
+ let desktop_root = resolve(&home.join(".openhuman"));
+ if resolve(root).starts_with(&desktop_root) {
return Some(format!(
"{} is inside the desktop app's {}",
root.display(),
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 1050424e75..021d15f898 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -226,6 +226,16 @@ impl CoreContext {
if crate::core::runtime::mode::is_saas() && host_kind != HostKind::Saas {
anyhow::bail!("[core-context] this process serves SaaS; refusing a {host_kind:?} core");
}
+ // A SaaS core boots only through `saas::build`, which runs the boot
+ // guard and locks the mode first, and only once per process.
+ if host_kind == HostKind::Saas {
+ if !crate::core::runtime::mode::is_saas() {
+ anyhow::bail!("[core-context] a SaaS core boots only through saas::build");
+ }
+ if DEFAULT_CONTEXT.get().is_some() {
+ anyhow::bail!("[core-context] this process already serves its SaaS core");
+ }
+ }
// 1. Ensure all controllers are registered before anything dispatches.
let _ = crate::core::all::all_registered_controllers();
diff --git a/crates/openhuman-core/src/core/runtime/mode.rs b/crates/openhuman-core/src/core/runtime/mode.rs
index e7071b3882..beeacea9f5 100644
--- a/crates/openhuman-core/src/core/runtime/mode.rs
+++ b/crates/openhuman-core/src/core/runtime/mode.rs
@@ -67,6 +67,30 @@ pub fn is_saas() -> bool {
current_mode() == Mode::Saas
}
+/// Whether the command line or `OPENHUMAN_MODE` asks for SaaS, read before
+/// the CLI parses its arguments. The CLI skips its early keyring set-up for a
+/// SaaS boot, which roots the keyring under the operator directory instead
+/// (`saas::build`).
+pub fn requested_in(args: &[String], env: Option<&str>) -> bool {
+ let saas = |raw: &str| raw.trim().parse::<Mode>() == Ok(Mode::Saas);
+ env.is_some_and(saas)
+ || args.windows(2).any(|w| w[0] == "--mode" && saas(&w[1]))
+ || args
+ .iter()
+ .any(|a| a.strip_prefix("--mode=").is_some_and(saas))
+}
+
+static SAAS_BOOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
+/// Claim the process's one SaaS boot. A second claim fails, even while the
+/// first boot is still building.
+pub(crate) fn reserve_saas_boot() -> Result<(), String> {
+ if SAAS_BOOT.swap(true, std::sync::atomic::Ordering::AcqRel) {
+ return Err("a SaaS core has already booted (or is booting) in this process".to_string());
+ }
+ Ok(())
+}
+
/// Fix the process mode. Locking the mode it already has is a no-op; locking
/// a different one fails, because one process never serves both shapes.
pub(crate) fn lock_mode(mode: Mode) -> Result<(), String> {
diff --git a/crates/openhuman-core/src/core/runtime/saas.rs b/crates/openhuman-core/src/core/runtime/saas.rs
index 4dddef668d..3ac6ccf871 100644
--- a/crates/openhuman-core/src/core/runtime/saas.rs
+++ b/crates/openhuman-core/src/core/runtime/saas.rs
@@ -147,6 +147,7 @@ pub async fn build(
"[saas] a core is already running in this process; a SaaS core must be the only one"
);
}
+ mode::reserve_saas_boot().map_err(|e| anyhow::anyhow!("[saas] {e}"))?;
let services = ServiceSet::saas();
let domains = DomainSet::saas();
@@ -172,6 +173,17 @@ pub async fn build(
std::fs::create_dir_all(dir)
.map_err(|e| anyhow::anyhow!("[saas] creating {}: {e}", dir.display()))?;
}
+ // Root the keyring (the master key and every stored credential) under the
+ // operator directory, never the host's `~/.openhuman`.
+ crate::security::keyring::init_workspace(&operator.workspace_dir);
+ let keyring_dir = crate::security::keyring::store::workspace_dir_for_file_backend();
+ if keyring_dir != operator.workspace_dir {
+ anyhow::bail!(
+ "[saas] the keyring is already rooted at {}; a SaaS core keeps it under {}",
+ keyring_dir.display(),
+ operator.workspace_dir.display()
+ );
+ }
log::info!(
"[saas] booting operator plane root={} max_agents_open={} idle_evict_secs={}",
config.root.display(),
diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rs
index 929054a663..f9454b05ed 100644
--- a/crates/openhuman-core/src/lib.rs
+++ b/crates/openhuman-core/src/lib.rs
@@ -112,6 +112,10 @@ pub use core::types::HostKind;
pub fn run_core_from_args(args: &[String]) -> anyhow::Result<()> {
core::cli::load_dotenv_for_cli()?;
platform::service::apply_startup_restart_delay_from_env();
- security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
+ // A SaaS boot roots the keyring under its operator directory
+ // (`saas::build`), so it must not be latched to the home directory here.
+ if !core::runtime::mode::requested_in(args, std::env::var("OPENHUMAN_MODE").ok().as_deref()) {
+ security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
+ }
core::cli::run_from_cli_args(args)
}
diff --git a/crates/openhuman-rpc/src/server/dev_connect.rs b/crates/openhuman-rpc/src/server/dev_connect.rs
index 52b4dffdb5..4c25014c87 100644
--- a/crates/openhuman-rpc/src/server/dev_connect.rs
+++ b/crates/openhuman-rpc/src/server/dev_connect.rs
@@ -41,7 +41,9 @@ pub struct DevConnectQuery {
/// Whether the route is live in this process.
pub fn dev_connect_enabled() -> bool {
- dev_connect_enabled_with(
+ // Never on a SaaS core: the route is auth-exempt and hands out the bearer.
+ !openhuman_core::core::runtime::is_saas()
+ && dev_connect_enabled_with(
cfg!(debug_assertions),
std::env::var(DEV_CONNECT_ENV).ok().as_deref(),
)