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
chore(security): reformat credential module code
Steven Enamakeld37851498fc1
diff --git a/crates/openhuman-core/src/security/credentials/identity_tests.rs b/crates/openhuman-core/src/security/credentials/identity_tests.rsindex 69b6e9afbe..73efe1f866 100644--- a/crates/openhuman-core/src/security/credentials/identity_tests.rs+++ b/crates/openhuman-core/src/security/credentials/identity_tests.rs@@ -21,7 +21,9 @@ fn placeholder_payloads_yield_no_identity() {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(),+ peek_credential_user_identity()+ .and_then(|i| i.id)+ .as_deref(),Some("slot-user"));set_current_user(Some(json!({})));diff --git a/crates/openhuman-core/src/security/credentials/ops.rs b/crates/openhuman-core/src/security/credentials/ops.rsindex ea1dba92cc..978675641f 100644--- a/crates/openhuman-core/src/security/credentials/ops.rs+++ b/crates/openhuman-core/src/security/credentials/ops.rs@@ -11,20 +11,20 @@ mod secrets;mod session_query;mod user_scope;+pub use boot_env::{+ seed_api_key_from_env, seed_session_from_env, BACKEND_API_KEY_ENV, BACKEND_SESSION_TOKEN_ENV,+};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 boot_env::{- seed_api_key_from_env, seed_session_from_env, BACKEND_API_KEY_ENV, BACKEND_SESSION_TOKEN_ENV,-};pub use credential::{clear_credential, clear_session, set_credential, store_session, SetCredentialRequest,PENDING_BACKEND_VALIDATION_FIELD,};pub use gated_services::{- start_credential_gated_services, start_login_gated_services,- stop_credential_gated_services, stop_login_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::{diff --git a/crates/openhuman-core/src/security/credentials/ops/boot_env.rs b/crates/openhuman-core/src/security/credentials/ops/boot_env.rsindex bbeba44234..78163851cf 100644--- a/crates/openhuman-core/src/security/credentials/ops/boot_env.rs+++ b/crates/openhuman-core/src/security/credentials/ops/boot_env.rs@@ -13,7 +13,7 @@use crate::config::Config;use crate::security::credentials::api_key;-use crate::security::credentials::session_support::{CredentialKind, get_session_token};+use crate::security::credentials::session_support::{get_session_token, CredentialKind};use super::credential::{set_credential, SetCredentialRequest};@@ -40,7 +40,9 @@ pub fn seed_api_key_from_env(config: &Config) {}match api_key::store_api_key(config, &key) {Ok(_) => log::info!("[auth][boot] api key installed from {BACKEND_API_KEY_ENV}"),- Err(error) => log::warn!("[auth][boot] failed to install api key from {BACKEND_API_KEY_ENV}: {error}"),+ Err(error) => {+ log::warn!("[auth][boot] failed to install api key from {BACKEND_API_KEY_ENV}: {error}")+ }}}diff --git a/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs b/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rsindex 2f14773fa2..7e288e7ce4 100644--- a/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs+++ b/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs@@ -29,11 +29,17 @@ fn api_key_env_seeds_only_an_empty_store() {unsafe { std::env::set_var(BACKEND_API_KEY_ENV, " ") };seed_api_key_from_env(&config);- assert!(!api_key::has_api_key(&config), "blank env must not install a key");+ assert!(+ !api_key::has_api_key(&config),+ "blank env must not install a key"+ );unsafe { std::env::set_var(BACKEND_API_KEY_ENV, "sk-boot") };seed_api_key_from_env(&config);- assert_eq!(api_key::get_api_key(&config).unwrap().as_deref(), Some("sk-boot"));+ assert_eq!(+ api_key::get_api_key(&config).unwrap().as_deref(),+ Some("sk-boot")+ );unsafe { std::env::set_var(BACKEND_API_KEY_ENV, "sk-rotated") };seed_api_key_from_env(&config);diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rsindex 5f1bdf1d5f..4b90999141 100644--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs@@ -17,8 +17,8 @@ use crate::config::Config;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, SESSION_EXPIRES_AT_META,+ build_session_state, load_app_session_profile, local_session_user_id,+ session_token_from_profile, 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,@@ -44,7 +44,8 @@ pub const PENDING_BACKEND_VALIDATION_FIELD: &str = "pendingBackendValidation";/// Serialises credential mutations so two hosts' callbacks cannot interleave/// their activation / teardown side effects.-pub(crate) static CREDENTIAL_MUTATION_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+pub(crate) static CREDENTIAL_MUTATION_LOCK: tokio::sync::Mutex<()> =+ tokio::sync::Mutex::const_new(());/// `auth.set_credential` parameters.#[derive(Debug, Clone, Default, Deserialize)]@@ -101,9 +102,15 @@ fn resolve(request: SetCredentialRequest) -> Result<Resolved, String> {if token.is_empty() {return Err("token is required".to_string());}- let kind = match request.kind.as_deref().map(str::trim).filter(|k| !k.is_empty()) {- Some(raw) => CredentialKind::parse(raw)- .ok_or_else(|| format!("unknown credential kind {raw:?}; expected session, api-key or local"))?,+ let kind = match request+ .kind+ .as_deref()+ .map(str::trim)+ .filter(|k| !k.is_empty())+ {+ Some(raw) => CredentialKind::parse(raw).ok_or_else(|| {+ format!("unknown credential kind {raw:?}; expected session, api-key or local")+ })?,None => CredentialKind::classify(&token),};let explicit_user_id = request@@ -178,7 +185,11 @@ pub async fn set_credential(if resolved.kind == CredentialKind::ApiKey {api_key::store_api_key(config, &resolved.token).map_err(|e| e.to_string())?;crate::cron::scheduler_gate::set_signed_out(false);- tracing::info!(domain = "credentials", operation = "set_credential", "{LOG_PREFIX} api key stored");+ tracing::info!(+ domain = "credentials",+ operation = "set_credential",+ "{LOG_PREFIX} api key stored"+ );let state = build_session_state(config)?;return Ok(RpcOutcome::single_log(state, "api key stored"));}@@ -237,8 +248,12 @@ pub async fn set_credential(let effective = reload_config_or(config).await;if resolved.kind == CredentialKind::Local {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}")),+ Ok(_) => {+ logs.push("onboarding left incomplete for local session setup".to_string())+ }+ Err(error) => logs.push(format!(+ "onboarding setup warning for local session: {error}"+ )),}logs.push("local session accepted without backend validation".to_string());}@@ -257,10 +272,17 @@ pub async fn set_credential(logs.push(format!("{} credential stored", resolved.kind.as_str()));if !refresh {- logs.extend(rebind_after_credential_change(&effective_config, "credential installed"));+ logs.extend(rebind_after_credential_change(+ &effective_config,+ "credential installed",+ ));start_credential_gated_services(&effective_config).await;logs.push("credential-gated services started".to_string());- crate::memory::ops::maintenance::reembed_best_effort(&effective_config, "credential stored").await;+ crate::memory::ops::maintenance::reembed_best_effort(+ &effective_config,+ "credential stored",+ )+ .await;logs.push("memory re-embed backfill checked".to_string());}@@ -269,12 +291,12 @@ pub async fn set_credential(crate::cron::scheduler_gate::set_signed_out(false);// Scope Sentry and the prompt-layer identity to this user (#3135, #926).sentry_scope::bind(&user_id);- identity::set_current_user(- resolved- .user- .clone()- .or_else(|| existing.as_ref().and_then(|p| p.metadata.get("user_json").cloned()).and_then(|raw| serde_json::from_str(&raw).ok())),- );+ identity::set_current_user(resolved.user.clone().or_else(|| {+ existing+ .as_ref()+ .and_then(|p| p.metadata.get("user_json").cloned())+ .and_then(|raw| serde_json::from_str(&raw).ok())+ }));tracing::info!(domain = "credentials",operation = "set_credential",@@ -299,7 +321,10 @@ pub async fn clear_credential(let mut removed_session = false;let mut removed_api_key = false;- if matches!(kind, None | Some(CredentialKind::Session) | Some(CredentialKind::Local)) {+ if matches!(+ kind,+ None | Some(CredentialKind::Session) | Some(CredentialKind::Local)+ ) {let outcome = clear_session_credential(config).await?;removed_session = outcome.value;logs.extend(outcome.logs);@@ -356,7 +381,10 @@ async fn clear_session_credential(config: &Config) -> Result<RpcOutcome<bool>, S// context until the process restarts.match crate::config::load_config_with_timeout().await {Ok(signed_out_config) => {- logs.extend(rebind_after_credential_change(&signed_out_config, "credential cleared"));+ logs.extend(rebind_after_credential_change(+ &signed_out_config,+ "credential cleared",+ ));logs.push(format!("process globals rebound to signed-out workspace {}",signed_out_config.workspace_dir.display()diff --git a/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs b/crates/openhuman-core/src/security/credentials/ops_credential_tests.rsindex 8310d86f43..be5981ae05 100644--- a/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs+++ b/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs@@ -75,9 +75,16 @@ async fn set_credential_rejects_an_expired_jwt_without_storing() {"sub": "user-1","exp": (chrono::Utc::now() - chrono::Duration::hours(1)).timestamp()}));- let err = store_session(&config, &token, None, None).await.unwrap_err();+ let err = store_session(&config, &token, None, None)+ .await+ .unwrap_err();assert!(err.starts_with("CREDENTIAL_EXPIRED:"), "{err}");- assert!(auth_get_state(&config).await.unwrap().value.user_id.is_none());+ assert!(auth_get_state(&config)+ .await+ .unwrap()+ .value+ .user_id+ .is_none());}#[tokio::test]@@ -87,12 +94,19 @@ async fn set_credential_requires_a_user_id_for_a_session() {let token = jwt_with_payload(json!({"exp": (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp()}));- let err = store_session(&config, &token, None, None).await.unwrap_err();- assert!(err.contains("userId required"), "{err}");- let err = store_session(&config, "opaque-token", None, Some(json!({ "name": "no id" })))+ let err = store_session(&config, &token, None, None).await.unwrap_err();assert!(err.contains("userId required"), "{err}");+ let err = store_session(+ &config,+ "opaque-token",+ None,+ Some(json!({ "name": "no id" })),+ )+ .await+ .unwrap_err();+ assert!(err.contains("userId required"), "{err}");}// ── set_credential (session) ──────────────────────────────────@@ -125,16 +139,24 @@ async fn set_credential_installs_a_session_without_touching_the_backend() {assert_eq!(state.user_id.as_deref(), Some("user-42"));assert_eq!(state.credential.as_deref(), Some("session"));assert_eq!(state.user.unwrap()["email"], "[email protected]");- assert!(state.expires_at.is_some(), "JWT exp is recorded for the local precheck");+ assert!(+ state.expires_at.is_some(),+ "JWT exp is recorded for the local precheck"+ );let logs = result.logs.join(" ");- assert!(logs.contains("user directory activated for user-42"), "{logs}");+ assert!(+ logs.contains("user directory activated for user-42"),+ "{logs}"+ );assert!(logs.contains("session credential stored"), "{logs}");assert_eq!(crate::config::read_active_user_id(&default_root_openhuman_dir().unwrap()).as_deref(),Some("user-42"));assert_eq!(- identity::peek_credential_user_identity().and_then(|i| i.email).as_deref(),+ identity::peek_credential_user_identity()+ .and_then(|i| i.email)+ .as_deref(),Some("[email protected]"));}@@ -152,7 +174,10 @@ async fn set_credential_derives_the_user_id_from_the_jwt_subject() {"sub": "from-claims","exp": (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp()}));- let state = store_session(&config, &token, None, None).await.unwrap().value;+ let state = store_session(&config, &token, None, None)+ .await+ .unwrap()+ .value;assert_eq!(state.user_id.as_deref(), Some("from-claims"));// Explicit userId wins over the claim; the user payload's id wins over// the claim too.@@ -199,7 +224,10 @@ async fn set_credential_with_the_same_token_and_user_is_a_cheap_refresh() {let logs = second.logs.join(" ");assert!(logs.contains("credential refreshed"), "{logs}");assert!(!logs.contains("user directory activated"), "{logs}");- assert!(!logs.contains("credential-gated services started"), "{logs}");+ assert!(+ !logs.contains("credential-gated services started"),+ "{logs}"+ );let user = second.value.user.unwrap();assert_eq!(user["name"], "Confirmed");assert!(user.get("pendingBackendValidation").is_none());@@ -215,9 +243,14 @@ async fn set_credential_for_a_different_user_signs_the_previous_one_out_first()let _home = EnvVarGuard::set_to_path("HOME", tmp.path());let config = test_config(&tmp);let exp = (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp();- store_session(&config, &jwt_with_payload(json!({ "sub": "alice", "exp": exp })), None, None)- .await- .unwrap();+ store_session(+ &config,+ &jwt_with_payload(json!({ "sub": "alice", "exp": exp })),+ None,+ None,+ )+ .await+ .unwrap();let alice_config = crate::config::load_config_with_timeout().await.unwrap();let result = store_session(&alice_config,@@ -236,7 +269,12 @@ async fn set_credential_for_a_different_user_signs_the_previous_one_out_first()Some("bob"));// Alice's profile is gone from her scope.- assert!(auth_get_state(&alice_config).await.unwrap().value.user_id.is_none());+ assert!(auth_get_state(&alice_config)+ .await+ .unwrap()+ .value+ .user_id+ .is_none());}// ── set_credential (api key) ──────────────────────────────────@@ -266,7 +304,13 @@ async fn set_and_clear_api_key_credential() {.value;assert_eq!(cleared["removedApiKey"], true);assert_eq!(cleared["removedSession"], false);- assert!(!auth_get_state(&config).await.unwrap().value.is_authenticated);+ assert!(+ !auth_get_state(&config)+ .await+ .unwrap()+ .value+ .is_authenticated+ );}#[tokio::test]@@ -291,7 +335,13 @@ async fn clear_credential_without_a_kind_removes_everything() {let cleared = clear_credential(&config, None).await.unwrap().value;assert_eq!(cleared["removed"], true);assert_eq!(cleared["removedApiKey"], true);- assert!(!auth_get_state(&config).await.unwrap().value.is_authenticated);+ assert!(+ !auth_get_state(&config)+ .await+ .unwrap()+ .value+ .is_authenticated+ );}// ── authed routes keep the SESSION_EXPIRED sentinel ───────────@@ -449,7 +499,10 @@ async fn store_session_local_token_succeeds_without_network_and_forces_local_use);// The forced local user id wins over the caller's hint, and the user// payload's id fields are rewritten to match.- assert_eq!(result.value.user_id.as_deref(), Some(expected_local_user_id.as_str()));+ assert_eq!(+ result.value.user_id.as_deref(),+ Some(expected_local_user_id.as_str())+ );let user = result.value.user.unwrap();assert_eq!(user["id"], expected_local_user_id);assert_eq!(user["_id"], expected_local_user_id);diff --git a/crates/openhuman-core/src/security/credentials/ops_tests.rs b/crates/openhuman-core/src/security/credentials/ops_tests.rsindex e7b1023027..10153aa60e 100644--- a/crates/openhuman-core/src/security/credentials/ops_tests.rs+++ b/crates/openhuman-core/src/security/credentials/ops_tests.rs@@ -119,7 +119,7 @@ fn store_live_session(user_id: &str) -> Config {config}-#[path = "ops_provider_oauth_tests.rs"]-mod provider_oauth_tests;#[path = "ops_credential_tests.rs"]mod credential_tests;+#[path = "ops_provider_oauth_tests.rs"]+mod provider_oauth_tests;diff --git a/crates/openhuman-core/src/security/credentials/schemas.rs b/crates/openhuman-core/src/security/credentials/schemas.rsindex 29c1184451..64d830a5cc 100644--- a/crates/openhuman-core/src/security/credentials/schemas.rs+++ b/crates/openhuman-core/src/security/credentials/schemas.rs@@ -213,9 +213,15 @@ pub fn schemas(function: &str) -> ControllerSchema {"Backend user id. Optional when `user` carries one or the JWT has a \subject claim.",),- optional_json("user", "User payload (the host's /auth/me answer, or the local user)."),+ optional_json(+ "user",+ "User payload (the host's /auth/me answer, or the local user).",+ ),],- outputs: vec![json_output("state", "Auth state after installing the credential.")],+ outputs: vec![json_output(+ "state",+ "Auth state after installing the credential.",+ )],},"auth_clear_credential" => ControllerSchema {namespace: "auth",@@ -236,7 +242,10 @@ pub fn schemas(function: &str) -> ControllerSchema {optional_json("user_id", "Optional user id hint."),optional_json("user", "Optional user payload."),],- outputs: vec![json_output("state", "Auth state after installing the credential.")],+ outputs: vec![json_output(+ "state",+ "Auth state after installing the credential.",+ )],},"auth_clear_session" => ControllerSchema {namespace: "auth",@@ -374,7 +383,8 @@ pub fn schemas(function: &str) -> ControllerSchema {fn handle_auth_set_credential(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let config = config_rpc::load_config_with_timeout().await?;- let payload = deserialize_params::<crate::security::credentials::SetCredentialRequest>(params)?;+ let payload =+ deserialize_params::<crate::security::credentials::SetCredentialRequest>(params)?;to_json(crate::security::credentials::rpc::set_credential(&config, payload).await?)})}@@ -383,7 +393,12 @@ fn handle_auth_clear_credential(params: Map<String, Value>) -> ControllerFutureBox::pin(async move {let config = config_rpc::load_config_with_timeout().await?;let payload = deserialize_params::<AuthClearCredentialParams>(params)?;- let kind = match payload.kind.as_deref().map(str::trim).filter(|k| !k.is_empty()) {+ let kind = match payload+ .kind+ .as_deref()+ .map(str::trim)+ .filter(|k| !k.is_empty())+ {Some(raw) => Some(crate::security::credentials::session_support::CredentialKind::parse(raw).ok_or_else(|| format!("unknown credential kind {raw:?}"))?,