Skip to content

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

fix(credentials): restore session query and validation ops

Steven Enamakela758290d247e
diff --git a/crates/openhuman-core/src/security/credentials/mod.rs b/crates/openhuman-core/src/security/credentials/mod.rs
index b60a9998dd..0a21cd15f8 100644
--- a/crates/openhuman-core/src/security/credentials/mod.rs
+++ b/crates/openhuman-core/src/security/credentials/mod.rs
@@ -6,6 +6,7 @@ pub mod cli;
mod core;
pub mod credential_ref;
pub mod http_creds;
+pub mod identity;
pub mod ops;
pub mod profiles;
pub mod responses;
diff --git a/crates/openhuman-core/src/security/credentials/ops.rs b/crates/openhuman-core/src/security/credentials/ops.rs
index 8f1bbd3dd5..3d2ccb4dcd 100644
--- a/crates/openhuman-core/src/security/credentials/ops.rs
+++ b/crates/openhuman-core/src/security/credentials/ops.rs
@@ -1,19 +1,28 @@
//! JSON-RPC / CLI controller surface for credentials and app session auth.
mod composio;
-mod login_services;
+mod credential;
+mod gated_services;
mod login_tokens;
mod oauth;
mod provider_credentials;
+mod secrets;
mod session_query;
-mod session_store;
-mod session_validation;
+mod user_scope;
pub use composio::{
clear_composio_api_key, get_composio_api_key, rpc_store_composio_api_key,
store_composio_api_key, COMPOSIO_DIRECT_PROVIDER,
};
-pub use login_services::{start_login_gated_services, stop_login_gated_services};
+pub use credential::{
+ clear_credential, clear_session, set_credential, store_session, SetCredentialRequest,
+ PENDING_BACKEND_VALIDATION_FIELD,
+};
+pub(crate) use credential::CREDENTIAL_MUTATION_LOCK;
+pub use gated_services::{
+ start_credential_gated_services, start_login_gated_services,
+ stop_credential_gated_services, stop_login_gated_services,
+};
pub use login_tokens::{auth_create_channel_link_token, consume_login_token};
pub use oauth::{
oauth_connect, oauth_fetch_client_key, oauth_fetch_integration_tokens, oauth_list_integrations,
@@ -23,22 +32,11 @@ pub use provider_credentials::{
list_provider_credentials, list_provider_credentials_by_prefix, remove_provider_credentials,
store_provider_credentials,
};
-pub use session_query::{
- auth_clear_api_key, auth_get_me, auth_get_session_token_json, auth_get_state,
- auth_store_api_key, clear_session,
-};
-pub use session_store::{
- decrypt_secret, encrypt_secret, store_session, store_session_with_deferred_validation,
-};
+pub use secrets::{decrypt_secret, encrypt_secret};
+pub use session_query::{auth_get_me, auth_get_session_token_json, auth_get_state};
#[cfg(test)]
-pub(crate) use session_store::secret_store_for_config;
-#[cfg(test)]
-pub(crate) use session_validation::{
- auth_me_store_failure_is_transient, auth_me_store_validation_budget,
- normalize_local_session_user, sanitize_stored_session_user, AUTH_ME_STORE_VALIDATION_BUDGET,
- AUTH_ME_STORE_VALIDATION_BUDGET_ENV,
-};
+pub(crate) use secrets::secret_store_for_config;
#[cfg(test)]
#[path = "ops_tests.rs"]
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index b6f3c17b7f..5f1bdf1d5f 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -18,7 +18,7 @@ use crate::rpc::RpcOutcome;
use crate::security::credentials::responses::AuthStateResponse;
use crate::security::credentials::session_support::{
build_session_state, load_app_session_profile, local_session_user_id, session_token_from_profile,
- user_id_from_jwt_claims, CredentialKind, LOCAL_SESSION_USER_ID, SESSION_EXPIRES_AT_META,
+ user_id_from_jwt_claims, CredentialKind, SESSION_EXPIRES_AT_META,
};
use crate::security::credentials::{
api_key, identity, sentry_scope, AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
@@ -124,7 +124,6 @@ fn resolve(request: SetCredentialRequest) -> Result<Resolved, String> {
let local_id = local_session_user_id();
let user = user.ok_or_else(|| "local session requires a user payload".to_string())?;
let user = normalize_local_user(user, &local_id);
- let _ = LOCAL_SESSION_USER_ID;
Ok(Resolved {
kind,
token,
diff --git a/crates/openhuman-core/src/security/credentials/ops/session_query.rs b/crates/openhuman-core/src/security/credentials/ops/session_query.rs
index 0255bd6a1d..2510b8502b 100644
--- a/crates/openhuman-core/src/security/credentials/ops/session_query.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/session_query.rs
@@ -1,100 +1,13 @@
-//! Session teardown (`clear_session`) and read-only session state lookups.
+//! Read-only session state lookups.
use serde_json::json;
use crate::api::config::effective_backend_api_url;
use crate::api::jwt::get_session_token;
use crate::api::rest::BackendOAuthClient;
-use crate::config::{default_root_openhuman_dir, Config};
+use crate::config::Config;
use crate::rpc::RpcOutcome;
use crate::security::credentials::session_support::build_session_state;
-use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};
-
-use super::login_services::stop_login_gated_services;
-
-pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Value>, String> {
- let mut logs = Vec::new();
- let removed = {
- let _session_mutation_lock = crate::desktop::app_state::CURRENT_USER_SESSION_MUTATION_LOCK
- .lock()
- .await;
- // Flip the scheduler-gate override first so any background worker that
- // is mid-iteration (or wakes up while we tear down) stalls at its next
- // `wait_for_capacity()` call instead of firing requests at a backend
- // we're about to invalidate. Idempotent.
- crate::cron::scheduler_gate::set_signed_out(true);
-
- // Invalidate before removing the profile so a pending revalidation cannot
- // recreate it after logout has finished the removal.
- crate::desktop::app_state::forget_current_user_caches();
-
- let auth = AuthService::from_config(config);
- auth.remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)
- .map_err(|e| e.to_string())?
- };
-
- // The core process stays alive on logout. Tear down its authenticated
- // Socket.IO transport and the user-pinned workflow bridge so neither can
- // keep serving the signed-out account until a later reconnect.
- if let Some(manager) = crate::platform::socket::global_socket_manager() {
- if let Err(error) = manager.disconnect().await {
- tracing::warn!(%error, "failed to disconnect backend socket on logout");
- }
- }
- crate::platform::socket::medulla::workflows::clear_workflow_bridge();
-
- // Clear the active user marker so subsequent config loads fall back to the
- // default (unauthenticated) openhuman directory.
- if let Ok(root_dir) = default_root_openhuman_dir() {
- if let Err(e) = crate::config::clear_active_user(&root_dir) {
- tracing::warn!(error = %e, "failed to clear active_user.toml on logout");
- }
- }
-
- // Stop all login-gated services (voice and local AI) so
- // they don't run as orphan processes after logout, consuming RAM/CPU with
- // no user context to operate against.
- stop_login_gated_services(config).await;
-
- // The process stays alive after desktop/TUI logout, so every process-global
- // store must follow the now-active pre-login workspace. Without this, a
- // signed-out caller can keep reading the previous account's context until
- // the process restarts.
- match crate::config::load_config_with_timeout().await {
- Ok(signed_out_config) => {
- let workspace = signed_out_config.workspace_dir.clone();
- // No `memory::global::init` twin here either — see the login site.
- // The context rebind below carries the signed-out workspace and its
- // `[subsystems.memory]` block, and the memory binding is keyed on
- // exactly that pair, so it follows without a second call.
- if let Err(error) = crate::core::runtime::context::CoreContext::rebind_default_workspace(
- &workspace,
- signed_out_config.subsystems.memory.clone(),
- ) {
- tracing::warn!(%error, "failed to rebind core context after logout");
- }
- crate::memory::conversations::register_conversation_persistence_subscriber(
- workspace.clone(),
- );
- logs.push(format!(
- "process globals rebound to signed-out workspace {}",
- workspace.display()
- ));
- }
- Err(error) => {
- tracing::warn!(%error, "failed to resolve signed-out workspace after logout");
- logs.push(format!("signed-out workspace rebind warning: {error}"));
- }
- }
-
- // Drop the Sentry scope user so events surfaced during/after teardown
- // (and before the next login) are no longer attributed to the
- // signed-out account — issue #3135.
- crate::security::credentials::sentry_scope::clear();
-
- logs.push("session cleared".to_string());
- Ok(RpcOutcome::new(json!({ "removed": removed }), logs))
-}
pub async fn auth_get_state(
config: &Config,
@@ -103,32 +16,6 @@ pub async fn auth_get_state(
Ok(RpcOutcome::single_log(state, "session state fetched"))
}
-/// Store the TinyHumans API key as the runtime's backend credential. Library
-/// runtimes install it before boot through `api_key::store_api_key_in`; this
-/// RPC is the same operation for a running core.
-pub async fn auth_store_api_key(
- config: &Config,
- key: &str,
-) -> Result<RpcOutcome<super::super::responses::AuthStateResponse>, String> {
- super::super::api_key::store_api_key(config, key).map_err(|e| e.to_string())?;
- crate::cron::scheduler_gate::set_signed_out(false);
- let state = build_session_state(config)?;
- Ok(RpcOutcome::single_log(state, "api key stored"))
-}
-
-/// Remove the stored TinyHumans API key. The scheduler gate follows whatever
-/// credential remains.
-pub async fn auth_clear_api_key(config: &Config) -> Result<RpcOutcome<serde_json::Value>, String> {
- let removed = super::super::api_key::clear_api_key(config).map_err(|e| e.to_string())?;
- if !super::super::session_support::has_backend_credential(config) {
- crate::cron::scheduler_gate::set_signed_out(true);
- }
- Ok(RpcOutcome::single_log(
- json!({ "removed": removed }),
- "api key cleared",
- ))
-}
-
pub async fn auth_get_session_token_json(
config: &Config,
) -> Result<RpcOutcome<serde_json::Value>, String> {
diff --git a/crates/openhuman-core/src/security/credentials/ops/session_store.rs b/crates/openhuman-core/src/security/credentials/ops/session_store.rs
deleted file mode 100644
index fe90152ad5..0000000000
--- a/crates/openhuman-core/src/security/credentials/ops/session_store.rs
+++ /dev/null
@@ -1,439 +0,0 @@
-//! Persisting the app-session auth profile: secret encryption helpers and
-//! the `store_session` / `store_session_with_deferred_validation` entry
-//! points and their shared worker.
-
-use serde_json::Value;
-
-use crate::api::config::effective_backend_api_url;
-use crate::api::jwt::decode_jwt_exp;
-use crate::api::rest::{user_id_from_profile_payload, BackendOAuthClient};
-use crate::config::Config;
-use crate::config::{
- default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, user_openhuman_dir,
- write_active_user_id,
-};
-use crate::memory::conversations;
-use crate::rpc::RpcOutcome;
-use crate::security::credentials::session_support::{
- is_local_session_token, local_session_user_id, summarize_auth_profile, LOCAL_SESSION_USER_ID,
-};
-use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};
-use crate::security::keyring::SecretStore;
-
-use super::login_services::{is_embedder_host, start_login_gated_services};
-use super::session_validation::{
- auth_me_store_failure_is_transient, fallback_session_user_for_deferred_validation,
- fetch_current_user_for_session_store, jwt_exp_live_at, normalize_local_session_user,
- sanitize_stored_session_user,
-};
-
-pub(crate) fn secret_store_for_config(config: &Config) -> SecretStore {
- let data_dir = config
- .config_path
- .parent()
- .map_or_else(|| std::path::PathBuf::from("."), std::path::PathBuf::from);
- SecretStore::new(&data_dir, true)
-}
-
-pub async fn encrypt_secret(
- config: &Config,
- plaintext: &str,
-) -> Result<RpcOutcome<String>, String> {
- let store = secret_store_for_config(config);
- let ciphertext = store.encrypt(plaintext).map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(ciphertext, "secret encrypted"))
-}
-
-pub async fn decrypt_secret(
- config: &Config,
- ciphertext: &str,
-) -> Result<RpcOutcome<String>, String> {
- let store = secret_store_for_config(config);
- let plaintext = store.decrypt(ciphertext).map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(plaintext, "secret decrypted"))
-}
-
-pub async fn store_session(
- config: &Config,
- token: &str,
- user_id: Option<String>,
- user: Option<serde_json::Value>,
-) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {
- store_session_inner(config, token, user_id, user, false).await
-}
-
-/// Store a session from a callback flow that already exchanged a backend
-/// login token. Generic callers should use `store_session`, which requires
-/// immediate `/auth/me` proof before persisting remote JWTs.
-pub async fn store_session_with_deferred_validation(
- config: &Config,
- token: &str,
- user_id: Option<String>,
- user: Option<serde_json::Value>,
-) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {
- store_session_inner(config, token, user_id, user, true).await
-}
-
-async fn store_session_inner(
- config: &Config,
- token: &str,
- user_id: Option<String>,
- user: Option<serde_json::Value>,
- allow_pending_backend_validation: bool,
-) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {
- let trimmed_token = token.trim();
- if trimmed_token.is_empty() {
- return Err("token is required".to_string());
- }
-
- let api_url = effective_backend_api_url(&config.api_url);
- let local_session = is_local_session_token(trimmed_token);
- let local_user_id = local_session.then(local_session_user_id);
- let mut session_validation_logs = Vec::new();
- let settings = if local_session {
- sanitize_stored_session_user(user.clone())
- .map(|value| {
- normalize_local_session_user(
- value,
- local_user_id.as_deref().unwrap_or(LOCAL_SESSION_USER_ID),
- )
- })
- .ok_or_else(|| "local session requires a user payload".to_string())?
- } else {
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- match fetch_current_user_for_session_store(&client, trimmed_token).await {
- Ok(fetched_user) => {
- session_validation_logs.push(format!(
- "session JWT verified via GET /auth/me on {}",
- api_url.trim_end_matches('/')
- ));
- fetched_user
- }
- Err(reason) => {
- // This is the store-time validation gate: if it fails the profile
- // is NEVER persisted, so the user bounces straight back to the
- // signin page after a "successful" OAuth. Timeouts/gateway 5xx are
- // otherwise dropped by the Sentry transient classifier, so log an
- // explicit, grep-friendly WARN to the app log regardless.
- if !auth_me_store_failure_is_transient(&reason) {
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- "[credentials][auth-store] GET /auth/me validation FAILED on {} — session NOT persisted; user will bounce to signin: {reason}",
- api_url.trim_end_matches('/')
- );
- return Err(format!(
- "Session validation failed (GET /auth/me): {reason}"
- ));
- }
-
- if !allow_pending_backend_validation {
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- "[credentials][auth-store] GET /auth/me transient validation failed on {} — session NOT persisted; backend proof required before storing remote JWT: {reason}",
- api_url.trim_end_matches('/')
- );
- return Err(format!(
- "Session validation failed (GET /auth/me): {reason}"
- ));
- }
-
- let Some(exp) = jwt_exp_live_at(trimmed_token, chrono::Utc::now()) else {
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- "[credentials][auth-store] GET /auth/me transient validation failed on {} but JWT has no live local exp — session NOT persisted: {reason}",
- api_url.trim_end_matches('/')
- );
- return Err(format!(
- "Session validation failed (GET /auth/me): {reason}"
- ));
- };
-
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- exp = %exp,
- "[credentials][auth-store] GET /auth/me transient validation failed on {} — persisting caller-authorized pending session for backend revalidation: {reason}",
- api_url.trim_end_matches('/')
- );
- session_validation_logs.push(format!(
- "session JWT accepted with deferred GET /auth/me validation on {} after transient failure",
- api_url.trim_end_matches('/')
- ));
- fallback_session_user_for_deferred_validation()
- }
- }
- };
-
- let mut metadata = std::collections::HashMap::new();
- if let Some(uid) = if local_session {
- local_user_id.clone()
- } else {
- user_id
- .and_then(|v| {
- let t = v.trim().to_string();
- (!t.is_empty()).then_some(t)
- })
- .or_else(|| user_id_from_profile_payload(&settings))
- } {
- metadata.insert("user_id".to_string(), uid);
- }
- let pending_backend_validation = settings
- .as_object()
- .and_then(|map| map.get("pendingBackendValidation"))
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let user_for_store = if local_session || pending_backend_validation {
- settings.clone()
- } else {
- sanitize_stored_session_user(user).unwrap_or(settings)
- };
- metadata.insert("user_json".to_string(), user_for_store.to_string());
-
- // Record the JWT `exp` so `require_live_session_token` can reject an expired
- // token locally instead of firing a doomed backend 401 (#3297 RCA — the
- // TAURI-RUST-8WY/8WZ flood). Local offline sessions aren't JWTs and carry no
- // `exp`; `decode_jwt_exp` returns None for them and the key is simply omitted
- // (presence-only check + the `flatten_authed_error` 401 net still apply).
- if !local_session {
- match decode_jwt_exp(trimmed_token) {
- Some(exp) => {
- metadata.insert(
- crate::security::credentials::session_support::SESSION_EXPIRES_AT_META
- .to_string(),
- exp.to_rfc3339(),
- );
- tracing::info!(
- domain = "credentials",
- operation = "store_session",
- "[credentials] recorded app-session expiry exp={exp} for local precheck"
- );
- }
- None => tracing::debug!(
- domain = "credentials",
- operation = "store_session",
- "[credentials] app-session token has no decodable `exp`; local expiry precheck disabled (falls back to 401 net)"
- ),
- }
- }
-
- // Determine user_id so we can scope the openhuman directory to this user.
- let resolved_user_id = metadata.get("user_id").cloned();
- if pending_backend_validation && resolved_user_id.is_none() && !is_embedder_host() {
- if let Ok(root_dir) = default_root_openhuman_dir() {
- if let Some(active_user_id) = read_active_user_id(&root_dir) {
- let active_user_dir = user_openhuman_dir(&root_dir, &active_user_id);
- if config.config_path.parent() == Some(active_user_dir.as_path()) {
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- active_user_id = %active_user_id,
- "[credentials][auth-store] unresolved pending session would replace active user's app-session; session NOT persisted"
- );
- return Err(
- "Session validation failed (GET /auth/me): backend user id required before replacing the active session"
- .to_string(),
- );
- }
- }
- }
- }
-
- // If we know the user_id, activate the user-scoped directory BEFORE storing
- // the auth profile so that credentials land in the correct place.
- let mut logs = if local_session {
- vec!["local session accepted without backend validation".to_string()]
- } else {
- session_validation_logs
- };
-
- // An embedder host (the harness) keeps session state under its own
- // `config_path` scope and must never touch the operator's global
- // `~/.openhuman/active_user.toml` or `users/` tree. Writing it would change
- // which user the operator's real install believes is active purely by
- // virtue of running a library call — the exact global side effect an
- // ephemeral harness exists to avoid. The scoped auth profile is still
- // stored below; only the global activation is skipped.
- let operator_user_activation = !is_embedder_host();
-
- if let Some(ref uid) = resolved_user_id
- .as_ref()
- .filter(|_| operator_user_activation)
- {
- if let Ok(root_dir) = default_root_openhuman_dir() {
- // Snapshot before we overwrite `active_user.toml` so we can tell
- // first activation from signed-out vs an in-place account switch.
- let previous_active = read_active_user_id(&root_dir);
- let user_dir = user_openhuman_dir(&root_dir, uid);
- if let Err(e) = std::fs::create_dir_all(&user_dir) {
- tracing::warn!(
- user_id = %uid,
- error = %e,
- "failed to create user directory"
- );
- } else if let Err(e) = write_active_user_id(&root_dir, uid) {
- tracing::warn!(
- user_id = %uid,
- error = %e,
- "failed to write active_user.toml"
- );
- } else {
- logs.push(format!("user directory activated for {uid}"));
- tracing::info!(
- user_id = %uid,
- user_dir = %user_dir.display(),
- "User-scoped directory activated"
- );
- // Onboarding and other pre-auth flows write threads under the
- // `users/local/workspace` tree. After the first successful login
- // there was no previous `active_user.toml`, wipe that anonymous
- // conversation store so a fresh account never inherits demo or
- // scratch threads from the pre-login bucket (#1157).
- //
- // This shares `memory::conversations`' process-wide mutex with
- // `list_threads` / `purge_threads` on any workspace, so purge and
- // concurrent thread RPC in this process cannot interleave.
- if previous_active.is_none() {
- let pre_ws = pre_login_user_dir(&root_dir).join("workspace");
- let pre_ws_log = pre_ws.display().to_string();
- match conversations::purge_threads(pre_ws) {
- Ok(stats) => {
- tracing::info!(
- pre_login_workspace = %pre_ws_log,
- threads = stats.thread_count,
- messages = stats.message_count,
- "[credentials] purged pre-login conversation threads after first session activation"
- );
- logs.push(format!(
- "purged pre-login conversation history (threads={}, messages={})",
- stats.thread_count, stats.message_count
- ));
- }
- Err(e) => {
- tracing::debug!(
- error = %e,
- pre_login_workspace = %pre_ws_log,
- "[credentials] pre-login conversation purge skipped (non-fatal)"
- );
- }
- }
- }
- }
- }
- }
-
- // Reload config so it picks up the newly activated user directory.
- // This ensures auth-profiles.json, encryption key, etc. are written
- // to the user-scoped location.
- let effective_config = if resolved_user_id.is_some() {
- match crate::config::load_config_with_timeout().await {
- Ok(c) => c,
- Err(_) => config.clone(),
- }
- } else {
- config.clone()
- };
-
- if let Err(error) = crate::cron::seed::prune_retired_jobs(&effective_config) {
- tracing::warn!(
- error = %error,
- "[credentials] failed to prune retired cron jobs after user workspace activation"
- );
- }
-
- if local_session {
- match crate::config::ops::set_onboarding_completed(false).await {
- Ok(_) => logs.push("onboarding left incomplete for local session setup".to_string()),
- Err(error) => logs.push(format!(
- "onboarding setup warning for local session: {error}"
- )),
- }
- }
-
- let auth = AuthService::from_config(&effective_config);
- let profile = auth
- .store_provider_token(
- APP_SESSION_PROVIDER,
- DEFAULT_AUTH_PROFILE_NAME,
- trimmed_token,
- metadata,
- true,
- )
- .map_err(|e| e.to_string())?;
-
- logs.push("session stored".to_string());
-
- // ── No explicit memory re-point here any more (#5560) ──────────────────
- //
- // This site used to call `tinymemory_core::global::init(...)` before the
- // context rebind below. That was load-bearing for the *engine singleton*: a
- // single process-global slot that keeps writing into the pre-login
- // workspace until something re-points it, which is why it needed its own
- // call at every login / logout / revalidation site.
- //
- // `memory::binding` is a workspace-keyed cache, not a slot, and
- // `CoreContext::memory_binding`'s own docs already state the consequence:
- // "there is **no** explicit 'rebind the memory driver' call at the login /
- // logout / revalidation sites the way `memory::global::init` needs one: the
- // accessor keys on the workspace dir and the subsystem config, both of
- // which those sites already re-point." The `rebind_default_workspace` call
- // immediately below re-points both, so memory follows it by construction.
- //
- // The binding is resolved lazily on the next memory call rather than warmed
- // here. Warming it would mean naming `binding::for_workspace` at a site
- // that never touches memory content, which the memory-guard bypass ratchet
- // is right to treat as reach-through.
- match crate::core::runtime::context::CoreContext::rebind_default_workspace(
- &effective_config.workspace_dir,
- effective_config.subsystems.memory.clone(),
- ) {
- Ok(_) => logs.push(format!(
- "core context bound to workspace {}",
- effective_config.workspace_dir.display()
- )),
- Err(e) => {
- tracing::warn!(error = %e, "[credentials] failed to rebind core context after login");
- logs.push(format!("core context bind warning: {e}"));
- }
- }
- // No people-store rebind here any more: people is served by the bound
- // memory driver, and `rebind_default_workspace` above already moved that
- // binding to the per-user workspace. Seeding a host-side global as well
- // opened the engine's database a second time in this process (#4378 fixed
- // the workspace it pointed at; the module port removes the second reader).
- crate::memory::conversations::register_conversation_persistence_subscriber(
- effective_config.workspace_dir.clone(),
- );
- logs.push("conversation persistence bound to active workspace".to_string());
-
- // Start all login-gated services (voice and local AI).
- // Uses the effective config so services see the user-scoped workspace
- // directory.
- start_login_gated_services(&effective_config).await;
- logs.push("login-gated services started".to_string());
-
- // Clear the scheduler-gate signed-out override now that a fresh JWT is
- // in place. Workers that were sleeping in the paused poll loop will
- // pick this up at their next iteration and resume LLM-bound work.
- crate::cron::scheduler_gate::set_signed_out(false);
- tracing::debug!(
- domain = "credentials",
- operation = "store_session",
- "[credentials][auth-store] scheduler gate cleared; ensuring re-embed backfill after login"
- );
- crate::memory::ops::maintenance::reembed_best_effort(&effective_config, "session stored").await;
- logs.push("memory re-embed backfill checked after login".to_string());
-
- // Bind the Sentry scope to this user so background events that fire
- // before the frontend's `app_state_snapshot` warms the user cache still
- // carry `user.id` — issue #3135. The `before_send` filter is now a
- // fallback for legacy cache-warming paths; setting scope here is the
- // primary source.
- if let Some(ref uid) = resolved_user_id {
- crate::security::credentials::sentry_scope::bind(uid);
- }
-
- Ok(RpcOutcome::new(summarize_auth_profile(&profile), logs))
-}
diff --git a/crates/openhuman-core/src/security/credentials/ops/session_validation.rs b/crates/openhuman-core/src/security/credentials/ops/session_validation.rs
deleted file mode 100644
index a70893e8b2..0000000000
--- a/crates/openhuman-core/src/security/credentials/ops/session_validation.rs
+++ /dev/null
@@ -1,166 +0,0 @@
-//! Store-time `GET /auth/me` session validation: transient-failure
-//! classification, the retry/timeout budget, and the small payload helpers
-//! `store_session_inner` uses while resolving what to persist.
-
-use serde_json::{json, Value};
-use std::time::Duration;
-
-use crate::api::jwt::decode_jwt_exp;
-use crate::api::rest::BackendOAuthClient;
-
-const AUTH_ME_STORE_RETRY_DELAY: Duration = Duration::from_millis(150);
-const AUTH_ME_STORE_TRANSIENT_STATUSES: &[u16] = &[408, 429, 500, 502, 503, 504, 520];
-
-/// Wall-clock budget for the store-time `GET /auth/me` validation (issue #5166).
-///
-/// The shared backend client allows a 120s request timeout + 15s connect timeout
-/// (`api::rest`), but the desktop sign-in RPC that drives `auth_store_session`
-/// gives up far sooner — `AUTH_STORE_TIMEOUT_MS` (25s) × `AUTH_STORE_RETRIES` in
-/// `desktopDeepLinkListener.ts`. If the backend is reachable but slow, that 120s
-/// ceiling lets `/auth/me` hang past the frontend's patience: the RPC times out
-/// and bounces a genuinely-authenticated user back to sign-in *before* the
-/// deferred-validation fallback in `store_session_inner` ever gets a chance to
-/// fire (the exact `auth_me_timeout` bounce in Sentry `TAURI-REACT-1V`).
-///
-/// Capping store-time validation well under the frontend budget makes a slow
-/// backend fail *fast* into the caller-authorized pending-session path (for a
-/// live-`exp` JWT), so the user lands in the app with deferred revalidation
-/// instead of being bounced. Overridable via `OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS`
-/// for ops tuning and tests.
-pub(crate) const AUTH_ME_STORE_VALIDATION_BUDGET: Duration = Duration::from_secs(12);
-pub(crate) const AUTH_ME_STORE_VALIDATION_BUDGET_ENV: &str = "OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS";
-
-/// Store-time `GET /auth/me` budget resolver. Reads the
-/// `OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS` override (positive integer milliseconds),
-/// otherwise the `AUTH_ME_STORE_VALIDATION_BUDGET` default.
-pub(crate) fn auth_me_store_validation_budget() -> Duration {
- std::env::var(AUTH_ME_STORE_VALIDATION_BUDGET_ENV)
- .ok()
- .and_then(|raw| raw.trim().parse::<u64>().ok())
- .filter(|ms| *ms > 0)
- .map(Duration::from_millis)
- .unwrap_or(AUTH_ME_STORE_VALIDATION_BUDGET)
-}
-
-/// Validate the freshly minted session token against `GET /auth/me`, bounded by
-/// `auth_me_store_validation_budget()`. On budget exhaustion returns a
-/// transient-classified timeout error so `store_session_inner` routes a
-/// live-`exp` JWT into the deferred-validation fallback rather than hanging until
-/// the desktop sign-in RPC times out and bounces the user (issue #5166).
-pub(super) async fn fetch_current_user_for_session_store(
- client: &BackendOAuthClient,
- token: &str,
-) -> Result<Value, String> {
- let budget = auth_me_store_validation_budget();
- match tokio::time::timeout(
- budget,
- fetch_current_user_for_session_store_inner(client, token),
- )
- .await
- {
- Ok(result) => result,
- Err(_elapsed) => {
- // Message must contain a `TRANSIENT_TRANSPORT_PHRASES` phrase
- // ("timeout") so `auth_me_store_failure_is_transient` buckets it as
- // transient and the deferred-validation path can take over.
- let reason = format!(
- "GET /auth/me validation timeout after {}ms (store-time budget exceeded)",
- budget.as_millis()
- );
- tracing::warn!(
- domain = "credentials",
- operation = "fetch_current_user_for_session_store",
- budget_ms = budget.as_millis() as u64,
- "[credentials][auth-store] {reason}"
- );
- Err(reason)
- }
- }
-}
-
-async fn fetch_current_user_for_session_store_inner(
- client: &BackendOAuthClient,
- token: &str,
-) -> Result<Value, String> {
- match client.fetch_current_user(token).await {
- Ok(user) => Ok(user),
- Err(first) => {
- let first_reason = format!("{first:#}");
- if !auth_me_store_failure_is_transient(&first_reason) {
- return Err(first_reason);
- }
-
- tokio::time::sleep(AUTH_ME_STORE_RETRY_DELAY).await;
- tracing::debug!(
- domain = "credentials",
- operation = "fetch_current_user_for_session_store",
- reason = %first_reason,
- "[credentials][auth-store] retrying GET /auth/me after transient failure"
- );
- client
- .fetch_current_user(token)
- .await
- .map_err(|second| format!("{second:#}"))
- }
- }
-}
-
-pub(crate) fn auth_me_store_failure_is_transient(reason: &str) -> bool {
- if let Some(status) = auth_me_failure_status(reason) {
- return AUTH_ME_STORE_TRANSIENT_STATUSES.contains(&status);
- }
-
- crate::core::observability::contains_transient_transport_phrase(reason)
-}
-
-fn auth_me_failure_status(reason: &str) -> Option<u16> {
- let lower = reason.to_ascii_lowercase();
- (100..600).find(|status| {
- let status = status.to_string();
- lower.contains(&format!("({status}"))
- || lower.contains(&format!("http {status}"))
- || lower.contains(&format!("status {status}"))
- || lower.contains(&format!("status code {status}"))
- })
-}
-
-pub(super) fn jwt_exp_live_at(
- token: &str,
- now: chrono::DateTime<chrono::Utc>,
-) -> Option<chrono::DateTime<chrono::Utc>> {
- let exp = decode_jwt_exp(token)?;
- (exp > now).then_some(exp)
-}
-
-pub(super) fn fallback_session_user_for_deferred_validation() -> Value {
- json!({ "pendingBackendValidation": true })
-}
-
-pub(crate) fn sanitize_stored_session_user(
- user: Option<serde_json::Value>,
-) -> Option<serde_json::Value> {
- match user {
- Some(serde_json::Value::Object(map)) if map.is_empty() => None,
- Some(serde_json::Value::Null) => None,
- other => other,
- }
-}
-
-pub(crate) fn normalize_local_session_user(
- user: serde_json::Value,
- local_user_id: &str,
-) -> serde_json::Value {
- let mut map = match user {
- serde_json::Value::Object(map) => map,
- other => return other,
- };
- map.insert(
- "id".to_string(),
- serde_json::Value::String(local_user_id.to_string()),
- );
- map.insert(
- "_id".to_string(),
- serde_json::Value::String(local_user_id.to_string()),
- );
- serde_json::Value::Object(map)
-}