Skip to content

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

fix(security): correct credential profile implementation to restore missing event bridge dependency

Steven Enamakelde99e41f15de
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs
index cd52c6907b..3ee35b3774 100644
--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs
@@ -40,10 +40,10 @@ pub(super) struct BridgeState {
/// keyed by iteration so the subsequent `ModelCompleted` projection reports
/// the same numbers as the wallet accounting.
#[derive(Clone, Copy, Debug)]
-struct ResolvedCallFigures {
- cost_usd: f64,
- cache_creation_tokens: u64,
- reasoning_tokens: u64,
+pub(super) struct ResolvedCallFigures {
+ pub(super) cost_usd: f64,
+ pub(super) cache_creation_tokens: u64,
+ pub(super) reasoning_tokens: u64,
}
/// An [`EventListener`] that mirrors harness events onto openhuman's progress
diff --git a/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_01.rs b/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_01.rs
deleted file mode 100644
index 95e9c49d13..0000000000
--- a/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_01.rs
+++ /dev/null
@@ -1,743 +0,0 @@
-impl AuthProfilesStore {
- pub fn new(state_dir: &Path, encrypt_secrets: bool) -> Self {
- let user_id = user_id_from_state_dir(state_dir);
- let policy = crate::security::keyring_consent::policy::check_secret_access();
- let use_keychain = policy
- == crate::security::keyring_consent::PolicyDecision::Proceed
- && crate::security::keyring::is_available();
- log::debug!(
- "[auth] AuthProfilesStore::new state_dir={} user_id={user_id} use_keychain={use_keychain} policy={policy:?}",
- state_dir.display()
- );
- match policy {
- crate::security::keyring_consent::PolicyDecision::Proceed => {
- if !use_keychain {
- // OS keychain unavailable despite Proceed policy (probe failed).
- log::info!(
- "[auth] OS keychain unavailable — using encrypted JSON for auth profiles user_id={user_id}"
- );
- }
- }
- crate::security::keyring_consent::PolicyDecision::ConsentRequired => {
- log::warn!(
- "[auth] keyring consent has not been given — secrets will NOT be persisted \
- to the OS keychain until the user grants consent. \
- Falling back to encrypted JSON for auth profiles user_id={user_id}"
- );
- }
- crate::security::keyring_consent::PolicyDecision::Declined => {
- log::warn!(
- "[auth] user explicitly declined OS keychain storage — \
- using encrypted JSON for auth profiles user_id={user_id}"
- );
- }
- }
- Self {
- path: state_dir.join(PROFILES_FILENAME),
- lock_path: state_dir.join(LOCK_FILENAME),
- secret_store: SecretStore::new(state_dir, encrypt_secrets),
- user_id,
- use_keychain,
- #[cfg(test)]
- force_transient_failures_write: Arc::new(AtomicUsize::new(0)),
- #[cfg(test)]
- force_transient_failures_rename: Arc::new(AtomicUsize::new(0)),
- #[cfg(test)]
- force_lock_unwritable: Arc::new(AtomicBool::new(false)),
- }
- }
-
- /// Build a keychain key for an auth profile's combined secret payload.
- fn keychain_key_for_profile(&self, profile_id: &str) -> String {
- format!("{KEYCHAIN_AUTH_PREFIX}{profile_id}")
- }
-
- /// Store auth secrets for a profile in the OS keychain.
- ///
- /// The secrets are serialized as a compact JSON object so a single
- /// keychain entry holds all token fields for the profile.
- fn keychain_store_secrets(&self, profile: &AuthProfile) -> anyhow::Result<()> {
- let key = self.keychain_key_for_profile(&profile.id);
- let secrets = serde_json::json!({
- "token": profile.token,
- "access_token": profile.token_set.as_ref().map(|ts| &ts.access_token),
- "refresh_token": profile.token_set.as_ref().and_then(|ts| ts.refresh_token.as_deref()),
- "id_token": profile.token_set.as_ref().and_then(|ts| ts.id_token.as_deref()),
- });
- let payload = serde_json::to_string(&secrets)
- .context("Failed to serialize auth secrets for keychain")?;
- crate::security::keyring::set(&self.user_id, &key, &payload).map_err(|e| {
- anyhow::anyhow!(
- "Keychain set failed for profile {}: {e} | detail={}",
- profile.id,
- e.diagnostic()
- )
- })?;
- log::debug!(
- "[auth] keychain_store_secrets stored profile_id={} user_id={}",
- profile.id,
- self.user_id
- );
- Ok(())
- }
-
- /// Load auth secrets for a profile from the OS keychain.
- ///
- /// Returns `None` if no keychain entry exists for the profile.
- fn keychain_load_secrets(&self, profile_id: &str) -> anyhow::Result<Option<KeychainSecrets>> {
- let key = self.keychain_key_for_profile(profile_id);
- let payload = match crate::security::keyring::get(&self.user_id, &key) {
- Ok(Some(p)) => p,
- Ok(None) => {
- log::debug!(
- "[auth] keychain_load_secrets miss profile_id={profile_id} user_id={}",
- self.user_id
- );
- return Ok(None);
- }
- Err(e) => {
- log::warn!(
- "[auth] keychain_load_secrets error profile_id={profile_id} user_id={}: {e} | detail={}",
- self.user_id,
- e.diagnostic()
- );
- return Ok(None);
- }
- };
- let secrets: KeychainSecrets = serde_json::from_str(&payload).map_err(|e| {
- anyhow::anyhow!("Keychain payload for profile {profile_id} is not valid JSON: {e}")
- })?;
- log::debug!(
- "[auth] keychain_load_secrets hit profile_id={profile_id} user_id={}",
- self.user_id
- );
- Ok(Some(secrets))
- }
-
- /// Delete keychain secrets for a profile (called on profile removal).
- fn keychain_delete_secrets(&self, profile_id: &str) {
- let key = self.keychain_key_for_profile(profile_id);
- if let Err(e) = crate::security::keyring::delete(&self.user_id, &key) {
- log::warn!(
- "[auth] keychain_delete_secrets error profile_id={profile_id} user_id={}: {e} | detail={}",
- self.user_id,
- e.diagnostic()
- );
- } else {
- log::debug!(
- "[auth] keychain_delete_secrets ok profile_id={profile_id} user_id={}",
- self.user_id
- );
- }
- }
-
- pub fn path(&self) -> &Path {
- &self.path
- }
-
- pub fn load(&self) -> Result<AuthProfilesData> {
- match self.acquire_lock() {
- Ok(_lock) => self.load_locked(),
- Err(e) if is_lock_create_unwritable_fs(&e) => {
- // RCA Sentry TAURI-RUST-4SZ: a full / read-only filesystem
- // can't create the exclusive lock file, but the store already
- // exists and writers publish via atomic tmp+rename, so a
- // lock-free read is still consistent. The read path is the
- // hot caller here (`app_state_snapshot` polls it every tick),
- // so failing it strands the UI AND floods Sentry once per
- // poll. Degrade to a lock-free read-only load instead — the
- // user keeps their session view, and because no error is
- // produced the noise stops at the source rather than being
- // suppressed downstream. Opportunistic migrations are skipped
- // (they couldn't persist on a full disk anyway).
- log::warn!(
- "[auth] auth-profile lock could not be created ({e}); \
- serving lock-free read-only load (likely disk full / read-only FS)"
- );
- self.load_unlocked_readonly()
- }
- Err(e) => Err(e),
- }
- }
-
- pub fn upsert_profile(&self, mut profile: AuthProfile, set_active: bool) -> Result<()> {
- let _lock = self.acquire_lock()?;
- let mut data = self.load_locked()?;
-
- profile.updated_at = Utc::now();
- if let Some(existing) = data.profiles.get(&profile.id) {
- profile.created_at = existing.created_at;
- }
-
- if set_active {
- data.active_profiles
- .insert(profile.provider.clone(), profile.id.clone());
- }
-
- data.profiles.insert(profile.id.clone(), profile);
- data.updated_at = Utc::now();
-
- self.save_locked(&data)
- }
-
- pub fn remove_profile(&self, profile_id: &str) -> Result<bool> {
- let _lock = self.acquire_lock()?;
- let mut data = self.load_locked()?;
-
- let removed = data.profiles.remove(profile_id).is_some();
- if !removed {
- return Ok(false);
- }
-
- data.active_profiles
- .retain(|_, active| active != profile_id);
- data.updated_at = Utc::now();
- self.save_locked(&data)?;
-
- // Clean up keychain entry for this profile (idempotent if keychain
- // is unavailable or no entry exists).
- if self.use_keychain {
- self.keychain_delete_secrets(profile_id);
- }
-
- Ok(true)
- }
-
- pub fn set_active_profile(&self, provider: &str, profile_id: &str) -> Result<()> {
- let _lock = self.acquire_lock()?;
- let mut data = self.load_locked()?;
-
- if !data.profiles.contains_key(profile_id) {
- anyhow::bail!("Auth profile not found: {profile_id}");
- }
-
- data.active_profiles
- .insert(provider.to_ascii_lowercase(), profile_id.to_string());
- data.updated_at = Utc::now();
- self.save_locked(&data)
- }
-
- pub fn clear_active_profile(&self, provider: &str) -> Result<()> {
- let _lock = self.acquire_lock()?;
- let mut data = self.load_locked()?;
- data.active_profiles.remove(&provider.to_ascii_lowercase());
- data.updated_at = Utc::now();
- self.save_locked(&data)
- }
-
- pub fn update_profile<F>(&self, profile_id: &str, mut updater: F) -> Result<AuthProfile>
- where
- F: FnMut(&mut AuthProfile) -> Result<()>,
- {
- let _lock = self.acquire_lock()?;
- let mut data = self.load_locked()?;
-
- let profile = data
- .profiles
- .get_mut(profile_id)
- .ok_or_else(|| anyhow::anyhow!("Auth profile not found: {profile_id}"))?;
-
- updater(profile)?;
- profile.updated_at = Utc::now();
- let updated_profile = profile.clone();
- data.updated_at = Utc::now();
- self.save_locked(&data)?;
- Ok(updated_profile)
- }
-
- fn load_locked(&self) -> Result<AuthProfilesData> {
- self.load_resolved(true)
- }
-
- /// Lock-free read-only load used as the [`AuthProfilesStore::load`]
- /// fallback when the exclusive lock can't be created because the
- /// filesystem won't accept the lock file (disk full / read-only mount —
- /// Sentry TAURI-RUST-4SZ). Safe without the lock because writers publish
- /// the store atomically (tmp + `fs::rename`), so a bare read always sees
- /// a complete file. Skips the opportunistic migration / dropped-profile
- /// rewrite that `load_locked` performs — that write needs both the lock
- /// and a writable disk, and this path runs precisely when neither holds.
- fn load_unlocked_readonly(&self) -> Result<AuthProfilesData> {
- self.load_resolved(false)
- }
-
- /// Shared read + in-memory resolution worker. Reads the persisted store,
- /// resolves/migrates secrets and drops unrecoverable profiles in memory,
- /// and — only when `persist` is true — writes back any resulting cleanup.
- /// The returned `AuthProfilesData` reflects the in-memory cleanup either
- /// way, so the lock-free read path (`persist = false`) still returns a
- /// correct, fully-resolved view without touching disk.
- fn load_resolved(&self, persist: bool) -> Result<AuthProfilesData> {
- let mut persisted = self.read_persisted_locked()?;
- // `migrated` tracks enc: → enc2: XOR-cipher upgrades (original behavior).
- let mut migrated = false;
- // `keychain_migrated` tracks enc2: → keychain promotions: when true the
- // persisted JSON must be rewritten with secret fields cleared.
- let mut keychain_migrated = false;
- let mut pending_keychain_deletes = Vec::new();
- let mut dropped_ids: Vec<String> = Vec::new();
-
- let mut profiles = BTreeMap::new();
- for (id, p) in &mut persisted.profiles {
- // ── Step 1: Resolve secrets ───────────────────────────────────────
- //
- // Priority order:
- // (a) OS keychain — preferred when available.
- // (b) enc2:/enc: JSON fields — legacy; decrypt and optionally
- // migrate to keychain on this read.
- // (c) Plaintext JSON fields — oldest legacy path; pass through.
- //
- // A decrypt failure (wrong key / tampered data) drops the profile
- // rather than poisoning every reader — the user falls back to a
- // clean logged-out state and re-authenticates cleanly.
-
- let (access_token, refresh_token, id_token, token) = if self.use_keychain {
- // ── (a) Keychain path ──────────────────────────────────────
- match self.keychain_load_secrets(id) {
- Ok(Some(secrets)) => {
- // Keychain has the entry — use it directly. Clear the
- // JSON secret fields so they're wiped on next save.
- let had_enc_fields = p.access_token.is_some()
- || p.refresh_token.is_some()
- || p.id_token.is_some()
- || p.token.is_some();
- if had_enc_fields {
- log::info!(
- "[auth] load: clearing legacy enc fields for profile_id={id} (already in keychain)"
- );
- p.access_token = None;
- p.refresh_token = None;
- p.id_token = None;
- p.token = None;
- keychain_migrated = true;
- }
- (
- secrets.access_token,
- secrets.refresh_token,
- secrets.id_token,
- secrets.token,
- )
- }
- Ok(None) => {
- // ── (b) No keychain entry yet — decrypt JSON fields and migrate ──
- let decrypted = (|| -> Result<_> {
- let (access_token, access_mig) =
- self.decrypt_optional(p.access_token.as_deref())?;
- let (refresh_token, refresh_mig) =
- self.decrypt_optional(p.refresh_token.as_deref())?;
- let (id_token, id_mig) =
- self.decrypt_optional(p.id_token.as_deref())?;
- let (token, token_mig) = self.decrypt_optional(p.token.as_deref())?;
- Ok((
- access_token,
- access_mig,
- refresh_token,
- refresh_mig,
- id_token,
- id_mig,
- token,
- token_mig,
- ))
- })();
- let (at, at_mig, rt, rt_mig, it, it_mig, tok, tok_mig) = match decrypted {
- Ok(v) => v,
- Err(e) => {
- log::warn!(
- "[auth] dropping unrecoverable profile provider={}: {e}. \
- Most likely cause: .secret_key was regenerated. \
- Re-authenticate to restore the session.",
- p.provider
- );
- dropped_ids.push(id.clone());
- continue;
- }
- };
- // Track XOR→enc2 cipher upgrades (existing behavior).
- if at_mig.is_some() {
- p.access_token = at_mig;
- migrated = true;
- }
- if rt_mig.is_some() {
- p.refresh_token = rt_mig;
- migrated = true;
- }
- if it_mig.is_some() {
- p.id_token = it_mig;
- migrated = true;
- }
- if tok_mig.is_some() {
- p.token = tok_mig;
- migrated = true;
- }
-
- // If any secrets were found in JSON, promote them to keychain
- // and clear the JSON fields so the next write is clean.
- let has_secrets =
- at.is_some() || rt.is_some() || it.is_some() || tok.is_some();
- if has_secrets {
- log::info!(
- "[auth] load: migrating enc fields to keychain profile_id={id} user_id={}",
- self.user_id
- );
- let dummy_profile = AuthProfile {
- id: id.clone(),
- provider: p.provider.clone(),
- profile_name: p.profile_name.clone(),
- kind: parse_profile_kind(&p.kind).unwrap_or(AuthProfileKind::Token),
- account_id: p.account_id.clone(),
- workspace_id: p.workspace_id.clone(),
- token_set: at.clone().map(|access| TokenSet {
- access_token: access,
- refresh_token: rt.clone(),
- id_token: it.clone(),
- expires_at: None,
- token_type: None,
- scope: None,
- }),
- token: tok.clone(),
- metadata: Default::default(),
- created_at: Utc::now(),
- updated_at: Utc::now(),
- };
- if let Err(e) = self.keychain_store_secrets(&dummy_profile) {
- // Non-fatal: keep the enc2: fields in JSON so the
- // next load can try again.
- log::warn!(
- "[auth] load: keychain migration failed profile_id={id}: {e}; \
- keeping enc fields in JSON"
- );
- } else {
- // Wipe JSON secret fields now that keychain has them.
- p.access_token = None;
- p.refresh_token = None;
- p.id_token = None;
- p.token = None;
- keychain_migrated = true;
- }
- }
- (at, rt, it, tok)
- }
- Err(_e) => {
- // Keychain I/O error — fall through to JSON decrypt path.
- log::warn!(
- "[auth] keychain error for profile_id={id}; falling back to JSON"
- );
- let decrypted = (|| -> Result<_> {
- let (at, _) = self.decrypt_optional(p.access_token.as_deref())?;
- let (rt, _) = self.decrypt_optional(p.refresh_token.as_deref())?;
- let (it, _) = self.decrypt_optional(p.id_token.as_deref())?;
- let (tok, _) = self.decrypt_optional(p.token.as_deref())?;
- Ok((at, rt, it, tok))
- })();
- match decrypted {
- Ok(v) => v,
- Err(e) => {
- log::warn!(
- "[auth] dropping unrecoverable profile provider={}: {e}",
- p.provider
- );
- dropped_ids.push(id.clone());
- continue;
- }
- }
- }
- }
- } else {
- // ── (b/c) No keychain — use existing JSON decrypt path ────────
- let decrypted = (|| -> Result<_> {
- let (access_token, access_migrated) =
- self.decrypt_optional(p.access_token.as_deref())?;
- let (refresh_token, refresh_migrated) =
- self.decrypt_optional(p.refresh_token.as_deref())?;
- let (id_token, id_migrated) = self.decrypt_optional(p.id_token.as_deref())?;
- let (token, token_migrated) = self.decrypt_optional(p.token.as_deref())?;
- Ok((
- access_token,
- access_migrated,
- refresh_token,
- refresh_migrated,
- id_token,
- id_migrated,
- token,
- token_migrated,
- ))
- })();
-
- let (
- access_token,
- access_migrated,
- refresh_token,
- refresh_migrated,
- id_token,
- id_migrated,
- token,
- token_migrated,
- ) = match decrypted {
- Ok(v) => v,
- Err(e) => {
- log::warn!(
- "[auth] dropping unrecoverable profile provider={}: {e}. \
- Most likely cause: .secret_key was regenerated after this profile \
- was stored. The store will be rewritten without this entry; \
- re-authenticate to restore the session.",
- p.provider
- );
- dropped_ids.push(id.clone());
- continue;
- }
- };
-
- if let Some(value) = access_migrated {
- p.access_token = Some(value);
- migrated = true;
- }
- if let Some(value) = refresh_migrated {
- p.refresh_token = Some(value);
- migrated = true;
- }
- if let Some(value) = id_migrated {
- p.id_token = Some(value);
- migrated = true;
- }
- if let Some(value) = token_migrated {
- p.token = Some(value);
- migrated = true;
- }
- (access_token, refresh_token, id_token, token)
- };
-
- let kind = match parse_profile_kind(&p.kind) {
- Ok(k) => k,
- Err(e) => {
- // A single profile with an unrecognized `kind` (e.g. a legacy value
- // like "OAuth" written before the kebab-case rename, or "api_key"
- // written by an older code path) must not poison the whole store —
- // otherwise every reader fails the entire load and the user is
- // locked out of *all* their auth profiles. Drop just this entry,
- // matching the decrypt-failure recovery pattern above; the next
- // login re-encodes the kind correctly.
- log::warn!(
- "[auth] dropping profile with unrecognized kind={:?} provider={}: {e}. \
- This usually means the profile was written by an older version of \
- OpenHuman. Re-authenticate to restore the session.",
- p.kind,
- p.provider
- );
- dropped_ids.push(id.clone());
- continue;
- }
- };
- let token_set = match kind {
- AuthProfileKind::OAuth => {
- let access = match access_token {
- Some(a) => a,
- None => {
- log::warn!(
- "[auth] dropping OAuth profile with missing access_token: \
- provider={}. Re-authenticate to restore.",
- p.provider
- );
- dropped_ids.push(id.clone());
- continue;
- }
- };
- Some(TokenSet {
- access_token: access,
- refresh_token,
- id_token,
- expires_at: parse_optional_datetime(p.expires_at.as_deref())?,
- token_type: p.token_type.clone(),
- scope: p.scope.clone(),
- })
- }
- AuthProfileKind::Token => None,
- };
-
- profiles.insert(
- id.clone(),
- AuthProfile {
- id: id.clone(),
- provider: p.provider.clone(),
- profile_name: p.profile_name.clone(),
- kind,
- account_id: p.account_id.clone(),
- workspace_id: p.workspace_id.clone(),
- token_set,
- token,
- metadata: p.metadata.clone(),
- created_at: parse_datetime_with_fallback(&p.created_at),
- updated_at: parse_datetime_with_fallback(&p.updated_at),
- },
- );
- }
-
- if !dropped_ids.is_empty() {
- for id in &dropped_ids {
- persisted.profiles.remove(id);
- }
- persisted
- .active_profiles
- .retain(|_, profile_id| !dropped_ids.contains(profile_id));
- persisted.updated_at = Utc::now().to_rfc3339();
- log::warn!(
- "[auth] purged {} unrecoverable profile(s) from store at {} \
- (provider list redacted to avoid leaking PII)",
- dropped_ids.len(),
- self.path.display(),
- );
- }
-
- let mut key_migrated = false;
- let mut new_active = BTreeMap::new();
- let mut active_entries: Vec<_> = persisted.active_profiles.iter().collect();
- active_entries.sort_by_key(|(k, _)| k.to_ascii_lowercase() != **k);
- for (k, v) in active_entries {
- let lower = k.to_ascii_lowercase();
- let normalized_value = normalize_profile_id_provider(v);
- if &lower != k || &normalized_value != v {
- key_migrated = true;
- }
- if new_active.contains_key(&lower) {
- if k == &lower {
- new_active.insert(lower.clone(), normalized_value.clone());
- }
- } else {
- new_active.insert(lower, normalized_value);
- }
- }
- if key_migrated {
- persisted.active_profiles = new_active;
- }
-
- let mut new_persisted_profiles: BTreeMap<String, PersistedAuthProfile> = BTreeMap::new();
- let mut new_profiles: BTreeMap<String, AuthProfile> = BTreeMap::new();
- let mut profile_id_migration_targets: BTreeMap<String, String> = BTreeMap::new();
- let mut profile_casing_changed_count: usize = 0;
- let mut profile_migration_conflicts: usize = 0;
-
- let mut profile_entries: Vec<_> = std::mem::take(&mut persisted.profiles)
- .into_iter()
- .collect();
- profile_entries.sort_by_key(|(id, p)| {
- id != &profile_id(&p.provider.to_ascii_lowercase(), &p.profile_name)
- });
- for (id, mut p) in profile_entries {
- let original_provider = p.provider.clone();
- let lower_provider = p.provider.to_ascii_lowercase();
- let normalized_id = profile_id(&lower_provider, &p.profile_name);
- let provider_or_id_changed = normalized_id != id || lower_provider != p.provider;
-
- if let Some(mut ap) = profiles.remove(&id) {
- if new_profiles.contains_key(&normalized_id) {
- profile_migration_conflicts += 1;
- key_migrated = true;
- if id == normalized_id {
- let old_id = new_profiles
- .insert(normalized_id.clone(), ap)
- .map(|old| old.id);
- new_persisted_profiles.insert(normalized_id.clone(), p);
- profile_id_migration_targets
- .insert(id.clone(), normalized_id.clone());
- profile_id_migration_targets.insert(
- normalize_profile_id_provider(&id),
- normalized_id.clone(),
- );
- if self.use_keychain {
- if let Some(old_id) = &old_id {
- pending_keychain_deletes.push(old_id.clone());
- }
- }
- log::debug!(
- "[auth] profile id migration collision: dropped mixed-case profile_id={:?}",
- old_id
- );
- } else {
- if self.use_keychain {
- pending_keychain_deletes.push(id.clone());
- }
- log::debug!(
- "[auth] profile id migration collision: dropped mixed-case profile_id={id}"
- );
- }
- } else {
- ap.id = normalized_id.clone();
- ap.provider = lower_provider.clone();
- p.provider = lower_provider;
-
- let migration_succeeded = if self.use_keychain
- && provider_or_id_changed
- && (ap.token.is_some() || ap.token_set.is_some())
- {
- match self.keychain_store_secrets(&ap) {
- Ok(()) => {
- keychain_migrated = true;
- pending_keychain_deletes.push(id.clone());
- true
- }
- Err(e) => {
- log::warn!(
- "[auth] load: keychain profile-id migration failed old_profile_id={id}: {e}; retaining legacy entry"
- );
- false
- }
- }
- } else {
- true
- };
-
- let final_id = if migration_succeeded {
- if provider_or_id_changed {
- key_migrated = true;
- profile_casing_changed_count += 1;
- }
- normalized_id.clone()
- } else {
- ap.id = id.clone();
- p.provider = original_provider;
- id.clone()
- };
- profile_id_migration_targets
- .insert(id.clone(), final_id.clone());
- profile_id_migration_targets
- .insert(normalize_profile_id_provider(&id), final_id.clone());
- new_profiles.insert(final_id.clone(), ap);
- new_persisted_profiles.insert(final_id, p);
- }
- }
- }
- for profile_id in persisted.active_profiles.values_mut() {
- let normalized = normalize_profile_id_provider(profile_id);
- if let Some(target) = profile_id_migration_targets.get(&normalized) {
- if profile_id != target {
- *profile_id = target.clone();
- key_migrated = true;
- }
- }
- }
- if profile_casing_changed_count > 0 {
- if profile_migration_conflicts > 0 {
- log::warn!(
- "[auth] profile migration: {profile_migration_conflicts} case-variant \
- collision(s) resolved by preferring the existing lowercase entry"
- );
- }
- log::debug!(
- "[auth] profile migration: normalized {profile_casing_changed_count} profile id(s) to lowercase"
- );
- }
- persisted.profiles = new_persisted_profiles;
- profiles = new_profiles;
- if persist && (!dropped_ids.is_empty() || migrated || keychain_migrated || key_migrated) {
- self.write_persisted_locked(&persisted)?;
- for id in pending_keychain_deletes {
- self.keychain_delete_secrets(&id);
- }
- }
- Ok(AuthProfilesData {
- schema_version: persisted.schema_version,
- updated_at: parse_datetime_with_fallback(&persisted.updated_at),
- active_profiles: persisted.active_profiles,
- profiles,
- })
- }
-}
diff --git a/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_02.rs b/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_02.rs
deleted file mode 100644
index 4b240bfea5..0000000000
--- a/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_02.rs
+++ /dev/null
@@ -1,585 +0,0 @@
-
-impl AuthProfilesStore {
- fn save_locked(&self, data: &AuthProfilesData) -> Result<()> {
- let mut persisted = PersistedAuthProfiles {
- schema_version: CURRENT_SCHEMA_VERSION,
- updated_at: data.updated_at.to_rfc3339(),
- active_profiles: data.active_profiles.clone(),
- profiles: BTreeMap::new(),
- };
-
- for (id, profile) in &data.profiles {
- // When the OS keychain is available, store all secret fields there and
- // leave them absent from the JSON file. This is the preferred path on
- // macOS / Windows / Linux-with-Secret-Service.
- //
- // When the keychain is unavailable (Linux headless / CI), fall back to
- // the existing ChaCha20-Poly1305 encrypted JSON fields.
- let (access_token, refresh_token, id_token, token, expires_at, token_type, scope) =
- if self.use_keychain {
- // Store secrets in the OS keychain — JSON gets no secret fields.
- if let Err(e) = self.keychain_store_secrets(profile) {
- // Non-fatal: fall back to encrypted JSON so data is not lost.
- log::warn!(
- "[auth] save: keychain store failed for profile_id={id}: {e}; \
- falling back to encrypted JSON"
- );
- self.encrypt_for_json(profile)?
- } else {
- log::debug!("[auth] save: secrets stored in keychain profile_id={id}");
- let (expires_at, token_type, scope) = match &profile.token_set {
- Some(ts) => (
- ts.expires_at.as_ref().map(DateTime::to_rfc3339),
- ts.token_type.clone(),
- ts.scope.clone(),
- ),
- None => (None, None, None),
- };
- // Secret fields deliberately omitted from JSON.
- (None, None, None, None, expires_at, token_type, scope)
- }
- } else {
- // Headless / no keychain — encrypt and store in JSON.
- self.encrypt_for_json(profile)?
- };
-
- persisted.profiles.insert(
- id.clone(),
- PersistedAuthProfile {
- provider: profile.provider.clone(),
- profile_name: profile.profile_name.clone(),
- kind: profile_kind_to_string(profile.kind).to_string(),
- account_id: profile.account_id.clone(),
- workspace_id: profile.workspace_id.clone(),
- access_token,
- refresh_token,
- id_token,
- token,
- expires_at,
- token_type,
- scope,
- metadata: profile.metadata.clone(),
- created_at: profile.created_at.to_rfc3339(),
- updated_at: profile.updated_at.to_rfc3339(),
- },
- );
- }
-
- self.write_persisted_locked(&persisted)
- }
-
- /// Encrypt a profile's secret fields for JSON storage (keychain-unavailable path).
- fn encrypt_for_json(&self, profile: &AuthProfile) -> Result<EncryptedProfileFields> {
- let (access_token, refresh_token, id_token, expires_at, token_type, scope) =
- match (&profile.kind, &profile.token_set) {
- (AuthProfileKind::OAuth, Some(token_set)) => (
- self.encrypt_optional(Some(&token_set.access_token))?,
- self.encrypt_optional(token_set.refresh_token.as_deref())?,
- self.encrypt_optional(token_set.id_token.as_deref())?,
- token_set.expires_at.as_ref().map(DateTime::to_rfc3339),
- token_set.token_type.clone(),
- token_set.scope.clone(),
- ),
- _ => (None, None, None, None, None, None),
- };
- let token = self.encrypt_optional(profile.token.as_deref())?;
- Ok((
- access_token,
- refresh_token,
- id_token,
- token,
- expires_at,
- token_type,
- scope,
- ))
- }
-
- fn read_persisted_locked(&self) -> Result<PersistedAuthProfiles> {
- if !self.path.exists() {
- return Ok(PersistedAuthProfiles::default());
- }
-
- let bytes = fs::read(&self.path).with_context(|| {
- format!(
- "Failed to read auth profile store at {}",
- self.path.display()
- )
- })?;
-
- if bytes.is_empty() {
- return Ok(PersistedAuthProfiles::default());
- }
-
- let mut persisted: PersistedAuthProfiles = match serde_json::from_slice(&bytes) {
- Ok(p) => p,
- Err(err) => {
- let quarantined = quarantine_corrupt_store(&self.path)?;
- let quarantined_file = quarantined
- .file_name()
- .and_then(|s| s.to_str())
- .unwrap_or("auth-profiles.corrupt");
- tracing::warn!(
- path_file = PROFILES_FILENAME,
- quarantined_file = quarantined_file,
- error = %err,
- "[credentials] auth profile store unparseable; quarantined and reset to empty"
- );
- return Ok(PersistedAuthProfiles::default());
- }
- };
-
- if persisted.schema_version == 0 {
- persisted.schema_version = CURRENT_SCHEMA_VERSION;
- }
-
- if persisted.schema_version > CURRENT_SCHEMA_VERSION {
- anyhow::bail!(
- "Unsupported auth profile schema version {} (max supported: {})",
- persisted.schema_version,
- CURRENT_SCHEMA_VERSION
- );
- }
-
- Ok(persisted)
- }
-
- fn write_persisted_locked(&self, persisted: &PersistedAuthProfiles) -> Result<()> {
- if let Some(parent) = self.path.parent() {
- fs::create_dir_all(parent).with_context(|| {
- format!(
- "Failed to create auth profile directory at {}",
- parent.display()
- )
- })?;
- }
-
- let json =
- serde_json::to_vec_pretty(persisted).context("Failed to serialize auth profiles")?;
- let tmp_name = format!(
- "{}.tmp.{}.{}",
- PROFILES_FILENAME,
- std::process::id(),
- Utc::now().timestamp_nanos_opt().unwrap_or_default()
- );
- let tmp_path = self.path.with_file_name(tmp_name);
-
- // Windows AV / Search-Indexer / Defender may briefly hold a handle on
- // the destination, returning transient `ERROR_SHARING_VIOLATION (32)`,
- // `ERROR_ACCESS_DENIED (5)`, or `ERROR_DELETE_PENDING (303)` —
- // recognised as retryable by `is_transient_fs_error`. Mirror the
- // lock-create retry budget at the bottom of `acquire_lock` so the
- // JSON write+rename path absorbs the same transient family that
- // closed Sentry OPENHUMAN-TAURI-H1 / H8 for the lock path. Outer
- // `with_context` preserved so the Sentry fingerprint shape is stable
- // across releases. (Sentry TAURI-RUST-92J / #3355.)
- retry_with_backoff(
- "write auth profile tmp",
- PERSIST_RETRY_ATTEMPTS,
- PERSIST_RETRY_BASE_MS,
- || {
- self.consume_test_transient_failure_write()?;
- write_owner_only(&tmp_path, &json).context("write auth profile tmp")
- },
- )
- .with_context(|| {
- format!(
- "Failed to write temporary auth profile file at {}",
- tmp_path.display()
- )
- })?;
-
- let rename_result = retry_with_backoff(
- "replace auth profile store",
- PERSIST_RETRY_ATTEMPTS,
- PERSIST_RETRY_BASE_MS,
- || {
- self.consume_test_transient_failure_rename()?;
- fs::rename(&tmp_path, &self.path).context("rename auth profile tmp -> store")
- },
- )
- .with_context(|| {
- format!(
- "Failed to replace auth profile store at {}",
- self.path.display()
- )
- });
-
- if rename_result.is_err() {
- // Best-effort orphan cleanup: `tmp_path` is `…tmp.{pid}.{nanos}`
- // — unique per call — so a permanently-failing rename otherwise
- // leaks one tmp file per `app_state_snapshot` poll (~2s cadence)
- // under sustained Windows AV / Search-Indexer holds. Cleaning
- // here keeps the directory tidy; the cleanup itself can fail
- // (the same AV that blocked the rename may block the unlink),
- // which is why we deliberately drop the result.
- let _ = fs::remove_file(&tmp_path);
- }
-
- rename_result
- }
-
- /// Consume one test-injected transient FS failure for the **write**
- /// stage if any are queued. No-op in production builds.
- #[cfg(test)]
- fn consume_test_transient_failure_write(&self) -> Result<()> {
- consume_one(&self.force_transient_failures_write)
- }
-
- /// Consume one test-injected transient FS failure for the **rename**
- /// stage if any are queued. No-op in production builds.
- #[cfg(test)]
- fn consume_test_transient_failure_rename(&self) -> Result<()> {
- consume_one(&self.force_transient_failures_rename)
- }
-
- #[cfg(not(test))]
- #[inline(always)]
- fn consume_test_transient_failure_write(&self) -> Result<()> {
- Ok(())
- }
-
- #[cfg(not(test))]
- #[inline(always)]
- fn consume_test_transient_failure_rename(&self) -> Result<()> {
- Ok(())
- }
-
- /// Queue `n` test-only forced transient FS failures for the write
- /// stage. The next `n` calls inside the `fs::write(tmp)` retry loop
- /// return a `__TEST_TRANSIENT__` error before the underlying FS op
- /// runs; the retry helper treats them as retryable.
- #[cfg(test)]
- pub(super) fn force_next_write_failures(&self, n: usize) {
- self.force_transient_failures_write
- .store(n, Ordering::SeqCst);
- }
-
- /// Queue `n` test-only forced transient FS failures for the rename
- /// stage. Separate from the write counter so tests can exercise the
- /// rename retry loop in isolation (PR #3364 review feedback).
- #[cfg(test)]
- pub(super) fn force_next_rename_failures(&self, n: usize) {
- self.force_transient_failures_rename
- .store(n, Ordering::SeqCst);
- }
-
- /// Test introspection: how many forced write-stage failures are still
- /// queued.
- #[cfg(test)]
- pub(super) fn remaining_forced_write_failures(&self) -> usize {
- self.force_transient_failures_write.load(Ordering::SeqCst)
- }
-
- /// Test introspection: how many forced rename-stage failures are still
- /// queued.
- #[cfg(test)]
- pub(super) fn remaining_forced_rename_failures(&self) -> usize {
- self.force_transient_failures_rename.load(Ordering::SeqCst)
- }
-
- /// Queue a single test-only forced `StorageFull` lock-create failure. The
- /// next `acquire_lock` returns the synthetic disk-full error so tests can
- /// drive the lock-free read-only fallback in [`AuthProfilesStore::load`].
- #[cfg(test)]
- pub(super) fn force_next_lock_unwritable(&self) {
- self.force_lock_unwritable.store(true, Ordering::SeqCst);
- }
-
- fn encrypt_optional(&self, value: Option<&str>) -> Result<Option<String>> {
- match value {
- Some(value) if !value.is_empty() => self.secret_store.encrypt(value).map(Some),
- Some(_) | None => Ok(None),
- }
- }
-
- fn decrypt_optional(&self, value: Option<&str>) -> Result<(Option<String>, Option<String>)> {
- match value {
- Some(value) if !value.is_empty() => {
- let (plaintext, migrated) = self.secret_store.decrypt_and_migrate(value)?;
- Ok((Some(plaintext), migrated))
- }
- Some(_) | None => Ok((None, None)),
- }
- }
-
- fn acquire_lock(&self) -> Result<AuthProfileLockGuard> {
- // Test-only: simulate a full / read-only filesystem that can't create
- // the lock file, to drive the read-only fallback in `load`.
- #[cfg(test)]
- if self.force_lock_unwritable.swap(false, Ordering::SeqCst) {
- let io = std::io::Error::from(std::io::ErrorKind::StorageFull);
- return Err(annotate_lock_create_failure(
- anyhow::Error::new(io).context("open lock file"),
- ));
- }
-
- if let Some(parent) = self.lock_path.parent() {
- fs::create_dir_all(parent)
- .with_context(|| "Failed to create auth profile lock directory".to_string())?;
- }
-
- // Drive timeout + stale-recheck off wall-clock elapsed time, not the
- // sum of explicit `thread::sleep(LOCK_WAIT_MS)` calls. The earlier
- // counter-based approach excluded time spent inside
- // `retry_with_backoff` (which can sleep up to ~30s on its own
- // schedule before returning AlreadyExists) and the lock-file I/O
- // syscalls. Under Windows AV contention that drift could push
- // both `LOCK_TIMEOUT_MS` and `next_stale_recheck_ms` significantly
- // later than intended.
- let started_at = Instant::now();
-
- // Serialize same-process acquirers on an in-memory lock keyed by this
- // path before we ever touch the on-disk lock file. Two things depend on
- // holding it: (1) concurrent `app_state_snapshot` calls in this process
- // queue here instead of racing `create_new`/`Drop` on the file, and
- // (2) it lets us treat an on-disk lock recording our own pid as a leaked
- // `Drop` unlink and reclaim it immediately — no other thread in this
- // process can hold a live guard while we own this in-memory lock (see
- // `reclaim_self_owned_lock`). Held for the lifetime of the returned
- // guard.
- //
- // Use `try_lock` against the *same* `LOCK_TIMEOUT_MS` budget as the
- // on-disk wait rather than a blocking `lock()`: a wedged in-process
- // holder must not be able to strand an RPC/blocking worker past the
- // timeout the caller (e.g. `app_state_snapshot`) expects. Poison is
- // recoverable — the `()` payload carries no invariant.
- let in_process_lock = in_process_lock_for(&self.lock_path);
- let in_process_guard = loop {
- match in_process_lock.try_lock() {
- Ok(guard) => break guard,
- Err(TryLockError::Poisoned(poisoned)) => break poisoned.into_inner(),
- Err(TryLockError::WouldBlock) => {
- if started_at.elapsed().as_millis() as u64 >= LOCK_TIMEOUT_MS {
- anyhow::bail!("Timed out waiting for auth profile lock");
- }
- thread::sleep(Duration::from_millis(LOCK_WAIT_MS));
- }
- }
- };
-
- let mut cleared_stale = false;
- // Periodically re-probe for stale locks during the busy-wait. A
- // lock that started fresh (live pid, recent mtime) can age past
- // STALE_LOCK_AGE_MS while we wait, and we want to recover from
- // that without bailing at the LOCK_TIMEOUT_MS boundary.
- let mut next_stale_recheck_ms: u64 = 1_000;
- loop {
- let open_result = crate::util::retry_with_backoff(
- "create auth profile lock",
- 6,
- 100,
- || {
- OpenOptions::new()
- .create_new(true)
- .write(true)
- .open(&self.lock_path)
- .context("open lock file")
- },
- );
-
- match open_result {
- Ok(mut file) => {
- // Issue #1612 — writing the pid line is what later lets
- // a future acquirer recognise a crashed owner; if the
- // write fails we must NOT report the lock as held with
- // a malformed/empty file behind us, or stale recovery
- // would silently degrade to the full 10s timeout for
- // every subsequent acquire.
- if let Err(e) = writeln!(file, "pid={}", std::process::id()) {
- let _ = fs::remove_file(&self.lock_path);
- return Err(e).with_context(|| {
- "Failed to write auth profile lock owner".to_string()
- });
- }
- return Ok(AuthProfileLockGuard {
- lock_path: self.lock_path.clone(),
- _in_process: in_process_guard,
- });
- }
- Err(e) => {
- let is_already_exists = e
- .chain()
- .find_map(|e| e.downcast_ref::<std::io::Error>())
- .is_some_and(|ioe| ioe.kind() == std::io::ErrorKind::AlreadyExists);
-
- if is_already_exists {
- // A lock file recording our own pid can only be a
- // leaked `Drop` unlink: we hold the in-process lock, so
- // no live same-process guard exists. Reclaim it
- // immediately rather than spinning the 30s age floor
- // (`STALE_LOCK_AGE_MS`) that sits *behind* the ~10s RPC
- // timeout — that gap is what produced the sustained
- // "Timed out waiting for auth profile lock" retry storm
- // (Sentry TAURI-RUST-B1 / #2318). Cheap enough (one tiny
- // read) to re-probe every spin, which also self-heals a
- // lock our own `Drop` leaks mid-wait.
- if self.reclaim_self_owned_lock() {
- continue;
- }
- // Issue #1612 — a previous openhuman crash can leave a
- // stale auth-profiles.lock behind (a *different*, now-dead
- // pid, or an aged leak), after which every RPC path that
- // touches the auth profile store fails for the
- // `LOCK_TIMEOUT_MS` window and the user gets stuck in a
- // retry storm. Before falling back to the busy-wait, try
- // once to peek at the writer's recorded PID and remove
- // the lock if that process is no longer alive. Flag is
- // flipped on the first probe (not only on success) so a
- // live-pid / malformed / unreadable lock doesn't trigger
- // a fresh sysinfo probe + log line on every busy-wait
- // iteration.
- if !cleared_stale {
- cleared_stale = true;
- if self.clear_lock_if_stale() {
- continue;
- }
- } else {
- let elapsed_ms = started_at.elapsed().as_millis() as u64;
- if elapsed_ms >= next_stale_recheck_ms {
- // The age-based reclaim check is cheap (one
- // `fs::metadata` call in the common case) and
- // safely no-ops on fresh, legitimate locks.
- // Re-probing periodically lets us recover from
- // a leaked-mid-wait lock without bailing at
- // the 10s timeout.
- next_stale_recheck_ms = next_stale_recheck_ms.saturating_add(1_000);
- if self.clear_lock_if_stale() {
- continue;
- }
- }
- }
- if started_at.elapsed().as_millis() as u64 >= LOCK_TIMEOUT_MS {
- anyhow::bail!("Timed out waiting for auth profile lock");
- }
- thread::sleep(Duration::from_millis(LOCK_WAIT_MS));
- } else {
- // Sentry OPENHUMAN-TAURI-H8 collapses every
- // non-AlreadyExists, non-transient `create_new`
- // failure into a single fingerprint with no
- // breadcrumb of which OS code actually fired.
- // `annotate_lock_create_failure` embeds the
- // underlying `io::ErrorKind` + `raw_os_error()` so
- // future events split by root cause and we can
- // widen `is_transient_fs_error` (or fix the
- // underlying condition) for whichever code is hot.
- return Err(annotate_lock_create_failure(e));
- }
- }
- }
- }
- }
-
- /// Returns `true` if an existing lock file was detected as stale and
- /// successfully removed. Two cases reclaim:
- ///
- /// 1. The recorded `pid=` line points at a process that is no longer
- /// running — classic crashed-owner recovery (Issue #1612).
- /// 2. The lock file's mtime is older than [`STALE_LOCK_AGE_MS`]. This
- /// catches a *different* still-alive process that leaked its lock (its
- /// `AuthProfileLockGuard::drop` could not unlink the file — e.g. Windows
- /// AV / indexer briefly held a handle — and orphaned it with that live
- /// pid inside). No legitimate auth-profile op holds the lock long enough
- /// to be affected, so a too-old lock is unambiguously a leak. A lock
- /// leaked by *this* process is handled far sooner — immediately, without
- /// the age floor — by [`reclaim_self_owned_lock`](Self::reclaim_self_owned_lock),
- /// which is sound because acquirers serialize on the in-process lock.
- ///
- /// 3. The lock file has no parseable `pid=` line and is older than
- /// [`MALFORMED_LOCK_GRACE_MS`]. A healthy holder writes its pid within
- /// microseconds of `create_new`, so a pidless lock past that short
- /// grace is an abandoned in-flight writer (crashed/killed between
- /// `create_new` and the `pid=` write) — reclaim it rather than make
- /// every reader spin the full [`STALE_LOCK_AGE_MS`]/`LOCK_TIMEOUT_MS`
- /// window (the ~30s "stuck on Initializing OpenHuman" after a
- /// kill+reopen). The grace is short but non-zero so we never reclaim a
- /// live writer that is mid-`create_new`/`pid=`.
- fn clear_lock_if_stale(&self) -> bool {
- let metadata = match fs::metadata(&self.lock_path) {
- Ok(m) => m,
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return false,
- Err(e) => {
- tracing::warn!(
- target: "auth-profiles",
- "[credentials] failed to stat lock file at {} for stale check: {e}",
- self.lock_path.display()
- );
- return false;
- }
- };
-
- let age = metadata
- .modified()
- .ok()
- .and_then(|mtime| std::time::SystemTime::now().duration_since(mtime).ok());
- let too_old = age.is_some_and(|a| a >= Duration::from_millis(STALE_LOCK_AGE_MS));
- // A pidless lock needs only a short grace: no healthy holder leaves the
- // file without a `pid=` line for more than the microsecond gap between
- // `create_new` and the write, so anything older is abandoned. If mtime
- // is unreadable (clock skew, platform limitation) default to stale —
- // no legitimate in-flight writer would be undetectable for that long.
- let malformed_too_old =
- age.is_none_or(|a| a >= Duration::from_millis(MALFORMED_LOCK_GRACE_MS));
-
- let content = match fs::read_to_string(&self.lock_path) {
- Ok(s) => s,
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return false,
- Err(e) => {
- tracing::warn!(
- target: "auth-profiles",
- "[credentials] failed to read lock file at {} for stale check: {e}",
- self.lock_path.display()
- );
- return false;
- }
- };
-
- let pid = content
- .lines()
- .find_map(|line| line.trim().strip_prefix("pid=")?.trim().parse::<u32>().ok());
-
- let reclaim_reason: Option<String> = match pid {
- Some(pid) if !is_pid_alive(pid) => Some(format!("pid {pid} not alive")),
- Some(pid) if too_old => Some(format!(
- "lock file older than {STALE_LOCK_AGE_MS}ms (recorded pid {pid}, presumed leaked)"
- )),
- None if malformed_too_old => Some(format!(
- "no parseable pid and older than {MALFORMED_LOCK_GRACE_MS}ms \
- (abandoned in-flight lock, reclaiming)"
- )),
- Some(_) => return false,
- None => {
- tracing::warn!(
- target: "auth-profiles",
- "[credentials] lock at {} has no parseable pid line and is younger than \
- {MALFORMED_LOCK_GRACE_MS}ms; leaving in place briefly",
- self.lock_path.display()
- );
- return false;
- }
- };
-
- let Some(reason) = reclaim_reason else {
- return false;
- };
-
- match fs::remove_file(&self.lock_path) {
- Ok(()) => {
- tracing::info!(
- target: "auth-profiles",
- "[credentials] removed stale auth profile lock at {} ({reason})",
- self.lock_path.display()
- );
- true
- }
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
- Err(e) => {
- tracing::warn!(
- target: "auth-profiles",
- "[credentials] failed to remove stale lock at {} ({reason}): {e}",
- self.lock_path.display()
- );
- false
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_03.rs b/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_03.rs
deleted file mode 100644
index f7653f4715..0000000000
--- a/crates/openhuman-core/src/security/credentials/profiles_impl_01_part_03.rs
+++ /dev/null
@@ -1,80 +0,0 @@
-
-impl AuthProfilesStore {
- /// Remove the on-disk lock file **iff** it records this process's own pid.
- /// Returns `true` when a self-owned lock was found and removed.
- ///
- /// MUST only be called while holding this path's in-process lock (acquired
- /// at the top of [`acquire_lock`](Self::acquire_lock) via
- /// [`in_process_lock_for`]). That invariant is what makes the removal safe:
- /// same-process acquirers serialize on the in-process lock, so no other
- /// thread in this process can be holding a live `AuthProfileLockGuard` while
- /// we run. A lock file carrying our own pid is therefore necessarily a leak
- /// — a previous guard's `Drop` could not unlink it (on Windows, AV / the
- /// Search indexer briefly hold a handle on the just-written file) and
- /// orphaned it with our still-alive pid inside.
- ///
- /// This is the fast self-heal for Sentry TAURI-RUST-B1 (#2318): without it
- /// the only recovery for a leaked-but-live-pid lock is the age branch in
- /// [`clear_lock_if_stale`](Self::clear_lock_if_stale), whose
- /// [`STALE_LOCK_AGE_MS`] floor (30s) is far longer than the ~10s RPC
- /// timeout, so every `app_state_snapshot` timed out and retry-stormed for
- /// the whole 30s window before age-reclaim kicked in.
- fn reclaim_self_owned_lock(&self) -> bool {
- let me = std::process::id();
- tracing::trace!(
- target: "auth-profiles",
- "[credentials] probing for self-owned leaked lock at {} (our pid {me})",
- self.lock_path.display()
- );
- let content = match fs::read_to_string(&self.lock_path) {
- Ok(s) => s,
- // NotFound: already gone (raced with another reclaim / the guard's
- // own Drop). Any other read error: fall back to the age-based and
- // busy-wait paths rather than guess at ownership.
- Err(e) => {
- tracing::debug!(
- target: "auth-profiles",
- "[credentials] self-owned probe could not read lock at {} ({e}); \
- deferring to stale/busy-wait recovery",
- self.lock_path.display()
- );
- return false;
- }
- };
-
- let pid = content
- .lines()
- .find_map(|line| line.trim().strip_prefix("pid=")?.trim().parse::<u32>().ok());
- if pid != Some(me) {
- tracing::trace!(
- target: "auth-profiles",
- "[credentials] lock at {} is not self-owned (recorded {pid:?}, our pid {me}); \
- deferring to stale/busy-wait recovery",
- self.lock_path.display()
- );
- return false;
- }
-
- match fs::remove_file(&self.lock_path) {
- Ok(()) => {
- tracing::info!(
- target: "auth-profiles",
- "[credentials] reclaimed leaked self-owned auth profile lock at {} \
- (recorded our own live pid {me}; a prior guard's Drop unlink was blocked, \
- most likely by Windows AV/indexer)",
- self.lock_path.display()
- );
- true
- }
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
- Err(e) => {
- tracing::warn!(
- target: "auth-profiles",
- "[credentials] failed to reclaim self-owned auth profile lock at {}: {e}",
- self.lock_path.display()
- );
- false
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
index 21012c33a8..a4681eb908 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -15,7 +15,7 @@ use crate::security::prompt_injection::{
use super::super::event_bus::publish_web_channel_event;
use super::super::run_task::run_chat_task;
-use super::super::types::ChatRequestMetadata;
+use super::super::types::{ChatRequestMetadata, InFlightEntry};
use super::super::web_errors::classify_inference_error;
use super::parallel_turn::spawn_parallel_turn;
use super::state::{cancel_in_flight_gracefully, key_for, IN_FLIGHT};