Skip to main content

agentmux_srv_core/identity/resolver/
inject_steps.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `inject_identity_env_with_broker`, one function each, in the order the gate runs
5//! them. They stay in the `inject` module tree (a child of `inject.rs`, where the gate and its tests
6//! live) so the gate is read and changed as one unit; the INV-A warning on
7//! `inject_identity_env_with_broker` covers every step here, `gate_oauth_failure` included.
8
9use super::*;
10
11use std::collections::HashSet;
12
13use crate::backend::storage::store::AgentInstance;
14
15/// A block with no active agent instance: nothing to inject, unless it names a deleted agent.
16pub(super) fn check_row_less_block(mstore: &Store, block_id: &str) -> Result<(), SpawnGateError> {
17    // #3577: a block that names an agent which was DELETED — its pane
18    // survived the delete (another window, or mid-spawn) — is refused,
19    // not spawned on the shared login with no identity. Only a
20    // positive "deleted" signal refuses; every other row-less block
21    // keeps today's behaviour.
22    if let Some(agent_id) = block_agent_id(mstore, block_id) {
23        if mstore.agent_was_deleted(&agent_id) {
24            return Err(SpawnGateError::AgentDeleted { agent_id });
25        }
26    }
27    // Otherwise the block has no agent instance row — nothing to
28    // inject, and no gating either: template sessions and quick-launch
29    // panes are outside the managed-credentials contract.
30    Ok(())
31}
32
33/// An empty or "blank" identity_id is expected on a modern launch, not a bypass: note it at debug
34/// with what actually resolves the credentials.
35///
36/// `identity_id` is a legacy column. A launch records a single account there only when it has
37/// one (reattach/fork/create); a plain launch has no single account pick, and credentials never
38/// resolve through this column — the layer-3 gate resolves the agent's per-provider account
39/// bindings (or, on a model route, the route) whether it is empty or not (#2463's bypass is
40/// closed by the binding/provider gate, steps 4-5, not by this line). A genuinely missing
41/// account is told by `gate_oauth_failure`'s own `identity.spawn.blocked` warning; this note
42/// explains the empty column without claiming a failure.
43///
44/// `resolve_bindings_for_instance` (step 3) keys strictly off `instance.definition_id`, so the
45/// outcome is the same whatever `identity_id` contains.
46pub(super) fn note_blank_identity(
47    instance: &AgentInstance,
48    block_id: &str,
49    bindings: &[IdentityBinding],
50    on_route: bool,
51) {
52    if !(instance.identity_id.is_empty() || instance.identity_id == "blank") {
53        return;
54    }
55    if on_route {
56        tracing::debug!(
57            target: "identity",
58            "instance {} has no launch account recorded (identity_id empty); it runs on a model \
59             route, so credentials come from the route",
60            block_id
61        );
62    } else if bindings.is_empty() {
63        tracing::debug!(
64            target: "identity",
65            "instance {} has no launch account recorded (identity_id empty) and no direct account \
66             links; the layer-3 gate decides",
67            block_id
68        );
69    } else {
70        tracing::debug!(
71            target: "identity",
72            "instance {} has no launch account recorded (identity_id empty); {} account binding(s) \
73             resolve credentials",
74            block_id,
75            bindings.len()
76        );
77    }
78}
79
80/// The agent definition's own CLI provider (canonical), and the launch's template parent.
81pub(super) fn definition_provider(mstore: &Store, id_store: &Store, instance: &AgentInstance) -> (Option<String>, String) {
82    // Layer-3 gate input: the agent definition's own CLI provider (the
83    // oauth-class provider every launch of this agent uses, whether or not
84    // a binding row exists for it). A missing definition row reads as no
85    // expected provider — the per-binding gate still applies to whatever
86    // links exist.
87    //
88    // Provider is resolved via `id_store.resolve_effective_provider_id`
89    // (`backend/storage/agents/definition.rs`), the one resolver `agent_open.rs`'s
90    // spawn path also uses, so this gate checks credentials for exactly the
91    // provider that will run: the agent's own, read-only after creation, or
92    // its bundle's when it has none (SPEC_AGENT_BUNDLE_FORMAT_V0_3_2026_10_05.md
93    // §3.1). One resolver for both call sites so they can't disagree (#2587).
94    //
95    // Canonicalized via `resolve_provider_alias` (codex P1 on PR #2377): a
96    // definition's own `provider` field predates this alias table in rare
97    // cases, and this value is compared in steps 4 and 5 against `injected_oauth` /
98    // `bindings`' raw (possibly aliased) provider strings — comparing
99    // uncanonicalized would let a genuinely-injected alias-only binding
100    // still trip the "no account bound" gate. Applied to the bundle-
101    // resolved value, not the raw column, so an aliased definition whose
102    // bundle already carries the canonical id doesn't get re-aliased
103    // incorrectly (resolve_provider_alias is idempotent on an
104    // already-canonical id, so this is safe either way).
105    match mstore.agent_def_get(&instance.definition_id) {
106        Ok(Some(d)) => {
107            let effective_provider = id_store.resolve_effective_provider_id(&d);
108            let template_parent_id = template_parent_id_if_seeded(mstore, &d.parent_id);
109            (
110                Some(resolve_provider_alias(&effective_provider).to_string()),
111                template_parent_id,
112            )
113        }
114        Ok(None) => (None, String::new()),
115        Err(e) => {
116            tracing::warn!(
117                target: "identity",
118                "definition lookup failed for {}: {}",
119                instance.definition_id,
120                e,
121            );
122            (None, String::new())
123        }
124    }
125}
126
127// Gate helper for an unresolvable oauth-class binding/provider. Always
128// blocks the spawn — an oauth-class provider must resolve to a real
129// bound IdentityAccount, full stop.
130//
131// `use_ambient_login` used to let this fall through to the user's
132// global/ambient CLI login instead of blocking. That escape hatch is
133// retired (PLAN_LOGIN_SINGLE_PATH_CONSOLIDATION_2026_07_20.md §7,
134// "single point, not global"): a credential the app can't attribute to
135// a specific account is exactly the state that left Marks
136// silently working with an untracked, unrefreshed shared-dir credential
137// and no visible account anywhere in Connectors. The flag is no longer read.
138pub(super) fn gate_oauth_failure(instance: &AgentInstance, provider: &str, linked: bool, detail: &str) -> Result<(), SpawnGateError> {
139    tracing::warn!(
140        target: "identity",
141        "identity.spawn.blocked: no credentials for provider {} \
142         (definition {}, identity {}) — {}; spawn refused \
143         (single-point enforcement)",
144        provider,
145        instance.definition_id,
146        instance.identity_id,
147        detail,
148    );
149    Err(SpawnGateError::MissingCredentials {
150        provider: provider.to_string(), linked,
151    })
152}
153
154/// The per-binding step (4): injects each binding's account into the spawn env, and remembers which
155/// oauth providers it injected for the unbound-provider gate that follows.
156pub(super) struct BindingInjector<'a> {
157    pub(super) id_store: &'a Arc<Store>,
158    pub(super) identity_store: &'a Arc<Store>,
159    pub(super) broker: Option<&'a Arc<Broker>>,
160    pub(super) instance: &'a AgentInstance,
161    /// Canonical ids of the oauth providers a binding injected.
162    pub(super) injected_oauth: HashSet<String>,
163    pub(super) mstore: &'a Store,
164    /// The agent definition's own provider, and whether it runs on a model server of its own.
165    pub(super) def_provider: Option<&'a str>,
166    pub(super) own_endpoint: bool,
167}
168
169impl BindingInjector<'_> {
170    // Step 4: per-binding resolution + env injection.
171    //
172    // Each binding's provider determines HOW its account contributes
173    // to the agent's env (SPEC_OAUTH_IDENTITY_BUNDLES §4.3):
174    //   - ApiKey  — resolve secret_ref to a string, inject as env var(s).
175    //   - OAuth   — expect SecretRef::OAuthConfigDir, inject its dir
176    //               as the provider's config-dir env var.
177    //
178    // Api-key-class per-binding failures (unknown provider, account row
179    // missing, mismatched secret_ref, secret resolution failed) are logged
180    // and skipped — other bindings still inject. Oauth-class failures go
181    // through the layer-3 gate, which always blocks.
182    pub(super) fn inject(&mut self, binding: &IdentityBinding, env_vars: &mut HashMap<String, String>) -> Result<(), SpawnGateError> {
183        let key_route = is_key_route_binding(binding, self.def_provider);
184        // The Claude account is discarded for an agent on its own endpoint: not injected, not required.
185        if self.own_endpoint && (key_route || resolve_provider_alias(&binding.provider) == "claude") {
186            return Ok(());
187        }
188        // An Anthropic API key on a Claude agent goes through the gateway: the agent never holds it.
189        if key_route {
190            if inject_key_route(self.mstore, self.id_store, self.identity_store, self.instance, binding, env_vars) {
191                self.injected_oauth.insert("claude".to_string());
192            }
193            return Ok(());
194        }
195        let class = match provider_class(&binding.provider) {
196            Some(c) => c,
197            None => {
198                tracing::warn!(
199                    target: "identity",
200                    "no provider class for {} (binding for identity {}) — skipping",
201                    binding.provider,
202                    self.instance.identity_id,
203                );
204                return Ok(());
205            }
206        };
207        let is_oauth_class = matches!(class, ProviderClass::OAuth { .. });
208
209        let Some((account, account_store)) = self.bound_account(binding, is_oauth_class)? else {
210            return Ok(());
211        };
212
213        match class {
214            ProviderClass::ApiKey { env_vars: env_keys } => {
215                self.inject_api_key(binding, env_keys, &account, env_vars);
216                Ok(())
217            }
218            ProviderClass::OAuth { config_dir_env_var } => {
219                self.inject_oauth(binding, config_dir_env_var, &account, &account_store, env_vars)
220            }
221        }
222    }
223
224    /// The binding's account, from this channel's store only (`resolve_account_for_spawn`). `None`
225    /// skips a binding that can't be read; an oauth-class one that can't is refused.
226    fn bound_account(&self, binding: &IdentityBinding, is_oauth_class: bool) -> Result<Option<(IdentityAccount, Arc<Store>)>, SpawnGateError> {
227        // Per-channel ONLY (see `resolve_account_for_spawn`) — a credential
228        // authenticated in another channel must not satisfy this spawn.
229        match resolve_account_for_spawn(self.id_store, &binding.account_id) {
230            Ok(Some(pair)) => Ok(Some(pair)),
231            Ok(None) => {
232                // The post-delete case (analysis §2.3): the link survived
233                // (or was cascaded and re-created stale) but the account
234                // row is gone. For oauth-class providers this is the
235                // load-bearing layer-3 gate — no more silent fallback to
236                // the user's global login.
237                if is_oauth_class {
238                    gate_oauth_failure(
239                        self.instance, &binding.provider, true,
240                        &format!("account {} row not found", binding.account_id),
241                    )?;
242                    return Ok(None);
243                }
244                tracing::warn!(
245                    target: "identity",
246                    "account {} bound to identity {} but row not found — skipping",
247                    binding.account_id,
248                    self.instance.identity_id,
249                );
250                Ok(None)
251            }
252            Err(e) => {
253                if is_oauth_class {
254                    gate_oauth_failure(
255                        self.instance, &binding.provider, true,
256                        &format!("account lookup failed for {}: {}", binding.account_id, e),
257                    )?;
258                    return Ok(None);
259                }
260                tracing::warn!(
261                    target: "identity",
262                    "account lookup failed for {}: {}",
263                    binding.account_id,
264                    e,
265                );
266                Ok(None)
267            }
268        }
269    }
270
271    /// An api-key-class binding: its secret goes into every env var the provider lists.
272    /// A secret that can't be resolved is logged and skipped; other bindings still inject.
273    fn inject_api_key(&self, binding: &IdentityBinding, env_keys: &[&str], account: &IdentityAccount, env_vars: &mut HashMap<String, String>) {
274        let secret = match resolve_account_secret(account, self.id_store, self.identity_store) {
275            Ok(s) => s,
276            Err(e) => {
277                tracing::warn!(
278                    target: "identity",
279                    "secret resolution failed for account {} (provider {}): {} — skipping",
280                    binding.account_id,
281                    binding.provider,
282                    e,
283                );
284                return;
285            }
286        };
287        // A key placed in an agent's environment is never written into a transcript.
288        crate::backend::transcript::withhold::register(&secret);
289        let env_key_count = env_keys.len();
290        for key in env_keys {
291            env_vars.insert(key.to_string(), secret.clone());
292        }
293        tracing::info!(
294            target: "identity",
295            "injected {} env var(s) for api-key provider {} (identity={}, account={})",
296            env_key_count,
297            binding.provider,
298            self.instance.identity_id,
299            binding.account_id,
300        );
301    }
302
303    /// An oauth-class binding: the account's config dir goes into the provider's config-dir env var,
304    /// after the isolation checks. Anything that can't be resolved is refused by the layer-3 gate.
305    fn inject_oauth(
306        &mut self,
307        binding: &IdentityBinding,
308        config_dir_env_var: &str,
309        account: &IdentityAccount,
310        account_store: &Arc<Store>,
311        env_vars: &mut HashMap<String, String>,
312    ) -> Result<(), SpawnGateError> {
313        // OAuth-class bindings expect SecretRef::OAuthConfigDir.
314        // Any other variant is a misconfiguration — the account is
315        // unresolvable for this provider, so it goes through the
316        // layer-3 gate rather than silently leaving the CLI on the
317        // user's global login.
318        let dir = match &account.secret_ref {
319            SecretRef::OAuthConfigDir { dir } => dir.clone(),
320            other => {
321                gate_oauth_failure(
322                    self.instance, &binding.provider, true,
323                    &format!(
324                        "non-OAuthConfigDir secret_ref ({:?}) on account {}",
325                        other, binding.account_id,
326                    ),
327                )?;
328                return Ok(());
329            }
330        };
331        self.refuse_unisolated_dir(binding, &dir)?;
332        env_vars.insert(config_dir_env_var.to_string(), dir.clone());
333        // Canonicalized (#2377) — see `definition_provider`;
334        // its provider is now canonical too, so
335        // this must match it on the same terms.
336        self.injected_oauth.insert(resolve_provider_alias(&binding.provider).to_string());
337        tracing::info!(
338            target: "identity",
339            "injected {} for oauth provider {} (identity={}, account={})",
340            config_dir_env_var,
341            binding.provider,
342            self.instance.identity_id,
343            binding.account_id,
344        );
345        self.link_conversation_history(binding, &dir);
346        self.refresh_oauth_status(binding, account, account_store, &dir);
347        Ok(())
348    }
349
350    /// Refuse a config dir that is the provider's ambient home, or whose CLAUDE.md isolation can't be seeded.
351    fn refuse_unisolated_dir(&self, binding: &IdentityBinding, dir: &str) -> Result<(), SpawnGateError> {
352        // Block unconditionally if this account's config dir IS the
353        // provider's literal ambient home (e.g. `~/.claude`) rather
354        // than an AgentMux-isolated dir — nothing upstream of this
355        // point validates that, and a real, currently-live account
356        // configured exactly this way was found in this repo's own
357        // data (docs/status/STATUS_IDENTITY_ISOLATION_GATE_NOT_ENFORCING_2026_08_20.md
358        // §8). See docs/specs/SPEC_BLOCK_AMBIENT_HOME_DIR_IDENTITY_BINDING_2026_08_25.md.
359        if let Some(provider_cfg) =
360            crate::backend::providers::get_provider(resolve_provider_alias(&binding.provider))
361        {
362            if crate::backend::providers::is_provider_ambient_home_dir(provider_cfg, dir) {
363                tracing::warn!(
364                    target: "identity",
365                    "identity.spawn.blocked: account {} for provider {} \
366                     resolves to the ambient home dir ({}) — refusing to \
367                     spawn (identity {})",
368                    binding.account_id,
369                    binding.provider,
370                    dir,
371                    self.instance.identity_id,
372                );
373                return Err(SpawnGateError::AmbientHomeDirNotAllowed {
374                    provider: binding.provider.clone(),
375                    dir: dir.to_string(),
376                });
377            }
378            // `dir` is confirmed NOT the ambient home at this point —
379            // but a genuinely separate isolated dir can still lack a
380            // CLAUDE.md of its own, which Claude Code CLI treats as
381            // "fall through to the real $HOME/.claude/CLAUDE.md,"
382            // not "no user-level memory file." Idempotent — cheap
383            // no-op after the first call. Fail closed (same as the
384            // ambient-home-dir check above) rather than warn-and-
385            // continue: Codex P1 + ReAgent P1 on PR #2854 — a
386            // warn-only failure here would launch the agent with
387            // exactly the unprotected condition this fix exists to
388            // close. See SPEC_ISOLATE_HOST_CLAUDE_MD_2026_08_31.md.
389            if let Err(e) =
390                crate::backend::providers::seed_claude_md_placeholder_if_missing(provider_cfg, dir)
391            {
392                tracing::warn!(
393                    target: "identity",
394                    "identity.spawn.blocked: account {} for provider {} \
395                     failed CLAUDE.md isolation seed ({}) — refusing to \
396                     spawn (identity {})",
397                    binding.account_id,
398                    binding.provider,
399                    e,
400                    self.instance.identity_id,
401                );
402                return Err(SpawnGateError::ClaudeMdSeedFailed {
403                    provider: binding.provider.clone(),
404                    dir: dir.to_string(),
405                    error: e.to_string(),
406                });
407            }
408            // Soft-fail: a missing setting costs old transcripts or a
409            // later compaction, not isolation, so it never blocks a spawn.
410            for (what, e) in crate::backend::providers::seed_managed_claude_settings(provider_cfg, dir) {
411                let (account, provider) = (&binding.account_id, &binding.provider);
412                tracing::warn!(target: "identity", "account {account} for provider {provider}: could not set {what} in {dir} ({e})");
413            }
414        }
415        Ok(())
416    }
417
418    /// Re-verify the conversation-history link on every spawn, best-effort and non-blocking.
419    fn link_conversation_history(&self, binding: &IdentityBinding, dir: &str) {
420        // (#2605) `dir` is read from this
421        // account's PREVIOUSLY STORED SecretRef::OAuthConfigDir —
422        // this is the ordinary spawn path, not `auth.start`, which
423        // is the only place that used to (re-)create the history
424        // link. An account provisioned before this whole feature
425        // shipped, or since its last `auth.start`, would otherwise
426        // never get linked at all. Re-verify/re-create it on every
427        // spawn instead, same best-effort, non-blocking guarantee
428        // as the rest of this function.
429        if let Some(paths) = agentmux_common::DataPaths::from_env() {
430            if let Some(provider_cfg) =
431                crate::backend::providers::get_provider(resolve_provider_alias(&binding.provider))
432            {
433                crate::identity::auth_dirs::link_history_if_isolated(
434                    &paths,
435                    std::path::Path::new(dir),
436                    provider_cfg,
437                    &binding.account_id,
438                    "inject_identity_env (spawn)",
439                );
440            }
441        }
442    }
443
444    /// Refine the account's status from the CLI's token file on disk. Best-effort: failures are logged.
445    fn refresh_oauth_status(&self, binding: &IdentityBinding, account: &IdentityAccount, account_store: &Arc<Store>, dir: &str) {
446        // Per spec §4.4 — cheap on-disk expiry probe. Reads the
447        // CLI's token file inside the bundle dir and refines
448        // the IdentityAccount's `status` so the UI can show
449        // valid/expired/needs_reauth. Best-effort: probe and
450        // upsert failures are logged + ignored (mirrors the
451        // per-binding "log + skip" pattern). The probe runs at
452        // every spawn but is a single `fs::read_to_string` +
453        // JSON parse — negligible overhead.
454        let now_ms = agentmux_common::time::now_ms();
455        // Canonicalized (codex P2 on PR #2377): probe_oauth_status
456        // only recognizes the canonical "claude"/"codex"/"openclaw"
457        // strings — passing a raw alias like "claude-code" always
458        // returned None, silently never refreshing an alias-bound
459        // account's status or publishing identityaccounts:changed.
460        let canonical_provider = resolve_provider_alias(&binding.provider);
461        let probed = probe_oauth_status(canonical_provider, dir, now_ms);
462        // Self-heal a stale false-positive (Codex P1, PR #2645): the
463        // macOS Keychain carve-out in oauth_probe.rs makes a missing
464        // token file return `None` for `claude` on macOS instead of
465        // `needs_reauth` — but an account probed BEFORE that
466        // carve-out existed may already have `needs_reauth`
467        // persisted from the old, buggy behavior. A `None` probe
468        // never upserts anything, so without this, an already-
469        // mislabeled account would stay stuck showing "reconnect"
470        // forever, even though this fix landed specifically to stop
471        // that. Correcting to "unknown" rather than "valid" — the
472        // probe genuinely can't tell on macOS, and a false "valid"
473        // would be exactly as dishonest as the "needs_reauth" this
474        // is fixing. Scoped tightly to the exact carve-out
475        // condition (not "any None"), so an unsupported provider's
476        // genuinely-earned needs_reauth (set by some other path)
477        // is never touched by this.
478        let new_status: Option<&'static str> = match probed {
479            Some(p) => Some(p.as_str()),
480            None if canonical_provider == "claude"
481                && cfg!(target_os = "macos")
482                && account.status == oauth_status::NEEDS_REAUTH =>
483            {
484                Some("unknown")
485            }
486            None => None,
487        };
488        if let Some(new_status) = new_status {
489            if account.status != new_status {
490                let mut updated = account.clone();
491                updated.status = new_status.to_string();
492                updated.updated_at = now_ms;
493                // Write back to whichever store the account was
494                // actually resolved from (`bound_account`) —
495                // not always id_store, since a fallback-mirror hit
496                // must update the mirror, not silently create a
497                // second, never-read copy in id_store.
498                match account_store.identity_upsert(&updated) {
499                    Ok(()) => {
500                        tracing::info!(
501                            target: "identity",
502                            provider = %binding.provider,
503                            account_id = %binding.account_id,
504                            old_status = %account.status,
505                            new_status,
506                            "oauth probe: status updated"
507                        );
508                        // Publish accounts-changed so any live
509                        // account list (Connectors → Accounts)
510                        // refreshes its Status
511                        // column without a reload — the account
512                        // row itself is what changed.
513                        if let Some(b) = self.broker {
514                            b.publish_event::<crate::backend::mps_events::IdentityAccountsChanged>(&(), vec![], 0);
515                        }
516                    }
517                    Err(e) => {
518                        tracing::warn!(
519                            target: "identity",
520                            provider = %binding.provider,
521                            account_id = %binding.account_id,
522                            error = %e,
523                            "oauth probe: identity_upsert failed — status not persisted",
524                        );
525                    }
526                }
527            }
528        }
529    }
530}
531
532/// Whether `binding` is an Anthropic API key linked to a Claude agent. Such a key is never put in the agent's
533/// environment: the agent is pointed at the gateway's key route instead ([`inject_key_route`]).
534pub(super) fn is_key_route_binding(binding: &IdentityBinding, def_provider: Option<&str>) -> bool {
535    def_provider == Some("claude") && binding.provider.eq_ignore_ascii_case(crate::backend::model_gateway::catalog::KEY_ROUTE_ID)
536}
537
538/// The folder an agent on an API key runs in (the provider's default one, whatever plan it was on before), for the
539/// readers that look where the spawn put it: the subagent watcher and the registration handler.
540pub(super) fn key_route_dir(bindings: &[IdentityBinding], provider: &str) -> Option<std::path::PathBuf> {
541    if !bindings.iter().any(|b| is_key_route_binding(b, Some(provider))) {
542        return None;
543    }
544    let config = crate::backend::providers::get_provider(provider)?;
545    crate::backend::providers::default_auth_dir(config).ok().map(std::path::PathBuf::from)
546}
547
548/// Point a Claude agent at the gateway's key route for the API-key account `binding` names: the gateway's address and
549/// the agent's token, and nothing of the key, which stays in the keychain and is read by the gateway for each request.
550/// A container agent is given the same: its container turn rewrites the address to one the container reaches and makes
551/// the token fresh and bound to the container (`container::key_route`).
552/// `Ok(true)` when the agent is set up; `Ok(false)` when it cannot be (no account, not a key, no srv address): the
553/// unbound-provider gate then refuses the spawn, as for any Claude agent with no usable account.
554pub(super) fn inject_key_route(
555    mstore: &Store,
556    id_store: &Arc<Store>,
557    identity_store: &Arc<Store>,
558    instance: &AgentInstance,
559    binding: &IdentityBinding,
560    env_vars: &mut HashMap<String, String>,
561) -> bool {
562    use crate::backend::model_gateway::{catalog, launch, token};
563    let account = match resolve_account_for_spawn(id_store, &binding.account_id) {
564        Ok(Some((a, _))) if a.kind == "api_key" => a,
565        other => {
566            tracing::warn!(target: "identity", account_id = %binding.account_id, found = other.as_ref().map_or(false, |o| o.is_some()), "the API-key account for the agent can't be used; the spawn gate decides");
567            return false;
568        }
569    };
570    let Ok(Some(def)) = mstore.agent_def_get(&instance.definition_id) else { return false };
571    // The gateway checks the agent's own link on every request, so a key link inherited from a template is not carried.
572    let own = identity_store.agent_identity_list_for_agent(&def.id).unwrap_or_default();
573    if !own.iter().any(|l| l.account_id == binding.account_id && l.provider.eq_ignore_ascii_case(catalog::KEY_ROUTE_ID)) {
574        tracing::warn!(target: "identity", account_id = %binding.account_id, "an API key account is carried only for an agent linked to it itself");
575        return false;
576    }
577    let Ok(local_url) = std::env::var("AGENTMUX_LOCAL_URL") else {
578        tracing::warn!(target: "identity", "srv's own address is not known; the API-key account can't be used for this spawn");
579        return false;
580    };
581    let token = token::token_for_account(&def.slug, &def.id, catalog::KEY_ROUTE_ID, &account.id);
582    env_vars.extend(launch::env_for_key_route(&token, &local_url));
583    // Not the folder of a plan account the agent was on: the key route has no sign-in of its own.
584    if let Some(dir) = crate::backend::providers::get_provider("claude").and_then(|p| crate::backend::providers::default_auth_dir(p).ok()) {
585        env_vars.insert("CLAUDE_CONFIG_DIR".to_string(), dir);
586    }
587    tracing::info!(target: "identity", account_id = %account.id, "pointed the agent at the gateway's key route");
588    true
589}
590
591/// Step 5: the agent's own oauth-class provider needs a bound account even when no binding row exists.
592pub(super) fn gate_unbound_provider(
593    def_provider: Option<String>,
594    injected_oauth: &HashSet<String>,
595    bindings: &[IdentityBinding],
596    identity_store: &Store,
597    instance: &AgentInstance,
598    parent_template_id: &str,
599) -> Result<(), SpawnGateError> {
600    // Step 5: definition-provider gate (spec §2.2 edge case). The agent's
601    // own CLI provider is an oauth-class provider it is "supposed to have
602    // credentials for" whether or not a binding row exists — an agent with
603    // NO binding for it (never bound, or the link was cascaded away by an
604    // account delete) must not silently launch on the user's global login.
605    // Bindings that existed but failed were already gated inside the loop,
606    // so this only fires for the genuinely-unbound case (no double logs).
607    if let Some(p) = def_provider {
608        if matches!(provider_class(&p), Some(ProviderClass::OAuth { .. }))
609            && !injected_oauth.contains(&p)
610            // Canonicalized (codex P1 on PR #2377): `b.provider` is the raw
611            // DB value and may still be a legacy alias even though `p` is
612            // canonical — without this, a binding that failed injection for
613            // an unrelated reason (already gated in `BindingInjector::inject`) would be
614            // misclassified as "no binding at all" here whenever it's
615            // stored under an alias.
616            && !bindings.iter().any(|b| resolve_provider_alias(&b.provider) == p)
617        {
618            gate_oauth_failure(instance, &p, refusal_linked(identity_store, &instance.definition_id, parent_template_id, &p), "no account bound for the agent's provider")?;
619        }
620    }
621    Ok(())
622}
623
624/// The last check: the agent can be deleted while the gate reads its definition and bindings.
625pub(super) fn recheck_agent_not_deleted(mstore: &Store, instance: &AgentInstance) -> Result<(), SpawnGateError> {
626    // #3577, re-checked at the gate's own exit: the instance resolved at step 1,
627    // but the agent can be deleted while this function reads its definition
628    // and bindings — then `def_provider` is `None`, `bindings` is empty, and
629    // the earlier steps pass vacuously (#3591). The
630    // only caller, `build_persistent_spawn_env`, re-checks again at its own
631    // last store read; this keeps the gate correct on its own.
632    if mstore.agent_was_deleted(&instance.id) {
633        return Err(SpawnGateError::AgentDeleted {
634            agent_id: instance.id.clone(),
635        });
636    }
637
638    Ok(())
639}
640
641/// Whether the agent runs on a model route (`model_gateway`): it is billed to the route's key and signs in nowhere, so the
642/// account gate does not apply to it.
643pub(super) fn on_model_route(mstore: &Store, instance: &AgentInstance) -> bool {
644    crate::backend::model_gateway::launch::choice_of(mstore, &instance.definition_id).is_some()
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650
651    /// A Claude agent in a pane, with an instance and no account bound.
652    fn unbound_claude_agent(store: &Store, block_id: &str) -> AgentInstance {
653        use crate::backend::obj::{Block, MetaMapType};
654        let mut def = crate::backend::storage::agents::test_agent_def("def-route", "Routed", "claude", "host", 1, "");
655        store.agent_def_insert(&mut def).unwrap();
656        let mut meta = MetaMapType::new();
657        meta.insert("view".to_string(), serde_json::json!("agent"));
658        meta.insert("agentId".to_string(), serde_json::json!("def-route"));
659        let mut block = Block { oid: block_id.to_string(), parentoref: String::new(), version: 0, runtimeopts: None, stickers: None, meta, subblockids: None };
660        store.insert(&mut block).unwrap();
661        let instance = crate::backend::storage::agents::test_agent_instance("inst-route", "def-route", block_id, 0);
662        store.instance_create(&instance).unwrap();
663        instance
664    }
665
666    #[test]
667    fn an_agent_on_a_model_route_skips_the_no_account_gate_and_nothing_else() {
668        let store = std::sync::Arc::new(Store::open_in_memory().unwrap());
669        let instance = unbound_claude_agent(&store, "block-route-gate");
670        assert!(!on_model_route(&store, &instance));
671        let gated = super::super::inject_identity_env(store.clone(), store.clone(), store.clone(), "block-route-gate", &mut HashMap::new());
672        assert!(matches!(gated, Err(SpawnGateError::MissingCredentials { .. })), "without a route it is the gate: {gated:?}");
673
674        crate::backend::model_gateway::launch::set_choice(&store, "def-route", "claude", "openrouter", "").unwrap();
675        assert!(on_model_route(&store, &instance));
676        let mut env = HashMap::new();
677        assert_eq!(super::super::inject_identity_env(store.clone(), store.clone(), store.clone(), "block-route-gate", &mut env), Ok(()));
678        assert!(env.is_empty(), "no account is bound, so none is injected: {env:?}");
679    }
680}