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
fix(credentials): restore identity verification in session responses
Steven Enamakelcd3e3f268a11
diff --git a/crates/openhuman-core/src/security/credentials/identity.rs b/crates/openhuman-core/src/security/credentials/identity.rsnew file mode 100644index 0000000000..c245b1e6ee--- /dev/null+++ b/crates/openhuman-core/src/security/credentials/identity.rs@@ -0,0 +1,83 @@+//! The signed-in user's identity, as the core knows it: the `user` payload the+//! host handed over with `auth.set_credential` (its own `/auth/me` answer),+//! kept in a process-global slot so prompt composition and Sentry scoping can+//! read it synchronously without touching the credential store.+//!+//! Set on `set_credential`, cleared on `clear_credential`, seeded at boot+//! from the stored profile. Only identifying fields are ever handed out —+//! never a token.++use std::sync::{OnceLock, RwLock};++use serde_json::Value;++use crate::agent::prompts::UserIdentity;++static CURRENT_USER: OnceLock<RwLock<Option<Value>>> = OnceLock::new();++fn slot() -> &'static RwLock<Option<Value>> {+ CURRENT_USER.get_or_init(|| RwLock::new(None))+}++/// Record the host-supplied user payload (or clear it with `None`).+pub fn set_current_user(user: Option<Value>) {+ let user = match user {+ Some(Value::Object(map)) if !map.is_empty() => Some(Value::Object(map)),+ _ => None,+ };+ let mut guard = slot().write().unwrap_or_else(|p| p.into_inner());+ *guard = user;+}++/// Forget the current user.+pub fn clear_current_user() {+ set_current_user(None);+}++/// The raw user payload, if one is known.+pub fn current_user() -> Option<Value> {+ slot().read().unwrap_or_else(|p| p.into_inner()).clone()+}++/// Synchronous, network-free peek at the signed-in user, reduced to the+/// identifying fields the prompt layer is allowed to embed (`id`, `name`,+/// `email`). Returns `None` when nobody is signed in or the payload carries+/// none of them (a `pendingBackendValidation` placeholder, say). See #926.+pub fn peek_credential_user_identity() -> Option<UserIdentity> {+ let user = current_user()?;+ identity_from_user(&user)+}++/// [`peek_credential_user_identity`]'s reduction, on an explicit payload.+pub fn identity_from_user(user: &Value) -> Option<UserIdentity> {+ let user = user.as_object()?;+ let pluck = |key: &str| -> Option<String> {+ user.get(key)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ };++ let id = pluck("id")+ .or_else(|| pluck("_id"))+ .or_else(|| pluck("user_id"))+ .or_else(|| pluck("userId"));+ let name = pluck("name")+ .or_else(|| pluck("displayName"))+ .or_else(|| pluck("display_name"))+ .or_else(|| pluck("full_name"))+ .or_else(|| pluck("fullName"));+ let email = pluck("email");++ let identity = UserIdentity { id, name, email };+ if identity.is_empty() {+ None+ } else {+ Some(identity)+ }+}++#[cfg(test)]+#[path = "identity_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/security/credentials/identity_tests.rs b/crates/openhuman-core/src/security/credentials/identity_tests.rsnew file mode 100644index 0000000000..69b6e9afbe--- /dev/null+++ b/crates/openhuman-core/src/security/credentials/identity_tests.rs@@ -0,0 +1,32 @@+use super::*;+use serde_json::json;++#[test]+fn identity_reduces_to_id_name_email() {+ let user = json!({ "_id": "u1", "displayName": "Ada", "email": "[email protected]", "token": "nope" });+ let identity = identity_from_user(&user).unwrap();+ assert_eq!(identity.id.as_deref(), Some("u1"));+ assert_eq!(identity.name.as_deref(), Some("Ada"));+ assert_eq!(identity.email.as_deref(), Some("[email protected]"));+}++#[test]+fn placeholder_payloads_yield_no_identity() {+ assert!(identity_from_user(&json!({ "pendingBackendValidation": true })).is_none());+ assert!(identity_from_user(&json!({ "id": " " })).is_none());+ assert!(identity_from_user(&json!("str")).is_none());+}++#[test]+fn slot_round_trip_ignores_empty_objects() {+ set_current_user(Some(json!({ "id": "slot-user" })));+ assert_eq!(+ peek_credential_user_identity().and_then(|i| i.id).as_deref(),+ Some("slot-user")+ );+ set_current_user(Some(json!({})));+ assert!(current_user().is_none());+ set_current_user(Some(json!({ "id": "again" })));+ clear_current_user();+ assert!(peek_credential_user_identity().is_none());+}diff --git a/crates/openhuman-core/src/security/credentials/responses.rs b/crates/openhuman-core/src/security/credentials/responses.rsindex f1445db033..8eae27a5f5 100644--- a/crates/openhuman-core/src/security/credentials/responses.rs+++ b/crates/openhuman-core/src/security/credentials/responses.rs@@ -11,15 +11,22 @@ pub struct AuthStateResponse {pub profile_id: Option<String>,/// Which credential backs `is_authenticated`: `"session"` for an app/// session JWT, `"api-key"` for a TinyHumans API key (library runtimes,- /// no user identity), absent when signed out.+ /// no user identity), `"local"` for the offline local session, absent+ /// when signed out.#[serde(default, skip_serializing_if = "Option::is_none")]pub credential: Option<String>,+ /// RFC3339 expiry recorded from the session JWT's `exp` at store time.+ /// Absent for API keys, local sessions and `exp`-less tokens.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub expires_at: Option<String>,}/// `AuthStateResponse::credential` value for an app-session JWT.pub const CREDENTIAL_SESSION: &str = "session";/// `AuthStateResponse::credential` value for a TinyHumans API key.pub const CREDENTIAL_API_KEY: &str = "api-key";+/// `AuthStateResponse::credential` value for the offline local session.+pub const CREDENTIAL_LOCAL: &str = "local";#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]diff --git a/crates/openhuman-core/src/security/credentials/session_support.rs b/crates/openhuman-core/src/security/credentials/session_support.rsindex ced36f8ad3..c457a1c98d 100644--- a/crates/openhuman-core/src/security/credentials/session_support.rs+++ b/crates/openhuman-core/src/security/credentials/session_support.rs@@ -132,6 +132,62 @@ fn session_user_value(.and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())}+/// The kinds of backend credential the core can hold. The `as_str` values are+/// the `auth.set_credential` / `auth.clear_credential` / `auth.get_state` wire+/// vocabulary.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CredentialKind {+ /// A TinyHumans session JWT.+ Session,+ /// A TinyHumans API key.+ ApiKey,+ /// The offline local session (`is_local_session_token`).+ Local,+}++impl CredentialKind {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Session => super::responses::CREDENTIAL_SESSION,+ Self::ApiKey => super::responses::CREDENTIAL_API_KEY,+ Self::Local => super::responses::CREDENTIAL_LOCAL,+ }+ }++ pub fn parse(raw: &str) -> Option<Self> {+ match raw.trim() {+ super::responses::CREDENTIAL_SESSION => Some(Self::Session),+ super::responses::CREDENTIAL_API_KEY => Some(Self::ApiKey),+ super::responses::CREDENTIAL_LOCAL => Some(Self::Local),+ _ => None,+ }+ }++ /// Classify a bare token the way the core always has: the local-session+ /// shape is `Local`, anything else is a session JWT. An API key is never+ /// inferred from shape — callers that hold one say so.+ pub fn classify(token: &str) -> Self {+ if is_local_session_token(token) {+ Self::Local+ } else {+ Self::Session+ }+ }+}++/// The subject of a JWT, read from its payload claims without verification.+/// Checked in order: `sub`, `userId`, `user_id`, `_id`, `id`.+pub fn user_id_from_jwt_claims(token: &str) -> Option<String> {+ let claims = crate::api::jwt::decode_jwt_payload(token)?;+ let obj = claims.as_object()?;+ ["sub", "userId", "user_id", "_id", "id"]+ .iter()+ .find_map(|key| obj.get(*key).and_then(serde_json::Value::as_str))+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+}+pub fn build_session_state(config: &Config) -> Result<AuthStateResponse, String> {// The API key wins whenever both are present — same precedence as// `resolve_backend_credential`, which every backend request actually@@ -149,6 +205,7 @@ pub fn build_session_state(config: &Config) -> Result<AuthStateResponse, String>user: None,profile_id: None,credential: Some(super::responses::CREDENTIAL_API_KEY.to_string()),+ expires_at: None,});}let profile = load_app_session_profile(config)?;@@ -383,21 +440,23 @@ pub fn session_state_from_profile(profile: Option<&AuthProfile>) -> AuthStateResuser: None,profile_id: None,credential: None,+ expires_at: None,};};- let is_authenticated = profile- .token- .as_ref()- .map(|token| !token.trim().is_empty())- .unwrap_or(false);+ let token = session_token_from_profile(Some(profile));+ let is_authenticated = token.is_some();+ let credential = token+ .as_deref()+ .map(|token| CredentialKind::classify(token).as_str().to_string());AuthStateResponse {is_authenticated,user_id: profile.metadata.get("user_id").cloned(),user: session_user_value(profile),profile_id: Some(profile.id.clone()),- credential: is_authenticated.then(|| super::responses::CREDENTIAL_SESSION.to_string()),+ credential,+ expires_at: session_expires_at_from_profile(Some(profile)).map(|dt| dt.to_rfc3339()),}}