Skip to content

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

fix(auth): keep local sessions signed in during hosted probes

Steven Enamakel12ca7b7e3972
diff --git a/crates/openhuman-core/src/core/jsonrpc.rs b/crates/openhuman-core/src/core/jsonrpc.rs
index 805c36d808..4abb80f870 100644
--- a/crates/openhuman-core/src/core/jsonrpc.rs
+++ b/crates/openhuman-core/src/core/jsonrpc.rs
@@ -259,8 +259,9 @@ pub async fn rpc_handler(State(state): State<AppState>, Json(req): Json<RpcReque
///
/// This is a high-level wrapper around [`invoke_method_inner`] that adds
/// automatic session management logic. If a call fails with a confirmed
-/// OpenHuman session-expired error, it will automatically clear the local
-/// session.
+/// OpenHuman session-expired error, it publishes the event that clears a
+/// backend session. The offline local credential has no backend session to
+/// expire and receives a recoverable hosted-unavailable error instead.
///
/// # Arguments
///
@@ -268,7 +269,7 @@ pub async fn rpc_handler(State(state): State<AppState>, Json(req): Json<RpcReque
/// * `method` - The name of the method to invoke.
/// * `params` - The JSON parameters for the method.
pub async fn invoke_method(state: AppState, method: &str, params: Value) -> Result<Value, String> {
- let result = invoke_method_inner(state, method, params).await;
+ let mut result = invoke_method_inner(state, method, params).await;
// Session auto-cleanup: if the OpenHuman auth session is explicitly
// expired, publish a `SessionExpired` event. The credentials subscriber
@@ -279,24 +280,35 @@ pub async fn invoke_method(state: AppState, method: &str, params: Value) -> Resu
if let Err(ref msg) = result {
let sanitized_reason = tinyinference_core::sanitize::sanitize_api_error(msg);
if is_session_expired_error(msg) {
- log::warn!(
- "[jsonrpc] confirmed session expiry for method='{}' — publishing SessionExpired: {}",
- method,
- sanitized_reason
- );
- // pasted-through provider replies. `sanitize_api_error` runs
- // `scrub_secret_patterns` and truncates.
- //
- // Local-session protection is handled by `SessionExpiredSubscriber`
- // in `crates/openhuman-core/src/security/credentials/bus.rs` — it checks `is_local_session_token`
- // after config load and short-circuits teardown with
- // `scheduler_gate::set_signed_out(false)`. Duplicating that check
- // here would pull a domain concern into the transport layer and would
- // add an extra config-load round-trip on every 401.
- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {
- source: format!("jsonrpc.invoke_method:{method}"),
- reason: sanitized_reason,
- });
+ // The subscriber ignores an offline local session, but Socket.IO
+ // also hears this event and broadcasts sign-out independently.
+ // Suppress it at the publisher for backend-only routes that the
+ // local credential cannot use. This extra config read happens only
+ // on a classified session-expiry error, never on the normal path.
+ let local =
+ crate::security::credentials::session_support::current_session_is_local().await;
+ if should_publish_session_expired(msg, local) {
+ log::warn!(
+ "[jsonrpc] confirmed session expiry for method='{}' — publishing SessionExpired: {}",
+ method,
+ sanitized_reason
+ );
+ // `sanitize_api_error` scrubs pasted-through provider replies.
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {
+ source: format!("jsonrpc.invoke_method:{method}"),
+ reason: sanitized_reason,
+ });
+ } else {
+ log::info!(
+ "[jsonrpc] backend session unavailable for local offline credential method='{}' — leaving local auth intact",
+ method
+ );
+ // The RPC error is also observed by the renderer's auth
+ // classifier. Keep the background hosted probe recoverable
+ // without asking it to infer the core's credential kind.
+ result = Err(translate_local_session_error(msg, local)
+ .expect("classified local session error"));
+ }
} else if is_unconfirmed_unauthorized_error(msg) {
log::info!(
"[jsonrpc] unconfirmed unauthorized error for method='{}' (not session expiry) — leaving session intact: {}",
@@ -309,6 +321,19 @@ pub async fn invoke_method(state: AppState, method: &str, params: Value) -> Resu
result
}
+fn should_publish_session_expired(msg: &str, credential_is_local: bool) -> bool {
+ is_session_expired_error(msg) && !credential_is_local
+}
+
+fn translate_local_session_error(msg: &str, credential_is_local: bool) -> Option<String> {
+ (credential_is_local && is_session_expired_error(msg)).then(|| {
+ format!(
+ "{}Hosted account data is unavailable in local offline mode",
+ crate::core::observability::BACKEND_UNAVAILABLE_PREFIX
+ )
+ })
+}
+
/// Helper to determine if an error message indicates an expired or invalid
/// OpenHuman backend session.
///
diff --git a/crates/openhuman-core/src/core/jsonrpc_tests.rs b/crates/openhuman-core/src/core/jsonrpc_tests.rs
index 1aac957c65..bcf13f25cb 100644
--- a/crates/openhuman-core/src/core/jsonrpc_tests.rs
+++ b/crates/openhuman-core/src/core/jsonrpc_tests.rs
@@ -9,7 +9,8 @@ use tokio_util::sync::CancellationToken;
use super::{
default_state, group_first_time_when_bus_ready, invoke_method, is_session_expired_error,
is_unconfirmed_unauthorized_error, learning_first_time_when_bus_ready, params_to_object,
- parse_json_params, type_name, DomainSubscriberPlan,
+ parse_json_params, should_publish_session_expired, translate_local_session_error, type_name,
+ DomainSubscriberPlan,
};
// These are the `http-server`-gated RPC-surface symbols (#5048); the tests that
// name them below carry the same `#[cfg]` so the disabled-build test compile
@@ -902,6 +903,30 @@ fn is_session_expired_error_matches_missing_backend_session_token() {
assert!(is_session_expired_error("NO BACKEND SESSION TOKEN"));
}
+#[test]
+fn local_offline_credential_does_not_publish_backend_session_expiry() {
+ let local = crate::security::credentials::session_support::is_local_session_token(
+ "header.payload.local",
+ );
+ let jwt = crate::security::credentials::session_support::is_local_session_token(
+ "header.payload.signature",
+ );
+ for error in [
+ "composio unavailable: no backend session token. Sign in first (auth_store_session).",
+ "SESSION_EXPIRED: backend rejected session token on GET /teams/me/usage",
+ ] {
+ assert!(!should_publish_session_expired(error, local), "{error}");
+ assert!(should_publish_session_expired(error, jwt), "{error}");
+ let translated = translate_local_session_error(error, local).expect("local fallback");
+ assert!(
+ translated.starts_with(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX),
+ "{translated}"
+ );
+ assert!(!is_session_expired_error(&translated));
+ assert!(translate_local_session_error(error, jwt).is_none());
+ }
+}
+
#[tokio::test(flavor = "current_thread")]
#[cfg(feature = "http-server")]
async fn structured_rpc_error_envelope_passes_through_generic_dispatch() {
diff --git a/crates/openhuman-core/src/core/socketio.rs b/crates/openhuman-core/src/core/socketio.rs
index 2244727402..ff40f588ef 100644
--- a/crates/openhuman-core/src/core/socketio.rs
+++ b/crates/openhuman-core/src/core/socketio.rs
@@ -1155,6 +1155,18 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {
break;
};
if let crate::core::events::DomainEvent::SessionExpired { source, reason } = event {
+ // Other publishers may emit a backend 401 while this core is
+ // using its offline local credential. The auth subscriber
+ // correctly keeps that credential, so the UI must not receive
+ // a contradictory sign-out event from this independent bus
+ // consumer. Real JWT expiry still broadcasts as before.
+ if crate::security::credentials::session_support::current_session_is_local().await {
+ log::info!(
+ "[socketio] suppress auth:session_expired for local offline credential source={}",
+ source
+ );
+ continue;
+ }
log::info!(
"[socketio] broadcast auth:session_expired source={} reason_len={}",
source,
diff --git a/crates/openhuman-core/src/security/credentials/session_support.rs b/crates/openhuman-core/src/security/credentials/session_support.rs
index a0e3fff983..6165f6a46a 100644
--- a/crates/openhuman-core/src/security/credentials/session_support.rs
+++ b/crates/openhuman-core/src/security/credentials/session_support.rs
@@ -61,6 +61,20 @@ pub fn is_local_session_token(token: &str) -> bool {
)
}
+/// Whether the current RPC workspace is authenticated by the offline local
+/// credential. A backend-only route may report a missing session or 401 while
+/// this credential remains valid; those errors must not broadcast sign-out.
+/// A failed lookup leaves the ordinary session-expiry path in place.
+pub async fn current_session_is_local() -> bool {
+ let Ok(config) = crate::config::rpc::load_config_with_timeout().await else {
+ return false;
+ };
+ get_session_token(&config)
+ .ok()
+ .flatten()
+ .is_some_and(|token| is_local_session_token(&token))
+}
+
pub fn parse_fields_value(
input: Option<serde_json::Value>,
) -> Result<std::collections::HashMap<String, String>, String> {