Skip to content

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

feat(rpc): report profiles held by another node as 409

Steven Enamakele3844e0a35d3
diff --git a/crates/openhuman-rpc/src/server/saas_gateway.rs b/crates/openhuman-rpc/src/server/saas_gateway.rs
index 973a2924d2..37f3e0e110 100644
--- a/crates/openhuman-rpc/src/server/saas_gateway.rs
+++ b/crates/openhuman-rpc/src/server/saas_gateway.rs
@@ -13,6 +13,11 @@
//! caller learns nothing about which users exist and cannot open profiles —
//! then the signature, then runs the request under that user's profile.
//!
+//! A profile another node hosts is refused with `409` and
+//! `{"error":"profile_held","owner","endpoint","retry_after_ms"}`, plus the
+//! `X-OpenHuman-Profile-Owner` header naming the holder: the gateway routes
+//! the user there, or retries after `retry_after_ms`.
+//!
//! The decision itself lives in `crate::core_host::profiles::gateway`.
use std::sync::Arc;
@@ -20,7 +25,8 @@ use std::time::{SystemTime, UNIX_EPOCH};
use crate::core_host::core::runtime::CoreContext;
use crate::core_host::profiles::gateway::{
- resolve_scope, GatewayRefusal, GatewayScope, USER_HEADER, USER_SIG_HEADER,
+ resolve_scope, GatewayRefusal, GatewayScope, PROFILE_OWNER_HEADER, USER_HEADER,
+ USER_SIG_HEADER,
};
use axum::extract::Request;
use axum::http::{header, StatusCode};
@@ -57,6 +63,41 @@ fn refuse(status: u16, message: &str) -> Response {
(status, axum::Json(serde_json::json!({ "error": message }))).into_response()
}
+/// The response for a refusal from the profile resolver: a plain error, or
+/// for a profile another node hosts the `409` that names it.
+pub(crate) fn refusal_response(refusal: GatewayRefusal) -> Response {
+ let Some(held) = refusal.held_by else {
+ return refuse(refusal.status, &refusal.message);
+ };
+ let body = serde_json::json!({
+ "error": refusal.message,
+ "owner": held.owner,
+ "endpoint": held.endpoint,
+ "retry_after_ms": held.retry_after_ms,
+ });
+ let mut response = (StatusCode::CONFLICT, axum::Json(body)).into_response();
+ match axum::http::HeaderValue::from_str(&held.owner) {
+ Ok(owner) => {
+ response.headers_mut().insert(PROFILE_OWNER_HEADER, owner);
+ }
+ Err(_) => log::warn!("[rpc:saas] the profile owner is not a valid header value"),
+ }
+ response
+}
+
+/// A request the gateway checks let through.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum Admitted {
+ /// No user header: the operator plane.
+ Operator,
+ /// A user request that presented the service bearer; its profile is
+ /// resolved next.
+ User {
+ user: String,
+ signature: Option<String>,
+ },
+}
+
fn header_str<'a>(req: &'a Request, name: &str) -> Option<&'a str> {
req.headers().get(name).and_then(|v| v.to_str().ok())
}
@@ -74,8 +115,14 @@ pub(crate) async fn saas_gateway(operator: Arc<CoreContext>, req: Request, next:
.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,
+ let (user, signature) = match decide(&req, secret) {
+ Err(response) => return response,
+ Ok(Admitted::Operator) => return CoreContext::scope(operator, next.run(req)).await,
+ Ok(Admitted::User { user, signature }) => (user, signature),
+ };
+ let secret = secret.expect("decide admits a user only once the core has a token");
+ match resolve_scope(Some(&user), signature.as_deref(), secret, now).await {
+ Err(refusal) => refusal_response(refusal),
Ok(GatewayScope::User(profile)) => {
let ctx = Arc::clone(profile.context());
// Holding the state for the request keeps the profile from being
@@ -88,18 +135,13 @@ pub(crate) async fn saas_gateway(operator: Arc<CoreContext>, req: Request, next:
}
}
-/// Which scope a request runs under, or the response that refuses it.
+/// Whether a request gets past the gateway checks, or the response that
+/// refuses it. A user request that passes still has its signature and
+/// profile resolved ([`resolve_scope`]).
///
-/// `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> {
+/// `secret` is the service bearer (`None` before the core has one). Taking it
+/// as an argument keeps the decision free of process-wide state.
+pub(crate) fn decide(req: &Request, secret: Option<&str>) -> Result<Admitted, Response> {
let path = req.uri().path();
if is_closed_in_saas(path) {
log::debug!("[rpc:saas] {path} is not served in SaaS mode");
@@ -115,7 +157,7 @@ pub(crate) fn decide(
if path == "/events" {
return Err(refuse(404, "not found"));
}
- return Ok(GatewayScope::Operator);
+ return Ok(Admitted::Operator);
};
if user_headers.next().is_some() {
log::debug!("[rpc:saas] refusing a request with more than one {USER_HEADER}");
@@ -142,9 +184,13 @@ pub(crate) fn decide(
log::debug!("[rpc:saas] refusing a request with more than one {USER_SIG_HEADER}");
return Err(refuse(400, "more than one user signature header"));
}
- let signature = signature.and_then(|value| value.to_str().ok());
- resolve(Some(user), signature, secret, now)
- .map_err(|refusal| refuse(refusal.status, &refusal.message))
+ let signature = signature
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned);
+ Ok(Admitted::User {
+ user: user.to_owned(),
+ signature,
+ })
}
#[cfg(test)]
diff --git a/crates/openhuman-rpc/src/server/saas_gateway_tests.rs b/crates/openhuman-rpc/src/server/saas_gateway_tests.rs
index 120b3a0685..15bcf017f4 100644
--- a/crates/openhuman-rpc/src/server/saas_gateway_tests.rs
+++ b/crates/openhuman-rpc/src/server/saas_gateway_tests.rs
@@ -52,10 +52,7 @@ mod decision {
secret: &str,
now: u64,
) -> Result<GatewayScope, GatewayRefusal> {
- let refuse = |status, message: &str| GatewayRefusal {
- status,
- message: message.to_string(),
- };
+ let refuse = |status, message: &str| GatewayRefusal::new(status, message);
let Some(user) = user else {
return Ok(GatewayScope::Operator);
};
@@ -66,6 +63,17 @@ mod decision {
// The real resolver returns the user's profile, which needs a
// booted host; the operator scope stands in for "accepted".
Ok(GatewayScope::Operator)
+ } else if user == "carol" {
+ // Hosted by another node.
+ Err(GatewayRefusal {
+ status: 409,
+ message: crate::core_host::profiles::gateway::PROFILE_HELD.to_string(),
+ held_by: Some(crate::core_host::profiles::gateway::HeldBy {
+ owner: "node-a".to_string(),
+ endpoint: Some("http://10.0.0.1:7788".to_string()),
+ retry_after_ms: 1_500,
+ }),
+ })
} else {
Err(refuse(403, "not provisioned"))
}
@@ -78,8 +86,14 @@ mod decision {
.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,
+ match decide(&req, secret) {
+ Ok(Admitted::Operator) => next.run(req).await,
+ Ok(Admitted::User { user, signature }) => {
+ match resolve(Some(&user), signature.as_deref(), SECRET, NOW) {
+ Ok(_) => next.run(req).await,
+ Err(refusal) => refusal_response(refusal),
+ }
+ }
Err(response) => response,
}
},
@@ -250,4 +264,44 @@ mod decision {
StatusCode::UNAUTHORIZED
);
}
+
+ #[tokio::test]
+ async fn a_profile_hosted_elsewhere_is_409_naming_the_owner() {
+ let headers = [bearer_header(), user("carol"), sig("carol", NOW)];
+ let mut req = Request::builder().uri("/rpc");
+ for (name, value) in &headers {
+ req = req.header(*name, value);
+ }
+ let response = app(Some(SECRET))
+ .oneshot(req.body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::CONFLICT);
+ assert_eq!(
+ response.headers()[PROFILE_OWNER_HEADER].to_str().unwrap(),
+ "node-a"
+ );
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ body,
+ serde_json::json!({
+ "error": "profile_held",
+ "owner": "node-a",
+ "endpoint": "http://10.0.0.1:7788",
+ "retry_after_ms": 1500,
+ })
+ );
+ }
+
+ #[tokio::test]
+ async fn a_held_profile_is_not_revealed_to_an_unauthenticated_caller() {
+ let headers = [user("carol"), sig("carol", NOW)];
+ assert_eq!(
+ status(app(Some(SECRET)), "/rpc", &headers).await,
+ StatusCode::UNAUTHORIZED
+ );
+ }
}