agentmux_srv_core/identity/resolver/provider.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Provider classification: [`ProviderClass`] and [`provider_class`].
5//!
6//! Split out of the single ~2193-line `resolver.rs` (pure relocation, no
7//! behavior change).
8
9/// What kind of credential a provider uses, and how
10/// `inject_identity_env` puts it into the agent's env at spawn time.
11/// Per `docs/specs/archive/SPEC_OAUTH_IDENTITY_BUNDLES_2026_05_22.md` §4.3.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum ProviderClass {
14 /// **API-key class.** The binding's `SecretRef` resolves to a
15 /// single secret string, injected as the listed env vars. All
16 /// listed vars receive the same value — multi-var emission
17 /// covers "two CLIs want different var names for the same secret"
18 /// (e.g. github writes both `GITHUB_TOKEN` and `GH_TOKEN`).
19 ApiKey { env_vars: &'static [&'static str] },
20 /// **OAuth class.** The binding's `SecretRef` is a
21 /// `SecretRef::OAuthConfigDir` pointer; the resolver sets
22 /// `config_dir_env_var = <dir>` at spawn so the CLI reads its
23 /// OAuth tokens from the per-bundle directory.
24 OAuth { config_dir_env_var: &'static str },
25}
26
27/// Classify a provider id. `None` for unknown providers — the
28/// resolver logs and skips them.
29///
30/// reagent P1 on #2263: this used to match only canonical IDs directly, but
31/// `backend/providers.rs` registers aliases (`gemini-cli`→`gemini`,
32/// `copilot-cli`/`github-copilot`→`copilot`, `claude-code`→`claude`, etc.)
33/// that `get_provider` already resolves — meaning `provider_class` and
34/// `get_provider` could disagree on a definition/link still using an alias
35/// ID, silently skipping both the spawn gate and config-dir injection for
36/// it. Resolve to the canonical ID first so the two can never drift.
37///
38/// `resolve_provider_alias` only knows the CLI-tool registry (claude/codex/
39/// gemini/etc.) — it returns `""` as a sentinel for anything outside that
40/// registry, which includes the api-key-class service identifiers below
41/// ("github"/"anthropic"/"openai"/"aws" — a completely different
42/// namespace, not CLI tools). Only substitute the resolved value when it's
43/// non-empty; otherwise keep matching on the original id so that namespace
44/// is untouched.
45pub fn provider_class(provider: &str) -> Option<ProviderClass> {
46 let resolved = crate::backend::providers::resolve_provider_alias(provider);
47 let provider = if resolved.is_empty() { provider } else { resolved };
48 match provider {
49 // ── API-key class ─────────────────────────────────────────
50 // ApiKey.env_vars values match the legacy provider_env_vars
51 // matrix exactly — the new dispatch is additive.
52 "github" => Some(ProviderClass::ApiKey {
53 env_vars: &["GITHUB_TOKEN", "GH_TOKEN"],
54 }),
55 "anthropic" => Some(ProviderClass::ApiKey {
56 env_vars: &["ANTHROPIC_API_KEY"],
57 }),
58 "openai" => Some(ProviderClass::ApiKey {
59 env_vars: &["OPENAI_API_KEY"],
60 }),
61 "aws" => Some(ProviderClass::ApiKey {
62 env_vars: &["AWS_ACCESS_KEY_ID"],
63 }),
64 // ── OAuth class ───────────────────────────────────────────
65 // Env-var names come from the CLI provider registry
66 // (`crates/srv-core/src/backend/providers.rs` —
67 // `ProviderConfig::auth_config_dir_env_var`) so the resolver
68 // can never drift from the launcher spawn path: there is one
69 // source of truth per CLI for which env var redirects its
70 // config / auth directory. The match arm enumerates which
71 // providers we currently treat as OAuth-class for identity
72 // bundles. Originally just claude / codex (spec
73 // §4.3) — grok and muse came last (they have no status command:
74 // `cli_sign_in_files` reads their login file); gemini and copilot were added later
75 // (REPORT_AUTH_ARCHITECTURE_STATE_AND_RETHINK_2026_07_21.md
76 // §2.5 / §6, Phase C) to close a drift gap: the frontend's
77 // `ProviderDefinition` table already marked both
78 // `authType: "oauth"`, but this match arm (the actual gate
79 // for the spawn-time enforcement AND the per-account
80 // isolation-dir minting in identity_handlers.rs, both of
81 // which key off this single function) hadn't caught up —
82 // meaning neither actually applied to them despite the UI
83 // already presenting them as oauth-class. See
84 // `oauth_class_matches_frontend_authtype_oauth_set` below,
85 // which pins this set staying in sync with the frontend going
86 // forward so this doesn't silently drift again.
87 "claude" | "codex" | "gemini" | "copilot" | "grok" | "muse" => {
88 crate::backend::providers::get_provider(provider).map(|cfg| {
89 ProviderClass::OAuth {
90 config_dir_env_var: cfg.auth_config_dir_env_var,
91 }
92 })
93 }
94 _ => None,
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 #[test]
103 fn provider_class_oauth_providers() {
104 // The known oauth providers must classify as OAuth with the SAME
105 // config-dir env vars the CLI provider registry defines (single
106 // source of truth). Pinning the expected strings here catches drift
107 // in either direction — if the registry changes a value, this test
108 // fails and the change becomes deliberate.
109 assert_eq!(
110 provider_class("claude"),
111 Some(ProviderClass::OAuth { config_dir_env_var: "CLAUDE_CONFIG_DIR" }),
112 );
113 assert_eq!(
114 provider_class("codex"),
115 Some(ProviderClass::OAuth { config_dir_env_var: "CODEX_HOME" }),
116 );
117 assert_eq!(
118 provider_class("gemini"),
119 Some(ProviderClass::OAuth { config_dir_env_var: "GEMINI_CLI_HOME" }),
120 );
121 assert_eq!(
122 provider_class("copilot"),
123 Some(ProviderClass::OAuth { config_dir_env_var: "COPILOT_HOME" }),
124 );
125 // Grok Build (`grok login`, files under GROK_HOME) and Muse Code (`muse login`, files
126 // under XDG_CONFIG_HOME): no status command, so `cli_sign_in_files` reads their login file.
127 assert_eq!(
128 provider_class("grok"),
129 Some(ProviderClass::OAuth { config_dir_env_var: "GROK_HOME" }),
130 );
131 assert_eq!(
132 provider_class("muse"),
133 Some(ProviderClass::OAuth { config_dir_env_var: "XDG_CONFIG_HOME" }),
134 );
135 }
136
137 #[test]
138 fn oauth_class_matches_frontend_authtype_oauth_set() {
139 // REPORT_AUTH_ARCHITECTURE_STATE_AND_RETHINK_2026_07_21.md §2.5
140 // found gemini/copilot marked `authType: "oauth"` in the frontend's
141 // `ProviderDefinition` table (frontend/app/view/agent/providers/
142 // index.ts) while this function — the actual gate for both the
143 // spawn-time enforcement AND the per-account isolation-dir minting
144 // — hadn't caught up, so neither mechanism applied to them despite
145 // the UI already presenting them as oauth-class. This pins the two
146 // sets staying equal going forward. There's no automated cross-
147 // language check available, so this list is a manually-maintained
148 // mirror of the frontend table — if you add a new `authType:
149 // "oauth"` provider there, update FRONTEND_OAUTH_TYPED here too, in
150 // the SAME change, not as a follow-up.
151 const FRONTEND_OAUTH_TYPED: &[&str] = &["claude", "codex", "gemini", "copilot", "grok", "muse"];
152 const ALL_KNOWN_PROVIDERS: &[&str] = &[
153 "claude", "codex", "gemini", "copilot", "pi", "opencode", "grok", "dsh", "muse",
154 ];
155 for p in ALL_KNOWN_PROVIDERS {
156 let is_oauth_class = matches!(provider_class(p), Some(ProviderClass::OAuth { .. }));
157 let is_frontend_oauth_typed = FRONTEND_OAUTH_TYPED.contains(p);
158 assert_eq!(
159 is_oauth_class, is_frontend_oauth_typed,
160 "provider '{p}': backend OAuth-class ({is_oauth_class}) must match \
161 frontend authType:\"oauth\" ({is_frontend_oauth_typed}) — see this \
162 test's doc comment",
163 );
164 }
165 }
166
167 /// Spec D2: srv holds Google tokens and makes the calls itself; nothing
168 /// for a Google (or Slack) account is ever put in an agent's environment.
169 #[test]
170 fn google_and_slack_inject_nothing() {
171 assert_eq!(provider_class("google"), None);
172 assert_eq!(provider_class("slack"), None);
173 }
174
175 #[test]
176 fn provider_class_resolves_aliases_to_the_same_result_as_canonical() {
177 // reagent P1 on #2263: provider_class used to match only canonical
178 // IDs, silently disagreeing with get_provider (which already
179 // resolves aliases) for any definition/link still using one.
180 assert_eq!(provider_class("claude-code"), provider_class("claude"));
181 assert_eq!(provider_class("claude_code"), provider_class("claude"));
182 assert_eq!(provider_class("codex-cli"), provider_class("codex"));
183 assert_eq!(provider_class("grok-cli"), provider_class("grok"));
184 // A truly unknown id must still classify as None, not panic or
185 // silently match something via an empty-string fallback.
186 assert_eq!(provider_class("totally-unknown-provider-xyz"), None);
187 }
188}