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
feat(user_agents): add gateway module for user agent routing
Steven Enamakelc1b08a713758
diff --git a/crates/openhuman-core/src/user_agents/gateway.rs b/crates/openhuman-core/src/user_agents/gateway.rsnew file mode 100644index 0000000000..3ba8bd1c0d--- /dev/null+++ b/crates/openhuman-core/src/user_agents/gateway.rs@@ -0,0 +1,134 @@+//! How a gateway request picks the context it runs under.+//!+//! The gateway authenticates users and calls the core with the service bearer+//! plus, for work on a user's behalf, the user's id:+//!+//! ```text+//! Authorization: Bearer <service token>+//! X-OpenHuman-User: <gateway user id>+//! X-OpenHuman-User-Sig: t=<unix secs>,v1=<hex hmac-sha256(service token, "<t>.<user id>")>+//! ```+//!+//! No user header means the operator plane. With one, the request runs under+//! that user's agent — which must already be provisioned — and nothing else.+//! The signature, required unless the operator turns it off, binds the user id+//! to the bearer holder and a ±60 s window: a gateway that forwards a client's+//! headers by mistake cannot be talked into acting as another user.+//!+//! The core never verifies the user's own credential; the gateway did that.++use std::sync::Arc;++use hmac::{Hmac, Mac};+use sha2::Sha256;++use super::host::{self, UserAgentState};+use super::types::UserAgentId;++/// The gateway's user header.+pub const USER_HEADER: &str = "x-openhuman-user";+/// The gateway's signature over the user header.+pub const USER_SIG_HEADER: &str = "x-openhuman-user-sig";+/// How far a signature's timestamp may be from the core's clock.+pub const SIGNATURE_WINDOW_SECS: u64 = 60;++type HmacSha256 = Hmac<Sha256>;++fn mac(secret: &str, user_id: &str, ts: u64) -> HmacSha256 {+ let mut mac =+ HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts keys of any length");+ mac.update(format!("{ts}.{user_id}").as_bytes());+ mac+}++/// The `X-OpenHuman-User-Sig` value for `user_id` at `ts` (unix seconds).+pub fn sign(secret: &str, user_id: &str, ts: u64) -> String {+ let tag = mac(secret, user_id, ts).finalize().into_bytes();+ format!("t={ts},v1={}", hex::encode(tag))+}++/// Check a signature header for `user_id` against `now` (unix seconds).+pub fn verify(secret: &str, user_id: &str, header: &str, now: u64) -> Result<(), String> {+ let mut ts = None;+ let mut tag = None;+ for part in header.split(',') {+ match part.trim().split_once('=') {+ Some(("t", value)) => ts = value.parse::<u64>().ok(),+ Some(("v1", value)) => tag = hex::decode(value).ok(),+ _ => {}+ }+ }+ let (Some(ts), Some(tag)) = (ts, tag) else {+ return Err("malformed user signature".to_string());+ };+ if ts.abs_diff(now) > SIGNATURE_WINDOW_SECS {+ return Err("user signature is outside the allowed clock window".to_string());+ }+ mac(secret, user_id, ts)+ .verify_slice(&tag)+ .map_err(|_| "user signature does not match".to_string())+}++/// Why a gateway request was refused.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct GatewayRefusal {+ /// The HTTP status to answer with.+ pub status: u16,+ pub message: String,+}++impl GatewayRefusal {+ fn new(status: u16, message: impl Into<String>) -> Self {+ Self {+ status,+ message: message.into(),+ }+ }+}++/// Where a gateway request runs.+#[derive(Debug)]+pub enum GatewayScope {+ /// No user header: the operator plane.+ Operator,+ /// One user's agent.+ User(Arc<UserAgentState>),+}++/// Pick the scope for a request that already presented the service bearer.+///+/// `secret` is the service bearer; `now` is unix seconds.+pub fn resolve_scope(+ user_id: Option<&str>,+ signature: Option<&str>,+ secret: &str,+ now: u64,+) -> Result<GatewayScope, GatewayRefusal> {+ let Some(user_id) = user_id else {+ return Ok(GatewayScope::Operator);+ };+ let host = host::host()+ .ok_or_else(|| GatewayRefusal::new(503, "this core serves no users"))?;+ let agent = UserAgentId::for_user(user_id).map_err(|e| GatewayRefusal::new(400, e))?;+ if host.saas().require_user_signature {+ let signature = signature.ok_or_else(|| {+ GatewayRefusal::new(401, format!("missing {USER_SIG_HEADER}"))+ })?;+ verify(secret, user_id, signature, now).map_err(|e| {+ log::warn!("[user_agents][gateway] refused agent={agent}: {e}");+ GatewayRefusal::new(401, e)+ })?;+ }+ match host.open(&agent) {+ Ok(state) => {+ log::debug!("[user_agents][gateway] scoped request to agent={agent}");+ Ok(GatewayScope::User(state))+ }+ Err(e) if e.contains("not provisioned") => Err(GatewayRefusal::new(403, e)),+ Err(e) => Err(GatewayRefusal::new(503, e)),+ }+}++#[cfg(test)]+#[path = "gateway_tests.rs"]+mod tests;