返回 CodeWhale
credential_resolve_tests.rs
根目录 / crates / tui / src / config_stay_tests / credential_resolve_tests.rs
1 //! The one place provider credential precedence is decided.
2 //!
3 //! Ported from pi-mono `packages/ai/src/auth/resolve.ts` (MIT, Copyright (c)
4 //! 2025 Mario Zechner; full notice in `codewhale_runtime::credentials`). The idea taken is
5 //! pi's: a single resolver, one precedence rule stated in a doc comment beside
6 //! it, and a result that names the place it resolved from. The walk itself is
7 //! CodeWhale's — it is the former body of `has_api_key_for`, moved here
8 //! unchanged in order so no existing decision changes, with a
9 //! [`CredentialSource`] attached to each outcome.
10 //!
11 //! # Precedence rule
12 //!
13 //! **An endpoint-bound exact session key on an authenticated eligible route
14 //! outranks durable and ambient sources. Required account ownership forbids
15 //! every fallback.**
16 //!
17 //! CodeWhale's order below is that rule instantiated over the stores it
18 //! actually has. Reading top to bottom:
19 //!
20 //! 1. Required Codewhale account model ownership, with no fallback.
21 //! 2. A process-only session key for the exact provider identity and endpoint,
22 //! subject to the durable secret store's route eligibility rules.
23 //! 3. `auth_mode = "none"` — the route sends no credential at all.
24 //! 4. An explicit `--api-key` on the active, non-OAuth provider.
25 //! 5. `[providers.<name>] api_key_env` — a credential the route *names*.
26 //! 6. An ambient provider environment variable (official endpoints only).
27 //! 7. Provider-owned login state: an explicitly consented supported external
28 //! CLI credential file (Codex or DeepSeek Harness) or CodeWhale's own xAI
29 //! OAuth storage.
30 //! 8. A keyless self-hosted / loopback route.
31 //! 9. `[providers.<name>] api_key` in the config file.
32 //! 10. CodeWhale's durable secret store.
33 //! 11. The root `api_key` compatibility slot.
34 //! 12. The user-global `~/.codewhale/config.toml`.
35 //! 13. Codewhale account model access when no owner is required.
36 //!
37 //! Two departures from pi are deliberate and load-bearing here:
38 //!
39 //! * Ambient env outranks the secret store for a *named* binding (step 5) and
40 //! for official-endpoint provider variables (step 6). That is CodeWhale's
41 //! existing, documented behavior and users depend on it; changing it is not
42 //! in this lane's scope. It is stated here so it is at least *visible*.
43 //! * External CLI credential files are only ever consulted through
44 //! [`Config::external_credential_read_grant`], which enforces the read-only
45 //! consent model (exact path, explicit consent, never refreshed, never
46 //! rewritten). This resolver adds no new way to reach them, and #5772 tightens
47 //! the two ends of that model:
48 //! - **Nothing happens before consent.** With no persisted consent record
49 //! for a provider, this resolver resolves no candidate path, performs no
50 //! filesystem access, and names no location. Deriving a candidate from
51 //! `HOME` just to say "absent" is itself an unconsented disclosure of where
52 //! another CLI keeps credentials.
53 //! - **A consent record is not a credential.** Consent proves the user
54 //! authorized reading one exact file; it does not prove that file still
55 //! holds a usable token. Once consent exists, the consented file is read
56 //! through the secure adapter — the read the user actually authorized — so
57 //! a missing, malformed, or expired external credential resolves as missing
58 //! rather than masquerading as a stored one.
59 //!
60 //! # Redaction
61 //!
62 //! This module never returns, logs, or renders secret material. It returns
63 //! only a [`CredentialSource`] label. Every probe that needs a value calls an
64 //! existing helper and discards the value with `.is_some()`.
65
66 use codewhale_config::ProviderKind;
67 use codewhale_runtime::config::*;
68
69 use codewhale_engine::provider_readiness::has_api_key_for;
70
71 use crate::test_support::EnvVarGuard;
72
73 use crate::test_support::lock_test_env;
74
75 /// The resolver is the sole authority; `has_api_key_for` must agree with
76 /// it for every provider, or two surfaces can disagree again.
77 #[test]
78 fn has_api_key_for_agrees_with_the_resolver_for_every_provider() {
79 let _lock = lock_test_env();
80 let mut config = Config::default();
81 config
82 .providers
83 .get_or_insert_with(Default::default)
84 .custom
85 .insert(
86 "custom".into(),
87 codewhale_runtime::config::ProviderConfig {
88 kind: Some("openai-compatible".into()),
89 base_url: Some("http://localhost:1234/v1".into()),
90 model: Some("fixture-model".into()),
91 ..Default::default()
92 },
93 );
94 for provider in ProviderKind::all() {
95 let identity = config.test_identity_for_kind(*provider);
96 let resolution = resolve_credential_source(&config, &identity);
97 assert_eq!(
98 has_api_key_for(&config, &identity),
99 resolution.is_present(),
100 "{provider:?} disagreed: {:?}",
101 resolution.source
102 );
103 }
104 }
105
106 /// #5772: with reuse off, an existing external CLI file must not be
107 /// stat'ed, read, or adopted — and the probe must not even claim whether
108 /// the candidate exists.
109 #[test]
110 fn unconsented_external_candidates_are_never_probed() {
111 let _lock = lock_test_env();
112 let temp = tempfile::tempdir().expect("external fixture");
113 let codex_path = temp
114 .path()
115 .canonicalize()
116 .expect("canonical temp root")
117 .join("auth.json");
118 std::fs::write(&codex_path, "{\"tokens\":{\"access_token\":\"x\"}}").expect("fixture");
119 let _auth = EnvVarGuard::set("OPENAI_CODEX_AUTH_FILE", &codex_path);
120 let _access = EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN");
121 let _legacy_access = EnvVarGuard::remove("CODEX_ACCESS_TOKEN");
122 let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY");
123 let config = {
124 let __cw_config_init_0_0 = Some("openai-codex".to_string());
125 let mut __cw_config_init_0_value: Config = Config::default();
126 __cw_config_init_0_value.provider = __cw_config_init_0_0;
127 __cw_config_init_0_value
128 };
129
130 codewhale_runtime::external_credentials::reset_side_effect_trap();
131 let resolution = resolve_credential_source(
132 &config,
133 &(config).test_identity_for_kind(ProviderKind::OpenaiCodex),
134 );
135 assert!(!resolution.is_present());
136 assert!(!has_api_key_for(
137 &config,
138 &(config).test_identity_for_kind(ProviderKind::OpenaiCodex)
139 ));
140 let checked = resolution.checked_places();
141 assert!(
142 checked.contains("Codewhale-owned ChatGPT sign-in"),
143 "the probe names the owned connection without accessing external state: {checked}"
144 );
145 assert!(
146 !checked.contains("(absent)") && !checked.contains("present, not consented"),
147 "no stat means no existence claim: {checked}"
148 );
149 assert_eq!(
150 codewhale_runtime::external_credentials::complete_side_effect_trap_counts(),
151 (0, 0, 0, 0, 0),
152 "resolution must not touch external credential state"
153 );
154 }
155
156 /// #5772: a consent record is not a credential. With a persisted consent
157 /// record whose pinned file is absent, resolution performs exactly the
158 /// read the user authorized — one secure open of the exact consented path —
159 /// and resolves as *missing* rather than masquerading as a stored
160 /// credential. No write, refresh, or network side effect is permitted.
161 #[test]
162 fn chatgpt_resolution_does_not_import_even_consented_external_files() {
163 let _lock = lock_test_env();
164 let temp = tempfile::tempdir().expect("external fixture");
165 let codex_path = temp
166 .path()
167 .canonicalize()
168 .expect("canonical temp root")
169 .join("absent-auth.json");
170 let _auth = EnvVarGuard::set("OPENAI_CODEX_AUTH_FILE", &codex_path);
171 let _access = EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN");
172 let _legacy_access = EnvVarGuard::remove("CODEX_ACCESS_TOKEN");
173 let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY");
174 let config = {
175 let __cw_config_init_1_0 = Some("openai-codex".to_string());
176 let __cw_config_init_1_1 = Some(ProvidersConfig {
177 openai_codex: ProviderConfig {
178 auth_mode: Some("oauth".to_string()),
179 external_credentials: Some(
180 codewhale_config::ExternalCredentialConsentToml::read_only(
181 codewhale_config::ProviderKind::OpenaiCodex,
182 codewhale_config::ExternalCredentialSource::CodexCli,
183 codex_path.clone(),
184 ),
185 ),
186 ..ProviderConfig::default()
187 },
188 ..ProvidersConfig::default()
189 });
190 let mut __cw_config_init_1_value: Config = Config::default();
191 __cw_config_init_1_value.provider = __cw_config_init_1_0;
192 __cw_config_init_1_value.providers = __cw_config_init_1_1;
193 __cw_config_init_1_value
194 };
195
196 codewhale_runtime::external_credentials::reset_side_effect_trap();
197 let resolution = resolve_credential_source(
198 &config,
199 &(config).test_identity_for_kind(ProviderKind::OpenaiCodex),
200 );
201 assert!(
202 !resolution.is_present(),
203 "a consent record whose file is gone must resolve as missing: {:?}",
204 resolution.source
205 );
206 assert!(
207 resolution
208 .checked_places()
209 .contains("Codewhale-owned ChatGPT sign-in"),
210 "the probe requires Codewhale sign-in despite external consent: {}",
211 resolution.checked_places()
212 );
213 assert_eq!(
214 codewhale_runtime::external_credentials::complete_side_effect_trap_counts(),
215 (0, 0, 0, 0, 0),
216 "external consent cannot authorize the public ChatGPT API"
217 );
218 assert!(!has_api_key_for(
219 &config,
220 &(config).test_identity_for_kind(ProviderKind::OpenaiCodex)
221 ));
222 assert_eq!(
223 codewhale_runtime::external_credentials::complete_side_effect_trap_counts(),
224 (0, 0, 0, 0, 0),
225 "has_api_key_for never reads another client credential"
226 );
227 }
228
228 lines RUST