Skip to content

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

feat(core): add session expiry handling to invoke

Steven Enamakelaf6abb0567e3
diff --git a/crates/openhuman-core/src/core/invoke.rs b/crates/openhuman-core/src/core/invoke.rs
new file mode 100644
index 0000000000..896669ddaa
--- /dev/null
+++ b/crates/openhuman-core/src/core/invoke.rs
@@ -0,0 +1,132 @@
+//! In-process controller dispatch: the one entry point every transport calls.
+//!
+//! The JSON-RPC server in `openhuman-rpc` (HTTP `/rpc` and Socket.IO
+//! `rpc:request`), the CLI, the device tunnel and [`CoreRuntime::invoke`](crate::core::runtime::CoreRuntime::invoke)
+//! all resolve a method through [`invoke_method`]. It validates params against
+//! the controller registry, dispatches, and on a confirmed session expiry
+//! publishes the event that signs the user out.
+
+use serde_json::Value;
+
+use super::session_expiry::{is_session_expired_error, is_unconfirmed_unauthorized_error};
+use crate::core::all;
+use crate::core::types::AppState;
+
+/// Invokes a JSON-RPC method by name.
+///
+/// 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 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
+///
+/// * `state` - The application state.
+/// * `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 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
+ // clears the stored token, flips the scheduler-gate signed-out override
+ // so background workers stand down, and (eventually) pushes a sign-out to
+ // the UI. Generic downstream/provider 401s must stay recoverable errors;
+ // otherwise a scoped integration failure can log the user out.
+ if let Err(ref msg) = result {
+ let sanitized_reason = tinyinference_core::sanitize::sanitize_api_error(msg);
+ if is_session_expired_error(msg) {
+ // 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: {}",
+ method,
+ sanitized_reason
+ );
+ }
+ }
+
+ 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
+ )
+ })
+}
+
+/// Internal method invocation logic.
+///
+/// It first attempts to match the method name against the static controller
+/// registry (schemas). If a schema is found, it validates the input parameters
+/// before execution. If no schema matches, it falls back to the dynamic
+/// [`crate::core::dispatch::dispatch`] system.
+async fn invoke_method_inner(
+ state: AppState,
+ method: &str,
+ params: Value,
+) -> Result<Value, String> {
+ // Phase 1: Check static controller registry.
+ if let Some(schema) = all::schema_for_rpc_method(method) {
+ let params_obj = crate::core::params::params_to_object(params.clone())?;
+ // Validate inputs against the schema before calling the handler.
+ all::validate_params(&schema, &params_obj)?;
+ if let Some(result) = all::try_invoke_registered_rpc(method, params_obj).await {
+ return result;
+ }
+ log::debug!(
+ "[jsonrpc] schema matched without registered handler; falling back method={}",
+ method
+ );
+ }
+
+ // Phase 2: Fall back to dynamic dispatch (internal core methods or legacy paths).
+ crate::core::dispatch::dispatch(state, method, params).await
+}
+
+/// Returns the default application state.
+pub fn default_state() -> AppState {
+ AppState {
+ core_version: env!("CARGO_PKG_VERSION").to_string(),
+ }
+}
+
+#[cfg(test)]
+#[path = "invoke_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/core/invoke_tests.rs b/crates/openhuman-core/src/core/invoke_tests.rs
new file mode 100644
index 0000000000..789a17f993
--- /dev/null
+++ b/crates/openhuman-core/src/core/invoke_tests.rs
@@ -0,0 +1,271 @@
+use serde_json::json;
+
+use super::super::session_expiry::is_session_expired_error;
+use super::{
+ default_state, invoke_method, should_publish_session_expired, translate_local_session_error,
+};
+
+#[tokio::test]
+async fn invoke_health_snapshot_via_registry() {
+ let result = invoke_method(default_state(), "openhuman.health_snapshot", json!({}))
+ .await
+ .expect("health snapshot should succeed");
+ assert!(result.get("result").is_some());
+}
+
+#[tokio::test]
+async fn invoke_encrypt_secret_missing_required_param_fails_validation() {
+ let err = invoke_method(default_state(), "openhuman.encrypt_secret", json!({}))
+ .await
+ .expect_err("missing plaintext should fail");
+ assert!(err.contains("missing required param 'plaintext'"));
+}
+
+#[tokio::test]
+async fn invoke_doctor_models_rejects_unknown_param() {
+ let err = invoke_method(
+ default_state(),
+ "openhuman.doctor_models",
+ json!({ "invalid": true }),
+ )
+ .await
+ .expect_err("unknown param should fail");
+ assert!(err.contains("unknown param 'invalid'"));
+}
+
+// Uses a `flows.*` method as its gated-family vehicle: without the `flows`
+// feature there is no flows controller in the registry and the `.expect()`
+// below would panic. The transport-layer gating it proves is orthogonal to the
+// compile-time gate (#4797).
+#[cfg(feature = "flows")]
+#[tokio::test]
+async fn gated_method_is_unknown_at_transport_even_with_malformed_params() {
+ // #4808 review (CodeRabbit): prove the schema-gate fix at the JSON-RPC
+ // TRANSPORT layer (`invoke_method`), not only via direct dispatch. Under a
+ // harness() ambient context a gated method must return an unknown-method
+ // error for BOTH well-formed and malformed params — never the controller's
+ // param-validation error, which would leak that the hidden method exists.
+ use crate::core::runtime::context::CoreContext;
+ use crate::core::runtime::DomainSet;
+
+ let gated_method = crate::core::all::all_registered_controllers()
+ .into_iter()
+ .find(|c| c.schema.namespace == "flows")
+ .map(|c| c.rpc_method_name())
+ .expect("a flows.* method exists in the full registry");
+
+ for params in [json!({}), json!({ "obviously_not_a_real_param_xyz": true })] {
+ let ctx = CoreContext::for_test(DomainSet::harness(), None, None);
+ let err = CoreContext::scope(
+ ctx,
+ invoke_method(default_state(), &gated_method, params.clone()),
+ )
+ .await
+ .expect_err("gated flows method must error under harness()");
+ assert!(
+ err.contains("unknown method"),
+ "gated `{gated_method}` with params {params} must be unknown-method at transport, got: {err}"
+ );
+ assert!(
+ !err.contains("param"),
+ "gated `{gated_method}` must NOT leak a param-validation error (surface leak), got: {err}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn invoke_config_get_runtime_flags_via_registry() {
+ let result = invoke_method(
+ default_state(),
+ "openhuman.config_get_runtime_flags",
+ json!({}),
+ )
+ .await
+ .expect("runtime flags should succeed");
+ assert!(result.get("result").is_some());
+}
+
+#[tokio::test]
+async fn invoke_auth_store_session_missing_token_fails_validation() {
+ let err = invoke_method(default_state(), "openhuman.auth_store_session", json!({}))
+ .await
+ .expect_err("missing token should fail");
+ assert!(err.contains("missing required param 'token'"));
+}
+
+#[tokio::test]
+async fn invoke_service_status_rejects_unknown_param() {
+ let err = invoke_method(
+ default_state(),
+ "openhuman.service_status",
+ json!({ "x": 1 }),
+ )
+ .await
+ .expect_err("unknown param should fail");
+ assert!(err.contains("unknown param 'x'"));
+}
+
+#[tokio::test]
+async fn invoke_memory_init_accepts_empty_params() {
+ // jwt_token is optional (accepted for backward compat but ignored).
+ // The call may still fail for workspace reasons in test, but must NOT
+ // fail with a missing-param error for jwt_token.
+ let result = invoke_method(default_state(), "openhuman.memory_init", json!({})).await;
+ if let Err(ref e) = result {
+ assert!(
+ !e.contains("missing required param") || !e.contains("jwt_token"),
+ "jwt_token should be optional, got: {e}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn invoke_memory_list_namespaces_rejects_unknown_param() {
+ let err = invoke_method(
+ default_state(),
+ "openhuman.memory_list_namespaces",
+ json!({ "extra": true }),
+ )
+ .await
+ .expect_err("unknown param should fail");
+ assert!(err.contains("extra"));
+}
+
+#[tokio::test]
+async fn invoke_memory_query_namespace_missing_namespace_fails() {
+ let err = invoke_method(
+ default_state(),
+ "openhuman.memory_query_namespace",
+ json!({ "query": "who owns atlas" }),
+ )
+ .await
+ .expect_err("missing namespace should fail");
+ assert!(err.contains("namespace"));
+}
+
+#[tokio::test]
+async fn invoke_memory_recall_memories_rejects_unknown_param() {
+ let err = invoke_method(
+ default_state(),
+ "openhuman.memory_recall_memories",
+ json!({ "namespace": "team", "extra": true }),
+ )
+ .await
+ .expect_err("unknown param should fail");
+ assert!(err.contains("extra"));
+}
+
+#[tokio::test]
+async fn invoke_migrate_openclaw_rejects_unknown_param() {
+ let err = invoke_method(
+ default_state(),
+ "openhuman.migrate_openclaw",
+ json!({ "x": 1 }),
+ )
+ .await
+ .expect_err("unknown param should fail");
+ assert!(err.contains("unknown param 'x'"));
+}
+
+#[tokio::test]
+async fn invoke_migrate_hermes_rejects_unknown_param() {
+ let err = invoke_method(
+ default_state(),
+ "openhuman.migrate_hermes",
+ json!({ "x": 1 }),
+ )
+ .await
+ .expect_err("unknown param should fail");
+ assert!(err.contains("unknown param 'x'"));
+}
+
+#[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]
+async fn invoke_method_rejects_array_params_for_registered_method() {
+ // Registered controllers expect named-argument style (JSON object).
+ // Passing an array must fail with a clear "invalid params" error
+ // instead of silently calling the handler with no args.
+ let err = invoke_method(
+ default_state(),
+ "openhuman.health_snapshot",
+ json!([1, 2, 3]),
+ )
+ .await
+ .expect_err("array params should be rejected");
+ assert!(err.contains("invalid params"));
+ assert!(err.contains("array"));
+}
+
+#[tokio::test]
+async fn invoke_method_rejects_string_params_for_registered_method() {
+ let err = invoke_method(default_state(), "openhuman.health_snapshot", json!("oops"))
+ .await
+ .expect_err("string params should be rejected");
+ assert!(err.contains("invalid params"));
+ assert!(err.contains("string"));
+}
+
+#[tokio::test]
+async fn invoke_method_accepts_null_params_for_registered_method() {
+ // JSON-RPC 2.0 allows omitting params; null must be treated like {}.
+ let result = invoke_method(default_state(), "openhuman.health_snapshot", json!(null)).await;
+ // Call should succeed or fail for domain reasons — but must NOT
+ // fail with the "invalid params" shape error.
+ if let Err(e) = result {
+ assert!(
+ !e.contains("invalid params"),
+ "null should be accepted as empty object, got: {e}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn invoke_method_unknown_method_returns_unknown_error() {
+ let err = invoke_method(default_state(), "openhuman.totally_made_up_xyz", json!({}))
+ .await
+ .expect_err("unknown methods must error");
+ assert!(err.contains("unknown method"));
+}
+
+#[tokio::test]
+async fn invoke_method_core_ping_via_tier1() {
+ // core.* methods aren't in the registry; they route through tier 1.
+ let result = invoke_method(default_state(), "core.ping", json!({}))
+ .await
+ .expect("core.ping should succeed via tier 1");
+ assert_eq!(result, json!({ "ok": true }));
+}
+
+#[tokio::test]
+async fn invoke_method_core_version_via_tier1_reflects_state() {
+ let state = super::AppState {
+ core_version: "0.0.1-abc".into(),
+ };
+ let result = invoke_method(state, "core.version", json!({}))
+ .await
+ .expect("core.version should succeed");
+ assert_eq!(result, json!({ "version": "0.0.1-abc" }));
+}
diff --git a/crates/openhuman-core/src/core/session_expiry.rs b/crates/openhuman-core/src/core/session_expiry.rs
new file mode 100644
index 0000000000..42c983a834
--- /dev/null
+++ b/crates/openhuman-core/src/core/session_expiry.rs
@@ -0,0 +1,85 @@
+//! Which controller errors mean the OpenHuman session has expired.
+//!
+//! [`invoke_method`](super::invoke::invoke_method) publishes `SessionExpired`
+//! when [`is_session_expired_error`] matches, and the JSON-RPC transport in
+//! `openhuman-rpc` uses the same predicate to keep those failures out of
+//! Sentry.
+
+/// Helper to determine if an error message indicates an expired or invalid
+/// OpenHuman backend session.
+///
+/// **Narrower than the previous implementation** (fixed in issue #2286):
+///
+/// The old predicate matched ANY `"401 + unauthorized"` pattern, which caused
+/// downstream provider 401s (Discord bot token failures, BYO-key OpenAI /
+/// Anthropic failures, Composio direct-mode errors) to clear the user's session
+/// and log them out. The fix distinguishes between:
+///
+/// - **OpenHuman backend 401s** (`authed_json` in `crates/openhuman-core/src/api/rest.rs`): formatted
+/// as `"{METHOD} /path failed (401 Unauthorized): {body}"`, e.g.
+/// `"GET /teams failed (401 Unauthorized): {"success":false}"`. These always
+/// start with an HTTP method verb followed by a space and a forward slash.
+/// - **Provider / downstream 401s** (`api_error` in
+/// `crates/openhuman-core/src/inference/provider/ops.rs`): formatted as
+/// `"{ProviderName} API error (401 Unauthorized): {body}"` or
+/// `"Discord API error: ... (401): Unauthorized"`. These start with a
+/// provider name, NOT an HTTP method verb.
+///
+/// **What still triggers session expiry:**
+/// - `"Session expired"` — explicit body text from the OpenHuman backend.
+/// - `"no backend session token"` — pre-flight guard; auth profile is missing.
+/// - `"session jwt required"` — local guard; JWT already cleared by a prior 401.
+/// - `"SESSION_EXPIRED"` — scheduler-gate sentinel (exact case).
+/// - HTTP-method-prefixed 401s (`GET /`, `POST /`, etc.) — backend path format.
+///
+/// **What no longer triggers session expiry (fixed in #2286):**
+/// - Provider-prefixed 401s (`"Discord API error: ..."`, `"OpenAI API error ..."`)
+/// - `"invalid token"` — too broad; also matches Discord / OAuth provider tokens.
+///
+/// Note: for inference-path OpenHuman backend 401s, `api_error` (in
+/// `inference/provider/ops.rs` lines 479–497) ALREADY publishes `SessionExpired`
+/// directly, so there is no regression if this predicate misses them — the
+/// subscriber is idempotent and a harmless double-publish would still be correct.
+pub fn is_session_expired_error(msg: &str) -> bool {
+ // Explicit session-expired markers from the OpenHuman backend / local
+ // guards — delegated to the shared observability classifier so both the
+ // Sentry expected-error pipeline and the JSON-RPC publish boundary stay
+ // in lock-step.
+ if crate::core::observability::is_session_expired_message(msg) {
+ return true;
+ }
+ // OpenHuman backend path 401s via `authed_json`:
+ // format is "{METHOD} /path failed (401 Unauthorized): {body}"
+ // The HTTP-method prefix distinguishes these from provider-prefixed errors.
+ // HEAD and OPTIONS are intentionally excluded — `authed_json` only issues
+ // the five listed verbs (GET/POST/PUT/DELETE/PATCH) for REST JSON endpoints.
+ let lower = msg.to_ascii_lowercase();
+ if (lower.contains("401") && lower.contains("unauthorized"))
+ && (msg.starts_with("GET /")
+ || msg.starts_with("POST /")
+ || msg.starts_with("PUT /")
+ || msg.starts_with("DELETE /")
+ || msg.starts_with("PATCH /"))
+ {
+ return true;
+ }
+ false
+}
+
+/// Detect auth-looking failures that are not specific enough to clear the
+/// OpenHuman session. This is only for diagnostics; it must not feed the
+/// `SessionExpired` publish path.
+///
+/// Matches a generic `401 Unauthorized` OR a bare `"invalid token"` string,
+/// either of which can come from BYO-key providers, Composio, channels, or
+/// other scoped downstream calls. Used exclusively for diagnostic logging
+/// at the `invoke_method` call site so provider auth failures are visible
+/// in the logs without being misclassified as session expiry.
+pub fn is_unconfirmed_unauthorized_error(msg: &str) -> bool {
+ let lower = msg.to_ascii_lowercase();
+ (lower.contains("401") && lower.contains("unauthorized")) || lower.contains("invalid token")
+}
+
+#[cfg(test)]
+#[path = "session_expiry_tests.rs"]
+mod tests;