Skip to content

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

chore: files changed app/src/services/session/__tests__/sessionOwner.test.ts,crates/openhuman-core/s

Steven Enamakelce47c3339b84
diff --git a/app/src/services/session/__tests__/sessionOwner.test.ts b/app/src/services/session/__tests__/sessionOwner.test.ts
index a07dccd0c4..27772beb4e 100644
--- a/app/src/services/session/__tests__/sessionOwner.test.ts
+++ b/app/src/services/session/__tests__/sessionOwner.test.ts
@@ -144,9 +144,11 @@ describe('sessionOwner (browser / cloud owner)', () => {
});
it('logs out through auth.clear_credential', async () => {
- mockCallCoreRpc.mockResolvedValue({ result: {} });
+ mockCallCoreRpc.mockResolvedValueOnce({ result: { credential: 'session' } }).mockResolvedValue({
+ result: {},
+ });
await owner.logoutSession();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
+ expect(mockCallCoreRpc).toHaveBeenLastCalledWith({
method: 'openhuman.auth_clear_credential',
params: { kind: 'session' },
});
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index 8f77a7bf71..69487ee065 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -245,10 +245,10 @@ pub async fn set_credential(
logs.push("credential refreshed (same secret, same user)".to_string());
config.clone()
} else {
- logs.extend(activate_user_scope(&user_id));
+ logs.extend(activate_user_scope(&user_id)?);
// Reload so auth-profiles.json, the encryption key and the workspace
// resolve to the user-scoped location before the profile is written.
- let effective = reload_config_or(config).await;
+ let effective = reload_config_or(config).await?;
if resolved.kind == CredentialKind::Local {
match crate::config::ops::set_onboarding_completed(false).await {
Ok(_) => {
@@ -278,7 +278,7 @@ pub async fn set_credential(
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(
@@ -292,15 +292,21 @@ pub async fn set_credential(
// Open the scheduler gate now that a live credential is in place; workers
// sleeping in the paused poll loop resume at their next iteration.
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()
- .filter(|_| refresh)
- .and_then(|p| p.metadata.get("user_json").cloned())
- .and_then(|raw| serde_json::from_str(&raw).ok())
- }));
+ // An API key wins over a session for every backend request. Keep the
+ // process identity aligned with that effective credential.
+ if api_key::has_api_key(&effective_config) {
+ sentry_scope::clear();
+ identity::clear_current_user();
+ } else {
+ sentry_scope::bind(&user_id);
+ identity::set_current_user(resolved.user.clone().or_else(|| {
+ existing
+ .as_ref()
+ .filter(|_| refresh)
+ .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",
@@ -340,6 +346,20 @@ pub async fn clear_credential(
}
if !crate::security::credentials::session_support::has_backend_credential(config) {
crate::cron::scheduler_gate::set_signed_out(true);
+ } else if removed_api_key {
+ // Clearing the preferred API key exposes the surviving session.
+ // Restore the session's process identity immediately.
+ if let Some(profile) = load_app_session_profile(config)? {
+ if let Some(user_id) = profile.metadata.get("user_id") {
+ sentry_scope::bind(user_id);
+ }
+ identity::set_current_user(
+ profile
+ .metadata
+ .get("user_json")
+ .and_then(|raw| serde_json::from_str(raw).ok()),
+ );
+ }
}
}
@@ -381,7 +401,7 @@ async fn clear_session_credential(config: &Config) -> Result<RpcOutcome<bool>, S
}
crate::platform::socket::medulla::workflows::clear_workflow_bridge();
- deactivate_user_scope();
+ deactivate_user_scope()?;
stop_credential_gated_services(config).await;
// Every process-global store must follow the now-active pre-login
@@ -392,16 +412,13 @@ async fn clear_session_credential(config: &Config) -> Result<RpcOutcome<bool>, S
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()
));
}
- Err(error) => {
- tracing::warn!(%error, "{LOG_PREFIX} failed to resolve signed-out workspace");
- logs.push(format!("signed-out workspace rebind warning: {error}"));
- }
+ Err(error) => return Err(format!("failed to resolve signed-out workspace: {error}")),
}
sentry_scope::clear();
diff --git a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs b/crates/openhuman-core/src/security/credentials/ops/user_scope.rs
index 126cc66d25..6d242d0b69 100644
--- a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/user_scope.rs
@@ -32,27 +32,19 @@ pub(super) fn operator_user_activation_allowed() -> bool {
/// anonymous pre-login conversation store is purged so a fresh account never
/// inherits demo or scratch threads from the pre-login bucket (#1157).
/// Returns human-readable log lines for the RPC outcome.
-pub(super) fn activate_user_scope(user_id: &str) -> Vec<String> {
+pub(super) fn activate_user_scope(user_id: &str) -> Result<Vec<String>, String> {
let mut logs = Vec::new();
if !operator_user_activation_allowed() {
log::debug!("{LOG_PREFIX} embedder host; skipping global user activation for {user_id}");
- return logs;
+ return Ok(logs);
}
- let Ok(root_dir) = default_root_openhuman_dir() else {
- return logs;
- };
+ let root_dir = default_root_openhuman_dir().map_err(|error| error.to_string())?;
// Snapshot before overwriting `active_user.toml` so first activation can be
// told apart from an in-place account switch.
let previous_active = read_active_user_id(&root_dir);
let user_dir = user_openhuman_dir(&root_dir, user_id);
- if let Err(e) = std::fs::create_dir_all(&user_dir) {
- tracing::warn!(user_id = %user_id, error = %e, "{LOG_PREFIX} failed to create user directory");
- return logs;
- }
- if let Err(e) = write_active_user_id(&root_dir, user_id) {
- tracing::warn!(user_id = %user_id, error = %e, "{LOG_PREFIX} failed to write active_user.toml");
- return logs;
- }
+ std::fs::create_dir_all(&user_dir).map_err(|error| error.to_string())?;
+ write_active_user_id(&root_dir, user_id).map_err(|error| error.to_string())?;
logs.push(format!("user directory activated for {user_id}"));
tracing::info!(user_id = %user_id, user_dir = %user_dir.display(), "{LOG_PREFIX} user-scoped directory activated");
@@ -82,58 +74,42 @@ pub(super) fn activate_user_scope(user_id: &str) -> Vec<String> {
),
}
}
- logs
+ Ok(logs)
}
/// Clear `active_user.toml` so subsequent config loads fall back to the
/// default (unauthenticated) openhuman directory.
-pub(super) fn deactivate_user_scope() {
+pub(super) fn deactivate_user_scope() -> Result<(), String> {
if !operator_user_activation_allowed() {
- return;
- }
- if let Ok(root_dir) = default_root_openhuman_dir() {
- if let Err(e) = crate::config::clear_active_user(&root_dir) {
- tracing::warn!(error = %e, "{LOG_PREFIX} failed to clear active_user.toml");
- }
+ return Ok(());
}
+ let root_dir = default_root_openhuman_dir().map_err(|error| error.to_string())?;
+ crate::config::clear_active_user(&root_dir).map_err(|error| error.to_string())
}
/// The config that reflects the current `active_user.toml` — reloaded after an
/// activation so credentials, keys and workspaces land in the user-scoped
/// location — or `fallback` when the reload fails.
-pub(super) async fn reload_config_or(fallback: &Config) -> Config {
- match crate::config::load_config_with_timeout().await {
- Ok(config) => config,
- Err(error) => {
- tracing::warn!(error = %error, "{LOG_PREFIX} config reload failed; keeping caller config");
- fallback.clone()
- }
- }
+pub(super) async fn reload_config_or(_fallback: &Config) -> Result<Config, String> {
+ crate::config::load_config_with_timeout().await.map_err(|error| error.to_string())
}
/// Point every process-global store at `config`'s workspace after a
/// credential change: cron seeds, the core context (which carries the memory
/// binding — see `CoreContext::memory_binding`, #5560), and conversation
/// persistence. Returns log lines for the RPC outcome.
-pub(super) fn rebind_after_credential_change(config: &Config, reason: &str) -> Vec<String> {
+pub(super) fn rebind_after_credential_change(config: &Config, _reason: &str) -> Result<Vec<String>, String> {
let mut logs = Vec::new();
- if let Err(error) = crate::cron::seed::prune_retired_jobs(config) {
- tracing::warn!(error = %error, "{LOG_PREFIX} failed to prune retired cron jobs ({reason})");
- }
- match crate::core::runtime::context::CoreContext::rebind_default_workspace(
+ crate::cron::seed::prune_retired_jobs(config).map_err(|error| error.to_string())?;
+ crate::core::runtime::context::CoreContext::rebind_default_workspace(
&config.workspace_dir,
config.subsystems.memory.clone(),
- ) {
- Ok(_) => logs.push(format!(
+ ).map_err(|error| error.to_string())?;
+ logs.push(format!(
"core context bound to workspace {}",
config.workspace_dir.display()
- )),
- Err(e) => {
- tracing::warn!(error = %e, "{LOG_PREFIX} failed to rebind core context ({reason})");
- logs.push(format!("core context bind warning: {e}"));
- }
- }
+ ));
conversations::register_conversation_persistence_subscriber(config.workspace_dir.clone());
logs.push("conversation persistence bound to active workspace".to_string());
- logs
+ Ok(logs)
}