Skip to main content

agentmux_srv_core/identity/resolver/
errors.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Resolver error types: [`SpawnGateError`] and [`ResolverError`].
5//!
6//! Split out of the single ~2193-line `resolver.rs` (pure relocation, no
7//! behavior change).
8
9use crate::backend::storage::error::StoreError;
10
11/// Blocking spawn-gate error — layer 3 of
12/// SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md (§2.2).
13///
14/// Returned by the injection entry points when an **oauth-class** provider
15/// the agent is supposed to have credentials for (a binding exists, or the
16/// provider is the agent definition's own CLI provider) has no resolvable
17/// account. There is no per-agent opt-out. The spawn callers surface
18/// `Display` verbatim in the agent pane (same `error_during_execution`
19/// frame other spawn failures use) — the wording is the spec's.
20///
21/// Api-key-class bindings keep the historical log-and-skip behavior; this
22/// error exists only for the oauth class, where silent fallback meant the
23/// CLI would read the user's global login (`~/.claude`) after an account
24/// was deleted.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum SpawnGateError {
27    /// The gate's credentials verdict: no resolvable account. `linked` says
28    /// whether the agent has a link for the provider at all: `false` is an
29    /// agent no account was ever linked to (or whose link went with its
30    /// account), `true` a link to an account that is gone or unusable.
31    MissingCredentials { provider: String, linked: bool },
32    /// The injection task itself could not run to completion (task-join
33    /// failure — e.g. a panic inside the blocking closure, which also
34    /// poisons the `Store` mutex for every later call). The gate FAILS
35    /// CLOSED on this: an open fallback would silently convert one panic
36    /// anywhere in the store into a permanent, systemic bypass of the
37    /// oauth gate (#2164). A
38    /// blocked spawn is retryable and visible; a silent ambient launch
39    /// is neither.
40    InjectionUnavailable { detail: String },
41    /// The bound account's `SecretRef::OAuthConfigDir` resolves to the
42    /// provider's own literal ambient home directory (e.g. `~/.claude`)
43    /// instead of an AgentMux-isolated dir. Blocked unconditionally — a
44    /// real, currently-live account
45    /// configured exactly this way was found in this repo's own data
46    /// (`docs/status/STATUS_IDENTITY_ISOLATION_GATE_NOT_ENFORCING_2026_08_20.md`
47    /// §8); this variant is the enforcement that closes that gap. See
48    /// `docs/specs/SPEC_BLOCK_AMBIENT_HOME_DIR_IDENTITY_BINDING_2026_08_25.md`.
49    AmbientHomeDirNotAllowed { provider: String, dir: String },
50    /// Failed to seed the isolated Claude Code config dir's `CLAUDE.md`
51    /// placeholder (`providers::seed_claude_md_placeholder_if_missing`).
52    /// Blocked rather than warn-and-continue: an isolated dir with no
53    /// `CLAUDE.md` of its own is exactly the condition where Claude Code
54    /// CLI falls through to the operator's real `~/.claude/CLAUDE.md` —
55    /// continuing to spawn would launch the agent with the leak this
56    /// fix exists to close. See
57    /// `docs/specs/SPEC_ISOLATE_HOST_CLAUDE_MD_2026_08_31.md`.
58    ClaudeMdSeedFailed { provider: String, dir: String, error: String },
59    /// The block names an agent that was deleted (its row is gone and the
60    /// shared definition registry holds only a retired record for it). The
61    /// pane survived the delete — deleted from another window, or mid-spawn
62    /// — and used to spawn on the shared login with no identity at all; it
63    /// is refused instead (#3577).
64    AgentDeleted { agent_id: String },
65}
66
67impl std::fmt::Display for SpawnGateError {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        match self {
70            // Starts "this agent's" so muxspect's `classify_last_error_source`
71            // files it under "identity" with the other gate refusals, and
72            // carries "was deleted, so this pane cannot start" — the phrase
73            // `agents/failure.rs` classifies it by (no Retry: a retry is
74            // refused identically).
75            SpawnGateError::AgentDeleted { agent_id } => write!(
76                f,
77                "this agent's definition ({agent_id}) was deleted, so this pane cannot \
78                 start. Close the pane, or launch another agent in it.",
79            ),
80            // "Bind an account in Connectors" is now the ONLY path — the
81            // ambient/"use global CLI login" opt-in this used to also
82            // suggest was retired (PLAN_LOGIN_SINGLE_PATH_CONSOLIDATION_
83            // 2026_07_20.md §7): it let a credential the app couldn't
84            // attribute to any account run indefinitely, invisible to
85            // Connectors. Don't point users at a toggle that no longer works.
86            // Both keep "no credentials for {provider}:" and "Bind an account
87            // for this provider in Connectors", which `agents/failure.rs` and
88            // muxspect classify the refusal by.
89            SpawnGateError::MissingCredentials { provider, linked: true } => write!(
90                f,
91                "no credentials for {}: the bound account was deleted or is \
92                 unresolvable. Bind an account for this provider in Connectors → Accounts.",
93                provider,
94            ),
95            SpawnGateError::MissingCredentials { provider, linked: false } => write!(
96                f,
97                "no credentials for {provider}: no {provider} account is linked to this \
98                 agent. Bind an account for this provider in Connectors → Accounts.",
99            ),
100            SpawnGateError::InjectionUnavailable { detail } => write!(
101                f,
102                "credential injection could not run ({detail}); the spawn was \
103                 refused rather than falling back to the global CLI login. \
104                 Retry, and check `muxlog auth` if it persists.",
105            ),
106            SpawnGateError::AmbientHomeDirNotAllowed { provider, dir } => write!(
107                f,
108                "this agent's {provider} identity points directly at your personal \
109                 {provider} config directory ({dir}) instead of an isolated AgentMux \
110                 account — AgentMux no longer allows spawning an agent against your \
111                 own global CLI login. Re-bind this identity to an isolated account \
112                 in Connectors → Accounts (delete the current {provider} account and log \
113                 in again to create a fresh, isolated one), then retry.",
114            ),
115            SpawnGateError::ClaudeMdSeedFailed { provider, dir, error } => write!(
116                f,
117                "could not isolate this agent's {provider} config directory ({dir}): \
118                 {error}. Refusing to spawn with an unprotected config dir — retry, \
119                 and check the directory's permissions if it persists.",
120            ),
121        }
122    }
123}
124
125impl std::error::Error for SpawnGateError {}
126
127/// The `linked` of a no-binding refusal for `provider`, following the
128/// binding lookup: the agent's own links, or its template's (`""` for none)
129/// only when the agent has none. `false` only when those links were read and
130/// none is for the provider. The binding lookup turns a failed read into an
131/// empty list, so a read that fails here too counts as linked: the refusal
132/// then says the account is unresolvable, not that none is linked.
133pub(super) fn refusal_linked(identity_store: &crate::backend::storage::store::Store, agent_id: &str, template_id: &str, provider: &str) -> bool {
134    let for_provider = |links: Vec<crate::backend::storage::identities::AgentIdentityLink>| {
135        links.iter().any(|l| crate::backend::providers::resolve_provider_alias(&l.provider) == provider)
136    };
137    match identity_store.agent_identity_list_for_agent(agent_id) {
138        Err(_) => true,
139        Ok(own) if !own.is_empty() => for_provider(own),
140        Ok(_) if template_id.is_empty() => false,
141        Ok(_) => identity_store.agent_identity_list_for_agent(template_id).map_or(true, for_provider),
142    }
143}
144
145/// Errors specific to the resolver. Every variant is recoverable
146/// (the spawn proceeds with whatever env vars resolved successfully)
147/// — they exist for tracing visibility, not control flow.
148#[derive(Debug, thiserror::Error)]
149pub enum ResolverError {
150    #[error("env var not set in srv environment: {0}")]
151    EnvVarMissing(String),
152
153    /// The read from AWS Secrets Manager failed. The text is one of the Vault's fixed sentences about what went wrong
154    /// (`vault::aws_import`), never any of the secret.
155    #[error("AWS Secrets Manager: {0}")]
156    SecretsManagerRead(String),
157
158    #[error("PlaintextDev secrets are disabled in release builds")]
159    #[cfg(not(debug_assertions))]
160    PlaintextDevDisabledInRelease,
161
162    /// `OAuthConfigDir` is a filesystem pointer, not a secret string —
163    /// `resolve_secret` cannot turn it into a credential value because
164    /// the credential lives in a CLI-managed token file inside the dir.
165    /// Oauth-class providers must be routed through the config-dir
166    /// injection path that PR B adds to `inject_identity_env`. Seeing
167    /// this error from `resolve_secret` means the caller forgot to
168    /// dispatch by provider class first.
169    #[error("OAuthConfigDir is a config-dir pointer, not a resolvable secret — routed via the oauth-class injection path, not resolve_secret")]
170    OAuthConfigDirNotASecret,
171
172    /// The OS keychain read failed (no entry, locked store, or no Secret
173    /// Service agent). Account API keys (`SecretRef::Keychain`) live
174    /// in the OS keychain; this surfaces a resolution failure at spawn.
175    #[error("keychain error: {0}")]
176    KeychainError(String),
177
178    /// The Vault entry that holds an account's key could not be read (gone, or sealed with another Vault key).
179    #[error("vault error: {0}")]
180    VaultError(String),
181
182    #[error("storage error: {0}")]
183    Storage(#[from] StoreError),
184}
185
186#[cfg(test)]
187mod tests {
188    use super::refusal_linked;
189    use crate::backend::storage::agents::test_agent_def;
190    use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
191
192    fn agent(store: &Store, id: &str) {
193        store.agent_def_insert(&mut test_agent_def(id, id, "claude", "host", 0, "")).unwrap();
194    }
195
196    fn link(store: &Store, agent_id: &str, provider: &str) {
197        let account = format!("acct-{agent_id}-{provider}");
198        store
199            .identity_upsert(&IdentityAccount {
200                id: account.clone(),
201                name: account.clone(),
202                provider: provider.to_string(),
203                kind: "pat".to_string(),
204                display_name: String::new(),
205                secret_ref: SecretRef::OAuthConfigDir { dir: String::new() },
206                context: serde_json::json!({}),
207                status: "unknown".to_string(),
208                created_at: 0,
209                updated_at: 0,
210            })
211            .unwrap();
212        store.agent_identity_link(agent_id, &account, provider).unwrap();
213    }
214
215    /// "Not linked" only when the links were read and none is for the provider:
216    /// the agent's own, or its template's when it has a template.
217    #[test]
218    fn a_refusal_is_unlinked_only_when_no_link_for_the_provider_was_found() {
219        let store = Store::open_in_memory().unwrap();
220        for id in ["def-none", "def-other", "def-own", "tmpl"] {
221            agent(&store, id);
222        }
223        assert!(!refusal_linked(&store, "def-none", "", "claude"), "no links at all");
224        link(&store, "def-other", "codex");
225        assert!(!refusal_linked(&store, "def-other", "", "claude"), "a link for another provider only");
226        link(&store, "def-own", "claude");
227        assert!(refusal_linked(&store, "def-own", "", "claude"), "a link the gate couldn't resolve");
228        link(&store, "tmpl", "claude");
229        assert!(refusal_linked(&store, "def-none", "tmpl", "claude"), "its template's link");
230        assert!(!refusal_linked(&store, "def-other", "tmpl", "claude"), "an agent with links of its own doesn't use its template's");
231    }
232}