Skip to main content

agentmux_srv_core/identity/
cleanup.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! On-disk / keychain credential cleanup for a deleted identity account.
5//!
6//! Layer 1 of the account-delete auth-lifecycle remediation
7//! (`docs/analysis/ANALYSIS_ACCOUNT_DELETE_AUTH_LIFECYCLE_GAP_2026_07_14.md`
8//! §4 option 1): deleting an account row must not leave its credential
9//! material behind. Two secret backends carry on-host state:
10//!
11//! - `SecretRef::Keychain` — delete the OS-keychain entry (moved here
12//!   from the inline block in the `deleteidentityaccount` handler).
13//! - `SecretRef::OAuthConfigDir { dir }` — the CLI's live access +
14//!   refresh tokens sit in that directory; remove the tree, **except the
15//!   provider's conversation history** (`ProviderConfig::history_native_subdir`,
16//!   e.g. Claude's `projects/`), which lives in the same directory when
17//!   auth is shared. History and credentials are separate persistence
18//!   categories (SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md
19//!   P1); deleting a login must not delete the conversations
20//!   (SPEC_ARMORY_ACCOUNTS_DELETE_AND_INLINE_DETAIL_2026_10_04.md H1). This is
21//!   best-effort and **containment-guarded**: the dir is only removed
22//!   when it resolves INSIDE the agentmux identities root
23//!   (`~/.agentmux/shared/identities/`). The legacy `~/.claude`
24//!   migration case (and any other ambient/global CLI dir) is the
25//!   user's own login — log and skip, never delete.
26//!
27//! Other variants (`Env`, `SecretsManager`, `PlaintextDev`) hold no
28//! agentmux-owned on-host state → no-op.
29//!
30//! All log lines use the `identity.delete:` prefix so they land in the
31//! `muxlog auth` vocabulary (regex `identity\.(unlink|delete|self\.|account)`),
32//! and use `info!`/`warn!` — the production filter is
33//! "agentmuxsrv=info,info", so `debug!` would be invisible (reagent P1,
34//! PR #2143). Provider-side token revocation (running the CLI's own
35//! `logout` against the dir before deleting) is an explicit follow-up —
36//! it needs per-provider subprocess plumbing this module doesn't have.
37
38use std::path::{Path, PathBuf};
39use std::time::SystemTime;
40
41use crate::backend::providers::{all_providers, get_provider};
42use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
43
44/// What `cleanup_account_secrets` did, for callers/tests to assert on.
45/// Logging already happened inside the function.
46#[derive(Debug, PartialEq, Eq)]
47pub enum SecretCleanup {
48    /// Keychain entry removed (or was already absent — idempotent).
49    KeychainRemoved,
50    /// Keychain delete failed (logged as warn; account delete proceeds).
51    KeychainFailed(String),
52    /// OAuth config dir tree removed.
53    OAuthDirRemoved(PathBuf),
54    /// Everything in the OAuth config dir removed except the provider's
55    /// conversation history subdirectory, which was kept (so the dir
56    /// itself remains).
57    OAuthDirHistoryKept { dir: PathBuf, history: PathBuf },
58    /// OAuth config dir was already gone — nothing to remove.
59    OAuthDirAbsent(PathBuf),
60    /// OAuth config dir NOT removed: it does not resolve inside the
61    /// agentmux identities root (e.g. the legacy `~/.claude` migration
62    /// account), or the root itself could not be resolved/canonicalized.
63    OAuthDirSkipped { dir: PathBuf, reason: String },
64    /// OAuth config dir removal failed (fs error; logged as warn).
65    OAuthDirFailed { dir: PathBuf, error: String },
66    /// Secret backend holds no agentmux-owned on-host state.
67    NoOp,
68}
69
70impl SecretCleanup {
71    /// The `cleanup` object `deleteidentityaccount` returns, so Connectors → Accounts can
72    /// say whether the saved login is really gone
73    /// (SPEC_ARMORY_ACCOUNTS_DELETE_AND_INLINE_DETAIL_2026_10_04.md §3.4).
74    /// `outcome` is `removed`, `absent`, `skipped`, `failed` or `none` (no
75    /// on-host secret).
76    pub fn report(&self) -> serde_json::Value {
77        let path = |p: &Path| p.to_string_lossy().to_string();
78        match self {
79            SecretCleanup::KeychainRemoved => serde_json::json!({ "outcome": "removed" }),
80            SecretCleanup::KeychainFailed(e) => serde_json::json!({ "outcome": "failed", "detail": e }),
81            SecretCleanup::OAuthDirRemoved(d) => serde_json::json!({ "outcome": "removed", "path": path(d) }),
82            SecretCleanup::OAuthDirHistoryKept { dir, history } => serde_json::json!({
83                "outcome": "removed", "path": path(dir), "historyKept": true, "historyPath": path(history),
84            }),
85            SecretCleanup::OAuthDirAbsent(d) => serde_json::json!({ "outcome": "absent", "path": path(d) }),
86            SecretCleanup::OAuthDirSkipped { dir, reason } => {
87                serde_json::json!({ "outcome": "skipped", "path": path(dir), "detail": reason })
88            }
89            SecretCleanup::OAuthDirFailed { dir, error } => {
90                serde_json::json!({ "outcome": "failed", "path": path(dir), "detail": error })
91            }
92            SecretCleanup::NoOp => serde_json::json!({ "outcome": "none" }),
93        }
94    }
95}
96
97/// Best-effort removal of the on-host credential material behind
98/// `acct.secret_ref`. Never returns `Err` — account deletion must not be
99/// blocked by cleanup trouble; every outcome is logged.
100///
101/// `identities_root` is the agentmux identities root
102/// (`DataPaths::identities_dir()`), `None` when `DataPaths::from_env()`
103/// could not resolve (CI / unusual envs) — OAuth dirs are then skipped,
104/// never guessed. Blocking (keyring + fs) — call via `spawn_blocking`
105/// from async contexts.
106pub fn cleanup_account_secrets(
107    acct: &IdentityAccount,
108    identities_root: Option<&Path>,
109) -> SecretCleanup {
110    match &acct.secret_ref {
111        SecretRef::Keychain { .. } => match crate::identity::secret_store::delete(&acct.id) {
112            Ok(()) => {
113                tracing::info!(
114                    account_id = %acct.id,
115                    provider = %acct.provider,
116                    "identity.delete: keychain secret removed"
117                );
118                SecretCleanup::KeychainRemoved
119            }
120            Err(e) => {
121                tracing::warn!(
122                    account_id = %acct.id,
123                    provider = %acct.provider,
124                    error = %e,
125                    "identity.delete: keychain secret delete failed"
126                );
127                SecretCleanup::KeychainFailed(e)
128            }
129        },
130        SecretRef::OAuthConfigDir { dir } => cleanup_oauth_dir(acct, Path::new(dir), identities_root),
131        // The Vault entry is deleted by the caller, which holds the store (`identity_delete`).
132        SecretRef::Env { .. } | SecretRef::SecretsManager { .. } | SecretRef::PlaintextDev { .. } | SecretRef::Vault { .. } => {
133            SecretCleanup::NoOp
134        }
135    }
136}
137
138fn cleanup_oauth_dir(
139    acct: &IdentityAccount,
140    dir: &Path,
141    identities_root: Option<&Path>,
142) -> SecretCleanup {
143    let skip = |reason: String| -> SecretCleanup {
144        tracing::warn!(
145            account_id = %acct.id,
146            provider = %acct.provider,
147            dir = %dir.display(),
148            reason = %reason,
149            "identity.delete: oauth config dir outside data root — skipped"
150        );
151        SecretCleanup::OAuthDirSkipped { dir: dir.to_path_buf(), reason }
152    };
153
154    let root = match identities_root {
155        Some(r) => r,
156        None => return skip("identities root unresolved (DataPaths::from_env() = None)".into()),
157    };
158    if !dir.exists() {
159        // Nothing on disk — already clean (e.g. the CLI never wrote tokens).
160        tracing::info!(
161            account_id = %acct.id,
162            provider = %acct.provider,
163            dir = %dir.display(),
164            "identity.delete: oauth config dir already absent"
165        );
166        return SecretCleanup::OAuthDirAbsent(dir.to_path_buf());
167    }
168    // Canonicalize BOTH sides so `..` segments, symlinks, and Windows
169    // `\\?\` prefixes can't defeat the containment check.
170    let canon_root = match std::fs::canonicalize(root) {
171        Ok(p) => p,
172        Err(e) => return skip(format!("identities root not canonicalizable: {e}")),
173    };
174    let canon_dir = match std::fs::canonicalize(dir) {
175        Ok(p) => p,
176        Err(e) => return skip(format!("dir not canonicalizable: {e}")),
177    };
178    // Strictly inside the root — refuse the root itself and anything
179    // outside it (the legacy `~/.claude` migration dir lands here).
180    if canon_dir == canon_root || !canon_dir.starts_with(&canon_root) {
181        return skip(format!(
182            "resolved path {} is not strictly inside identities root {}",
183            canon_dir.display(),
184            canon_root.display()
185        ));
186    }
187    let history = history_subdir_for(acct, &canon_dir);
188    match remove_credentials_keep_history(&canon_dir, history) {
189        Ok(Some(kept)) => {
190            tracing::info!(
191                account_id = %acct.id,
192                provider = %acct.provider,
193                dir = %dir.display(),
194                history = %kept.display(),
195                "identity.delete: oauth credentials removed, conversation history kept"
196            );
197            SecretCleanup::OAuthDirHistoryKept { dir: dir.to_path_buf(), history: kept }
198        }
199        Ok(None) => {
200            // Verify the removal actually took — a "removed" log that leaves
201            // the credential on disk is the exact login/logout-round bug this
202            // diagnostic exists to catch (e.g. a racing re-seed, a bind-mount,
203            // or a handle keeping the tree alive). Escalate to WARN if so.
204            if canon_dir.exists() {
205                tracing::warn!(
206                    account_id = %acct.id,
207                    provider = %acct.provider,
208                    dir = %dir.display(),
209                    "identity.delete: oauth config dir STILL PRESENT after remove_dir_all — credential not cleared"
210                );
211            } else {
212                tracing::info!(
213                    account_id = %acct.id,
214                    provider = %acct.provider,
215                    dir = %dir.display(),
216                    "identity.delete: oauth config dir removed (verified absent)"
217                );
218            }
219            SecretCleanup::OAuthDirRemoved(dir.to_path_buf())
220        }
221        // Gone between the `exists()` check above and the removal (a second
222        // delete racing this one): already clean.
223        Err(e) if e.kind() == std::io::ErrorKind::NotFound => SecretCleanup::OAuthDirAbsent(dir.to_path_buf()),
224        Err(e) => {
225            tracing::warn!(
226                account_id = %acct.id,
227                provider = %acct.provider,
228                dir = %dir.display(),
229                error = %e,
230                "identity.delete: oauth config dir removal failed"
231            );
232            SecretCleanup::OAuthDirFailed { dir: dir.to_path_buf(), error: e.to_string() }
233        }
234    }
235}
236
237/// The conversation-history subdirectory name for an OAuth config dir:
238/// from the account's provider, or else from the dir's own name, which is
239/// the provider's `auth_dir_name` (`identities/<account>/<auth_dir_name>/`).
240fn history_subdir_for(acct: &IdentityAccount, dir: &Path) -> Option<&'static str> {
241    if let Some(sub) = get_provider(&acct.provider).and_then(|p| p.history_native_subdir) {
242        return Some(sub);
243    }
244    history_subdir_for_auth_dir(dir.file_name()?.to_str()?)
245}
246
247fn history_subdir_for_auth_dir(auth_dir_name: &str) -> Option<&'static str> {
248    all_providers()
249        .find(|p| p.auth_dir_name == auth_dir_name)
250        .and_then(|p| p.history_native_subdir)
251}
252
253/// Remove `dir`, keeping its `history` child when that child is a real,
254/// non-empty directory. Returns the kept path, or `None` when the whole
255/// tree was removed.
256///
257/// A history child that is a link (a symlink, or a Windows junction — the
258/// isolated-auth redirect to the always-global history, see
259/// `identity_auth_dirs::link_history_if_isolated`) does not hold the
260/// history itself, so the whole tree goes; `remove_dir_all` removes the
261/// link without following it. An empty history child is nothing to keep.
262///
263/// Keeps removing the other entries after one fails, so one locked file
264/// doesn't leave the rest of the credential behind, then reports the first
265/// failure.
266fn remove_credentials_keep_history(dir: &Path, history: Option<&str>) -> std::io::Result<Option<PathBuf>> {
267    let keep = history.map(|h| dir.join(h)).filter(|h| {
268        std::fs::symlink_metadata(h).map(|m| m.file_type().is_dir()).unwrap_or(false)
269            && std::fs::read_dir(h).map(|mut it| it.next().is_some()).unwrap_or(false)
270    });
271    let Some(keep) = keep else {
272        std::fs::remove_dir_all(dir)?;
273        return Ok(None);
274    };
275    let mut first_err: Option<std::io::Error> = None;
276    for entry in std::fs::read_dir(dir)? {
277        let entry = entry?;
278        let path = entry.path();
279        if path == keep {
280            continue;
281        }
282        let res = match entry.file_type() {
283            Ok(ft) if ft.is_dir() => std::fs::remove_dir_all(&path),
284            // A file or a link: `remove_file` for files and Unix links,
285            // `remove_dir` for Windows directory links and junctions.
286            _ => std::fs::remove_file(&path).or_else(|_| std::fs::remove_dir(&path)),
287        };
288        if let Err(e) = res {
289            if e.kind() != std::io::ErrorKind::NotFound && first_err.is_none() {
290                first_err = Some(std::io::Error::new(e.kind(), format!("{}: {e}", path.display())));
291            }
292        }
293    }
294    match first_err {
295        Some(e) => Err(e),
296        None => Ok(Some(keep)),
297    }
298}
299
300enum PruneOutcome {
301    /// The whole account dir was removed.
302    Removed,
303    /// Credentials removed; at least one provider's conversation history kept.
304    HistoryKept,
305    /// The dir held nothing but already-kept history.
306    NothingToRemove,
307}
308
309/// Removes an orphaned account dir (`<root>/<account_id>/`), only if it
310/// resolves strictly inside `root` (the same escape guard
311/// `cleanup_oauth_dir` uses), except that each provider subdir's
312/// conversation history is kept, the same rule account delete follows
313/// (`remove_credentials_keep_history`). Without this, the sweep would
314/// delete, a few minutes later, the history that deleting the account kept.
315fn prune_orphan_keeping_history(dir: &Path, root: &Path) -> Result<PruneOutcome, String> {
316    let canon_root = std::fs::canonicalize(root).map_err(|e| format!("root not canonicalizable: {e}"))?;
317    let canon_dir = std::fs::canonicalize(dir).map_err(|e| format!("dir not canonicalizable: {e}"))?;
318    if canon_dir == canon_root || !canon_dir.starts_with(&canon_root) {
319        return Err(format!("{} is not strictly inside {}", canon_dir.display(), canon_root.display()));
320    }
321    let mut kept_any = false;
322    let mut removed_any = false;
323    for entry in std::fs::read_dir(&canon_dir).map_err(|e| e.to_string())? {
324        let entry = entry.map_err(|e| e.to_string())?;
325        let path = entry.path();
326        let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
327        let history = if is_dir {
328            path.file_name().and_then(|n| n.to_str()).and_then(history_subdir_for_auth_dir)
329        } else {
330            None
331        };
332        if let Some(h) = history {
333            // Already only history: leave it, and don't count it as a removal.
334            let only_history = std::fs::read_dir(&path)
335                .map(|it| it.flatten().all(|e| e.file_name() == h))
336                .unwrap_or(false);
337            if only_history && path.join(h).is_dir() {
338                kept_any = true;
339                continue;
340            }
341        }
342        if is_dir {
343            if remove_credentials_keep_history(&path, history).map_err(|e| e.to_string())?.is_some() {
344                kept_any = true;
345            }
346        } else {
347            std::fs::remove_file(&path).or_else(|_| std::fs::remove_dir(&path)).map_err(|e| e.to_string())?;
348        }
349        removed_any = true;
350    }
351    if kept_any {
352        return Ok(if removed_any { PruneOutcome::HistoryKept } else { PruneOutcome::NothingToRemove });
353    }
354    std::fs::remove_dir_all(&canon_dir).map_err(|e| e.to_string())?;
355    Ok(PruneOutcome::Removed)
356}
357
358/// Sweep `identities_root`'s direct children for orphaned per-account
359/// dirs: `compute_and_ensure_account_dir` mints a fresh `<account_id>/`
360/// dir and writes real credential files into it BEFORE the login that
361/// dir belongs to ever completes, so no `IdentityAccount` row exists yet
362/// to reference it. A login that's abandoned, times out, or crashes the
363/// app mid-flow leaves that directory behind forever — reagent's finding
364/// on #2260: "abandoned/failed attempts leave orphaned directories with
365/// no cleanup path."
366///
367/// Called opportunistically from `compute_and_ensure_account_dir` right
368/// before every FRESH mint (never on a reconnect — reusing an existing
369/// account's dir needs no sweep). Age-gated via `min_age_secs` so a
370/// login that's still genuinely in progress — which legitimately has no
371/// DB row yet either — is never swept out from under it; callers should
372/// pick a margin comfortably above every frontend poll timeout (5
373/// minutes as of this writing) to leave room for a slow user plus retry.
374///
375/// Best-effort and silent-safe: `identity_get` failures or an unreadable
376/// root skip that candidate (or the whole sweep) rather than risk
377/// deleting a real, in-use account's dir on a false read. Returns the
378/// dirs actually removed, mainly for tests to assert on.
379pub fn sweep_orphaned_account_dirs(
380    store: &Store,
381    identities_root: &Path,
382    min_age_secs: u64,
383) -> Vec<PathBuf> {
384    let mut removed = Vec::new();
385    let entries = match std::fs::read_dir(identities_root) {
386        Ok(e) => e,
387        Err(_) => return removed, // root doesn't exist yet — nothing to sweep
388    };
389    for entry in entries.flatten() {
390        let path = entry.path();
391        if !path.is_dir() {
392            continue;
393        }
394        let Some(account_id) = path.file_name().and_then(|n| n.to_str()) else {
395            continue;
396        };
397        match store.identity_get(account_id) {
398            // A real, persisted account — never touch it.
399            Ok(Some(_)) => continue,
400            Ok(None) => {}
401            Err(e) => {
402                tracing::warn!(
403                    account_id,
404                    error = %e,
405                    "identity.sweep: identity_get failed — skipping candidate rather than risk a false orphan"
406                );
407                continue;
408            }
409        }
410        let age_secs = match entry.metadata().and_then(|m| m.modified()) {
411            Ok(mtime) => SystemTime::now()
412                .duration_since(mtime)
413                .map(|d| d.as_secs())
414                .unwrap_or(0),
415            Err(_) => continue, // can't determine age — skip, don't guess
416        };
417        if age_secs < min_age_secs {
418            continue; // could still be a login in progress
419        }
420        match prune_orphan_keeping_history(&path, identities_root) {
421            // Only conversation history was left, already pruned: nothing to do.
422            Ok(PruneOutcome::NothingToRemove) => {}
423            Ok(PruneOutcome::HistoryKept) => {
424                tracing::info!(
425                    account_id,
426                    dir = %path.display(),
427                    age_secs,
428                    "identity.sweep: orphaned account dir pruned, conversation history kept"
429                );
430                removed.push(path);
431            }
432            Ok(PruneOutcome::Removed) => {
433                tracing::info!(
434                    account_id,
435                    dir = %path.display(),
436                    age_secs,
437                    "identity.sweep: orphaned account dir removed (no matching account row, past age threshold)"
438                );
439                removed.push(path);
440            }
441            Err(e) => {
442                tracing::debug!(account_id, dir = %path.display(), error = %e, "identity.sweep: candidate not removed");
443            }
444        }
445    }
446    removed
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452
453    fn acct_with(secret_ref: SecretRef) -> IdentityAccount {
454        IdentityAccount {
455            id: "acct-test".to_string(),
456            name: "asaf-anthropic".to_string(),
457            provider: "anthropic".to_string(),
458            kind: "oauth".to_string(),
459            display_name: String::new(),
460            secret_ref,
461            context: serde_json::json!({}),
462            status: "ok".to_string(),
463            created_at: 0,
464            updated_at: 0,
465        }
466    }
467
468    /// OAuthConfigDir inside the identities root → tree removed.
469    #[test]
470    fn oauth_dir_inside_data_root_is_removed() {
471        let tmp = tempfile::tempdir().unwrap();
472        let root = tmp.path().join("identities");
473        let dir = root.join("acct-test").join("claude");
474        std::fs::create_dir_all(&dir).unwrap();
475        std::fs::write(dir.join(".credentials.json"), "{}").unwrap();
476
477        let acct = acct_with(SecretRef::OAuthConfigDir {
478            dir: dir.to_string_lossy().to_string(),
479        });
480        let out = cleanup_account_secrets(&acct, Some(&root));
481
482        assert!(matches!(out, SecretCleanup::OAuthDirRemoved(_)), "got {out:?}");
483        assert!(!dir.exists(), "token dir must be gone");
484        // The account's parent folder under the root may remain; only the
485        // configured dir tree is removed.
486        assert!(root.exists(), "identities root itself must survive");
487    }
488
489    /// OAuthConfigDir OUTSIDE the identities root (the legacy `~/.claude`
490    /// migration case) → NOT removed, skip outcome.
491    #[test]
492    fn oauth_dir_outside_data_root_is_skipped() {
493        let tmp = tempfile::tempdir().unwrap();
494        let root = tmp.path().join("identities");
495        std::fs::create_dir_all(&root).unwrap();
496        // A stand-in for the user's global ~/.claude dir.
497        let ambient = tmp.path().join("dot-claude");
498        std::fs::create_dir_all(&ambient).unwrap();
499        std::fs::write(ambient.join(".credentials.json"), "{}").unwrap();
500
501        let acct = acct_with(SecretRef::OAuthConfigDir {
502            dir: ambient.to_string_lossy().to_string(),
503        });
504        let out = cleanup_account_secrets(&acct, Some(&root));
505
506        assert!(
507            matches!(out, SecretCleanup::OAuthDirSkipped { .. }),
508            "must refuse to delete outside the identities root, got {out:?}"
509        );
510        assert!(ambient.exists(), "ambient CLI dir must be untouched");
511        assert!(ambient.join(".credentials.json").exists());
512    }
513
514    /// A `..`-laden path that textually starts under the root but resolves
515    /// outside it must also be skipped (canonicalization guard).
516    #[test]
517    fn oauth_dir_dotdot_escape_is_skipped() {
518        let tmp = tempfile::tempdir().unwrap();
519        let root = tmp.path().join("identities");
520        std::fs::create_dir_all(&root).unwrap();
521        let ambient = tmp.path().join("dot-claude");
522        std::fs::create_dir_all(&ambient).unwrap();
523
524        let sneaky = root.join("..").join("dot-claude");
525        let acct = acct_with(SecretRef::OAuthConfigDir {
526            dir: sneaky.to_string_lossy().to_string(),
527        });
528        let out = cleanup_account_secrets(&acct, Some(&root));
529
530        assert!(matches!(out, SecretCleanup::OAuthDirSkipped { .. }), "got {out:?}");
531        assert!(ambient.exists());
532    }
533
534    /// Unresolvable identities root (DataPaths::from_env() = None) → skip,
535    /// never guess.
536    #[test]
537    fn oauth_dir_with_no_root_is_skipped() {
538        let tmp = tempfile::tempdir().unwrap();
539        let dir = tmp.path().join("identities").join("acct-test").join("claude");
540        std::fs::create_dir_all(&dir).unwrap();
541
542        let acct = acct_with(SecretRef::OAuthConfigDir {
543            dir: dir.to_string_lossy().to_string(),
544        });
545        let out = cleanup_account_secrets(&acct, None);
546
547        assert!(matches!(out, SecretCleanup::OAuthDirSkipped { .. }), "got {out:?}");
548        assert!(dir.exists(), "dir must be untouched when the root is unknown");
549    }
550
551    /// Already-absent dir → absent outcome, nothing created.
552    #[test]
553    fn oauth_dir_absent_is_noop() {
554        let tmp = tempfile::tempdir().unwrap();
555        let root = tmp.path().join("identities");
556        std::fs::create_dir_all(&root).unwrap();
557        let dir = root.join("acct-test").join("claude");
558
559        let acct = acct_with(SecretRef::OAuthConfigDir {
560            dir: dir.to_string_lossy().to_string(),
561        });
562        let out = cleanup_account_secrets(&acct, Some(&root));
563
564        assert!(matches!(out, SecretCleanup::OAuthDirAbsent(_)), "got {out:?}");
565        assert!(!dir.exists());
566    }
567
568    /// Env / dev variants hold no on-host state → no-op, filesystem untouched.
569    #[test]
570    fn env_and_dev_variants_touch_nothing() {
571        let tmp = tempfile::tempdir().unwrap();
572        let root = tmp.path().join("identities");
573        let canary = root.join("acct-test").join("claude");
574        std::fs::create_dir_all(&canary).unwrap();
575
576        for secret_ref in [
577            SecretRef::Env { env_var: "ANTHROPIC_API_KEY".to_string() },
578            SecretRef::PlaintextDev { plaintext_dev: "sk-dev".to_string() },
579            SecretRef::SecretsManager { sm_path: "path/x".to_string(), sm_json_path: None },
580        ] {
581            let out = cleanup_account_secrets(&acct_with(secret_ref), Some(&root));
582            assert_eq!(out, SecretCleanup::NoOp);
583        }
584        assert!(canary.exists(), "no filesystem side effects for non-oauth variants");
585    }
586
587    /// Keychain variant must never touch the filesystem (outcome depends on
588    /// the host's keychain — absent entry deletes idempotently, headless CI
589    /// may fail — but both are non-filesystem outcomes).
590    #[test]
591    fn keychain_variant_touches_no_filesystem() {
592        let tmp = tempfile::tempdir().unwrap();
593        let root = tmp.path().join("identities");
594        let canary = root.join("acct-test").join("claude");
595        std::fs::create_dir_all(&canary).unwrap();
596
597        // Deliberately unresolvable id so the delete is a guaranteed
598        // no-entry (idempotent Ok) on a dev machine's real keychain.
599        let mut acct = acct_with(SecretRef::Keychain {
600            service: "agentmux".to_string(),
601            account: "acct:zz-unit-test-never-provisioned".to_string(),
602        });
603        acct.id = "zz-unit-test-never-provisioned".to_string();
604        let out = cleanup_account_secrets(&acct, Some(&root));
605
606        assert!(
607            matches!(out, SecretCleanup::KeychainRemoved | SecretCleanup::KeychainFailed(_)),
608            "got {out:?}"
609        );
610        assert!(canary.exists(), "keychain cleanup must not touch the filesystem");
611    }
612
613    fn make_store() -> Store {
614        Store::open_in_memory().unwrap()
615    }
616
617    /// An orphaned dir (no matching `IdentityAccount` row) past the age
618    /// threshold is removed and reported.
619    #[test]
620    fn sweep_removes_orphaned_dir_past_age_threshold() {
621        let store = make_store();
622        let tmp = tempfile::tempdir().unwrap();
623        let root = tmp.path().join("identities");
624        let orphan = root.join("orphan-uuid").join("claude");
625        std::fs::create_dir_all(&orphan).unwrap();
626        std::fs::write(orphan.join(".credentials.json"), "{}").unwrap();
627
628        let removed = sweep_orphaned_account_dirs(&store, &root, 0);
629
630        assert_eq!(removed, vec![root.join("orphan-uuid")]);
631        assert!(!root.join("orphan-uuid").exists(), "orphaned dir must be gone");
632    }
633
634    /// A dir with a real, persisted `IdentityAccount` row is never swept,
635    /// no matter the age threshold — this is the guard that keeps an
636    /// in-use account's credentials safe.
637    #[test]
638    fn sweep_never_removes_a_dir_with_a_real_account_row() {
639        let store = make_store();
640        let tmp = tempfile::tempdir().unwrap();
641        let root = tmp.path().join("identities");
642        let real = root.join("real-account-id").join("claude");
643        std::fs::create_dir_all(&real).unwrap();
644
645        store
646            .identity_upsert(&IdentityAccount {
647                id: "real-account-id".to_string(),
648                name: "asaf-claude".to_string(),
649                provider: "claude".to_string(),
650                kind: "oauth".to_string(),
651                display_name: String::new(),
652                secret_ref: SecretRef::OAuthConfigDir {
653                    dir: real.to_string_lossy().to_string(),
654                },
655                context: serde_json::json!({}),
656                status: "valid".to_string(),
657                created_at: 0,
658                updated_at: 0,
659            })
660            .unwrap();
661
662        let removed = sweep_orphaned_account_dirs(&store, &root, 0);
663
664        assert!(removed.is_empty());
665        assert!(real.exists(), "a real account's dir must survive the sweep");
666    }
667
668    /// An orphaned dir younger than `min_age_secs` is left alone — it
669    /// could be a login that's still genuinely in progress.
670    #[test]
671    fn sweep_never_removes_a_dir_younger_than_the_age_threshold() {
672        let store = make_store();
673        let tmp = tempfile::tempdir().unwrap();
674        let root = tmp.path().join("identities");
675        let fresh = root.join("fresh-uuid").join("claude");
676        std::fs::create_dir_all(&fresh).unwrap();
677
678        // Effectively "just created" vs. an implausibly high age floor.
679        let removed = sweep_orphaned_account_dirs(&store, &root, 999_999);
680
681        assert!(removed.is_empty());
682        assert!(root.join("fresh-uuid").exists(), "a fresh in-progress dir must survive");
683    }
684
685    /// The identities root not existing yet (fresh install, nothing ever
686    /// minted) is a normal state, not an error — empty result, no panic.
687    #[test]
688    fn sweep_on_missing_root_returns_empty_without_panicking() {
689        let store = make_store();
690        let tmp = tempfile::tempdir().unwrap();
691        let root = tmp.path().join("identities-never-created");
692
693        let removed = sweep_orphaned_account_dirs(&store, &root, 0);
694
695        assert!(removed.is_empty());
696    }
697
698    fn claude_dir_with_history(root: &Path, account: &str) -> PathBuf {
699        let dir = root.join(account).join("claude");
700        std::fs::create_dir_all(dir.join("projects").join("C--work")).unwrap();
701        std::fs::create_dir_all(dir.join("sessions")).unwrap();
702        std::fs::write(dir.join(".credentials.json"), "{}").unwrap();
703        std::fs::write(dir.join("settings.json"), "{}").unwrap();
704        std::fs::write(dir.join("sessions").join("s.json"), "{}").unwrap();
705        std::fs::write(dir.join("projects").join("C--work").join("t.jsonl"), "{}").unwrap();
706        dir
707    }
708
709    /// Deleting a Claude account removes its login but keeps the
710    /// conversation history that shares its config dir
711    /// (SPEC_ARMORY_ACCOUNTS_DELETE_AND_INLINE_DETAIL_2026_10_04.md H1).
712    #[test]
713    fn oauth_delete_keeps_conversation_history() {
714        let tmp = tempfile::tempdir().unwrap();
715        let root = tmp.path().join("identities");
716        let dir = claude_dir_with_history(&root, "acct-test");
717        let mut acct = acct_with(SecretRef::OAuthConfigDir {
718            dir: dir.to_string_lossy().to_string(),
719        });
720        acct.provider = "claude".to_string();
721
722        let out = cleanup_account_secrets(&acct, Some(&root));
723
724        assert!(matches!(out, SecretCleanup::OAuthDirHistoryKept { .. }), "got {out:?}");
725        assert!(dir.join("projects").join("C--work").join("t.jsonl").exists(), "history must survive");
726        assert!(!dir.join(".credentials.json").exists(), "the login must be gone");
727        assert!(!dir.join("settings.json").exists());
728        assert!(!dir.join("sessions").exists());
729    }
730
731    /// The history subdir is found from the dir's own name when the
732    /// account's provider string isn't a registered provider id.
733    #[test]
734    fn oauth_delete_finds_history_by_dir_name() {
735        let tmp = tempfile::tempdir().unwrap();
736        let root = tmp.path().join("identities");
737        let dir = claude_dir_with_history(&root, "acct-test");
738        // acct_with's provider is "anthropic", not a registered provider id.
739        let acct = acct_with(SecretRef::OAuthConfigDir {
740            dir: dir.to_string_lossy().to_string(),
741        });
742
743        let out = cleanup_account_secrets(&acct, Some(&root));
744
745        assert!(matches!(out, SecretCleanup::OAuthDirHistoryKept { .. }), "got {out:?}");
746        assert!(dir.join("projects").join("C--work").join("t.jsonl").exists());
747        assert!(!dir.join(".credentials.json").exists());
748    }
749
750    /// An empty history dir is nothing to keep: the whole tree goes.
751    #[test]
752    fn oauth_delete_with_empty_history_removes_everything() {
753        let tmp = tempfile::tempdir().unwrap();
754        let root = tmp.path().join("identities");
755        let dir = root.join("acct-test").join("claude");
756        std::fs::create_dir_all(dir.join("projects")).unwrap();
757        std::fs::write(dir.join(".credentials.json"), "{}").unwrap();
758        let mut acct = acct_with(SecretRef::OAuthConfigDir {
759            dir: dir.to_string_lossy().to_string(),
760        });
761        acct.provider = "claude".to_string();
762
763        let out = cleanup_account_secrets(&acct, Some(&root));
764
765        assert!(matches!(out, SecretCleanup::OAuthDirRemoved(_)), "got {out:?}");
766        assert!(!dir.exists());
767    }
768
769    /// The orphan sweep follows the same rule: it removes the leftover
770    /// login but keeps history, and a second sweep finds nothing to do.
771    #[test]
772    fn sweep_keeps_history_of_an_orphaned_account_dir() {
773        let store = make_store();
774        let tmp = tempfile::tempdir().unwrap();
775        let root = tmp.path().join("identities");
776        let dir = claude_dir_with_history(&root, "deleted-uuid");
777
778        let removed = sweep_orphaned_account_dirs(&store, &root, 0);
779
780        assert_eq!(removed, vec![root.join("deleted-uuid")]);
781        assert!(dir.join("projects").join("C--work").join("t.jsonl").exists(), "history must survive the sweep");
782        assert!(!dir.join(".credentials.json").exists());
783        assert!(!dir.join("sessions").exists());
784
785        let again = sweep_orphaned_account_dirs(&store, &root, 0);
786        assert!(again.is_empty(), "history-only dir must not be reported again: {again:?}");
787        assert!(dir.join("projects").join("C--work").join("t.jsonl").exists());
788    }
789}