Skip to main content

agentmux_srv/server/agent_handlers/
identity_delete.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Deleting an identity account, whoever asks: the window's `deleteidentityaccount` and an
5//! agent's `Google disconnect` run this one function, so the grant is revoked at the provider,
6//! the secrets, links, Google grants and log are removed, and the windows and the agents that
7//! held it are told, the same way either time.
8
9use std::sync::Arc;
10
11use serde_json::json;
12
13use super::identity::{revoke_keeps_account, DeleteIdentityAccountResult};
14use crate::backend::mps::Broker;
15use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
16
17/// Revokes the account's grant at its provider, removes its credential material and rows, and
18/// announces it. With `require_revoke` a revoke that failed keeps the account (`deleted: false`),
19/// so the delete can be retried while the grant can still be ended.
20pub(crate) async fn delete_identity_account(
21    mstore: &Arc<Store>,
22    identity_store: &Arc<Store>,
23    broker: &Arc<Broker>,
24    id: &str,
25    require_revoke: bool,
26) -> Result<DeleteIdentityAccountResult, String> {
27    // The credential material goes BEFORE the row (layer 1 of
28    // ANALYSIS_ACCOUNT_DELETE_AUTH_LIFECYCLE_GAP_2026_07_14.md §4), best-effort: cleanup trouble
29    // never blocks the delete. The provider is read first so the log lines can carry it.
30    let acct = mstore.identity_get(id).ok().flatten();
31    let provider = acct.as_ref().map(|a| a.provider.clone()).unwrap_or_default();
32    let revoke_report = revoke_at_provider(mstore, acct.as_ref()).await;
33    if revoke_keeps_account(&revoke_report, require_revoke) {
34        return Ok(DeleteIdentityAccountResult {
35            deleted: false,
36            affected_agents: Vec::new(),
37            cleanup: serde_json::Value::Null,
38            revoke: revoke_report,
39        });
40    }
41    let cleanup_report = remove_secrets(acct.clone(), identity_store).await;
42    if acct.as_ref().is_some_and(|a| matches!(a.secret_ref, SecretRef::Vault { .. })) {
43        crate::server::vault_handlers::publish_change(broker);
44    }
45    let outcome = mstore
46        .identity_delete(id)
47        .map_err(|e| format!("deleteidentityaccount: {e}"))?;
48    let deleted = outcome.deleted;
49    if deleted {
50        release_sign_in_values(acct.as_ref(), &revoke_report, &cleanup_report);
51    }
52    // Links live in identity_store, not the store holding the account row, so the cascade above
53    // finds none (SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md): remove the real rows here and merge the
54    // two outcomes, or every delete would orphan its links.
55    let (links_cascaded_from_identity_store, mut affected_agents) = identity_store
56        .agent_identity_unlink_by_account(id)
57        .map_err(|e| format!("deleteidentityaccount: identity_store cleanup: {e}"))?;
58    let links_cascaded = outcome.links_cascaded + links_cascaded_from_identity_store;
59    affected_agents.extend(outcome.affected_agents);
60    affected_agents.sort();
61    affected_agents.dedup();
62    // Also remove the account's MIRROR row (identity_upsert_with_mirror's
63    // counterpart on delete) — without this, a stale copy of a
64    // deleted account survives in identity_store, and
65    // resolve_account's fallback would incorrectly resolve it
66    // again on the next spawn once id_store's own row is gone.
67    // Best-effort: a mirror cleanup failure must not block the
68    // real delete, which already succeeded above.
69    if let Err(e) = identity_store.identity_delete(id) {
70        tracing::warn!(
71            account_id = %id,
72            error = %e,
73            "deleteidentityaccount: identity_store mirror row cleanup failed (non-fatal)"
74        );
75    }
76    // A Google account's grants and call log go with it (connectors spec D4, D7).
77    if let Err(e) = identity_store.google_account_forget(id) {
78        tracing::warn!(account_id = %id, error = %e, "deleteidentityaccount: Google grants cleanup failed (non-fatal)");
79    }
80    if links_cascaded > 0 {
81        // info!, not debug!: the production filter is
82        // "agentmuxsrv=info,info" (reagent P1, PR #2143).
83        // "identity.delete:" is `muxlog auth` vocabulary.
84        tracing::info!(
85            account_id = %id,
86            provider = %provider,
87            links = links_cascaded,
88            "identity.delete: links cascaded"
89        );
90    }
91    tracing::info!(
92        account_id = %id,
93        provider = %provider,
94        deleted,
95        "identity.delete: account removed (deleteidentityaccount)"
96    );
97    if deleted {
98        tell_windows_and_agents(broker, id, &provider, &affected_agents);
99    }
100    Ok(DeleteIdentityAccountResult {
101        deleted,
102        // Layer 4: delete-time disclosure (spec §4).
103        affected_agents,
104        // Null when there was no account row to clean up after.
105        cleanup: cleanup_report,
106        revoke: revoke_report,
107    })
108}
109
110/// The values read from the account's sign-in files are no longer withheld from transcripts once the account is
111/// deleted, the provider has revoked the grant and the credential directory is removed. Otherwise (a grant not
112/// revoked, a directory kept or not removed) they stay withheld.
113pub(super) fn release_sign_in_values(acct: Option<&IdentityAccount>, revoke_report: &serde_json::Value, cleanup_report: &serde_json::Value) {
114    use crate::backend::storage::store::SecretRef;
115    let outcome_is = |report: &serde_json::Value, outcome: &str| report.get("outcome").and_then(|v| v.as_str()) == Some(outcome);
116    let gone = outcome_is(revoke_report, "revoked") && outcome_is(cleanup_report, "removed");
117    if let (true, Some(SecretRef::OAuthConfigDir { dir })) = (gone, acct.map(|a| &a.secret_ref)) {
118        crate::identity::resolver::release_sign_in(dir);
119    }
120}
121
122/// An OAuth grant is revoked at the provider first, while the token is still in the keychain;
123/// otherwise it would live on there (spec §7 "Disconnect"). Null when there's none.
124async fn revoke_at_provider(mstore: &Arc<Store>, acct: Option<&IdentityAccount>) -> serde_json::Value {
125    let Some(acct) = acct else { return serde_json::Value::Null };
126    use crate::identity::oauth_tokens::{revoke_before_delete, KeychainSecrets, LiveHttp};
127    // A GitHub grant made through the broker is ended there.
128    let report = match crate::identity::github_connect::revoke_before_delete(mstore, &KeychainSecrets, acct).await {
129        Some(report) => Some(report),
130        None => revoke_before_delete(&LiveHttp, &KeychainSecrets, acct).await,
131    };
132    report.unwrap_or(serde_json::Value::Null)
133}
134
135/// What the cleanup did, returned to Connectors so a login that couldn't be removed is reported,
136/// not hidden (SPEC_ARMORY_ACCOUNTS_DELETE_AND_INLINE_DETAIL_2026_10_04.md H3). Null when there
137/// was no account row to clean up after.
138async fn remove_secrets(acct: Option<IdentityAccount>, identity_store: &Arc<Store>) -> serde_json::Value {
139    let Some(acct) = acct else { return serde_json::Value::Null };
140    if matches!(acct.secret_ref, SecretRef::Vault { .. }) {
141        return remove_vault_entry(identity_store.clone(), acct).await;
142    }
143    // Containment root for OAuth dirs: only paths inside ~/.agentmux/shared/identities/ are ever
144    // removed (the legacy ~/.claude migration dir is the user's global CLI login: never ours to delete).
145    let identities_root = agentmux_common::DataPaths::from_env().map(|p| p.identities_dir());
146    match tokio::task::spawn_blocking(move || crate::identity::cleanup::cleanup_account_secrets(&acct, identities_root.as_deref())).await {
147        Ok(outcome) => outcome.report(),
148        Err(e) => json!({ "outcome": "failed", "detail": e.to_string() }),
149    }
150}
151
152/// An API key account's key is a Vault entry: it goes with the account. A failure is reported like a keychain one.
153async fn remove_vault_entry(identity_store: Arc<Store>, account: IdentityAccount) -> serde_json::Value {
154    match tokio::task::spawn_blocking(move || crate::backend::vault::account_key::remove(&identity_store, &account.id, &account.secret_ref)).await {
155        Ok(Ok(())) => json!({ "outcome": "removed" }),
156        Ok(Err(e)) => json!({ "outcome": "failed", "detail": e }),
157        Err(e) => json!({ "outcome": "failed", "detail": e.to_string() }),
158    }
159}
160
161/// The windows read the accounts again, and each agent that held the account hears its credentials
162/// were revoked.
163fn tell_windows_and_agents(broker: &Arc<Broker>, id: &str, provider: &str, affected_agents: &[String]) {
164    broker.publish_event::<crate::backend::mps_events::IdentityAccountsChanged>(&(), vec![], 0);
165    // Layer 2 — running-agent reconciliation (spec SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md
166    // §3): the cascaded links name agents that may have a LIVE process still holding this account's
167    // tokens. We surface, not hard-kill — a per-agent revocation event drives the pane chip;
168    // enforcement lands at the next spawn (layer 3). Also poke the per-agent link-changed event so
169    // link tables refresh.
170    if affected_agents.is_empty() {
171        return;
172    }
173    // info!, not debug!: the production filter is "agentmuxsrv=info,info". "identity.delete:" is
174    // `muxlog auth` vocabulary.
175    tracing::info!(
176        account_id = %id,
177        provider = %provider,
178        count = affected_agents.len(),
179        agent_ids = %affected_agents.join(","),
180        "identity.delete: running agent(s) affected"
181    );
182    for agent_id in affected_agents {
183        broker.publish_event_for::<crate::backend::mps_events::AgentIdentitiesChanged>(agent_id, &(), vec![], 0);
184        let revoked = crate::backend::mps_events::CredentialsRevokedEvent {
185            credentials_revoked: true,
186            provider: provider.to_string(),
187            account_id: Some(id.to_string()),
188        };
189        broker.publish_event_for::<crate::backend::mps_events::AgentCredentialsRevoked>(agent_id, &revoked, vec![], 0);
190    }
191}
192
193#[cfg(test)]
194#[path = "identity_delete_tests.rs"]
195mod tests;