返回 CodeWhale
oauth.rs
根目录 / crates / runtime / src / oauth.rs
1 //! Codewhale-owned OAuth login and protected credential lifecycle.
2 //! ChatGPT uses its official dynamic registration and direct inference grant.
3 //! Providers are data rows in the parameter table below, not modules.
4 //!
5 //! External Codex CLI credentials are read only after an exact, provider-scoped
6 //! consent grant. Codewhale never refreshes or rewrites that external file.
7 //!
8 //! # Security
9 //!
10 //! Token values are never logged or printed. All debug representations
11 //! redact sensitive fields.
12
13 use std::collections::BTreeMap;
14 use std::io::{IsTerminal, Read, Write as _};
15 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, TcpListener, TcpStream};
16 use std::path::{Path, PathBuf};
17 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
18
19 use anyhow::{Context, Result, bail};
20 use base64::Engine as _;
21 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
22 use codewhale_config::ExternalCredentialReadGrant;
23 use jsonwebtoken::{
24 Algorithm, DecodingKey, Validation, decode, decode_header, errors::ErrorKind, jwk::JwkSet,
25 };
26 use serde::{Deserialize, Serialize};
27 use serde_json::Value;
28 use sha2::{Digest, Sha256};
29
30 use crate::config::Config;
31
32 /// OAuth token payload stored in `auth.json`.
33 #[derive(Clone, Deserialize)]
34 #[serde(rename_all = "snake_case")]
35 struct AuthTokens {
36 access_token: Option<String>,
37 }
38
39 impl std::fmt::Debug for AuthTokens {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 f.debug_struct("AuthTokens")
42 .field("access_token", &redacted(self.access_token.is_some()))
43 .finish()
44 }
45 }
46
47 /// Top-level structure of Codex CLI's `auth.json`.
48 #[derive(Debug, Clone, Deserialize)]
49 #[serde(rename_all = "snake_case")]
50 struct CodexAuthFile {
51 tokens: Option<AuthTokens>,
52 }
53
54 /// Resolved OAuth credentials ready for API use.
55 #[derive(Clone)]
56 pub struct CodexCredentials {
57 pub access_token: String,
58 }
59
60 impl std::fmt::Debug for CodexCredentials {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 f.debug_struct("CodexCredentials")
63 .field("access_token", &"<redacted>")
64 .finish()
65 }
66 }
67
68 /// JWT claims subset for expiry extraction.
69 #[derive(Debug, Deserialize)]
70 struct JwtClaims {
71 exp: Option<u64>,
72 }
73
74 /// Resolve the path to the Codex auth file.
75 ///
76 /// Priority:
77 /// 1. `OPENAI_CODEX_AUTH_FILE` env var
78 /// 2. `$CODEX_HOME/auth.json`
79 /// 3. `~/.codex/auth.json`
80 pub fn auth_file_path() -> PathBuf {
81 if let Ok(path) = std::env::var("OPENAI_CODEX_AUTH_FILE") {
82 let p = PathBuf::from(&path);
83 if !p.as_os_str().is_empty() {
84 return codewhale_config::resolve_external_credential_path(&p).unwrap_or(p);
85 }
86 }
87 let codex_home = std::env::var("CODEX_HOME")
88 .map(PathBuf::from)
89 .unwrap_or_else(|_| {
90 codewhale_paths::user_home()
91 .unwrap_or_else(|| PathBuf::from("."))
92 .join(".codex")
93 });
94 let path = codex_home.join("auth.json");
95 codewhale_config::resolve_external_credential_path(&path).unwrap_or(path)
96 }
97
98 /// Try to extract `exp` (epoch seconds) from a JWT without verifying
99 /// the signature. Returns `None` on any parse failure.
100 fn jwt_expiry_seconds(token: &str) -> Option<u64> {
101 let parts: Vec<&str> = token.split('.').collect();
102 if parts.len() < 2 {
103 return None;
104 }
105 let payload = parts[1];
106 let decoded = URL_SAFE_NO_PAD.decode(payload).ok()?;
107 let claims: JwtClaims = serde_json::from_slice(&decoded).ok()?;
108 claims.exp
109 }
110
111 /// Check whether an access token is expired, with a 60-second safety margin.
112 fn token_is_expired(access_token: &str) -> bool {
113 match jwt_expiry_seconds(access_token) {
114 Some(exp) => {
115 let now = SystemTime::now()
116 .duration_since(UNIX_EPOCH)
117 .unwrap_or(Duration::ZERO)
118 .as_secs();
119 // 60-second safety margin
120 now + 60 >= exp
121 }
122 // If we can't prove freshness, fail closed. External credentials are
123 // never refreshed by Codewhale.
124 None => true,
125 }
126 }
127
128 /// Load Codex credentials from the auth file.
129 ///
130 /// Returns `Ok(None)` if the file doesn't exist or has no usable tokens.
131 /// Returns `Err` only on parse/IO errors that aren't "file not found".
132 fn load_credentials(grant: &ExternalCredentialReadGrant) -> Result<Option<CodexCredentials>> {
133 let Some(contents) = crate::external_credentials::read_to_string(grant)? else {
134 return Ok(None);
135 };
136 let auth: CodexAuthFile = serde_json::from_str(&contents).map_err(|_| {
137 anyhow::anyhow!(
138 "Codex credential file {} is not valid credential JSON",
139 codewhale_config::quote_os_path(grant.path())
140 )
141 })?;
142 let tokens = match auth.tokens {
143 Some(t) => t,
144 None => return Ok(None),
145 };
146 let access_token = match tokens.access_token {
147 Some(t) if !t.trim().is_empty() => t,
148 _ => return Ok(None),
149 };
150 Ok(Some(CodexCredentials { access_token }))
151 }
152
153 /// Validate only the stored OAuth file, excluding token environment
154 /// overrides so config-vs-env provenance remains truthful.
155 ///
156 /// This consumes a grant, so it can only run for a path the user explicitly
157 /// consented to. Consent is not a credential (#5772): status surfaces call
158 /// this to find out whether the consented file *still* holds a usable token,
159 /// because a record that outlives its token would otherwise read as stored.
160 #[must_use]
161 #[cfg(any(test, feature = "test-support"))]
162 pub fn stored_credentials_present(grant: &ExternalCredentialReadGrant) -> bool {
163 load_credentials(grant)
164 .ok()
165 .flatten()
166 .is_some_and(|credentials| !token_is_expired(&credentials.access_token))
167 }
168
169 /// Load read-only credentials from the exact external path authorized by
170 /// `grant`. Expired tokens fail with guidance; they are never refreshed.
171 pub fn get_credentials(grant: &ExternalCredentialReadGrant) -> Result<CodexCredentials> {
172 let creds =
173 load_credentials(grant)?.with_context(|| missing_auth_message(OAuthProvider::Chatgpt))?;
174
175 // Check if the access token is still valid.
176 if !token_is_expired(&creds.access_token) {
177 return Ok(creds);
178 }
179
180 bail!(
181 "Codex access token in {} is expired. Read-only consent never refreshes or rewrites another CLI's credentials. Use `codewhale auth chatgpt` for the official ChatGPT plan route. To inspect this legacy credential file again, renew its login with `codex login`.",
182 codewhale_config::quote_os_path(grant.path())
183 )
184 }
185
186 /// Providers with an OAuth login Codewhale can own.
187 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
188 pub enum OAuthProvider {
189 Xai,
190 Chatgpt,
191 }
192
193 /// Test/dev knobs a provider reads from the environment. Data, so a new
194 /// provider adds rows here instead of a new module.
195 pub struct OAuthEnvOverrides {
196 pub issuer_vars: &'static [&'static str],
197 pub client_id_vars: &'static [&'static str],
198 pub scope_vars: &'static [&'static str],
199 pub no_browser_var: &'static str,
200 /// Set (to anything) to drop [`OAuthProviderParams::account_choice_extras`]
201 /// from the authorize URL, in case the issuer rejects them.
202 pub no_account_prompt_var: Option<&'static str>,
203 }
204
205 /// Everything about one provider's OAuth login that is not logic.
206 pub struct OAuthProviderParams<'a> {
207 /// Human name for prompts and errors: "xAI", "ChatGPT".
208 pub display_name: &'a str,
209 pub default_issuer: &'a str,
210 pub default_client_id: &'a str,
211 pub default_scopes: &'a str,
212 pub env: OAuthEnvOverrides,
213 /// `Some` device-authorization path under the issuer (xAI); `None`
214 /// means the issuer offers no device flow and device login must fail
215 /// loudly instead of guessing (ChatGPT).
216 pub device_code_path: Option<&'a str>,
217 /// `Some` browser authorization path under the issuer (ChatGPT PKCE);
218 /// `None` means the issuer offers no browser flow and browser login
219 /// fails the same loud way (xAI is device-code only).
220 pub authorize_path: Option<&'a str>,
221 /// Token path under the issuer.
222 pub token_path: &'a str,
223 /// Whether the issuer was discovered (xAI) or pinned (ChatGPT paths).
224 pub discover_endpoints: bool,
225 /// Seconds the device-code poll runs past the server's `expires_in`.
226 pub device_poll_floor_secs: u64,
227 /// Extra authorize-endpoint parameters beyond the standard OAuth set,
228 /// sent verbatim so the issuer sees exactly who is calling.
229 pub authorize_extras: &'a [(&'a str, &'a str)],
230 /// Authorize parameters that ask the issuer to let the user choose the
231 /// account instead of reusing the browser's session. Sent unless
232 /// [`OAuthEnvOverrides::no_account_prompt_var`] is set.
233 pub account_choice_extras: &'a [(&'a str, &'a str)],
234 /// Remote revoke path under the issuer, pinned rather than discovered:
235 /// revoke must still clear local credentials when the issuer is
236 /// unreachable, so a discovery fetch would only add a failure mode to a
237 /// path whose contract is to clean up regardless. `None` when
238 /// revocation is purely local (xAI).
239 pub revoke_path: Option<&'a str>,
240 /// Registered loopback redirect for browser flows.
241 pub callback_path: &'a str,
242 /// Loopback ports the public client registered, in preference order.
243 pub loopback_ports: &'a [u16],
244 /// The command that re-runs this provider's login, for error guidance.
245 pub relogin_hint: &'a str,
246 /// The slash command that re-runs this login inside a running session
247 /// and switches that session's live client.
248 pub session_login_hint: &'a str,
249 /// What to tell the user when every callback port is taken.
250 pub callback_conflict_hint: &'a str,
251 }
252
253 pub const XAI_OAUTH_PARAMS: OAuthProviderParams<'static> = OAuthProviderParams {
254 display_name: "xAI",
255 // Single source: the legacy module still owns these strings until its
256 // activation path unifies and they move here in 3b-iii.
257 default_issuer: XAI_OIDC_ISSUER,
258 default_client_id: GROK_OIDC_CLIENT_ID,
259 default_scopes: DEFAULT_SCOPES,
260 env: OAuthEnvOverrides {
261 issuer_vars: &["GROK_OIDC_ISSUER", "XAI_OIDC_ISSUER"],
262 client_id_vars: &["GROK_OIDC_CLIENT_ID", "XAI_OIDC_CLIENT_ID"],
263 scope_vars: &["GROK_OIDC_SCOPES", "XAI_OIDC_SCOPES"],
264 no_browser_var: "CODEWHALE_XAI_OAUTH_NO_BROWSER",
265 no_account_prompt_var: None,
266 },
267 device_code_path: Some("oauth2/device/code"),
268 authorize_path: None,
269 token_path: "oauth2/token",
270 discover_endpoints: true,
271 device_poll_floor_secs: 30,
272 authorize_extras: &[],
273 account_choice_extras: &[],
274 revoke_path: None,
275 callback_path: "",
276 loopback_ports: &[],
277 relogin_hint: "codewhale auth xai-device",
278 session_login_hint: "/auth xai-device",
279 callback_conflict_hint: "",
280 };
281
282 pub const CHATGPT_OAUTH_PARAMS: OAuthProviderParams<'static> = OAuthProviderParams {
283 display_name: "ChatGPT",
284 // Single source: same arrangement as the xAI row above.
285 default_issuer: CHATGPT_OAUTH_ISSUER,
286 default_client_id: CHATGPT_OAUTH_CLIENT_ID,
287 default_scopes: CHATGPT_OAUTH_SCOPE,
288 env: OAuthEnvOverrides {
289 issuer_vars: &["CODEWHALE_CHATGPT_OAUTH_ISSUER"],
290 client_id_vars: &["CODEWHALE_CHATGPT_OAUTH_CLIENT_ID"],
291 scope_vars: &[],
292 no_browser_var: "CODEWHALE_CHATGPT_OAUTH_NO_BROWSER",
293 no_account_prompt_var: Some("CODEWHALE_CHATGPT_OAUTH_NO_PROMPT"),
294 },
295 device_code_path: None,
296 authorize_path: Some("api/accounts/authorize"),
297 token_path: "api/accounts/oauth/token",
298 discover_endpoints: false,
299 device_poll_floor_secs: 30,
300 authorize_extras: &[("resource", CHATGPT_OAUTH_RESOURCE)],
301 // `prompt=login` (OIDC Core 1.0 §3.1.2.1) asks the issuer to re-prompt
302 // instead of silently reusing whichever ChatGPT account the browser is
303 // already signed into. Returning registrations still require the same
304 // verified account; a new account explicitly starts dynamic registration.
305 // Every browser login here is user-initiated; refresh
306 // never visits the authorize endpoint. CODEWHALE_CHATGPT_OAUTH_NO_PROMPT
307 // drops it should the issuer ever refuse it.
308 account_choice_extras: &[("prompt", "login")],
309 revoke_path: Some("api/accounts/oauth/revoke"),
310 callback_path: "/auth/callback",
311 loopback_ports: &[1455, 1457, 0],
312 relogin_hint: "codewhale auth chatgpt",
313 session_login_hint: "/auth chatgpt",
314 callback_conflict_hint: "Close the process holding the callback port and retry `codewhale auth chatgpt`.",
315 };
316
317 /// The parameter table. A provider login looks its row up here; adding a
318 /// provider means adding a row, never a module.
319 #[must_use]
320 pub fn oauth_provider_params(provider: OAuthProvider) -> &'static OAuthProviderParams<'static> {
321 match provider {
322 OAuthProvider::Xai => &XAI_OAUTH_PARAMS,
323 OAuthProvider::Chatgpt => &CHATGPT_OAUTH_PARAMS,
324 }
325 }
326
327 /// OrcaRouter's public authentication origin. Inference lives on a different
328 /// host (`https://api.orcarouter.ai/v1`); neither origin is derived from the
329 /// other.
330 pub const ORCAROUTER_AUTH_BASE: &str = "https://www.orcarouter.ai";
331 /// OrcaRouter's public inference/catalog origin.
332 pub const ORCAROUTER_API_BASE: &str = "https://api.orcarouter.ai/v1";
333 /// OrcaRouter's authorize contract carries no client id: this public label is
334 /// a constant, not a secret. PKCE — not a client secret — binds the auth code
335 /// to this process.
336 pub const ORCAROUTER_CLIENT_ID: &str = "codewhale";
337 /// Shown on the OrcaRouter consent screen.
338 pub const ORCAROUTER_APP_NAME: &str = "Codewhale";
339 /// Consent endpoint path. Not an API route: the browser is pointed at it.
340 pub const ORCAROUTER_AUTHORIZE_PATH: &str = "auth";
341 /// Code-for-key exchange path under the **auth** origin. The relay's
342 /// `/v1/auth/keys` is a different route and a 404; the auth API lives at
343 /// `/api/v1/auth/keys`.
344 pub const ORCAROUTER_EXCHANGE_PATH: &str = "/api/v1/auth/keys";
345 /// The scope this client asks for, and the only scope it accepts back.
346 pub const ORCAROUTER_SCOPE: &str = "api";
347 pub const ORCAROUTER_REF: &str = "ref_df843907ad10d887b867";
348 pub const ORCAROUTER_APP_ID: Option<&str> = None;
349
350 pub const ORCAROUTER_OAUTH_PARAMS: OAuthProviderParams<'static> = OAuthProviderParams {
351 display_name: "OrcaRouter",
352 default_issuer: ORCAROUTER_AUTH_BASE,
353 default_client_id: ORCAROUTER_CLIENT_ID,
354 default_scopes: ORCAROUTER_SCOPE,
355 env: OAuthEnvOverrides {
356 // Loopback HTTP fixtures only. See [`resolve_orcarouter_auth_base`].
357 issuer_vars: &["ORCA_AUTH_BASE_URL", "ORCAROUTER_AUTH_BASE_URL"],
358 client_id_vars: &["ORCAROUTER_OAUTH_CLIENT_ID"],
359 scope_vars: &["ORCAROUTER_OAUTH_SCOPE"],
360 no_browser_var: "CODEWHALE_ORCAROUTER_OAUTH_NO_BROWSER",
361 no_account_prompt_var: None,
362 },
363 device_code_path: None,
364 // Empty so the generic builder emits no `client_id`/`redirect_uri`;
365 // OrcaRouter's authorize contract is built by
366 // [`build_orcarouter_authorize_url`] instead.
367 authorize_path: Some(""),
368 // Unused: the exchange is form-encoded by
369 // [`exchange_orcarouter_code`]. Kept empty so a future generic caller
370 // cannot silently hit the wrong path.
371 token_path: "",
372 discover_endpoints: false,
373 device_poll_floor_secs: 30,
374 authorize_extras: &[],
375 account_choice_extras: &[],
376 revoke_path: None,
377 callback_path: "/callback",
378 // OrcaRouter validates `callback_url` per request and accepts any
379 // loopback port, so ask the OS for a free one rather than guessing.
380 loopback_ports: &[0],
381 relogin_hint: "codewhale auth orcarouter",
382 session_login_hint: "/auth orcarouter",
383 callback_conflict_hint: "Close the process holding the OrcaRouter callback port and retry `codewhale auth orcarouter`.",
384 };
385
386 /// Resolve the OrcaRouter **authentication** origin.
387 ///
388 /// An override moves the origin only to plain HTTP on a loopback host, for
389 /// local fixtures; any other value, HTTPS included, is ignored and the public
390 /// default is used. The inference origin is never derived from this value.
391 #[must_use]
392 pub fn resolve_orcarouter_auth_base() -> String {
393 ORCAROUTER_OAUTH_PARAMS
394 .env
395 .issuer_vars
396 .iter()
397 .filter_map(|var| std::env::var(var).ok())
398 .map(|value| value.trim().to_string())
399 .find(|value| {
400 reqwest::Url::parse(value).is_ok_and(|url| {
401 url.scheme() == "http"
402 && codewhale_config::device_code::validate_browser_verification_uri(
403 url.as_str(),
404 "OrcaRouter auth base",
405 )
406 .is_ok()
407 })
408 })
409 .unwrap_or_else(|| ORCAROUTER_AUTH_BASE.to_string())
410 }
411
412 /// Resolve the OrcaRouter **inference/catalog** origin.
413 ///
414 /// Precedence: an explicit API override, then the shared self-hosted
415 /// fallback, then the public default. The auth origin is never derived from
416 /// this value.
417 #[must_use]
418 pub fn resolve_orcarouter_api_base() -> String {
419 let first_set = |vars: &[&str]| {
420 vars.iter()
421 .filter_map(|var| std::env::var(var).ok())
422 .find(|value| !value.trim().is_empty())
423 };
424 first_set(&["ORCA_API_BASE_URL", "ORCA_BASE_URL", "ORCAROUTER_BASE_URL"])
425 .unwrap_or_else(|| ORCAROUTER_API_BASE.to_string())
426 }
427
428 /// The credential the rest of Codewhale consumes for OrcaRouter.
429 ///
430 /// Both authentication adapters produce **this same value**: the hand-typed
431 /// API-key adapter wraps the pasted `sk-orca-…` string, and the PKCE adapter
432 /// wraps the key the exchange returned. Downstream code — the secret-store
433 /// write, the route binding, model discovery, and every AI entry point — must
434 /// read only this type and never branch on how the key was obtained.
435 ///
436 /// No `Debug`: the key must not reach a log, an error, or a snapshot.
437 #[derive(Clone)]
438 pub struct OrcaCredential {
439 key: String,
440 /// The scope OrcaRouter actually granted, read back from the response.
441 /// Never the scope this client requested.
442 granted_scope: String,
443 source: OrcaCredentialSource,
444 }
445
446 /// How an [`OrcaCredential`] was obtained. Presentation only: it selects copy,
447 /// never behaviour. Nothing downstream of the credential seam may read it to
448 /// decide whether the key is usable.
449 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
450 pub enum OrcaCredentialSource {
451 /// Pasted by the user through the API-key path.
452 ApiKey,
453 /// Issued by the OrcaRouter PKCE exchange.
454 Pkce,
455 }
456
457 impl OrcaCredentialSource {
458 #[must_use]
459 pub const fn as_str(self) -> &'static str {
460 match self {
461 Self::ApiKey => "api_key",
462 Self::Pkce => "pkce",
463 }
464 }
465 }
466
467 impl OrcaCredential {
468 /// The API-key adapter: a key the user already holds.
469 ///
470 /// Prefix checking is deliberately only a shape check — an `sk-orca-`
471 /// prefix is not proof the credential is valid, and no billing request is
472 /// sent from a settings form to find out.
473 pub fn from_api_key(raw: &str) -> Result<Self> {
474 let key = codewhale_secrets::normalize_api_key(raw);
475 anyhow::ensure!(!key.is_empty(), "OrcaRouter API key must not be empty");
476 anyhow::ensure!(
477 key.starts_with("sk-orca-"),
478 "OrcaRouter API keys start with `sk-orca-`; paste the full key from the OrcaRouter console"
479 );
480 Ok(Self {
481 key,
482 // A pasted key carries no response scope; the API-key path asks
483 // for `api` and accepts it.
484 granted_scope: ORCAROUTER_SCOPE.to_string(),
485 source: OrcaCredentialSource::ApiKey,
486 })
487 }
488
489 pub(crate) fn from_exchange(
490 key: String,
491 granted_scope: String,
492 source: OrcaCredentialSource,
493 ) -> Self {
494 Self {
495 key,
496 granted_scope,
497 source,
498 }
499 }
500
501 /// The key material. Callers must not log, echo, or embed this value.
502 #[must_use]
503 pub fn expose(&self) -> &str {
504 &self.key
505 }
506
507 #[must_use]
508 pub fn granted_scope(&self) -> &str {
509 &self.granted_scope
510 }
511
512 #[must_use]
513 pub const fn source(&self) -> OrcaCredentialSource {
514 self.source
515 }
516
517 /// Whether the granted scope satisfies this client's purpose. A
518 /// downgraded grant must be surfaced, not assumed away.
519 #[must_use]
520 pub fn scope_satisfies_purpose(&self) -> bool {
521 self.granted_scope == ORCAROUTER_SCOPE
522 }
523 }
524
525 /// Where an injected OrcaRouter login reads its inputs from. Tests override
526 /// this so the whole adapter — bind, authorize URL, callback, exchange — runs
527 /// against a local fake auth server with no network egress.
528 pub struct OrcaLoginInputs {
529 pub auth_base: String,
530 pub api_base: String,
531 pub app_name: String,
532 pub open_browser: bool,
533 }
534
535 impl OrcaLoginInputs {
536 /// Production inputs: env-resolved origins, the real app name, and the
537 /// browser open flag (off when the no-browser var is set).
538 #[must_use]
539 pub fn from_env() -> Self {
540 Self {
541 auth_base: resolve_orcarouter_auth_base(),
542 api_base: resolve_orcarouter_api_base(),
543 app_name: ORCAROUTER_APP_NAME.to_string(),
544 open_browser: std::env::var_os(ORCAROUTER_OAUTH_PARAMS.env.no_browser_var).is_none(),
545 }
546 }
547 }
548
549 /// The OrcaRouter authorize URL.
550 ///
551 /// Deliberately NOT [`build_authorize_url`]: OrcaRouter's contract is
552 /// `GET {auth}/auth?callback_url=…&code_challenge=…&code_challenge_method=S256&state=…&app_name=…&scope=api[&app_id=…]&ref=…`.
553 /// There is no `client_id`, no `response_type`, and the redirect parameter is
554 /// named `callback_url` — three facts the generic builder gets wrong.
555 pub fn build_orcarouter_authorize_url(
556 inputs: &OrcaLoginInputs,
557 callback_url: &str,
558 state: &str,
559 pkce: &PkceChallenge,
560 ) -> Result<String> {
561 let mut url = oauth_endpoint_url(&format!(
562 "{}/{}",
563 inputs.auth_base.trim_end_matches('/'),
564 ORCAROUTER_AUTHORIZE_PATH
565 ))
566 .with_context(|| "OrcaRouter auth base is not a valid secure URL — check ORCA_AUTH_BASE_URL")?;
567 url.query_pairs_mut()
568 .append_pair("callback_url", callback_url)
569 .append_pair("code_challenge", &pkce.challenge)
570 .append_pair("code_challenge_method", "S256")
571 .append_pair("state", state)
572 .append_pair("app_name", &inputs.app_name)
573 .append_pair("scope", ORCAROUTER_SCOPE);
574 if let Some(app_id) = ORCAROUTER_APP_ID {
575 url.query_pairs_mut().append_pair("app_id", app_id);
576 }
577 url.query_pairs_mut().append_pair("ref", ORCAROUTER_REF);
578 Ok(url.to_string())
579 }
580
581 /// The OrcaRouter code-for-key exchange endpoint, always on the **auth**
582 /// origin.
583 pub fn orcarouter_exchange_url(auth_base: &str) -> String {
584 format!(
585 "{}{}",
586 auth_base.trim_end_matches('/'),
587 ORCAROUTER_EXCHANGE_PATH
588 )
589 }
590
591 /// The response body shape of a successful exchange:
592 /// `{ "key": "sk-orca-…", "user_id": "…", "scope": "api" }`.
593 #[derive(Deserialize)]
594 struct OrcaExchangeResponse {
595 #[serde(default, alias = "access_token")]
596 key: Option<String>,
597 #[serde(default)]
598 user_id: Option<String>,
599 #[serde(default)]
600 scope: Option<String>,
601 #[serde(default)]
602 error: Option<String>,
603 }
604
605 /// Exchange an OrcaRouter auth code for a durable API key.
606 ///
607 /// A PKCE-issued key is **not** a refresh token; there is no refresh grant and
608 /// no long-lived secret is stored. The response's granted `scope` is read back
609 /// and returned, never the scope this client asked for.
610 pub fn exchange_orcarouter_code(
611 client: &dyn OAuthFormClient,
612 auth_base: &str,
613 code: &str,
614 verifier: &str,
615 ) -> Result<OrcaCredential> {
616 let url = orcarouter_exchange_url(auth_base);
617 let (status, body) = client.post_form(
618 &url,
619 &[
620 ("code", code),
621 ("code_verifier", verifier),
622 ("code_challenge_method", "S256"),
623 ],
624 )?;
625 let parsed: OrcaExchangeResponse = serde_json::from_str(&body).map_err(|_| {
626 // Never echo the body: it carries the freshly minted key.
627 anyhow::anyhow!(
628 "OrcaRouter code exchange returned HTTP {status} that was not exchange JSON"
629 )
630 })?;
631 if !(200..300).contains(&status) {
632 // The server may reflect credentials or control text in `error` too.
633 // Only fixed protocol codes may cross the display/log boundary.
634 let err = match parsed.error.as_deref() {
635 Some("invalid_grant") => "invalid_grant",
636 Some("invalid_request") => "invalid_request",
637 Some("access_denied") => "access_denied",
638 Some("server_error") => "server_error",
639 Some("temporarily_unavailable") => "temporarily_unavailable",
640 _ => "exchange_failed",
641 };
642 // 400 = method mismatch / downgrade defence; 403 = code unknown,
643 // expired, or already used, or verifier mismatch. Both are terminal
644 // for this attempt; neither is retried.
645 bail!(
646 "OrcaRouter sign-in could not exchange the authorization code (HTTP {status}, {err}). Run `codewhale auth orcarouter` again."
647 );
648 }
649 let key = parsed
650 .key
651 .filter(|key| !key.trim().is_empty())
652 .context("OrcaRouter sign-in returned no API key")?;
653 let key = codewhale_secrets::normalize_api_key(&key);
654 anyhow::ensure!(
655 key.starts_with("sk-orca-"),
656 "OrcaRouter sign-in returned a key this client cannot use"
657 );
658 let granted_scope = parsed
659 .scope
660 .filter(|scope| !scope.trim().is_empty())
661 .unwrap_or_else(|| ORCAROUTER_SCOPE.to_string());
662 let _ = parsed.user_id;
663 Ok(OrcaCredential::from_exchange(
664 key,
665 granted_scope,
666 OrcaCredentialSource::Pkce,
667 ))
668 }
669
670 /// Bind the OrcaRouter loopback callback: always `127.0.0.1`, ephemeral port.
671 ///
672 /// OrcaRouter validates `http://127.0.0.1:<port>` (and `localhost`/`[::1]`)
673 /// per request, and a registered loopback callback matches any port, so a
674 /// fresh port per attempt is correct rather than a conflict.
675 pub fn bind_orcarouter_callback() -> Result<Vec<TcpListener>> {
676 let params = &ORCAROUTER_OAUTH_PARAMS;
677 let mut listeners = Vec::new();
678 let listener = TcpListener::bind(("127.0.0.1", 0)).with_context(|| {
679 format!(
680 "{} callback could not bind 127.0.0.1; {}",
681 params.display_name, params.callback_conflict_hint
682 )
683 })?;
684 listener
685 .set_nonblocking(true)
686 .with_context(|| format!("{} callback listener is not pollable", params.display_name))?;
687 listeners.push(listener);
688 Ok(listeners)
689 }
690
691 /// One interactive OrcaRouter PKCE login.
692 ///
693 /// Protocol-identical to the ChatGPT flow — the crypto, the loopback listener,
694 /// the callback handling, the timeout and the terminal gate are the same code
695 /// paths — but it produces an [`OrcaCredential`] instead of refreshable token
696 /// material, because what OrcaRouter hands back is a durable API key.
697 pub fn orcarouter_pkce_login(
698 inputs: &OrcaLoginInputs,
699 challenge: &mut dyn std::io::Write,
700 ) -> Result<OrcaCredential> {
701 let params = &ORCAROUTER_OAUTH_PARAMS;
702 let listeners = bind_orcarouter_callback()?;
703 let request = start_orcarouter_auth_request(&listeners, inputs)?;
704 writeln!(
705 challenge,
706 "{} sign-in (OAuth 2.0 + PKCE)",
707 params.display_name
708 )?;
709 writeln!(challenge, " Open: {}", request.authorize_url)?;
710 if inputs.open_browser && crate::browser::open_url(&request.authorize_url).is_err() {
711 writeln!(
712 challenge,
713 " Browser could not be opened; copy the URL above into a browser."
714 )?;
715 }
716 let code = wait_for_callback(&listeners, params, &request.state)?;
717 let client = ReqwestOAuthFormClient;
718 let credential =
719 exchange_orcarouter_code(&client, &inputs.auth_base, &code.0, &request.pkce.verifier)?;
720 if !credential.scope_satisfies_purpose() {
721 writeln!(
722 challenge,
723 " Note: OrcaRouter granted scope \"{}\" while this client asked for \"{}\"; continuing with the narrower grant.",
724 credential.granted_scope(),
725 ORCAROUTER_SCOPE
726 )?;
727 }
728 Ok(credential)
729 }
730
731 /// Persist an [`OrcaCredential`] through the host's ordinary, transactional
732 /// provider-credential path.
733 ///
734 /// This is the single activation seam for **both** OrcaRouter adapters: the
735 /// pasted API key and the PKCE exchange both arrive here and are stored
736 /// identically, under the existing `orcarouter` secret-store slot with
737 /// `auth_mode = "api_key"` metadata. Nothing downstream can tell which adapter
738 /// produced the key, and nothing here treats it as refreshable OAuth material.
739 ///
740 /// Live-config mirroring is the caller's job, exactly as it is for the other
741 /// owned logins: a shell command reloads config, while the in-session path
742 /// mutates the running `Config`.
743 pub fn activate_orcarouter_credential(
744 credential: &OrcaCredential,
745 route_config: &Config,
746 ) -> Result<crate::config::SavedCredential> {
747 let identity = route_config
748 .builtin_provider_identity(codewhale_config::ProviderKind::Orcarouter)
749 .map_err(anyhow::Error::msg)?;
750 // Audit only the adapter, never the key: `api_key` or `pkce`. Both
751 // adapters reach this seam and nothing downstream distinguishes them.
752 tracing::info!(
753 target: "codewhale::oauth",
754 source = credential.source().as_str(),
755 "OrcaRouter credential activated"
756 );
757 crate::config::save_api_key_for_identity(&identity, route_config, credential.expose())
758 }
759
760 /// Build the loopback callback URL + authorize URL for one OrcaRouter attempt.
761 ///
762 /// `redirect_uri` uses the literal `127.0.0.1` the listener bound, so the
763 /// value the user's browser is sent cannot disagree with the socket that is
764 /// waiting for it.
765 pub fn start_orcarouter_auth_request(
766 listeners: &[TcpListener],
767 inputs: &OrcaLoginInputs,
768 ) -> Result<BrowserAuthRequest> {
769 let port = listeners
770 .first()
771 .context("OrcaRouter OAuth callback has no bound listener")?
772 .local_addr()
773 .context("OrcaRouter OAuth callback listener has no local address")?
774 .port();
775 let redirect_uri = format!(
776 "http://127.0.0.1:{port}{}",
777 ORCAROUTER_OAUTH_PARAMS.callback_path
778 );
779 let pkce = generate_pkce();
780 let state = generate_state();
781 let authorize_url = build_orcarouter_authorize_url(inputs, &redirect_uri, &state, &pkce)?;
782 Ok(BrowserAuthRequest {
783 state,
784 nonce: String::new(),
785 pkce,
786 redirect_uri,
787 authorize_url,
788 })
789 }
790
791 /// Resolved login inputs: schema defaults, environment-tested in order.
792 #[derive(Clone)]
793 pub struct ResolvedOAuthInputs {
794 pub issuer: String,
795 pub client_id: String,
796 pub scopes: String,
797 pub open_browser: bool,
798 }
799
800 impl OAuthProviderParams<'_> {
801 /// Resolve issuer/client/scopes from the environment, first var wins.
802 #[must_use]
803 pub fn resolve_inputs(&self) -> ResolvedOAuthInputs {
804 let first_set = |vars: &[&str], fallback: &str| {
805 vars.iter()
806 .filter_map(|var| std::env::var(var).ok())
807 .find(|value| !value.trim().is_empty())
808 .unwrap_or_else(|| fallback.to_string())
809 };
810 ResolvedOAuthInputs {
811 issuer: first_set(self.env.issuer_vars, self.default_issuer),
812 client_id: first_set(self.env.client_id_vars, self.default_client_id),
813 scopes: first_set(self.env.scope_vars, self.default_scopes),
814 open_browser: std::env::var_os(self.env.no_browser_var).is_none(),
815 }
816 }
817 }
818
819 /// Token material from a completed grant. No Debug: the tokens never print.
820 /// `interval` rides along because a `slow_down` error response may carry
821 /// the server's new minimum, which the loop prefers over its own tracked
822 /// value (RFC 8628 §3.5; WSL/VM clock drift).
823 #[derive(Clone, Deserialize)]
824 pub struct OAuthTokenMaterial {
825 pub access_token: Option<String>,
826 pub refresh_token: Option<String>,
827 pub expires_in: Option<u64>,
828 #[serde(default)]
829 pub earliest_refresh_at: Option<Value>,
830 /// OpenID Connect id token; carries the account claim when issued.
831 #[serde(default)]
832 pub id_token: Option<String>,
833 #[serde(default)]
834 pub scope: Option<String>,
835 #[serde(default)]
836 pub token_type: Option<String>,
837 /// Set only after cryptographic validation, never deserialized from a server.
838 #[serde(skip)]
839 pub(crate) verified_chatgpt: Option<ChatgptRegistration>,
840 #[serde(default)]
841 pub interval: Option<u64>,
842 #[serde(default)]
843 pub error: Option<String>,
844 #[serde(default)]
845 pub error_description: Option<String>,
846 }
847
848 /// A completed login awaiting activation (owned-generation commit).
849 /// The provider is the table row it resolved through; unified activation
850 /// (3b-ii) matches on it.
851 pub struct PendingOAuthLogin {
852 pub provider: OAuthProvider,
853 pub issuer: String,
854 pub client_id: String,
855 pub token: OAuthTokenMaterial,
856 }
857
858 /// Device-authorization response. Error fields ride along so a refused
859 /// grant classifies instead of failing to parse.
860 #[derive(Clone, Deserialize)]
861 struct DeviceGrantResponse {
862 device_code: Option<String>,
863 user_code: Option<String>,
864 verification_uri: Option<String>,
865 verification_uri_complete: Option<String>,
866 expires_in: Option<u64>,
867 interval: Option<u64>,
868 #[serde(default)]
869 error: Option<String>,
870 #[serde(default)]
871 error_description: Option<String>,
872 }
873
874 /// Bounds copied with the behavior: 20 s requests, 64 KiB bodies, 256 B of
875 /// error detail. A server that will not fit in the budget is an error, and
876 /// error text is whitespace-collapsed so a hostile endpoint cannot smuggle
877 /// terminal controls into diagnostics.
878 const OAUTH_REQUEST_TIMEOUT_SECS: u64 = 20;
879 const OAUTH_RESPONSE_BODY_LIMIT: u64 = 64 * 1024;
880 const OAUTH_ERROR_DETAIL_LIMIT: usize = 256;
881
882 /// Apply the existing OAuth browser URI policy to the URL that reqwest will
883 /// actually use. Parsing first keeps transport and loopback interpretation
884 /// identical; an issuer override does not authorize remote plaintext forms.
885 fn oauth_endpoint_url(raw: &str) -> Result<reqwest::Url> {
886 let url = reqwest::Url::parse(raw).context("OAuth endpoint is not a valid URL")?;
887 codewhale_config::device_code::validate_browser_verification_uri(
888 url.as_str(),
889 "OAuth endpoint",
890 )
891 .context("OAuth endpoints require HTTPS, except for local loopback HTTP")?;
892 Ok(url)
893 }
894
895 fn oauth_http_client(endpoint: &reqwest::Url, purpose: &str) -> Result<reqwest::blocking::Client> {
896 let builder = codewhale_release::tls::reqwest_blocking_client_builder()
897 // An issuer-approved endpoint cannot delegate credential-bearing forms
898 // to a redirect destination, including HTTPS-to-HTTP downgrades.
899 .redirect(reqwest::redirect::Policy::none())
900 .timeout(Duration::from_secs(OAUTH_REQUEST_TIMEOUT_SECS));
901 // Every caller admits this URL through oauth_endpoint_url. Its HTTP
902 // exception authorizes only a local exchange, never forwarding the form
903 // through an ambient system or environment proxy.
904 let builder = if endpoint.scheme() == "http" {
905 builder.no_proxy()
906 } else {
907 builder
908 };
909 builder
910 .build()
911 .with_context(|| format!("Failed to build OAuth {purpose} client"))
912 }
913
914 fn parse_oauth_json<T: serde::de::DeserializeOwned>(
915 response: reqwest::blocking::Response,
916 operation: &str,
917 ) -> Result<(reqwest::StatusCode, T)> {
918 let status = response.status();
919 let mut reader = response.take(OAUTH_RESPONSE_BODY_LIMIT + 1);
920 let mut body = Vec::new();
921 reader
922 .read_to_end(&mut body)
923 .with_context(|| format!("reading {operation} response"))?;
924 let truncated = body.len() as u64 > OAUTH_RESPONSE_BODY_LIMIT;
925 if truncated {
926 body.truncate(OAUTH_RESPONSE_BODY_LIMIT as usize);
927 }
928 let parsed = serde_json::from_slice(&body).map_err(|_| {
929 let limit = if truncated {
930 " (body exceeded the 64 KiB diagnostic limit)"
931 } else {
932 ""
933 };
934 anyhow::anyhow!("{operation} returned HTTP {status}; expected JSON{limit}")
935 })?;
936 Ok((status, parsed))
937 }
938
939 fn bounded_oauth_error_text(raw: &str) -> String {
940 let mut output = String::with_capacity(raw.len().min(OAUTH_ERROR_DETAIL_LIMIT));
941 let mut previous_was_space = false;
942 let mut written = 0;
943 for character in raw.chars() {
944 let character = if character.is_whitespace() {
945 ' '
946 } else if character.is_control() {
947 continue;
948 } else {
949 character
950 };
951 if character == ' ' && previous_was_space {
952 continue;
953 }
954 if written == OAUTH_ERROR_DETAIL_LIMIT {
955 break;
956 }
957 output.push(character);
958 previous_was_space = character == ' ';
959 written += 1;
960 }
961 output.trim().to_string()
962 }
963
964 fn oauth_failure_detail(
965 error: Option<&str>,
966 description: Option<&str>,
967 status: reqwest::StatusCode,
968 ) -> String {
969 let mut code = bounded_oauth_error_text(error.unwrap_or("request_failed"));
970 if code.is_empty() {
971 code = "request_failed".to_string();
972 }
973 let description = description
974 .map(bounded_oauth_error_text)
975 .filter(|description| !description.is_empty() && description != &code);
976 match description {
977 Some(description) => format!("{code}: {description}; HTTP {status}"),
978 None => format!("{code}; HTTP {status}"),
979 }
980 }
981
982 /// Resolved token + device endpoints for one login.
983 #[derive(Clone, Debug, PartialEq, Eq)]
984 struct OAuthEndpoints {
985 device_authorization_endpoint: Option<String>,
986 token_endpoint: String,
987 }
988
989 /// OIDC discovery document. Only the fields a login needs.
990 #[derive(Clone, Deserialize)]
991 struct OidcDiscoveryDocument {
992 issuer: Option<String>,
993 device_authorization_endpoint: Option<String>,
994 token_endpoint: Option<String>,
995 }
996
997 /// Resolve endpoints: OIDC discovery when the provider row asks for it,
998 /// documented-path fallback otherwise — and fallback on ANY discovery
999 /// failure, loudly logged. A hostile or broken discovery document must
1000 /// never brick login; it only loses the custom endpoints.
1001 fn resolve_oauth_endpoints(params: &OAuthProviderParams, issuer: &str) -> OAuthEndpoints {
1002 let fallback = || fallback_oauth_endpoints(params, issuer);
1003 if !params.discover_endpoints {
1004 return fallback();
1005 }
1006 match discover_oauth_endpoints(params, issuer) {
1007 Ok(endpoints) => endpoints,
1008 Err(err) => {
1009 tracing::warn!(
1010 target: "codewhale::oauth",
1011 error = %err,
1012 "{} OIDC discovery failed; using documented endpoint fallback",
1013 params.display_name
1014 );
1015 fallback()
1016 }
1017 }
1018 }
1019
1020 fn discover_oauth_endpoints(params: &OAuthProviderParams, issuer: &str) -> Result<OAuthEndpoints> {
1021 let name = params.display_name;
1022 let discovery_url = oauth_endpoint_url(&format!(
1023 "{}/.well-known/openid-configuration",
1024 issuer.trim_end_matches('/')
1025 ))?;
1026 let client = oauth_http_client(&discovery_url, "OIDC discovery")?;
1027 #[cfg(any(test, feature = "test-support"))]
1028 crate::external_credentials::record_oauth_network();
1029 let response = client
1030 .get(discovery_url)
1031 .header(reqwest::header::ACCEPT, "application/json")
1032 .send()
1033 .with_context(|| format!("{name} OIDC discovery request failed"))?;
1034 let (status, discovery): (_, OidcDiscoveryDocument) =
1035 parse_oauth_json(response, &format!("{name} OIDC discovery"))?;
1036 if !status.is_success() {
1037 bail!("{name} OIDC discovery failed with HTTP {status}");
1038 }
1039 validate_discovered_issuer(discovery.issuer, issuer)
1040 .with_context(|| format!("{name} OIDC discovery"))?;
1041 Ok(OAuthEndpoints {
1042 device_authorization_endpoint: params
1043 .device_code_path
1044 .map(|_| {
1045 validate_discovered_oauth_endpoint(
1046 discovery.device_authorization_endpoint,
1047 "device_authorization_endpoint",
1048 issuer,
1049 )
1050 })
1051 .transpose()?,
1052 token_endpoint: validate_discovered_oauth_endpoint(
1053 discovery.token_endpoint,
1054 "token_endpoint",
1055 issuer,
1056 )?,
1057 })
1058 }
1059
1060 /// Validate that an OIDC discovery document's issuer matches the requested issuer.
1061 fn validate_discovered_issuer(discovered: Option<String>, expected: &str) -> Result<()> {
1062 let discovered = discovered
1063 .as_deref()
1064 .map(str::trim)
1065 .filter(|issuer| !issuer.is_empty())
1066 .context("OIDC discovery missing issuer")?;
1067 if discovered.trim_end_matches('/') != expected.trim_end_matches('/') {
1068 bail!("OIDC discovery issuer does not match the requested issuer");
1069 }
1070 let _ = oauth_endpoint_url(expected).context("OIDC issuer is not a trusted URL")?;
1071 Ok(())
1072 }
1073
1074 /// Validate one discovered endpoint against the issuer: https-or-http scheme,
1075 /// no plaintext downgrade, no embedded credentials, same origin.
1076 fn validate_discovered_oauth_endpoint(
1077 endpoint: Option<String>,
1078 field: &str,
1079 issuer: &str,
1080 ) -> Result<String> {
1081 let endpoint = endpoint
1082 .as_deref()
1083 .map(str::trim)
1084 .filter(|endpoint| !endpoint.is_empty())
1085 .with_context(|| format!("OIDC discovery missing {field}"))?;
1086 let parsed = reqwest::Url::parse(endpoint)
1087 .with_context(|| format!("OIDC discovery returned an invalid {field}"))?;
1088 if !matches!(parsed.scheme(), "http" | "https") {
1089 bail!("OIDC discovery returned unsupported {field} scheme");
1090 }
1091 let issuer = oauth_endpoint_url(issuer).context("OIDC issuer is not a trusted URL")?;
1092 if issuer.scheme() == "https" && parsed.scheme() != "https" {
1093 bail!("OIDC discovery attempted to downgrade {field} from HTTPS");
1094 }
1095 if !parsed.username().is_empty() || parsed.password().is_some() {
1096 bail!("OIDC discovery returned credentials in {field}");
1097 }
1098 if parsed.origin() != issuer.origin() {
1099 bail!("OIDC discovery returned {field} on a different origin than the issuer");
1100 }
1101 let _ = oauth_endpoint_url(parsed.as_str())?;
1102 Ok(endpoint.to_string())
1103 }
1104
1105 /// Documented-path endpoints for a provider row, no discovery.
1106 fn fallback_oauth_endpoints(params: &OAuthProviderParams, issuer: &str) -> OAuthEndpoints {
1107 OAuthEndpoints {
1108 device_authorization_endpoint: params
1109 .device_code_path
1110 .map(|path| format!("{}/{}", issuer.trim_end_matches('/'), path)),
1111 token_endpoint: format!("{}/{}", issuer.trim_end_matches('/'), params.token_path),
1112 }
1113 }
1114
1115 /// POST a device-authorization request. Pure transport over an explicit
1116 /// endpoint: discovery (or its absence) is the caller's decision.
1117 fn request_device_grant(
1118 device_authorization_endpoint: &str,
1119 client_id: &str,
1120 scopes: &str,
1121 ) -> Result<DeviceGrantResponse> {
1122 let device_authorization_endpoint = oauth_endpoint_url(device_authorization_endpoint)?;
1123 let client = oauth_http_client(&device_authorization_endpoint, "device-code")?;
1124 let params = [("client_id", client_id), ("scope", scopes)];
1125 #[cfg(any(test, feature = "test-support"))]
1126 crate::external_credentials::record_oauth_network();
1127 let response = client
1128 .post(device_authorization_endpoint)
1129 .form(&params)
1130 .send()
1131 .context("OAuth device-code request failed")?;
1132 let (status, body): (_, DeviceGrantResponse) =
1133 parse_oauth_json(response, "OAuth device-code request")?;
1134 if !status.is_success() || body.error.is_some() {
1135 let detail = oauth_failure_detail(
1136 body.error.as_deref(),
1137 body.error_description.as_deref(),
1138 status,
1139 );
1140 bail!("OAuth device-code request failed ({detail})");
1141 }
1142 if body
1143 .device_code
1144 .as_deref()
1145 .is_some_and(|code| !code.trim().is_empty())
1146 && body
1147 .user_code
1148 .as_deref()
1149 .is_some_and(|code| !code.trim().is_empty())
1150 {
1151 return Ok(body);
1152 }
1153 bail!("OAuth device-code request returned success without a device and user code");
1154 }
1155
1156 /// Poll the token endpoint once, classifying the RFC 8628 outcome. Matches
1157 /// the legacy per-provider poll so the ported tests pin identical behavior.
1158 fn poll_device_grant(
1159 token_endpoint: &str,
1160 client_id: &str,
1161 device_code: &str,
1162 ) -> Result<codewhale_config::device_code::DevicePollOutcome<OAuthTokenMaterial>> {
1163 use codewhale_config::device_code::DevicePollOutcome;
1164 let token_endpoint = oauth_endpoint_url(token_endpoint)?;
1165 let client = oauth_http_client(&token_endpoint, "device-code poll")?;
1166 let params = [
1167 ("client_id", client_id),
1168 ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
1169 ("device_code", device_code),
1170 ];
1171 #[cfg(any(test, feature = "test-support"))]
1172 crate::external_credentials::record_oauth_network();
1173 let response = client
1174 .post(token_endpoint)
1175 .form(&params)
1176 .send()
1177 .context("OAuth device-code poll failed")?;
1178 let (status, body): (_, OAuthTokenMaterial) =
1179 parse_oauth_json(response, "OAuth device-code poll")?;
1180 if status.is_success() && body.error.is_none() {
1181 return Ok(DevicePollOutcome::Complete(body));
1182 }
1183 match body.error.as_deref().unwrap_or("") {
1184 "authorization_pending" => Ok(DevicePollOutcome::Pending),
1185 "slow_down" => Ok(DevicePollOutcome::SlowDown {
1186 interval_seconds: body.interval,
1187 }),
1188 _ => {
1189 let detail = oauth_failure_detail(
1190 body.error.as_deref(),
1191 body.error_description.as_deref(),
1192 status,
1193 );
1194 bail!("OAuth device-code poll failed ({detail})");
1195 }
1196 }
1197 }
1198
1199 #[derive(Debug, PartialEq, Eq)]
1200 enum OAuthChallengeStream {
1201 Stderr,
1202 Stdout,
1203 }
1204
1205 fn oauth_challenge_stream(
1206 stderr_terminal: bool,
1207 stdout_terminal: bool,
1208 ) -> Result<OAuthChallengeStream> {
1209 if stderr_terminal {
1210 Ok(OAuthChallengeStream::Stderr)
1211 } else if stdout_terminal {
1212 Ok(OAuthChallengeStream::Stdout)
1213 } else {
1214 bail!(
1215 "Sign-in requires a terminal for the private login challenge; run codewhale auth in an interactive terminal without redirecting both output streams"
1216 );
1217 }
1218 }
1219
1220 fn oauth_challenge_writer() -> Result<Box<dyn std::io::Write + Send>> {
1221 match oauth_challenge_stream(
1222 std::io::stderr().is_terminal(),
1223 std::io::stdout().is_terminal(),
1224 )? {
1225 OAuthChallengeStream::Stderr => Ok(Box::new(std::io::stderr())),
1226 OAuthChallengeStream::Stdout => Ok(Box::new(std::io::stdout())),
1227 }
1228 }
1229
1230 /// Interactive device-code login for any provider whose row offers it.
1231 /// Shows the verification URL + user code only on a terminal and polls until
1232 /// approved. A provider with no device flow (ChatGPT) fails here with the
1233 /// reason, instead of deep in transport code.
1234 pub async fn device_code_login(provider: OAuthProvider) -> Result<PendingOAuthLogin> {
1235 // Endpoint resolution does blocking HTTP (discovery): it must run on the
1236 // blocking worker, never on the async executor. Providers with no device
1237 // flow fail here, before any thread spawns and before any network.
1238 let params = oauth_provider_params(provider);
1239 if params.device_code_path.is_none() {
1240 bail!(
1241 "{} offers no device-code flow; sign in through the browser login instead",
1242 params.display_name
1243 );
1244 }
1245 let inputs = params.resolve_inputs();
1246 let display_name = params.display_name;
1247 let challenge = oauth_challenge_writer()?;
1248 device_code_login_on_worker(provider, inputs, challenge)
1249 .await
1250 .with_context(|| format!("{display_name} device-code login worker failed"))
1251 }
1252
1253 async fn device_code_login_on_worker(
1254 provider: OAuthProvider,
1255 inputs: ResolvedOAuthInputs,
1256 mut challenge: Box<dyn std::io::Write + Send>,
1257 ) -> Result<PendingOAuthLogin> {
1258 tokio::task::spawn_blocking(move || {
1259 device_code_login_with(provider, &inputs, challenge.as_mut())
1260 })
1261 .await
1262 .context("device-code protocol worker failed")?
1263 }
1264
1265 /// Blocking protocol worker. Production callers capture a terminal first;
1266 /// protocol tests inject a private output buffer or sink.
1267 fn device_code_login_with(
1268 provider: OAuthProvider,
1269 inputs: &ResolvedOAuthInputs,
1270 challenge: &mut dyn std::io::Write,
1271 ) -> Result<PendingOAuthLogin> {
1272 let params = oauth_provider_params(provider);
1273 let display_name = params.display_name;
1274 let endpoints = resolve_oauth_endpoints(params, &inputs.issuer);
1275 let Some(device_endpoint) = endpoints.device_authorization_endpoint else {
1276 bail!(
1277 "{display_name} offers no device-code flow; sign in through the browser login instead"
1278 );
1279 };
1280 let token_endpoint = endpoints.token_endpoint;
1281 let poll_floor_secs = params.device_poll_floor_secs;
1282 let grant = request_device_grant(&device_endpoint, &inputs.client_id, &inputs.scopes)?;
1283 let verify = grant
1284 .verification_uri_complete
1285 .clone()
1286 .or(grant.verification_uri.clone())
1287 .unwrap_or_else(|| format!("{}/device", inputs.issuer.trim_end_matches('/')));
1288 // Off the wire, headed for `webbrowser::open`: must be a bare
1289 // navigation, never a scheme or credential smuggle.
1290 let verify = codewhale_config::device_code::validate_browser_verification_uri(
1291 &verify,
1292 &format!("{display_name} device-code request"),
1293 )?;
1294 let user_code = grant.user_code.unwrap_or_default();
1295 anyhow::ensure!(
1296 user_code.len() <= 1024 && !user_code.chars().any(char::is_control),
1297 "device-code login returned invalid user-code display data"
1298 );
1299
1300 writeln!(challenge, "{display_name} device-code login")?;
1301 writeln!(challenge, " Open: {verify}")?;
1302 writeln!(challenge, " Code: {user_code}")?;
1303 writeln!(
1304 challenge,
1305 "{}",
1306 account_choice_hint(display_name, ChatgptLoginMode::FreshAccount)
1307 )?;
1308 writeln!(
1309 challenge,
1310 "Waiting for approval in the browser… (Ctrl+C to abort)"
1311 )?;
1312 challenge.flush()?;
1313 if inputs.open_browser && crate::browser::open_url(&verify).is_err() {
1314 writeln!(
1315 challenge,
1316 "Could not open the browser automatically; open the displayed URL manually"
1317 )?;
1318 }
1319
1320 let lifetime = Duration::from_secs(
1321 grant
1322 .expires_in
1323 .unwrap_or(DEVICE_POLL_MAX_SECS)
1324 .max(poll_floor_secs),
1325 );
1326 let token = codewhale_config::device_code::DeviceCodePoll::new(
1327 lifetime,
1328 format!(
1329 "{display_name} device-code authorization timed out. Re-run device login \
1330 and approve the code before it expires."
1331 ),
1332 )
1333 .interval_seconds(grant.interval)
1334 .wait_before_first_poll(true)
1335 .slow_down_timeout_message(format!(
1336 "{display_name} device-code authorization timed out after one or more slow_down \
1337 responses. That is usually clock drift in a WSL or VM environment; \
1338 sync the clock, then re-run device login and approve the code before \
1339 it expires."
1340 ))
1341 .run(std::thread::sleep, || {
1342 poll_device_grant(
1343 &token_endpoint,
1344 &inputs.client_id,
1345 grant.device_code.as_deref().unwrap_or(""),
1346 )
1347 })?;
1348
1349 Ok(PendingOAuthLogin {
1350 provider,
1351 issuer: inputs.issuer.clone(),
1352 client_id: inputs.client_id.clone(),
1353 token,
1354 })
1355 }
1356
1357 /// One login entry point for every provider: the params row decides whether
1358 /// the grant is device-code or browser PKCE. A provider with neither fails
1359 /// here with the reason.
1360 pub async fn login(provider: OAuthProvider) -> Result<PendingOAuthLogin> {
1361 let params = oauth_provider_params(provider);
1362 if params.device_code_path.is_some() {
1363 device_code_login(provider).await
1364 } else if params.authorize_path.is_some() {
1365 pkce_login(provider).await
1366 } else {
1367 bail!("{} offers no sign-in flow", params.display_name);
1368 }
1369 }
1370
1371 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1372 pub enum ChatgptLoginMode {
1373 #[default]
1374 FreshAccount,
1375 ReauthorizeCurrent,
1376 }
1377
1378 /// Sign in using the caller's actual config. ChatGPT starts a fresh account
1379 /// login by default unless `ChatgptLoginMode::ReauthorizeCurrent` is requested.
1380 pub async fn login_with_config(
1381 provider: OAuthProvider,
1382 config: &Config,
1383 ) -> Result<PendingOAuthLogin> {
1384 login_with_config_mode(provider, config, ChatgptLoginMode::FreshAccount).await
1385 }
1386
1387 pub async fn login_with_config_mode(
1388 provider: OAuthProvider,
1389 config: &Config,
1390 mode: ChatgptLoginMode,
1391 ) -> Result<PendingOAuthLogin> {
1392 if provider != OAuthProvider::Chatgpt {
1393 let params = oauth_provider_params(provider);
1394 return if params.device_code_path.is_some() {
1395 device_code_login(provider).await
1396 } else {
1397 pkce_login(provider).await
1398 };
1399 }
1400 let selected = official_chatgpt_registration(config).ok();
1401 let inputs = oauth_provider_params(provider).resolve_inputs();
1402 anyhow::ensure!(
1403 inputs.issuer == CHATGPT_OAUTH_ISSUER,
1404 "Official ChatGPT sign-in requires https://auth.openai.com; remove the issuer override"
1405 );
1406 let mut challenge = oauth_challenge_writer()?;
1407 tokio::task::spawn_blocking(move || {
1408 pkce_login_with_selected(provider, &inputs, selected, mode, challenge.as_mut())
1409 })
1410 .await
1411 .context("ChatGPT PKCE login worker failed")?
1412 }
1413
1414 // ── form-post transport seam ──────────────────────────────────────────
1415 //
1416 // One seam for every OAuth form post (PKCE exchange, refresh, revoke): the
1417 // production client is reqwest with the shared bounds; tests substitute a
1418 // mock issuer. The seam records network/refresh in test builds so the
1419 // side-effect trap can still prove "zero external I/O" assertions.
1420
1421 pub trait OAuthFormClient {
1422 fn post_form(&self, url: &str, form: &[(&str, &str)]) -> Result<(u16, String)>;
1423 fn chatgpt_jwks(&self, issuer: &str) -> Result<ChatgptKeys> {
1424 fetch_chatgpt_jwks(issuer)
1425 }
1426 fn revocation_endpoint(&self, params: &OAuthProviderParams, issuer: &str) -> Result<String> {
1427 remote_revoke_url(params, issuer).context("OAuth has no remote revoke endpoint")
1428 }
1429 }
1430
1431 pub struct ReqwestOAuthFormClient;
1432
1433 impl OAuthFormClient for ReqwestOAuthFormClient {
1434 fn revocation_endpoint(&self, params: &OAuthProviderParams, issuer: &str) -> Result<String> {
1435 if params.display_name != "ChatGPT" {
1436 return remote_revoke_url(params, issuer)
1437 .context("OAuth has no remote revoke endpoint");
1438 }
1439 anyhow::ensure!(
1440 issuer == CHATGPT_OAUTH_ISSUER,
1441 "ChatGPT revocation issuer is invalid"
1442 );
1443 let discovery_url =
1444 oauth_endpoint_url(&format!("{issuer}/.well-known/openid-configuration"))?;
1445 let response = oauth_http_client(&discovery_url, "revocation discovery")?
1446 .get(discovery_url)
1447 .send()
1448 .context("ChatGPT revocation discovery failed")?;
1449 let (status, document): (_, Value) =
1450 parse_oauth_json(response, "ChatGPT revocation discovery")?;
1451 anyhow::ensure!(
1452 status.is_success() && document.get("issuer").and_then(Value::as_str) == Some(issuer),
1453 "ChatGPT revocation discovery issuer is invalid"
1454 );
1455 let endpoint = document
1456 .get("revocation_endpoint")
1457 .and_then(Value::as_str)
1458 .context("ChatGPT did not publish a revocation endpoint")?;
1459 let url = oauth_endpoint_url(endpoint)?;
1460 anyhow::ensure!(
1461 url.origin() == oauth_endpoint_url(issuer)?.origin()
1462 && url.query().is_none()
1463 && url.fragment().is_none(),
1464 "ChatGPT revocation endpoint is invalid"
1465 );
1466 Ok(url.to_string())
1467 }
1468 fn post_form(&self, url: &str, form: &[(&str, &str)]) -> Result<(u16, String)> {
1469 let url = oauth_endpoint_url(url)?;
1470 #[cfg(any(test, feature = "test-support"))]
1471 crate::external_credentials::record_oauth_network();
1472 let client = oauth_http_client(&url, "form")?;
1473 let request = client.post(url).form(form);
1474 let response = request.send().context("OAuth token request failed")?;
1475 let status = response.status().as_u16();
1476 let mut reader = response.take(OAUTH_RESPONSE_BODY_LIMIT + 1);
1477 let mut body = Vec::new();
1478 reader
1479 .read_to_end(&mut body)
1480 .context("reading OAuth form response")?;
1481 if body.len() as u64 > OAUTH_RESPONSE_BODY_LIMIT {
1482 body.truncate(OAUTH_RESPONSE_BODY_LIMIT as usize);
1483 }
1484 Ok((status, String::from_utf8(body).unwrap_or_default()))
1485 }
1486 }
1487
1488 /// Token/authorize endpoint URLs for one provider row.
1489 pub(crate) fn form_token_url(params: &OAuthProviderParams, issuer: &str) -> String {
1490 format!("{}/{}", issuer.trim_end_matches('/'), params.token_path)
1491 }
1492
1493 /// Pinned remote revoke URL; `None` when the provider revokes locally only.
1494 pub(crate) fn remote_revoke_url(params: &OAuthProviderParams, issuer: &str) -> Option<String> {
1495 params
1496 .revoke_path
1497 .map(|path| format!("{}/{}", issuer.trim_end_matches('/'), path))
1498 }
1499
1500 /// Parse a form-post token response. Error bodies are never echoed: the
1501 /// detail names the error code only, so a hostile issuer cannot smuggle
1502 /// secret-bearing text back through diagnostics.
1503 pub(crate) fn parse_oauth_form_response(
1504 status: u16,
1505 body: &str,
1506 operation: &str,
1507 params: &OAuthProviderParams,
1508 ) -> Result<OAuthTokenMaterial> {
1509 let name = params.display_name;
1510 let parsed: OAuthTokenMaterial = serde_json::from_str(body).map_err(|_| {
1511 anyhow::anyhow!("{name} OAuth {operation} returned HTTP {status} that was not token JSON")
1512 })?;
1513 if !(200..300).contains(&status) || parsed.error.is_some() {
1514 let err = parsed.error.as_deref().unwrap_or("token_error");
1515 if matches!(
1516 err,
1517 "invalid_grant"
1518 | "refresh_token_reused"
1519 | "refresh_token_expired"
1520 | "refresh_token_invalidated"
1521 ) || status == 401
1522 {
1523 bail!(
1524 "{name} OAuth {operation} failed permanently ({err}). Sign in again with `{}`.",
1525 params.relogin_hint
1526 );
1527 }
1528 bail!("{name} OAuth {operation} failed ({err})");
1529 }
1530 anyhow::ensure!(
1531 parsed
1532 .access_token
1533 .as_deref()
1534 .is_some_and(|token| !token.trim().is_empty()),
1535 "{name} OAuth {operation} returned an empty access token"
1536 );
1537 Ok(parsed)
1538 }
1539
1540 fn compact_form_error(body: &str) -> String {
1541 body.chars().filter(|c| !c.is_control()).take(80).collect()
1542 }
1543
1544 /// Refresh an owned token through the seam at an explicit token URL —
1545 /// discovered when the provider row demands it, pinned otherwise. Refresh is
1546 /// a Codewhale-owned credential operation only: external imports never
1547 /// refresh.
1548 pub(crate) fn refresh_access_token_via(
1549 client: &dyn OAuthFormClient,
1550 params: &OAuthProviderParams,
1551 token_url: &str,
1552 client_id: &str,
1553 refresh_token: &str,
1554 ) -> Result<OAuthTokenMaterial> {
1555 #[cfg(any(test, feature = "test-support"))]
1556 crate::external_credentials::record_oauth_refresh();
1557 let mut fields = vec![
1558 ("grant_type", "refresh_token"),
1559 ("client_id", client_id),
1560 ("refresh_token", refresh_token),
1561 ];
1562 if params.display_name == "ChatGPT" {
1563 fields.push(("resource", CHATGPT_OAUTH_RESOURCE));
1564 }
1565 let (status, body) = client.post_form(token_url, &fields)?;
1566 parse_oauth_form_response(status, &body, "refresh", params)
1567 }
1568
1569 /// Best-effort remote revoke through the seam. Callers clear local
1570 /// credentials regardless of this outcome.
1571 pub(crate) fn revoke_remote_token_via(
1572 client: &dyn OAuthFormClient,
1573 params: &OAuthProviderParams,
1574 issuer: &str,
1575 client_id: &str,
1576 token: &str,
1577 ) -> Result<()> {
1578 let revoke_url = client.revocation_endpoint(params, issuer)?;
1579 let mut fields = vec![("token", token), ("client_id", client_id)];
1580 if params.display_name == "ChatGPT" {
1581 fields.push(("token_type_hint", "refresh_token"));
1582 }
1583 let (status, _) = client.post_form(&revoke_url, &fields)?;
1584 anyhow::ensure!(
1585 (200..300).contains(&status),
1586 "{} OAuth revoke failed with HTTP {status}",
1587 params.display_name
1588 );
1589 Ok(())
1590 }
1591
1592 // ── PKCE browser login ────────────────────────────────────────────────
1593
1594 /// RFC 7636 S256 PKCE pair. Custom Debug: the verifier is exchanged for
1595 /// bearer material and never prints.
1596 #[derive(Clone)]
1597 pub struct PkceChallenge {
1598 pub verifier: String,
1599 pub challenge: String,
1600 }
1601
1602 impl std::fmt::Debug for PkceChallenge {
1603 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1604 f.debug_struct("PkceChallenge")
1605 .field("verifier", &"<redacted>")
1606 .field("challenge", &self.challenge)
1607 .finish()
1608 }
1609 }
1610
1611 /// A browser authorization request in flight: state, PKCE pair, and the
1612 /// registered redirect the callback server answers on.
1613 #[derive(Clone)]
1614 pub struct BrowserAuthRequest {
1615 pub state: String,
1616 pub nonce: String,
1617 pub pkce: PkceChallenge,
1618 pub redirect_uri: String,
1619 pub authorize_url: String,
1620 }
1621
1622 impl std::fmt::Debug for BrowserAuthRequest {
1623 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1624 f.debug_struct("BrowserAuthRequest")
1625 .field("state", &self.state)
1626 .field("pkce", &self.pkce)
1627 .field("redirect_uri", &self.redirect_uri)
1628 .field("authorize_url", &"<redacted>")
1629 .finish()
1630 }
1631 }
1632
1633 /// Parsed callback query: a code+state pair, or the issuer's refusal.
1634 #[derive(Clone, PartialEq, Eq)]
1635 pub enum CallbackOutcome {
1636 Success {
1637 code: String,
1638 state: String,
1639 client_id: Option<String>,
1640 },
1641 Error {
1642 error: String,
1643 description: Option<String>,
1644 state: Option<String>,
1645 },
1646 }
1647
1648 impl std::fmt::Debug for CallbackOutcome {
1649 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1650 match self {
1651 Self::Success {
1652 state, client_id, ..
1653 } => f
1654 .debug_struct("Success")
1655 .field("code", &"<redacted>")
1656 .field("state", state)
1657 .field("client_id", client_id)
1658 .finish(),
1659 Self::Error { state, .. } => f
1660 .debug_struct("Error")
1661 .field("error", &"<redacted>")
1662 .field("state", state)
1663 .finish(),
1664 }
1665 }
1666 }
1667
1668 /// RFC 7636 S256 PKCE pair.
1669 #[must_use]
1670 pub fn generate_pkce() -> PkceChallenge {
1671 let verifier = random_url_token(32);
1672 let digest = Sha256::digest(verifier.as_bytes());
1673 PkceChallenge {
1674 verifier,
1675 challenge: URL_SAFE_NO_PAD.encode(digest),
1676 }
1677 }
1678
1679 #[must_use]
1680 pub fn generate_state() -> String {
1681 random_url_token(16)
1682 }
1683
1684 fn random_url_token(nbytes: usize) -> String {
1685 let mut bytes = vec![0u8; nbytes.max(16)];
1686 let mut offset = 0;
1687 while offset < bytes.len() {
1688 let chunk = uuid::Uuid::new_v4();
1689 let take = (bytes.len() - offset).min(16);
1690 bytes[offset..offset + take].copy_from_slice(&chunk.as_bytes()[..take]);
1691 offset += take;
1692 }
1693 URL_SAFE_NO_PAD.encode(bytes)
1694 }
1695
1696 pub fn build_authorize_url(
1697 params: &OAuthProviderParams,
1698 issuer: &str,
1699 client_id: &str,
1700 scopes: &str,
1701 redirect_uri: &str,
1702 state: &str,
1703 pkce: &PkceChallenge,
1704 ) -> Result<String> {
1705 let Some(authorize_path) = params.authorize_path else {
1706 bail!("{} offers no browser sign-in flow", params.display_name);
1707 };
1708 // A malformed configured issuer must fail loudly. Silently redirecting
1709 // the browser to the production authorize endpoint would hand the
1710 // issuer a sign-in the user aimed somewhere else.
1711 let issuer_var = params
1712 .env
1713 .issuer_vars
1714 .first()
1715 .copied()
1716 .unwrap_or("the issuer environment variable");
1717 let mut url = oauth_endpoint_url(&format!(
1718 "{}/{}",
1719 issuer.trim_end_matches('/'),
1720 authorize_path
1721 ))
1722 .with_context(|| {
1723 format!(
1724 "{} OAuth issuer is not a valid URL or uses an insecure endpoint — check {issuer_var}",
1725 params.display_name
1726 )
1727 })?;
1728 url.query_pairs_mut()
1729 .append_pair("response_type", "code")
1730 .append_pair("client_id", client_id)
1731 .append_pair("redirect_uri", redirect_uri)
1732 .append_pair("scope", scopes)
1733 .append_pair("code_challenge", &pkce.challenge)
1734 .append_pair("code_challenge_method", "S256")
1735 .append_pair("state", state);
1736 for (key, value) in params.authorize_extras {
1737 url.query_pairs_mut().append_pair(key, value);
1738 }
1739 let account_prompt_disabled = params
1740 .env
1741 .no_account_prompt_var
1742 .is_some_and(|var| std::env::var_os(var).is_some());
1743 if !account_prompt_disabled {
1744 for (key, value) in params.account_choice_extras {
1745 url.query_pairs_mut().append_pair(key, value);
1746 }
1747 }
1748 Ok(url.to_string())
1749 }
1750
1751 pub fn parse_callback_query(params: &OAuthProviderParams, query: &str) -> Result<CallbackOutcome> {
1752 let parsed = reqwest::Url::parse(&format!("http://127.0.0.1{}?{query}", params.callback_path))
1753 .context("OAuth callback query is not valid")?;
1754 let mut code = None;
1755 let mut state = None;
1756 let mut error = None;
1757 let mut description = None;
1758 let mut client_id = None;
1759 let mut seen = std::collections::HashSet::new();
1760 for (key, value) in parsed.query_pairs() {
1761 if matches!(
1762 key.as_ref(),
1763 "code" | "state" | "error" | "error_description" | "client_id"
1764 ) {
1765 anyhow::ensure!(
1766 seen.insert(key.to_string()),
1767 "OAuth callback contains a duplicate parameter"
1768 );
1769 }
1770 match key.as_ref() {
1771 "code" => code = Some(value.into_owned()),
1772 "state" => state = Some(value.into_owned()),
1773 "error" => error = Some(value.into_owned()),
1774 "error_description" => description = Some(value.into_owned()),
1775 "client_id" => client_id = Some(value.into_owned()),
1776 _ => {}
1777 }
1778 }
1779 anyhow::ensure!(
1780 code.is_none() || error.is_none(),
1781 "OAuth callback contains both success and error"
1782 );
1783 if let Some(error) = error {
1784 return Ok(CallbackOutcome::Error {
1785 error,
1786 description,
1787 state,
1788 });
1789 }
1790 let code = code
1791 .filter(|c| !c.trim().is_empty())
1792 .context("OAuth callback missing authorization code")?;
1793 let state = state
1794 .filter(|s| !s.trim().is_empty())
1795 .context("OAuth callback missing state")?;
1796 Ok(CallbackOutcome::Success {
1797 code,
1798 state,
1799 client_id,
1800 })
1801 }
1802
1803 #[cfg(any(test, feature = "test-support"))]
1804 pub fn accept_callback(expected_state: &str, outcome: CallbackOutcome) -> Result<String> {
1805 accept_callback_with_client(expected_state, outcome).map(|(code, _)| code)
1806 }
1807
1808 fn validate_callback_state(expected_state: &str, outcome: &CallbackOutcome) -> Result<()> {
1809 let state = match outcome {
1810 CallbackOutcome::Success { state, .. } => Some(state.as_str()),
1811 CallbackOutcome::Error { state, .. } => state.as_deref(),
1812 };
1813 anyhow::ensure!(
1814 state.is_some_and(|state| codewhale_core::secret_eq::constant_time_eq(
1815 state.as_bytes(),
1816 expected_state.as_bytes(),
1817 )),
1818 "OAuth callback state did not match the pending login"
1819 );
1820 Ok(())
1821 }
1822
1823 fn accept_callback_with_client(
1824 expected_state: &str,
1825 outcome: CallbackOutcome,
1826 ) -> Result<(String, Option<String>)> {
1827 validate_callback_state(expected_state, &outcome)?;
1828 match outcome {
1829 CallbackOutcome::Success {
1830 code, client_id, ..
1831 } => Ok((code, client_id)),
1832 CallbackOutcome::Error { error, .. } => {
1833 let error = compact_form_error(&error);
1834 bail!("sign-in was not completed ({error})")
1835 }
1836 }
1837 }
1838
1839 fn parse_http_request_target(request_line: &str) -> Result<String> {
1840 let mut parts = request_line.split_whitespace();
1841 let method = parts.next().unwrap_or_default();
1842 anyhow::ensure!(
1843 method.eq_ignore_ascii_case("GET"),
1844 "OAuth callback must be GET"
1845 );
1846 let target = parts
1847 .next()
1848 .context("OAuth callback missing request target")?;
1849 Ok(target.to_string())
1850 }
1851
1852 fn query_from_target<'a>(params: &OAuthProviderParams, target: &'a str) -> Result<&'a str> {
1853 let path = target.split('?').next().unwrap_or(target);
1854 anyhow::ensure!(
1855 path == params.callback_path,
1856 "OAuth callback path was not {}",
1857 params.callback_path
1858 );
1859 Ok(target.split_once('?').map(|(_, q)| q).unwrap_or(""))
1860 }
1861
1862 /// Bind ChatGPT's exact 127.0.0.1 callback, with an ephemeral-port fallback.
1863 /// Other providers using localhost bind both IP stacks when available.
1864 pub fn bind_loopback_callback(params: &OAuthProviderParams) -> Result<Vec<TcpListener>> {
1865 let name = params.display_name;
1866 let mut last_error = None;
1867 for port in params.loopback_ports {
1868 let mut bound = Vec::new();
1869 for addr in [
1870 SocketAddr::from((Ipv4Addr::LOCALHOST, *port)),
1871 SocketAddr::from((Ipv6Addr::LOCALHOST, *port)),
1872 ] {
1873 if params.display_name == "ChatGPT" && addr.is_ipv6() {
1874 continue;
1875 }
1876 match TcpListener::bind(addr) {
1877 Ok(listener) => {
1878 listener.set_nonblocking(true).with_context(|| {
1879 format!("{name} OAuth callback listener could not be set non-blocking")
1880 })?;
1881 bound.push(listener);
1882 }
1883 Err(error) => last_error = Some(error),
1884 }
1885 }
1886 if !bound.is_empty() {
1887 return Ok(bound);
1888 }
1889 }
1890 let ports = params
1891 .loopback_ports
1892 .iter()
1893 .map(u16::to_string)
1894 .collect::<Vec<_>>()
1895 .join(" or ");
1896 let hint = if params.callback_conflict_hint.is_empty() {
1897 String::new()
1898 } else {
1899 format!(" {}", params.callback_conflict_hint)
1900 };
1901 Err(last_error
1902 .map(anyhow::Error::from)
1903 .unwrap_or_else(|| anyhow::anyhow!("unable to bind {name} OAuth callback ports")))
1904 .with_context(|| format!("{name} sign-in needs loopback port {ports}.{hint}"))
1905 }
1906
1907 pub(crate) fn start_auth_request_on(
1908 listeners: &[TcpListener],
1909 params: &OAuthProviderParams,
1910 inputs: &ResolvedOAuthInputs,
1911 ) -> Result<BrowserAuthRequest> {
1912 let port = listeners
1913 .first()
1914 .with_context(|| {
1915 format!(
1916 "{} OAuth callback has no bound listener",
1917 params.display_name
1918 )
1919 })?
1920 .local_addr()
1921 .with_context(|| {
1922 format!(
1923 "{} OAuth callback listener has no local address",
1924 params.display_name
1925 )
1926 })?
1927 .port();
1928 let host = if params.display_name == "ChatGPT" {
1929 "127.0.0.1"
1930 } else {
1931 "localhost"
1932 };
1933 let redirect_uri = format!("http://{host}:{port}{}", params.callback_path);
1934 let pkce = generate_pkce();
1935 let state = generate_state();
1936 let nonce = generate_state();
1937 let mut authorize_url = reqwest::Url::parse(&build_authorize_url(
1938 params,
1939 &inputs.issuer,
1940 &inputs.client_id,
1941 &inputs.scopes,
1942 &redirect_uri,
1943 &state,
1944 &pkce,
1945 )?)?;
1946 if params.display_name == "ChatGPT" {
1947 authorize_url.query_pairs_mut().append_pair("nonce", &nonce);
1948 if inputs.client_id == CHATGPT_OAUTH_CLIENT_ID {
1949 authorize_url
1950 .query_pairs_mut()
1951 .append_pair("agent_name_hint", "Codewhale");
1952 }
1953 }
1954 Ok(BrowserAuthRequest {
1955 state,
1956 nonce,
1957 pkce,
1958 redirect_uri,
1959 authorize_url: authorize_url.to_string(),
1960 })
1961 }
1962
1963 // Allow time for browser authentication and 2FA, as in the MCP OAuth flow.
1964 pub const CALLBACK_TIMEOUT: Duration = Duration::from_secs(900);
1965 const CALLBACK_HTML_OK: &str = "<!doctype html><html><body><p>Signed in to Codewhale. You can close this tab.</p></body></html>";
1966 const CALLBACK_HTML_ERR: &str = "<!doctype html><html><body><p>Sign-in did not complete. You can close this tab and retry in Codewhale.</p></body></html>";
1967
1968 fn wait_for_callback(
1969 listeners: &[TcpListener],
1970 params: &OAuthProviderParams,
1971 expected_state: &str,
1972 ) -> Result<(String, Option<String>)> {
1973 wait_for_callback_validated(listeners, params, expected_state, None)
1974 }
1975
1976 pub fn wait_for_callback_validated(
1977 listeners: &[TcpListener],
1978 params: &OAuthProviderParams,
1979 expected_state: &str,
1980 expected_issuer: Option<&str>,
1981 ) -> Result<(String, Option<String>)> {
1982 let Some(outcome) = wait_for_callback_outcome(
1983 listeners,
1984 params,
1985 expected_state,
1986 expected_issuer,
1987 Instant::now() + CALLBACK_TIMEOUT,
1988 &|| false,
1989 )?
1990 else {
1991 bail!(
1992 "{} sign-in timed out waiting for the browser callback",
1993 params.display_name
1994 );
1995 };
1996 accept_callback_with_client(expected_state, outcome)
1997 }
1998
1999 pub enum OrcaCallback {
2000 Code(String),
2001 Declined,
2002 Refused,
2003 Stopped,
2004 }
2005
2006 pub fn wait_for_orcarouter_callback(
2007 listeners: &[TcpListener],
2008 expected_state: &str,
2009 deadline: Instant,
2010 cancelled: &dyn Fn() -> bool,
2011 ) -> Result<OrcaCallback> {
2012 Ok(
2013 match wait_for_callback_outcome(
2014 listeners,
2015 &ORCAROUTER_OAUTH_PARAMS,
2016 expected_state,
2017 None,
2018 deadline,
2019 cancelled,
2020 )? {
2021 None => OrcaCallback::Stopped,
2022 Some(CallbackOutcome::Success { code, .. }) => OrcaCallback::Code(code),
2023 Some(CallbackOutcome::Error { error, .. }) if error == "access_denied" => {
2024 OrcaCallback::Declined
2025 }
2026 Some(CallbackOutcome::Error { .. }) => OrcaCallback::Refused,
2027 },
2028 )
2029 }
2030
2031 fn wait_for_callback_outcome(
2032 listeners: &[TcpListener],
2033 params: &OAuthProviderParams,
2034 expected_state: &str,
2035 expected_issuer: Option<&str>,
2036 deadline: Instant,
2037 cancelled: &dyn Fn() -> bool,
2038 ) -> Result<Option<CallbackOutcome>> {
2039 loop {
2040 if Instant::now() >= deadline || cancelled() {
2041 return Ok(None);
2042 }
2043 // Whichever stack `localhost` resolved to for the browser is the one
2044 // that gets the connection; poll them all.
2045 for listener in listeners {
2046 match listener.accept() {
2047 Ok((stream, _)) => {
2048 if let Ok(outcome) = handle_callback_stream_validated(
2049 stream,
2050 params,
2051 expected_state,
2052 expected_issuer,
2053 deadline,
2054 ) {
2055 return Ok(Some(outcome));
2056 }
2057 }
2058 Err(error)
2059 if error.kind() == std::io::ErrorKind::WouldBlock
2060 || error.kind() == std::io::ErrorKind::Interrupted => {}
2061 Err(error) => {
2062 return Err(error).context(format!(
2063 "{} OAuth callback accept failed",
2064 params.display_name
2065 ));
2066 }
2067 }
2068 }
2069 std::thread::sleep(
2070 deadline
2071 .saturating_duration_since(Instant::now())
2072 .min(Duration::from_millis(50)),
2073 );
2074 }
2075 }
2076
2077 #[cfg(test)]
2078 fn handle_callback_stream(
2079 stream: TcpStream,
2080 params: &OAuthProviderParams,
2081 expected_state: &str,
2082 ) -> Result<(String, Option<String>)> {
2083 let outcome = handle_callback_stream_validated(
2084 stream,
2085 params,
2086 expected_state,
2087 None,
2088 Instant::now() + CALLBACK_TIMEOUT,
2089 )?;
2090 accept_callback_with_client(expected_state, outcome)
2091 }
2092
2093 fn handle_callback_stream_validated(
2094 mut stream: TcpStream,
2095 params: &OAuthProviderParams,
2096 expected_state: &str,
2097 expected_issuer: Option<&str>,
2098 deadline: Instant,
2099 ) -> Result<CallbackOutcome> {
2100 let deadline = deadline.min(Instant::now() + Duration::from_secs(5));
2101 // BSD sockets (macOS) hand the accepted stream the listener's O_NONBLOCK;
2102 // the bounded read below needs a blocking socket with a timeout.
2103 stream.set_nonblocking(false).with_context(|| {
2104 format!(
2105 "{} OAuth callback stream could not be set blocking",
2106 params.display_name
2107 )
2108 })?;
2109 let result = (|| {
2110 // One read is not one request: TCP may deliver the callback in
2111 // fragments, and a truncated query parses as a missing parameter.
2112 // Read until the blank line that ends the HTTP headers.
2113 let mut buf = [0u8; 4096];
2114 let mut len = 0usize;
2115 loop {
2116 if len == buf.len() {
2117 break;
2118 }
2119 let remaining = deadline
2120 .checked_duration_since(Instant::now())
2121 .filter(|remaining| !remaining.is_zero())
2122 .context("OAuth callback request timed out")?;
2123 stream.set_read_timeout(Some(remaining))?;
2124 let n = stream.read(&mut buf[len..]).with_context(|| {
2125 format!("reading {} OAuth callback request", params.display_name)
2126 })?;
2127 if n == 0 {
2128 break;
2129 }
2130 len += n;
2131 if buf[..len].windows(4).any(|window| window == b"\r\n\r\n") {
2132 break;
2133 }
2134 }
2135 anyhow::ensure!(
2136 buf[..len].windows(4).any(|window| window == b"\r\n\r\n"),
2137 "OAuth callback request headers are incomplete"
2138 );
2139 let request = String::from_utf8_lossy(&buf[..len]);
2140 let request_line = request.lines().next().unwrap_or_default();
2141 let target = parse_http_request_target(request_line)?;
2142 let query = query_from_target(params, &target)?;
2143 if let Some(issuer) = expected_issuer {
2144 validate_plugin_callback(query, issuer)?;
2145 }
2146 let outcome = parse_callback_query(params, query)?;
2147 validate_callback_state(expected_state, &outcome)?;
2148 Ok(outcome)
2149 })();
2150 let (status, body) = match &result {
2151 Ok(CallbackOutcome::Success { .. }) => ("200 OK", CALLBACK_HTML_OK),
2152 _ => ("400 Bad Request", CALLBACK_HTML_ERR),
2153 };
2154 if let Some(remaining) = deadline
2155 .checked_duration_since(Instant::now())
2156 .filter(|remaining| !remaining.is_zero())
2157 && stream.set_write_timeout(Some(remaining)).is_ok()
2158 {
2159 let _ = write!(
2160 stream,
2161 "HTTP/1.1 {status}\r\ncontent-type: text/html; charset=utf-8\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
2162 body.len()
2163 );
2164 }
2165 result
2166 }
2167
2168 pub(crate) fn exchange_authorization_code(
2169 client: &dyn OAuthFormClient,
2170 params: &OAuthProviderParams,
2171 token_endpoint: &str,
2172 client_id: &str,
2173 redirect_uri: &str,
2174 code: &str,
2175 verifier: &str,
2176 ) -> Result<OAuthTokenMaterial> {
2177 let mut fields = vec![
2178 ("grant_type", "authorization_code"),
2179 ("client_id", client_id),
2180 ("redirect_uri", redirect_uri),
2181 ("code", code),
2182 ("code_verifier", verifier),
2183 ];
2184 if params.display_name == "ChatGPT" {
2185 fields.push(("resource", CHATGPT_OAUTH_RESOURCE));
2186 }
2187 let (status, body) = client.post_form(token_endpoint, &fields)?;
2188 parse_oauth_form_response(status, &body, "authorization code exchange", params)
2189 }
2190
2191 /// Terminal-or-stdout challenge writer for shell commands that drive a login
2192 /// outside the TUI (`codewhale auth ...`).
2193 pub fn cli_challenge_writer() -> Result<Box<dyn std::io::Write + Send>> {
2194 oauth_challenge_writer()
2195 }
2196
2197 /// Interactive PKCE browser login for any provider whose row offers it.
2198 /// Shows the authorize URL only on a terminal, opens a browser, and waits for the loopback
2199 /// callback. A provider with no browser flow (xAI) fails here with the
2200 /// reason, before any listener binds.
2201 pub async fn pkce_login(provider: OAuthProvider) -> Result<PendingOAuthLogin> {
2202 let params = oauth_provider_params(provider);
2203 if params.authorize_path.is_none() {
2204 bail!(
2205 "{} offers no browser sign-in flow; sign in through the device-code login instead",
2206 params.display_name
2207 );
2208 }
2209 let inputs = params.resolve_inputs();
2210 if provider == OAuthProvider::Chatgpt {
2211 anyhow::ensure!(
2212 inputs.issuer == CHATGPT_OAUTH_ISSUER,
2213 "Official ChatGPT sign-in requires https://auth.openai.com; remove the issuer override"
2214 );
2215 }
2216 let display_name = params.display_name;
2217 let mut challenge = oauth_challenge_writer()?;
2218 tokio::task::spawn_blocking(move || {
2219 pkce_login_with_selected(
2220 provider,
2221 &inputs,
2222 None,
2223 ChatgptLoginMode::FreshAccount,
2224 challenge.as_mut(),
2225 )
2226 })
2227 .await
2228 .with_context(|| format!("{display_name} PKCE login worker failed"))?
2229 }
2230
2231 fn effective_chatgpt_login_mode(mode: ChatgptLoginMode) -> ChatgptLoginMode {
2232 if std::env::var("CODEWHALE_CHATGPT_NEW_ACCOUNT").is_ok_and(|value| value == "1") {
2233 ChatgptLoginMode::FreshAccount
2234 } else {
2235 mode
2236 }
2237 }
2238
2239 fn apply_chatgpt_host_to_authorize_url(authorize_url: &str, host: &ChatgptHost) -> Result<String> {
2240 let mut url = reqwest::Url::parse(authorize_url)?;
2241 url.query_pairs_mut()
2242 .append_pair("ext_agent_host_id", &host.host_id);
2243 if let Some(email) = host
2244 .registration
2245 .as_ref()
2246 .and_then(|registration| registration.email.as_deref())
2247 {
2248 url.query_pairs_mut().append_pair("login_hint", email);
2249 }
2250 Ok(url.to_string())
2251 }
2252
2253 /// Blocking browser protocol worker with a previously admitted terminal.
2254 fn pkce_login_with_selected(
2255 provider: OAuthProvider,
2256 inputs: &ResolvedOAuthInputs,
2257 selected: Option<ChatgptRegistration>,
2258 mode: ChatgptLoginMode,
2259 challenge: &mut dyn std::io::Write,
2260 ) -> Result<PendingOAuthLogin> {
2261 let params = oauth_provider_params(provider);
2262 let display_name = params.display_name;
2263 let effective_mode = effective_chatgpt_login_mode(mode);
2264 let mut host = if provider == OAuthProvider::Chatgpt {
2265 Some(prepare_chatgpt_host_for_mode(effective_mode)?)
2266 } else {
2267 None
2268 };
2269 if let Some(host) = &mut host {
2270 if effective_mode == ChatgptLoginMode::ReauthorizeCurrent
2271 && let Some(mut selected) = selected
2272 {
2273 selected.host_id = host.host_id.clone();
2274 host.registration = Some(selected);
2275 }
2276 if let Some(registration) = &host.registration {
2277 anyhow::ensure!(
2278 registration.issuer == inputs.issuer,
2279 "Saved ChatGPT registration belongs to a different issuer; credentials were not replaced"
2280 );
2281 }
2282 }
2283 let mut inputs = inputs.clone();
2284 if let Some(host) = &host {
2285 inputs.client_id = host.registration.as_ref().map_or_else(
2286 || CHATGPT_OAUTH_CLIENT_ID.to_string(),
2287 |registration| registration.client_id.clone(),
2288 );
2289 }
2290 let listeners = bind_loopback_callback(params)?;
2291 let mut request = start_auth_request_on(&listeners, params, &inputs)?;
2292 if let Some(host) = &host {
2293 request.authorize_url = apply_chatgpt_host_to_authorize_url(&request.authorize_url, host)?;
2294 }
2295 writeln!(challenge, "{display_name} sign-in (PKCE)")?;
2296 writeln!(challenge, " Open: {}", request.authorize_url)?;
2297 writeln!(
2298 challenge,
2299 "{}",
2300 account_choice_hint(display_name, effective_mode)
2301 )?;
2302 writeln!(
2303 challenge,
2304 "Waiting for the browser callback… (Ctrl+C to abort)"
2305 )?;
2306 challenge.flush()?;
2307 if inputs.open_browser && crate::browser::open_url(&request.authorize_url).is_err() {
2308 writeln!(
2309 challenge,
2310 "Could not open the browser automatically; open the displayed URL manually"
2311 )?;
2312 }
2313 let (code, callback_id) = wait_for_callback(&listeners, params, &request.state)?;
2314 let client_id = if provider == OAuthProvider::Chatgpt {
2315 issued_callback_client_id(&inputs.client_id, callback_id.as_deref())?
2316 } else {
2317 inputs.client_id.clone()
2318 };
2319 let mut token = exchange_authorization_code(
2320 &ReqwestOAuthFormClient,
2321 params,
2322 &form_token_url(params, &inputs.issuer),
2323 &client_id,
2324 &request.redirect_uri,
2325 &code,
2326 &request.pkce.verifier,
2327 )?;
2328 if let Some(host) = &host {
2329 require_chatgpt_scopes(token.scope.as_deref())?;
2330 anyhow::ensure!(
2331 token
2332 .token_type
2333 .as_deref()
2334 .is_some_and(|value| value.eq_ignore_ascii_case("bearer")),
2335 "ChatGPT token response did not return Bearer credentials"
2336 );
2337 let id_token = token
2338 .id_token
2339 .as_deref()
2340 .context("ChatGPT sign-in omitted its ID token")?;
2341 let access_token = token
2342 .access_token
2343 .as_deref()
2344 .context("ChatGPT sign-in omitted its access token")?;
2345 let keys = chatgpt_keys_covering(&[id_token, access_token], || {
2346 fetch_chatgpt_jwks(&inputs.issuer)
2347 })?;
2348 let registration = verify_chatgpt_id_token(
2349 id_token,
2350 &keys,
2351 &inputs.issuer,
2352 &client_id,
2353 Some(&request.nonce),
2354 host.registration
2355 .as_ref()
2356 .map(|registration| registration.subject.as_str()),
2357 &host.host_id,
2358 )?;
2359 verify_chatgpt_access_token(access_token, &keys, &registration)?;
2360 token.verified_chatgpt = Some(registration);
2361 }
2362 Ok(PendingOAuthLogin {
2363 provider,
2364 issuer: inputs.issuer.clone(),
2365 client_id,
2366 token,
2367 })
2368 }
2369
2370 // ── owned credential storage (one shared store) ───────────────
2371 //
2372 // Codewhale-owned OAuth generations live in the config crate's credential
2373 // store under per-provider generation prefixes. xAI historically stored the
2374 // access token as `key` (Grok CLI shape); ChatGPT as `access_token`. One
2375 // entry type reads both; new generations write the unified shape.
2376
2377 /// xAI issuer and public client (constants the params rows and the route
2378 /// surfaces share).
2379 pub const XAI_OIDC_ISSUER: &str = "https://auth.x.ai";
2380 pub const GROK_OIDC_CLIENT_ID: &str = "b1a00492-073a-47ea-816f-4c329264a828";
2381 pub const DEFAULT_SCOPES: &str = "openid profile email offline_access api:access grok-cli:access";
2382 /// Hard ceiling past a device grant's own `expires_in`.
2383 pub(crate) const DEVICE_POLL_MAX_SECS: u64 = 900;
2384
2385 /// ChatGPT issuer and public client.
2386 pub const CHATGPT_OAUTH_ISSUER: &str = "https://auth.openai.com";
2387 pub const CHATGPT_OAUTH_CLIENT_ID: &str = "dynamic_agent_client";
2388 pub const CHATGPT_OAUTH_RESOURCE: &str = "https://api.openai.com/v1";
2389 pub const CHATGPT_OAUTH_SCOPE: &str =
2390 "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";
2391 const CHATGPT_CLOCK_SKEW_LEEWAY_SECS: i64 = 60;
2392
2393 #[derive(Clone)]
2394 pub struct ChatgptKeys {
2395 set: JwkSet,
2396 issuer_clock_offset: Option<i64>,
2397 }
2398
2399 impl From<JwkSet> for ChatgptKeys {
2400 fn from(set: JwkSet) -> Self {
2401 Self {
2402 set,
2403 issuer_clock_offset: None,
2404 }
2405 }
2406 }
2407
2408 /// Verified registration identity. The client ID also binds the selected workspace.
2409 /// One active registration is supported; ordinary sign-in replaces it after a
2410 /// new, fully validated browser sign-in, while `--reauth` stays on the current one.
2411 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2412 pub struct ChatgptRegistration {
2413 pub issuer: String,
2414 pub client_id: String,
2415 pub subject: String,
2416 pub email: Option<String>,
2417 pub host_id: String,
2418 }
2419
2420 #[derive(Serialize, Deserialize)]
2421 struct ChatgptHost {
2422 host_id: String,
2423 #[serde(default)]
2424 registration: Option<ChatgptRegistration>,
2425 }
2426
2427 fn valid_issued_chatgpt_client_id(value: &str) -> bool {
2428 value.starts_with("oaiapp_")
2429 && value.len() > 7
2430 && value.len() <= 256
2431 && value
2432 .bytes()
2433 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
2434 }
2435
2436 fn validate_chatgpt_host(host: &ChatgptHost) -> Result<()> {
2437 let id = host
2438 .host_id
2439 .strip_prefix("urn:uuid:")
2440 .and_then(|value| uuid::Uuid::parse_str(value).ok())
2441 .context("ChatGPT host identifier is invalid")?;
2442 anyhow::ensure!(
2443 id.get_version_num() == 4,
2444 "ChatGPT host identifier must be a UUIDv4"
2445 );
2446 if let Some(registration) = &host.registration {
2447 anyhow::ensure!(
2448 registration.host_id == host.host_id
2449 && valid_issued_chatgpt_client_id(&registration.client_id)
2450 && !registration.subject.trim().is_empty(),
2451 "Saved ChatGPT registration is invalid"
2452 );
2453 }
2454 Ok(())
2455 }
2456
2457 fn prepare_chatgpt_host_for_mode(mode: ChatgptLoginMode) -> Result<ChatgptHost> {
2458 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
2459 let name = codewhale_config::CHATGPT_HOST_FILE_NAME;
2460 let mut host: ChatgptHost = match store.read_to_string(name)? {
2461 Some(raw) => {
2462 serde_json::from_str(&raw).context("Saved ChatGPT host metadata is invalid")?
2463 }
2464 None => ChatgptHost {
2465 host_id: format!("urn:uuid:{}", uuid::Uuid::new_v4()),
2466 registration: None,
2467 },
2468 };
2469 validate_chatgpt_host(&host)?;
2470 // Persist before opening a browser, including after a cancelled first login.
2471 store.write(name, &serde_json::to_vec(&host)?, true)?;
2472 if effective_chatgpt_login_mode(mode) == ChatgptLoginMode::FreshAccount {
2473 host.registration = None;
2474 }
2475 Ok(host)
2476 })
2477 }
2478
2479 fn require_chatgpt_scopes(scope: Option<&str>) -> Result<()> {
2480 let scope = scope.context("ChatGPT token response omitted granted scopes; sign in again")?;
2481 for required in ["chatgpt.tokens.use.direct", "resource.invoke"] {
2482 anyhow::ensure!(
2483 scope
2484 .split_ascii_whitespace()
2485 .any(|value| value == required),
2486 "ChatGPT plan permission was not granted; authorize plan usage in ChatGPT and sign in again"
2487 );
2488 }
2489 Ok(())
2490 }
2491
2492 #[derive(Clone, Deserialize)]
2493 struct ChatgptIdClaims {
2494 sub: String,
2495 #[serde(default)]
2496 nonce: Option<String>,
2497 #[serde(default)]
2498 email: Option<String>,
2499 }
2500
2501 fn fetch_chatgpt_jwks(issuer: &str) -> Result<ChatgptKeys> {
2502 let url = oauth_endpoint_url(&format!(
2503 "{}/.well-known/jwks.json",
2504 issuer.trim_end_matches('/')
2505 ))?;
2506 let response = oauth_http_client(&url, "identity verification")?
2507 .get(url)
2508 .send()
2509 .context("ChatGPT identity verification keys could not be retrieved")?;
2510 let issuer_clock_offset = response
2511 .headers()
2512 .get(reqwest::header::DATE)
2513 .and_then(|value| value.to_str().ok())
2514 .and_then(|value| chrono::DateTime::parse_from_rfc2822(value).ok())
2515 .zip(now_unix_secs())
2516 .map(|(issuer_now, local_now)| issuer_now.timestamp().saturating_sub(local_now));
2517 let (status, set) = parse_oauth_json(response, "ChatGPT verification keys")?;
2518 anyhow::ensure!(
2519 status.is_success(),
2520 "ChatGPT identity verification keys are unavailable"
2521 );
2522 Ok(ChatgptKeys {
2523 set,
2524 issuer_clock_offset,
2525 })
2526 }
2527
2528 fn chatgpt_keys_covering(
2529 tokens: &[&str],
2530 fetch: impl Fn() -> Result<ChatgptKeys>,
2531 ) -> Result<ChatgptKeys> {
2532 let keys = fetch()?;
2533 let unknown_key = tokens.iter().any(|token| {
2534 decode_header(token)
2535 .ok()
2536 .and_then(|header| header.kid)
2537 .is_some_and(|kid| keys.set.find(&kid).is_none())
2538 });
2539 if unknown_key { fetch() } else { Ok(keys) }
2540 }
2541
2542 fn chatgpt_clock_difference(issuer_clock_offset: Option<i64>) -> String {
2543 match issuer_clock_offset {
2544 Some(offset) if offset.abs() > CHATGPT_CLOCK_SKEW_LEEWAY_SECS => format!(
2545 " (this device's clock is {} s {} the issuer's)",
2546 offset.unsigned_abs(),
2547 if offset > 0 { "behind" } else { "ahead of" }
2548 ),
2549 _ => String::new(),
2550 }
2551 }
2552
2553 fn verify_chatgpt_token_time(claims: &Value, keys: &ChatgptKeys) -> Result<()> {
2554 let local_now =
2555 now_unix_secs().context("System clock is unavailable for ChatGPT token verification")?;
2556 let now = local_now.saturating_add(keys.issuer_clock_offset.unwrap_or(0));
2557 let numeric_date = |claim: &str| -> Result<Option<i64>> {
2558 claims
2559 .get(claim)
2560 .map(|value| {
2561 value
2562 .as_i64()
2563 .or_else(|| {
2564 value
2565 .as_f64()
2566 .filter(|seconds| seconds.is_finite())
2567 .map(|seconds| seconds as i64)
2568 })
2569 .with_context(|| format!("ChatGPT token has an invalid {claim} claim format"))
2570 })
2571 .transpose()
2572 };
2573 let difference = chatgpt_clock_difference(keys.issuer_clock_offset);
2574 if numeric_date("exp")?
2575 .is_some_and(|exp| exp.saturating_add(CHATGPT_CLOCK_SKEW_LEEWAY_SECS) < now)
2576 {
2577 anyhow::bail!(if keys.issuer_clock_offset.is_some() {
2578 format!("ChatGPT token has expired by the issuer's clock{difference}; sign in again")
2579 } else {
2580 "ChatGPT token has expired; check your device date and time, then sign in again"
2581 .to_string()
2582 });
2583 }
2584 if numeric_date("nbf")?
2585 .is_some_and(|nbf| nbf > now.saturating_add(CHATGPT_CLOCK_SKEW_LEEWAY_SECS))
2586 {
2587 anyhow::bail!(if keys.issuer_clock_offset.is_some() {
2588 format!(
2589 "ChatGPT token is not valid yet by the issuer's clock{difference}; sign in again"
2590 )
2591 } else {
2592 "ChatGPT token is not valid yet; synchronize your device clock, then sign in again"
2593 .to_string()
2594 });
2595 }
2596 Ok(())
2597 }
2598
2599 fn verify_chatgpt_jwt<T: serde::de::DeserializeOwned + Clone>(
2600 token: &str,
2601 keys: &ChatgptKeys,
2602 issuer: &str,
2603 audience: &str,
2604 text_claims: &[&'static str],
2605 ) -> Result<T> {
2606 let header = decode_header(token).context("ChatGPT identity token header is invalid")?;
2607 anyhow::ensure!(
2608 matches!(
2609 header.alg,
2610 Algorithm::RS256
2611 | Algorithm::RS384
2612 | Algorithm::RS512
2613 | Algorithm::ES256
2614 | Algorithm::ES384
2615 | Algorithm::EdDSA
2616 ),
2617 "ChatGPT identity token uses an unsupported signature algorithm"
2618 );
2619 let kid = header
2620 .kid
2621 .as_deref()
2622 .context("ChatGPT identity token omitted its verification key")?;
2623 let jwk = keys
2624 .set
2625 .find(kid)
2626 .context("ChatGPT identity token verification key is unknown")?;
2627 let key = DecodingKey::from_jwk(jwk).context("ChatGPT identity verification key is invalid")?;
2628 let mut validation = Validation::new(header.alg);
2629 validation.set_issuer(&[issuer]);
2630 validation.set_audience(&[audience]);
2631 validation.set_required_spec_claims(&["exp", "iss", "aud", "sub"]);
2632 validation.validate_exp = false;
2633 validation.validate_nbf = false;
2634 let claims = decode::<Value>(token, &key, &validation)
2635 .map_err(|error| match error.kind() {
2636 ErrorKind::InvalidSignature => {
2637 anyhow::anyhow!("ChatGPT token signature verification failed")
2638 }
2639 ErrorKind::InvalidIssuer => {
2640 anyhow::anyhow!("ChatGPT token issuer does not match the expected issuer")
2641 }
2642 ErrorKind::InvalidAudience => {
2643 anyhow::anyhow!("ChatGPT token audience does not match this registration")
2644 }
2645 ErrorKind::InvalidSubject => {
2646 anyhow::anyhow!("ChatGPT token subject does not match the expected account")
2647 }
2648 ErrorKind::MissingRequiredClaim(claim)
2649 if ["exp", "iss", "aud", "sub"].contains(&claim.as_str()) =>
2650 {
2651 anyhow::anyhow!("ChatGPT token is missing required {claim} claim")
2652 }
2653 ErrorKind::InvalidClaimFormat(claim)
2654 if ["exp", "iss", "aud", "sub", "nbf"].contains(&claim.as_str()) =>
2655 {
2656 anyhow::anyhow!("ChatGPT token has an invalid {claim} claim format")
2657 }
2658 ErrorKind::InvalidAlgorithm | ErrorKind::UnsupportedAlgorithm => anyhow::anyhow!(
2659 "ChatGPT token signature algorithm does not match the verification key"
2660 ),
2661 _ => anyhow::anyhow!("ChatGPT token format or identity claims failed verification"),
2662 })?
2663 .claims;
2664 verify_chatgpt_token_time(&claims, keys)?;
2665 let exact_audience = claims.get("aud").is_some_and(|aud| {
2666 aud.as_str() == Some(audience)
2667 || aud
2668 .as_array()
2669 .is_some_and(|values| values.len() == 1 && values[0].as_str() == Some(audience))
2670 });
2671 anyhow::ensure!(
2672 exact_audience,
2673 "ChatGPT token audience does not match this registration"
2674 );
2675 for claim in text_claims {
2676 match claims.get(*claim) {
2677 None => anyhow::bail!("ChatGPT token is missing required {claim} claim"),
2678 Some(value) if !value.is_string() => {
2679 anyhow::bail!("ChatGPT token has an invalid {claim} claim format")
2680 }
2681 Some(_) => {}
2682 }
2683 }
2684 serde_json::from_value(claims).context("ChatGPT token identity claims are invalid")
2685 }
2686
2687 fn verify_chatgpt_id_token(
2688 token: &str,
2689 keys: &ChatgptKeys,
2690 issuer: &str,
2691 client_id: &str,
2692 nonce: Option<&str>,
2693 expected_subject: Option<&str>,
2694 host_id: &str,
2695 ) -> Result<ChatgptRegistration> {
2696 let claims: ChatgptIdClaims = verify_chatgpt_jwt(token, keys, issuer, client_id, &["sub"])?;
2697 anyhow::ensure!(
2698 !claims.sub.trim().is_empty(),
2699 "ChatGPT identity token has no subject"
2700 );
2701 if let Some(nonce) = nonce {
2702 anyhow::ensure!(
2703 claims.nonce.as_deref() == Some(nonce),
2704 "ChatGPT identity token nonce did not match the pending login"
2705 );
2706 }
2707 if let Some(subject) = expected_subject {
2708 anyhow::ensure!(
2709 claims.sub == subject,
2710 "ChatGPT sign-in returned a different account; the selected registration was not replaced"
2711 );
2712 }
2713 Ok(ChatgptRegistration {
2714 issuer: issuer.to_string(),
2715 client_id: client_id.to_string(),
2716 subject: claims.sub,
2717 email: claims.email,
2718 host_id: host_id.to_string(),
2719 })
2720 }
2721
2722 #[derive(Clone, Deserialize)]
2723 struct ChatgptAccessClaims {
2724 sub: String,
2725 client_id: String,
2726 scope: String,
2727 }
2728
2729 fn verify_chatgpt_access_token(
2730 token: &str,
2731 keys: &ChatgptKeys,
2732 registration: &ChatgptRegistration,
2733 ) -> Result<()> {
2734 let claims: ChatgptAccessClaims = verify_chatgpt_jwt(
2735 token,
2736 keys,
2737 &registration.issuer,
2738 CHATGPT_OAUTH_RESOURCE,
2739 &["sub", "client_id", "scope"],
2740 )?;
2741 anyhow::ensure!(
2742 claims.sub == registration.subject && claims.client_id == registration.client_id,
2743 "ChatGPT access token does not match the selected account registration"
2744 );
2745 require_chatgpt_scopes(Some(&claims.scope))
2746 }
2747
2748 fn issued_callback_client_id(pending_id: &str, callback_id: Option<&str>) -> Result<String> {
2749 if pending_id == CHATGPT_OAUTH_CLIENT_ID {
2750 let issued =
2751 callback_id.context("ChatGPT registration did not return an issued client ID")?;
2752 anyhow::ensure!(
2753 valid_issued_chatgpt_client_id(issued),
2754 "ChatGPT registration returned an invalid client ID"
2755 );
2756 Ok(issued.to_string())
2757 } else {
2758 anyhow::ensure!(
2759 valid_issued_chatgpt_client_id(pending_id),
2760 "Saved ChatGPT client ID is invalid; register again"
2761 );
2762 anyhow::ensure!(
2763 callback_id.is_none_or(|value| value == pending_id),
2764 "ChatGPT callback changed the selected registration; credentials were not replaced"
2765 );
2766 Ok(pending_id.to_string())
2767 }
2768 }
2769
2770 fn registration_from_entry(entry: &OwnedAuthEntry) -> Result<ChatgptRegistration> {
2771 let registration: ChatgptRegistration =
2772 serde_json::from_value(entry.extra.get("siwc_registration").cloned().context(
2773 "Existing ChatGPT credentials need reauthorization; run `codewhale auth chatgpt`",
2774 )?)
2775 .context("Saved official ChatGPT registration is invalid; sign in again")?;
2776 anyhow::ensure!(
2777 registration.issuer == CHATGPT_OAUTH_ISSUER
2778 && entry.oidc_issuer.as_deref() == Some(registration.issuer.as_str())
2779 && entry.oidc_client_id.as_deref() == Some(registration.client_id.as_str())
2780 && entry.account_id.as_deref() == Some(registration.subject.as_str())
2781 && valid_issued_chatgpt_client_id(&registration.client_id)
2782 && !registration.subject.trim().is_empty(),
2783 "Saved ChatGPT grant does not match its verified registration; sign in again"
2784 );
2785 require_chatgpt_scopes(entry.extra.get("siwc_scope").and_then(Value::as_str))?;
2786 let access = entry
2787 .access_token
2788 .as_deref()
2789 .context("Saved ChatGPT access token is missing")?;
2790 let fingerprint = URL_SAFE_NO_PAD.encode(Sha256::digest(access.as_bytes()));
2791 anyhow::ensure!(
2792 entry.extra.get("siwc_token_sha256").and_then(Value::as_str) == Some(fingerprint.as_str()),
2793 "Saved ChatGPT token does not match its validated grant; sign in again"
2794 );
2795 Ok(registration)
2796 }
2797
2798 /// Metadata only: no network, refresh, token return, or external credential import.
2799 pub fn official_chatgpt_registration(config: &Config) -> Result<ChatgptRegistration> {
2800 let identity = config
2801 .builtin_provider_identity(OAuthProvider::Chatgpt.api())
2802 .map_err(anyhow::Error::msg)?;
2803 anyhow::ensure!(
2804 config
2805 .provider_config_for(&identity)
2806 .and_then(|entry| entry.auth_mode.as_deref())
2807 == Some("oauth"),
2808 "Sign in with ChatGPT using `codewhale auth chatgpt`; the selected route has no official OAuth grant"
2809 );
2810 let path = configured_owned_auth_file_path(OAuthProvider::Chatgpt, config)?
2811 .context("Sign in with ChatGPT using `codewhale auth chatgpt`")?;
2812 let mut file = load_owned_auth_file(&path)?.context("Saved ChatGPT credentials are missing")?;
2813 let (_, entry) = select_entry(OAuthProvider::Chatgpt, &mut file)
2814 .context("Saved ChatGPT credentials are missing")?;
2815 registration_from_entry(&entry)
2816 }
2817
2818 impl OAuthProvider {
2819 /// The engine provider this OAuth row belongs to.
2820 #[must_use]
2821 pub fn api(self) -> codewhale_config::ProviderKind {
2822 match self {
2823 OAuthProvider::Xai => codewhale_config::ProviderKind::Xai,
2824 OAuthProvider::Chatgpt => codewhale_config::ProviderKind::OpenaiCodex,
2825 }
2826 }
2827
2828 /// `[providers.<key>]` table this provider's auth state lives under.
2829 fn config_key(self) -> &'static str {
2830 codewhale_config::descriptors::compatibility_for_kind(self.api()).config_key
2831 }
2832
2833 fn legacy_file_name(self) -> &'static str {
2834 match self {
2835 OAuthProvider::Xai => codewhale_config::LEGACY_XAI_OAUTH_FILE_NAME,
2836 OAuthProvider::Chatgpt => codewhale_config::LEGACY_CHATGPT_OAUTH_FILE_NAME,
2837 }
2838 }
2839
2840 #[must_use]
2841 pub fn is_valid_generation(self, name: &str) -> bool {
2842 match self {
2843 OAuthProvider::Xai => codewhale_config::is_valid_xai_oauth_generation(name),
2844 OAuthProvider::Chatgpt => codewhale_config::is_valid_chatgpt_oauth_generation(name),
2845 }
2846 }
2847
2848 fn validate_generation(self, name: &str) -> Result<()> {
2849 match self {
2850 OAuthProvider::Xai => codewhale_config::validate_xai_oauth_generation(name),
2851 OAuthProvider::Chatgpt => codewhale_config::validate_chatgpt_oauth_generation(name),
2852 }
2853 .map(|_| ())
2854 }
2855
2856 fn generation_path(self, name: &str) -> Result<PathBuf> {
2857 match self {
2858 OAuthProvider::Xai => codewhale_config::xai_oauth_generation_path(name),
2859 OAuthProvider::Chatgpt => codewhale_config::chatgpt_oauth_generation_path(name),
2860 }
2861 }
2862
2863 /// A fresh, uniquely named generation file name for this provider.
2864 fn new_generation(self) -> String {
2865 let (prefix, suffix) = match self {
2866 OAuthProvider::Xai => (
2867 codewhale_config::XAI_OAUTH_GENERATION_PREFIX,
2868 codewhale_config::XAI_OAUTH_GENERATION_SUFFIX,
2869 ),
2870 OAuthProvider::Chatgpt => (
2871 codewhale_config::CHATGPT_OAUTH_GENERATION_PREFIX,
2872 codewhale_config::CHATGPT_OAUTH_GENERATION_SUFFIX,
2873 ),
2874 };
2875 format!("{prefix}{}{suffix}", uuid::Uuid::new_v4().simple())
2876 }
2877 }
2878
2879 /// One entry in a Codewhale-owned auth generation. Reads both historical
2880 /// on-disk shapes; `key` was the xAI/Grok field name for the access token.
2881 #[derive(Clone, Serialize, Deserialize)]
2882 pub struct OwnedAuthEntry {
2883 #[serde(default, alias = "key", skip_serializing_if = "Option::is_none")]
2884 pub access_token: Option<String>,
2885 #[serde(default, skip_serializing_if = "Option::is_none")]
2886 pub refresh_token: Option<String>,
2887 #[serde(default, skip_serializing_if = "Option::is_none")]
2888 pub expires_at: Option<String>,
2889 #[serde(default, skip_serializing_if = "Option::is_none")]
2890 pub id_token: Option<String>,
2891 #[serde(default, skip_serializing_if = "Option::is_none")]
2892 pub account_id: Option<String>,
2893 #[serde(default, skip_serializing_if = "Option::is_none")]
2894 pub oidc_issuer: Option<String>,
2895 #[serde(default, skip_serializing_if = "Option::is_none")]
2896 pub oidc_client_id: Option<String>,
2897 #[serde(default, skip_serializing_if = "Option::is_none")]
2898 pub originator: Option<String>,
2899 #[serde(default, skip_serializing_if = "Option::is_none")]
2900 pub auth_mode: Option<String>,
2901 #[serde(flatten)]
2902 pub extra: BTreeMap<String, Value>,
2903 }
2904
2905 impl std::fmt::Debug for OwnedAuthEntry {
2906 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2907 f.debug_struct("OwnedAuthEntry")
2908 .field("access_token", &redacted(self.access_token.is_some()))
2909 .field("refresh_token", &redacted(self.refresh_token.is_some()))
2910 .field("expires_at", &self.expires_at)
2911 .field("id_token", &redacted(self.id_token.is_some()))
2912 .field("account_id", &self.account_id)
2913 .field("oidc_issuer", &self.oidc_issuer)
2914 .field("oidc_client_id", &self.oidc_client_id)
2915 .field("originator", &self.originator)
2916 .field("auth_mode", &self.auth_mode)
2917 .field("extra_keys", &self.extra.keys().collect::<Vec<_>>())
2918 .finish()
2919 }
2920 }
2921
2922 fn redacted(present: bool) -> &'static str {
2923 if present { "<redacted>" } else { "<none>" }
2924 }
2925
2926 /// Resolved owned credentials ready for API use. No Debug: bearer material
2927 /// never prints; consumers redact explicitly.
2928 #[derive(Clone)]
2929 pub struct OwnedOAuthCredentials {
2930 pub access_token: String,
2931 pub account_id: Option<String>,
2932 /// Display label (email, plan) of the entry these credentials came from.
2933 pub account_label: Option<String>,
2934 pub refresh_token: Option<String>,
2935 pub expires_at: Option<String>,
2936 pub issuer: String,
2937 pub client_id: String,
2938 }
2939
2940 /// Receipt for a committed Codewhale-owned OAuth generation.
2941 pub struct OAuthActivation {
2942 pub credentials: OwnedOAuthCredentials,
2943 pub config_path: PathBuf,
2944 pub auth_path: PathBuf,
2945 pub provider: OAuthProvider,
2946 /// Non-secret label (email, plan) of the account just signed in.
2947 pub account_label: Option<String>,
2948 /// `Some` when this login replaced an existing Codewhale-owned sign-in;
2949 /// the inner value is that account's label when it had one.
2950 pub replaced: Option<Option<String>>,
2951 }
2952
2953 impl OAuthActivation {
2954 /// "Signed in to ChatGPT as you@example.com (plus)." plus, on its own
2955 /// line, which sign-in this login replaced. Never token material. Shell
2956 /// commands pass [`Locale::En`](codewhale_localization::Locale::En); the
2957 /// TUI passes its UI locale.
2958 #[must_use]
2959 pub fn summary(&self, locale: codewhale_localization::Locale) -> String {
2960 use codewhale_localization::{MessageId, tr};
2961 let name = oauth_provider_params(self.provider).display_name;
2962 let signed_in = match self.account_label.as_deref() {
2963 Some(label) => tr(locale, MessageId::AuthSignedInAs)
2964 .replace("{provider}", name)
2965 .replace("{account}", label),
2966 None => tr(locale, MessageId::AuthSignedInWithoutEmail).replace("{provider}", name),
2967 };
2968 let replaced = match &self.replaced {
2969 Some(Some(previous)) if Some(previous) != self.account_label.as_ref() => Some(
2970 tr(locale, MessageId::AuthReplacedPreviousSignInAs)
2971 .replace("{provider}", name)
2972 .replace("{account}", previous),
2973 ),
2974 Some(Some(_)) => {
2975 Some(tr(locale, MessageId::AuthSameAccountAsBefore).replace("{provider}", name))
2976 }
2977 Some(None) => {
2978 Some(tr(locale, MessageId::AuthReplacedPreviousSignIn).replace("{provider}", name))
2979 }
2980 None => None,
2981 };
2982 match replaced {
2983 Some(replaced) => format!("{signed_in}\n{replaced}"),
2984 None => signed_in,
2985 }
2986 }
2987
2988 /// Official ChatGPT sign-in never uses an ambient process token.
2989 #[must_use]
2990 pub fn env_override_warning(&self, _locale: codewhale_localization::Locale) -> Option<String> {
2991 None
2992 }
2993 }
2994
2995 impl std::fmt::Debug for OAuthActivation {
2996 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2997 f.debug_struct("OAuthActivation")
2998 .field("credentials", &redacted(true))
2999 .field("config_path", &self.config_path)
3000 .field("auth_path", &self.auth_path)
3001 .field("provider", &self.provider)
3002 .field("account_label", &self.account_label)
3003 .field("replaced", &self.replaced)
3004 .finish()
3005 }
3006 }
3007
3008 type AuthFile = BTreeMap<String, OwnedAuthEntry>;
3009
3010 fn load_owned_auth_file(path: &Path) -> Result<Option<AuthFile>> {
3011 let Some(raw) = crate::external_credentials::read_codewhale_owned_to_string(path)? else {
3012 return Ok(None);
3013 };
3014 parse_auth_file(&raw, path).map(Some)
3015 }
3016
3017 fn load_owned_auth_file_from_store(
3018 store: &codewhale_config::XaiOAuthCredentialStore,
3019 name: &str,
3020 ) -> Result<Option<AuthFile>> {
3021 let Some(raw) = store.read_to_string(name)? else {
3022 return Ok(None);
3023 };
3024 parse_auth_file(&raw, &store.path_for(name)?).map(Some)
3025 }
3026
3027 fn parse_auth_file(raw: &str, path: &Path) -> Result<AuthFile> {
3028 let value: Value = serde_json::from_str(raw).map_err(|_| {
3029 anyhow::anyhow!(
3030 "credential file {} is not valid credential JSON",
3031 codewhale_config::quote_os_path(path)
3032 )
3033 })?;
3034 let obj = value.as_object().ok_or_else(|| {
3035 anyhow::anyhow!(
3036 "credential file {} must be a JSON object of entries",
3037 codewhale_config::quote_os_path(path)
3038 )
3039 })?;
3040 let mut out = BTreeMap::new();
3041 for (k, v) in obj {
3042 match serde_json::from_value::<OwnedAuthEntry>(v.clone()) {
3043 Ok(entry) => {
3044 out.insert(k.clone(), entry);
3045 }
3046 Err(_) => {
3047 tracing::warn!(
3048 target: "codewhale::oauth",
3049 "skipping unreadable owned auth entry"
3050 );
3051 }
3052 }
3053 }
3054 Ok(out)
3055 }
3056
3057 fn write_auth_file_to_store(
3058 store: &codewhale_config::XaiOAuthCredentialStore,
3059 name: &str,
3060 file: &AuthFile,
3061 allow_replace: bool,
3062 ) -> Result<()> {
3063 let serialized =
3064 serde_json::to_vec_pretty(file).context("serializing owned OAuth credentials")?;
3065 store
3066 .write(name, &serialized, allow_replace)
3067 .with_context(|| {
3068 format!(
3069 "writing owned OAuth credentials to {}",
3070 codewhale_config::quote_os_path(&store.directory().join(name))
3071 )
3072 })?;
3073 #[cfg(any(test, feature = "test-support"))]
3074 crate::external_credentials::record_owned_credential_write();
3075 Ok(())
3076 }
3077
3078 /// Read-only parse of another CLI's granted credential file.
3079 fn load_external_auth_file(
3080 grant: &codewhale_config::ExternalCredentialReadGrant,
3081 ) -> Result<AuthFile> {
3082 let Some(raw) = crate::external_credentials::read_to_string(grant)? else {
3083 bail!(
3084 "external credential file not found at {}",
3085 codewhale_config::quote_os_path(grant.path())
3086 );
3087 };
3088 parse_auth_file(&raw, grant.path())
3089 }
3090
3091 fn select_entry(provider: OAuthProvider, file: &mut AuthFile) -> Option<(String, OwnedAuthEntry)> {
3092 if provider == OAuthProvider::Chatgpt {
3093 let mut official = file
3094 .iter()
3095 .filter(|(_, entry)| registration_from_entry(entry).is_ok());
3096 if let Some((scope, entry)) = official.next() {
3097 // Ambiguous profile selection fails closed. Login writes one account.
3098 return official
3099 .next()
3100 .is_none()
3101 .then(|| (scope.clone(), entry.clone()));
3102 }
3103 }
3104 // Prefer this provider's registered client-id scope when present.
3105 let preferred_suffix = format!("::{}", oauth_provider_params(provider).default_client_id);
3106 if let Some((k, v)) = file
3107 .iter()
3108 .find(|(k, e)| k.ends_with(&preferred_suffix) && entry_has_usable_secret(e))
3109 {
3110 return Some((k.clone(), v.clone()));
3111 }
3112 file.iter()
3113 .find(|(_, e)| entry_has_usable_secret(e))
3114 .map(|(k, v)| (k.clone(), v.clone()))
3115 }
3116
3117 fn entry_has_usable_secret(entry: &OwnedAuthEntry) -> bool {
3118 entry
3119 .access_token
3120 .as_deref()
3121 .is_some_and(|t| !t.trim().is_empty())
3122 || entry
3123 .refresh_token
3124 .as_deref()
3125 .is_some_and(|t| !t.trim().is_empty())
3126 }
3127
3128 fn chatgpt_refresh_not_before(value: &Value) -> Result<i64> {
3129 value
3130 .as_i64()
3131 .or_else(|| {
3132 value.as_str().and_then(|value| {
3133 value
3134 .parse::<i64>()
3135 .ok()
3136 .or_else(|| parse_rfc3339_secs(value))
3137 })
3138 })
3139 .filter(|value| *value >= 0)
3140 .context("ChatGPT earliest refresh time is invalid; sign in again")
3141 }
3142
3143 const REFRESH_SKEW_SECS: i64 = 60;
3144
3145 fn entry_access_token_is_fresh(entry: &OwnedAuthEntry) -> bool {
3146 let Some(token) = entry
3147 .access_token
3148 .as_deref()
3149 .filter(|t| !t.trim().is_empty())
3150 else {
3151 return false;
3152 };
3153 let stored_expiry = entry.expires_at.as_deref().and_then(parse_rfc3339_secs);
3154 let token_expiry = jwt_expiry_seconds(token).and_then(|exp| i64::try_from(exp).ok());
3155 // A later stored expiry must not hide an already-expired access token.
3156 // Opaque tokens still use stored expiry; no known expiry remains stale.
3157 let now = now_unix_secs().unwrap_or(0);
3158 let refresh_blocked = entry
3159 .extra
3160 .get("siwc_earliest_refresh_at")
3161 .and_then(|value| chatgpt_refresh_not_before(value).ok())
3162 .is_some_and(|earliest| earliest > now);
3163 stored_expiry
3164 .into_iter()
3165 .chain(token_expiry)
3166 .min()
3167 .is_some_and(|exp| {
3168 exp.saturating_sub(now) > REFRESH_SKEW_SECS || (refresh_blocked && exp > now)
3169 })
3170 }
3171
3172 fn credentials_from_entry(
3173 provider: OAuthProvider,
3174 scope: &str,
3175 entry: &OwnedAuthEntry,
3176 access_token: String,
3177 ) -> OwnedOAuthCredentials {
3178 OwnedOAuthCredentials {
3179 access_token,
3180 account_id: entry.account_id.clone(),
3181 account_label: entry.account_label(),
3182 refresh_token: entry.refresh_token.clone(),
3183 expires_at: entry.expires_at.clone(),
3184 issuer: entry
3185 .oidc_issuer
3186 .clone()
3187 .filter(|s| !s.trim().is_empty())
3188 .unwrap_or_else(|| issuer_from_scope(provider, scope)),
3189 client_id: entry
3190 .oidc_client_id
3191 .clone()
3192 .filter(|s| !s.trim().is_empty())
3193 .unwrap_or_else(|| client_id_from_scope(provider, scope)),
3194 }
3195 }
3196
3197 fn issuer_from_scope(provider: OAuthProvider, scope: &str) -> String {
3198 scope
3199 .split_once("::")
3200 .map(|(issuer, _)| issuer.to_string())
3201 .unwrap_or_else(|| oauth_provider_params(provider).default_issuer.to_string())
3202 }
3203
3204 fn client_id_from_scope(provider: OAuthProvider, scope: &str) -> String {
3205 scope
3206 .split_once("::")
3207 .map(|(_, id)| id.to_string())
3208 .unwrap_or_else(|| {
3209 oauth_provider_params(provider)
3210 .default_client_id
3211 .to_string()
3212 })
3213 }
3214
3215 fn apply_token_response(
3216 provider: OAuthProvider,
3217 entry: &mut OwnedAuthEntry,
3218 issuer: &str,
3219 client_id: &str,
3220 token: &OAuthTokenMaterial,
3221 ) -> Result<()> {
3222 if provider == OAuthProvider::Chatgpt {
3223 let registration = token
3224 .verified_chatgpt
3225 .as_ref()
3226 .context("ChatGPT credentials were not cryptographically verified; sign in again")?;
3227 anyhow::ensure!(
3228 registration.issuer == issuer && registration.client_id == client_id,
3229 "Verified ChatGPT registration does not match the token exchange"
3230 );
3231 require_chatgpt_scopes(token.scope.as_deref())?;
3232 entry.extra.insert(
3233 "siwc_registration".to_string(),
3234 serde_json::to_value(registration)?,
3235 );
3236 entry.extra.insert(
3237 "siwc_scope".to_string(),
3238 Value::String(token.scope.clone().unwrap_or_default()),
3239 );
3240 let access = token
3241 .access_token
3242 .as_deref()
3243 .context("token response missing access_token")?;
3244 entry.extra.insert(
3245 "siwc_token_sha256".to_string(),
3246 Value::String(URL_SAFE_NO_PAD.encode(Sha256::digest(access.as_bytes()))),
3247 );
3248 if let Some(value) = &token.earliest_refresh_at {
3249 let earliest = chatgpt_refresh_not_before(value)?;
3250 entry.extra.insert(
3251 "siwc_earliest_refresh_at".to_string(),
3252 Value::from(earliest),
3253 );
3254 } else {
3255 entry.extra.remove("siwc_earliest_refresh_at");
3256 }
3257 entry.account_id = Some(registration.subject.clone());
3258 }
3259 let access = token
3260 .access_token
3261 .as_deref()
3262 .filter(|t| !t.trim().is_empty())
3263 .context("token response missing access_token")?;
3264 entry.access_token = Some(access.to_string());
3265 if let Some(rt) = token
3266 .refresh_token
3267 .as_deref()
3268 .filter(|t| !t.trim().is_empty())
3269 {
3270 entry.refresh_token = Some(rt.to_string());
3271 }
3272 entry.oidc_issuer = Some(issuer.to_string());
3273 entry.oidc_client_id = Some(client_id.to_string());
3274 entry.auth_mode = Some("oidc".to_string());
3275 entry.originator = None;
3276 if let Some(id_token) = token.id_token.clone() {
3277 if provider != OAuthProvider::Chatgpt
3278 && let Some(account_id) = account_id_from_id_token(&id_token)
3279 {
3280 entry.account_id = Some(account_id);
3281 }
3282 entry.id_token = Some(id_token);
3283 }
3284 if let Some(expires_in) = token.expires_in {
3285 entry.expires_at = Some(rfc3339_from_now(expires_in));
3286 } else if let Some(exp) = jwt_expiry_seconds(access) {
3287 entry.expires_at = Some(rfc3339_from_unix(exp as i64));
3288 }
3289 Ok(())
3290 }
3291
3292 fn account_id_from_id_token(token: &str) -> Option<String> {
3293 let payload = jwt_payload(token)?;
3294 if let Some(id) = payload.get("chatgpt_account_id").and_then(Value::as_str) {
3295 let trimmed = id.trim();
3296 if !trimmed.is_empty() {
3297 return Some(trimmed.to_string());
3298 }
3299 }
3300 payload
3301 .get("https://api.openai.com/auth")
3302 .and_then(|auth| auth.get("chatgpt_account_id"))
3303 .and_then(Value::as_str)
3304 .map(str::trim)
3305 .filter(|id| !id.is_empty())
3306 .map(ToOwned::to_owned)
3307 }
3308
3309 /// Longest email the label keeps (RFC 5321 path limit); plan names are short.
3310 const ACCOUNT_EMAIL_MAX_CHARS: usize = 254;
3311 const ACCOUNT_PLAN_MAX_CHARS: usize = 32;
3312 /// Leading characters of a ChatGPT account id shown to tell two workspaces
3313 /// on one email apart.
3314 const ACCOUNT_ID_PREFIX_CHARS: usize = 8;
3315 /// ChatGPT plans that belong to one person, where email and plan already
3316 /// identify the account. Any other plan (team, business, enterprise, edu,
3317 /// or one this list has not seen) is a workspace a person may hold several
3318 /// of under one email, so its label carries an account-id prefix.
3319 const PERSONAL_CHATGPT_PLANS: &[&str] = &["free", "go", "plus", "pro"];
3320
3321 /// Non-secret account label from an ID token's claims, decoded locally:
3322 /// `email`, `email (plan)`, or for a workspace plan
3323 /// `email (plan, workspace 1a2b3c4d)`. The signature is not verified: the
3324 /// label is for display only and never authorizes anything. Claim text is
3325 /// bounded and stripped of control characters so a hostile token cannot
3326 /// smuggle terminal escapes into status output. `None` when no usable email
3327 /// claim exists.
3328 #[must_use]
3329 pub fn account_label_from_id_token(token: &str) -> Option<String> {
3330 let payload = jwt_payload(token)?;
3331 let claim_text = |value: Option<&Value>, max: usize| {
3332 let text: String = value?
3333 .as_str()?
3334 .chars()
3335 .filter(|ch| !ch.is_control())
3336 .take(max)
3337 .collect();
3338 let text = text.trim();
3339 (!text.is_empty()).then(|| text.to_string())
3340 };
3341 let email = claim_text(payload.get("email"), ACCOUNT_EMAIL_MAX_CHARS).or_else(|| {
3342 claim_text(
3343 payload
3344 .get("https://api.openai.com/profile")
3345 .and_then(|profile| profile.get("email")),
3346 ACCOUNT_EMAIL_MAX_CHARS,
3347 )
3348 })?;
3349 let plan = claim_text(
3350 payload
3351 .get("https://api.openai.com/auth")
3352 .and_then(|auth| auth.get("chatgpt_plan_type")),
3353 ACCOUNT_PLAN_MAX_CHARS,
3354 );
3355 let workspace = plan
3356 .as_deref()
3357 .filter(|plan| {
3358 !PERSONAL_CHATGPT_PLANS
3359 .iter()
3360 .any(|personal| plan.eq_ignore_ascii_case(personal))
3361 })
3362 .and_then(|_| account_id_from_id_token(token))
3363 .map(|id| {
3364 id.chars()
3365 .filter(char::is_ascii_alphanumeric)
3366 .take(ACCOUNT_ID_PREFIX_CHARS)
3367 .collect::<String>()
3368 })
3369 .filter(|prefix| !prefix.is_empty());
3370 Some(match (plan, workspace) {
3371 (Some(plan), Some(workspace)) => format!("{email} ({plan}, workspace {workspace})"),
3372 (Some(plan), None) => format!("{email} ({plan})"),
3373 (None, _) => email,
3374 })
3375 }
3376
3377 impl OwnedAuthEntry {
3378 /// Display label for the account this entry signs in as.
3379 fn account_label(&self) -> Option<String> {
3380 self.id_token
3381 .as_deref()
3382 .and_then(account_label_from_id_token)
3383 }
3384 }
3385
3386 /// Whether an owned entry can still produce a bearer: a fresh access token,
3387 /// or a refresh token to mint one. The same test gates [`credentials_valid`]
3388 /// and the account label, so a label is never shown for an entry the
3389 /// runtime would refuse.
3390 fn owned_entry_is_usable(entry: &OwnedAuthEntry) -> bool {
3391 entry_access_token_is_fresh(entry)
3392 || entry
3393 .refresh_token
3394 .as_deref()
3395 .is_some_and(|token| !token.trim().is_empty())
3396 }
3397
3398 /// Account label of the Codewhale-owned sign-in stored in one generation
3399 /// file. Reads only that file; never refreshes, writes, or touches the
3400 /// network. `Ok(None)` when the usable entry's ID token carries no email;
3401 /// `Err` (a fixed, token-free reason) when the generation name is invalid,
3402 /// the file is missing or unreadable, or it holds no usable sign-in.
3403 pub fn owned_account_label_for_generation(
3404 provider: OAuthProvider,
3405 generation: &str,
3406 ) -> Result<Option<String>> {
3407 let path = provider
3408 .generation_path(generation)
3409 .map_err(|_| anyhow::anyhow!("invalid generation pointer"))?;
3410 owned_account_label_at(provider, &path)
3411 }
3412
3413 fn owned_account_label_at(provider: OAuthProvider, path: &Path) -> Result<Option<String>> {
3414 let mut file = load_owned_auth_file(path)
3415 .map_err(|_| anyhow::anyhow!("sign-in file is unreadable"))?
3416 .ok_or_else(|| anyhow::anyhow!("sign-in file is missing"))?;
3417 let (_, entry) = select_entry(provider, &mut file)
3418 .filter(|(_, entry)| {
3419 (provider != OAuthProvider::Chatgpt || registration_from_entry(entry).is_ok())
3420 && owned_entry_is_usable(entry)
3421 })
3422 .ok_or_else(|| anyhow::anyhow!("sign-in file holds no usable sign-in"))?;
3423 Ok(entry.account_label())
3424 }
3425
3426 /// What to tell someone whose subscription sign-in hit a plan limit: which
3427 /// account made the request (label only, never a token) and how to sign in
3428 /// with a different one, both inside a running session and from a shell.
3429 /// A shell login does not reach a session that is already open, so the
3430 /// shell route says to restart.
3431 #[must_use]
3432 pub fn usage_limit_guidance(provider: OAuthProvider, account_label: Option<&str>) -> String {
3433 let params = oauth_provider_params(provider);
3434 let name = params.display_name;
3435 let switch = if provider == OAuthProvider::Chatgpt {
3436 "To continue with a different ChatGPT account, run `/auth chatgpt` in Codewhale, or `codewhale auth chatgpt` in a shell and then restart open Codewhale sessions.".to_string()
3437 } else {
3438 format!(
3439 "To continue with a different {name} account, run `{}` in Codewhale, or `{}` in a shell and then restart open Codewhale sessions.",
3440 params.session_login_hint, params.relogin_hint
3441 )
3442 };
3443 match account_label {
3444 Some(label) => format!("This request used the {name} account {label}. {switch}"),
3445 None => switch,
3446 }
3447 }
3448
3449 /// Printed beside a login URL: the issuer signs in whichever account the
3450 /// browser already holds unless the user picks another.
3451 fn account_choice_hint(display_name: &str, mode: ChatgptLoginMode) -> String {
3452 if display_name == "ChatGPT" {
3453 return match mode {
3454 ChatgptLoginMode::FreshAccount => "Approve with the ChatGPT account and workspace Codewhale should use. If the page is already signed in to a different account, sign out there first or open the URL above in a private window.".to_string(),
3455 ChatgptLoginMode::ReauthorizeCurrent => "Returning sign-in must use the selected ChatGPT account. To sign in with a different account instead, run `codewhale auth chatgpt` (without `--reauth`) or `/auth chatgpt`. If the browser shows a different account, sign out there first or open the login URL in a private window.".to_string(),
3456 };
3457 }
3458 format!(
3459 "Approve with the {display_name} account Codewhale should use. If the page is already \
3460 signed in to a different account, sign out there first or open the URL above in a \
3461 private window."
3462 )
3463 }
3464
3465 fn jwt_payload(token: &str) -> Option<Value> {
3466 let mut parts = token.split('.');
3467 let _header = parts.next()?;
3468 let payload = parts.next()?;
3469 let decoded = URL_SAFE_NO_PAD.decode(payload).ok()?;
3470 serde_json::from_slice(&decoded).ok()
3471 }
3472
3473 fn now_unix_secs() -> Option<i64> {
3474 SystemTime::now()
3475 .duration_since(UNIX_EPOCH)
3476 .ok()
3477 .and_then(|d| i64::try_from(d.as_secs()).ok())
3478 }
3479
3480 fn parse_rfc3339_secs(raw: &str) -> Option<i64> {
3481 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
3482 return Some(dt.timestamp());
3483 }
3484 // Simple UTC forms chrono's strict parser rejects, e.g. a missing
3485 // fractional second on an offset-less timestamp.
3486 let trimmed = raw.trim().trim_end_matches('Z');
3487 let (date, time) = trimmed.split_once('T')?;
3488 let mut d = date.split('-');
3489 let y: i32 = d.next()?.parse().ok()?;
3490 let m: u32 = d.next()?.parse().ok()?;
3491 let day: u32 = d.next()?.parse().ok()?;
3492 let time = time.split('+').next()?.split('-').next()?;
3493 let mut t = time.split(':');
3494 let hh: u32 = t.next()?.parse().ok()?;
3495 let mm: u32 = t.next()?.parse().ok()?;
3496 let ss: u32 = t
3497 .next()
3498 .and_then(|s| s.split('.').next())
3499 .and_then(|s| s.parse().ok())
3500 .unwrap_or(0);
3501 let ndt = chrono::NaiveDate::from_ymd_opt(y, m, day)?.and_hms_opt(hh, mm, ss)?;
3502 Some(ndt.and_utc().timestamp())
3503 }
3504
3505 fn rfc3339_from_now(expires_in: u64) -> String {
3506 let ts = now_unix_secs().unwrap_or(0) + expires_in as i64;
3507 rfc3339_from_unix(ts)
3508 }
3509
3510 fn rfc3339_from_unix(ts: i64) -> String {
3511 chrono::DateTime::from_timestamp(ts, 0)
3512 .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
3513 .unwrap_or_else(|| format!("{ts}"))
3514 }
3515
3516 /// Refresh through the seam, resolving the token endpoint the provider's
3517 /// row demands (discovered for xAI, pinned for ChatGPT).
3518 fn refresh_for_provider(
3519 provider: OAuthProvider,
3520 client: &dyn OAuthFormClient,
3521 issuer: &str,
3522 client_id: &str,
3523 refresh_token: &str,
3524 ) -> Result<OAuthTokenMaterial> {
3525 let params = oauth_provider_params(provider);
3526 let token_url = if params.discover_endpoints {
3527 resolve_oauth_endpoints(params, issuer).token_endpoint
3528 } else {
3529 form_token_url(params, issuer)
3530 };
3531 refresh_access_token_via(client, params, &token_url, client_id, refresh_token)
3532 }
3533
3534 fn configured_owned_auth_file_path(
3535 provider: OAuthProvider,
3536 config: &Config,
3537 ) -> Result<Option<PathBuf>> {
3538 let identity = config
3539 .builtin_provider_identity(provider.api())
3540 .map_err(anyhow::Error::msg)?;
3541 let generation = config
3542 .provider_config_for(&identity)
3543 .and_then(|entry| entry.oauth_credential_generation.as_deref());
3544 match generation {
3545 Some(generation) => provider.generation_path(generation).map(Some),
3546 None => Ok(None),
3547 }
3548 }
3549
3550 /// A subscription sign-in the structural check found usable, named by the
3551 /// same read that proved it usable. Holds a display label only.
3552 #[derive(Debug, Clone, PartialEq, Eq)]
3553 pub struct UsableSignIn {
3554 /// Email (and plan) of the account that entry signs in as; `None` when
3555 /// its ID token carries no email claim.
3556 pub account_label: Option<String>,
3557 }
3558
3559 /// Prompt-free structural check for owned OAuth material. Never refreshes,
3560 /// writes, or makes network requests. External storage is not inspected
3561 /// until exact read-only consent has been persisted, and then only at the
3562 /// exact consented path — no ambient candidate is ever resolved or opened
3563 /// (#5772).
3564 #[must_use]
3565 pub fn credentials_valid(provider: OAuthProvider, config: &Config) -> bool {
3566 usable_sign_in(provider, config).is_some()
3567 }
3568
3569 /// [`credentials_valid`], also naming the account of the entry that passed:
3570 /// the configured Codewhale-owned generation, else (xAI) the legacy owned
3571 /// file or the consented Grok CLI import — the credential the route would
3572 /// send. Readiness surfaces take the label from here so naming the account
3573 /// costs no second credential read.
3574 #[must_use]
3575 pub fn usable_sign_in(provider: OAuthProvider, config: &Config) -> Option<UsableSignIn> {
3576 let identity = config.builtin_provider_identity(provider.api()).ok()?;
3577 let usable = |entry: &OwnedAuthEntry| UsableSignIn {
3578 account_label: entry.account_label(),
3579 };
3580 // Codewhale-owned OAuth bytes are inert until the provider route
3581 // explicitly selects OAuth. A failed post-login config finalization can
3582 // therefore never make a newly written token silently ready on the next
3583 // launch.
3584 if provider == OAuthProvider::Chatgpt
3585 && config
3586 .provider_config_for(&identity)
3587 .and_then(|entry| entry.auth_mode.as_deref())
3588 != Some("oauth")
3589 {
3590 return None;
3591 }
3592 if provider == OAuthProvider::Xai
3593 && !config
3594 .provider_config_for(&identity)
3595 .and_then(|entry| entry.auth_mode.as_deref())
3596 .is_some_and(auth_mode_uses_xai_oauth)
3597 {
3598 return None;
3599 }
3600 if let Ok(Some(path)) = configured_owned_auth_file_path(provider, config)
3601 && let Ok(Some(mut file)) = load_owned_auth_file(&path)
3602 && let Some((_, entry)) = select_entry(provider, &mut file)
3603 && (provider != OAuthProvider::Chatgpt || registration_from_entry(&entry).is_ok())
3604 && owned_entry_is_usable(&entry)
3605 {
3606 return Some(usable(&entry));
3607 }
3608 if config
3609 .provider_config_for(&identity)
3610 .and_then(|entry| entry.oauth_credential_generation.as_deref())
3611 .is_some()
3612 {
3613 // A configured generation is authoritative. Invalid, missing, unsafe,
3614 // or malformed owned storage must not fall through to an external CLI.
3615 return None;
3616 }
3617 if provider == OAuthProvider::Xai {
3618 // The pre-generation legacy file is the last owned location.
3619 if let Ok(path) = codewhale_config::legacy_xai_oauth_path()
3620 && let Ok(Some(mut file)) = load_owned_auth_file(&path)
3621 && let Some((_, entry)) = select_entry(provider, &mut file)
3622 && owned_entry_is_usable(&entry)
3623 {
3624 return Some(usable(&entry));
3625 }
3626 // #5772: with no persisted consent record there is no external path
3627 // to resolve and nothing to open.
3628 if let Some(consent_path) = config
3629 .provider_config_for(&identity)
3630 .and_then(|entry| entry.external_credentials.as_ref())
3631 .map(|consent| consent.path.clone())
3632 && let Ok(grant) = config.external_credential_read_grant(
3633 &identity,
3634 codewhale_config::ExternalCredentialSource::GrokCli,
3635 &consent_path,
3636 )
3637 && let Ok(mut file) = load_external_auth_file(&grant)
3638 {
3639 return select_entry(provider, &mut file)
3640 .filter(|(_, entry)| entry_access_token_is_fresh(entry))
3641 .map(|(_, entry)| usable(&entry));
3642 }
3643 }
3644 None
3645 }
3646
3647 #[must_use]
3648 pub fn credentials_present(provider: OAuthProvider, config: &Config) -> bool {
3649 credentials_valid(provider, config)
3650 }
3651
3652 /// Grant-time validation for an external Grok CLI credential file (#5772).
3653 ///
3654 /// Reads exactly the granted path through the secure adapter and requires a
3655 /// usable, unexpired entry. Never refreshes, rewrites, or makes a network
3656 /// request. Consent is persisted only after this succeeds, so a consent
3657 /// record can never be written for a file that holds nothing usable.
3658 pub fn validate_grok_external_credentials(
3659 grant: &codewhale_config::ExternalCredentialReadGrant,
3660 ) -> Result<()> {
3661 let mut file = load_external_auth_file(grant)?;
3662 let (_, entry) = select_entry(OAuthProvider::Xai, &mut file).ok_or_else(|| {
3663 anyhow::anyhow!(
3664 "xAI OAuth credentials at {} have no usable entry. Run `grok login` again or use `codewhale auth xai-device` for Codewhale-owned storage.",
3665 codewhale_config::quote_os_path(grant.path())
3666 )
3667 })?;
3668 if !entry_access_token_is_fresh(&entry) {
3669 bail!(
3670 "xAI OAuth access token in {} is expired. Read-only consent never refreshes or rewrites another CLI's credentials. Run `grok login` again or use `codewhale auth xai-device`.",
3671 codewhale_config::quote_os_path(grant.path())
3672 );
3673 }
3674 Ok(())
3675 }
3676
3677 /// Load xAI OAuth credentials with full precedence: configured generation,
3678 /// legacy owned file, then the consented Grok CLI import. Codewhale-owned
3679 /// credentials may refresh and rewrite Codewhale-owned storage; external
3680 /// credentials are read-only.
3681 pub fn get_xai_credentials(config: &Config) -> Result<OwnedOAuthCredentials> {
3682 let identity = config
3683 .active_provider_identity()
3684 .map_err(anyhow::Error::msg)?;
3685 anyhow::ensure!(
3686 identity.provider == codewhale_config::ProviderKind::Xai
3687 && identity.key.as_str() == codewhale_config::ProviderKind::Xai.as_str()
3688 && config
3689 .provider_config_for(&identity)
3690 .and_then(|entry| entry.auth_mode.as_deref())
3691 .is_some_and(auth_mode_uses_xai_oauth),
3692 "Codewhale-owned xAI OAuth credentials are inactive until the xAI route explicitly selects OAuth"
3693 );
3694 if let Some(owned_path) = configured_owned_auth_file_path(OAuthProvider::Xai, config)? {
3695 return get_owned_credentials_at(OAuthProvider::Xai, &owned_path);
3696 }
3697 let owned_path = codewhale_config::legacy_xai_oauth_path()?;
3698 if load_owned_auth_file(&owned_path)?.is_some() {
3699 return get_owned_credentials_at(OAuthProvider::Xai, &owned_path);
3700 }
3701
3702 let external_path = grok_auth_file_path();
3703 let grant = config.external_credential_read_grant(
3704 &identity,
3705 codewhale_config::ExternalCredentialSource::GrokCli,
3706 &external_path,
3707 )?;
3708 let mut file = load_external_auth_file(&grant)?;
3709 let (scope, entry) = select_entry(OAuthProvider::Xai, &mut file).ok_or_else(|| {
3710 anyhow::anyhow!(
3711 "xAI OAuth credentials at {} have no usable entry. Run `grok login` again or use `codewhale auth xai-device` for Codewhale-owned storage.",
3712 codewhale_config::quote_os_path(grant.path())
3713 )
3714 })?;
3715 if !entry_access_token_is_fresh(&entry) {
3716 bail!(
3717 "xAI OAuth access token in {} is expired. Read-only consent never refreshes or rewrites another CLI's credentials. Run `grok login` again or use `codewhale auth xai-device`.",
3718 codewhale_config::quote_os_path(grant.path())
3719 );
3720 }
3721 let token = entry
3722 .access_token
3723 .clone()
3724 .filter(|token| !token.trim().is_empty())
3725 .context("xAI OAuth access token is empty")?;
3726 Ok(credentials_from_entry(
3727 OAuthProvider::Xai,
3728 &scope,
3729 &entry,
3730 token,
3731 ))
3732 }
3733
3734 /// Load owned subscription credentials from the configured generation,
3735 /// refreshing through the seam when stale.
3736 pub fn get_owned_credentials(
3737 provider: OAuthProvider,
3738 config: &Config,
3739 ) -> Result<OwnedOAuthCredentials> {
3740 let identity = config
3741 .builtin_provider_identity(provider.api())
3742 .map_err(anyhow::Error::msg)?;
3743 if provider == OAuthProvider::Chatgpt {
3744 anyhow::ensure!(
3745 config
3746 .provider_config_for(&identity)
3747 .and_then(|entry| entry.auth_mode.as_deref())
3748 == Some("oauth"),
3749 "Owned subscription credentials are inactive; sign in again"
3750 );
3751 }
3752 get_owned_credentials_with(provider, config, &ReqwestOAuthFormClient)
3753 }
3754
3755 /// Read-only diagnostics: never refreshes or changes protected storage.
3756 pub fn get_owned_credentials_read_only(
3757 provider: OAuthProvider,
3758 config: &Config,
3759 ) -> Result<OwnedOAuthCredentials> {
3760 anyhow::ensure!(
3761 provider == OAuthProvider::Chatgpt,
3762 "Read-only credentials require an owned subscription sign-in"
3763 );
3764 official_chatgpt_registration(config)?;
3765 let label = oauth_provider_params(provider).display_name;
3766 let path = configured_owned_auth_file_path(provider, config)?
3767 .with_context(|| format!("{label} credentials are not configured"))?;
3768 let mut file =
3769 load_owned_auth_file(&path)?.with_context(|| format!("{label} credentials are missing"))?;
3770 let (scope, entry) = select_entry(provider, &mut file)
3771 .with_context(|| format!("{label} credentials are unavailable"))?;
3772 registration_from_entry(&entry)?;
3773 anyhow::ensure!(
3774 entry_access_token_is_fresh(&entry),
3775 "{label} access token needs runtime refresh; read-only diagnostics do not refresh"
3776 );
3777 let access = entry
3778 .access_token
3779 .clone()
3780 .with_context(|| format!("{label} access token is missing"))?;
3781 Ok(credentials_from_entry(provider, &scope, &entry, access))
3782 }
3783
3784 fn get_owned_credentials_with(
3785 provider: OAuthProvider,
3786 config: &Config,
3787 client: &dyn OAuthFormClient,
3788 ) -> Result<OwnedOAuthCredentials> {
3789 let Some(path) = configured_owned_auth_file_path(provider, config)? else {
3790 bail!(
3791 "Codewhale-owned {} OAuth credentials are not configured",
3792 oauth_provider_params(provider).display_name
3793 );
3794 };
3795 let name = path
3796 .file_name()
3797 .and_then(|name| name.to_str())
3798 .context("Codewhale-owned OAuth path must have a UTF-8 basename")?;
3799 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
3800 get_owned_credentials_locked(
3801 provider,
3802 store,
3803 name,
3804 client,
3805 |issuer, client_id, refresh| {
3806 refresh_for_provider(provider, client, issuer, client_id, refresh)
3807 },
3808 )
3809 })
3810 }
3811
3812 fn get_owned_credentials_at(provider: OAuthProvider, path: &Path) -> Result<OwnedOAuthCredentials> {
3813 let directory = codewhale_config::xai_oauth_credentials_dir()?;
3814 anyhow::ensure!(
3815 path.parent() == Some(directory.as_path()),
3816 "Codewhale-owned OAuth path escaped the credentials directory"
3817 );
3818 let name = path
3819 .file_name()
3820 .and_then(|name| name.to_str())
3821 .context("Codewhale-owned OAuth path must have a UTF-8 basename")?;
3822 anyhow::ensure!(
3823 name == provider.legacy_file_name() || provider.is_valid_generation(name),
3824 "Codewhale-owned OAuth path has an invalid basename"
3825 );
3826 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
3827 get_owned_credentials_locked(
3828 provider,
3829 store,
3830 name,
3831 &ReqwestOAuthFormClient,
3832 |issuer, client_id, refresh| {
3833 refresh_for_provider(
3834 provider,
3835 &ReqwestOAuthFormClient,
3836 issuer,
3837 client_id,
3838 refresh,
3839 )
3840 },
3841 )
3842 })
3843 }
3844
3845 fn get_owned_credentials_locked<F>(
3846 provider: OAuthProvider,
3847 store: &codewhale_config::XaiOAuthCredentialStore,
3848 name: &str,
3849 client: &dyn OAuthFormClient,
3850 refresh_access: F,
3851 ) -> Result<OwnedOAuthCredentials>
3852 where
3853 F: FnOnce(&str, &str, &str) -> Result<OAuthTokenMaterial>,
3854 {
3855 let hint = oauth_provider_params(provider).relogin_hint;
3856 let path = store.path_for(name)?;
3857 let mut file = load_owned_auth_file_from_store(store, name)?.ok_or_else(|| {
3858 anyhow::anyhow!(
3859 "Codewhale-owned OAuth credentials were not found at {}. Run `{hint}` again.",
3860 codewhale_config::quote_os_path(&path)
3861 )
3862 })?;
3863 let (scope, mut entry) = select_entry(provider, &mut file).ok_or_else(|| {
3864 anyhow::anyhow!(
3865 "Codewhale-owned OAuth credentials at {} have no usable entry. Run `{hint}` again.",
3866 codewhale_config::quote_os_path(&path)
3867 )
3868 })?;
3869 let registration = if provider == OAuthProvider::Chatgpt {
3870 Some(registration_from_entry(&entry)?)
3871 } else {
3872 None
3873 };
3874
3875 if entry_access_token_is_fresh(&entry) {
3876 let token = entry
3877 .access_token
3878 .clone()
3879 .filter(|t| !t.trim().is_empty())
3880 .context("OAuth access token is empty")?;
3881 return Ok(credentials_from_entry(provider, &scope, &entry, token));
3882 }
3883
3884 let refresh = entry
3885 .refresh_token
3886 .as_deref()
3887 .filter(|t| !t.trim().is_empty())
3888 .context(format!(
3889 "OAuth access token expired and no refresh_token is stored. Run `{hint}` again."
3890 ))?;
3891 let issuer = entry
3892 .oidc_issuer
3893 .clone()
3894 .filter(|s| !s.trim().is_empty())
3895 .unwrap_or_else(|| issuer_from_scope(provider, &scope));
3896 let client_id = entry
3897 .oidc_client_id
3898 .clone()
3899 .filter(|s| !s.trim().is_empty())
3900 .unwrap_or_else(|| client_id_from_scope(provider, &scope));
3901
3902 if let Some(value) = entry.extra.get("siwc_earliest_refresh_at") {
3903 anyhow::ensure!(
3904 chatgpt_refresh_not_before(value)?
3905 <= now_unix_secs().context("System clock is unavailable for ChatGPT refresh")?,
3906 "ChatGPT refresh window has not opened; retry later"
3907 );
3908 }
3909 let mut refreshed = refresh_access(&issuer, &client_id, refresh)?;
3910 if let Some(registration) = registration {
3911 require_chatgpt_scopes(refreshed.scope.as_deref())?;
3912 anyhow::ensure!(
3913 refreshed
3914 .token_type
3915 .as_deref()
3916 .is_some_and(|value| value.eq_ignore_ascii_case("bearer")),
3917 "ChatGPT refresh did not return Bearer credentials"
3918 );
3919 anyhow::ensure!(
3920 refreshed
3921 .refresh_token
3922 .as_deref()
3923 .is_some_and(|token| !token.trim().is_empty()),
3924 "ChatGPT refresh omitted its rotating refresh token; sign in again"
3925 );
3926 let access_token = refreshed
3927 .access_token
3928 .as_deref()
3929 .context("ChatGPT refresh omitted its access token")?;
3930 let presented: Vec<&str> = std::iter::once(access_token)
3931 .chain(refreshed.id_token.as_deref())
3932 .collect();
3933 let keys = chatgpt_keys_covering(&presented, || client.chatgpt_jwks(&issuer))?;
3934 verify_chatgpt_access_token(access_token, &keys, &registration)?;
3935 if let Some(id_token) = &refreshed.id_token {
3936 let refreshed_registration = verify_chatgpt_id_token(
3937 id_token,
3938 &keys,
3939 &issuer,
3940 &client_id,
3941 None,
3942 Some(&registration.subject),
3943 &registration.host_id,
3944 )?;
3945 refreshed.verified_chatgpt = Some(refreshed_registration);
3946 } else {
3947 refreshed.verified_chatgpt = Some(registration);
3948 }
3949 }
3950 apply_token_response(provider, &mut entry, &issuer, &client_id, &refreshed)?;
3951 file.insert(scope.clone(), entry.clone());
3952 write_auth_file_to_store(store, name, &file, true)?;
3953
3954 let token = entry
3955 .access_token
3956 .clone()
3957 .filter(|t| !t.trim().is_empty())
3958 .context("OAuth refresh returned an empty access token")?;
3959 Ok(credentials_from_entry(provider, &scope, &entry, token))
3960 }
3961
3962 /// Commit a pending login as a uniquely named owned generation and
3963 /// atomically point the provider's config table at it under the shared
3964 /// config lock.
3965 ///
3966 /// The credential file is staged while the config lock is held. If config
3967 /// persistence fails, the unreferenced stage is removed. Only after the new
3968 /// pointer commits is the previously selected generation removed best-effort.
3969 pub fn activate_login(
3970 pending: PendingOAuthLogin,
3971 config_path: Option<&Path>,
3972 live_config: Option<&mut Config>,
3973 ) -> Result<OAuthActivation> {
3974 codewhale_config::with_xai_oauth_lifecycle_lock(move |store| {
3975 activate_login_locked(pending, config_path, live_config, store)
3976 })
3977 }
3978
3979 fn activate_login_locked(
3980 pending: PendingOAuthLogin,
3981 config_path: Option<&Path>,
3982 live_config: Option<&mut Config>,
3983 store: &codewhale_config::XaiOAuthCredentialStore,
3984 ) -> Result<OAuthActivation> {
3985 let provider = pending.provider;
3986 let display_name = oauth_provider_params(provider).display_name;
3987 let config_path = crate::config_persistence::config_toml_path(config_path)?;
3988 let generation = provider.new_generation();
3989 provider.validate_generation(&generation)?;
3990 let auth_path = store.path_for(&generation)?;
3991 let key_inside = provider.config_key();
3992 let mut stage_written = false;
3993
3994 let activation = codewhale_config::mutate_config_document(&config_path, |document| {
3995 let previous_generation_item = document
3996 .get("providers")
3997 .and_then(toml_edit::Item::as_table_like)
3998 .and_then(|providers| providers.get(key_inside))
3999 .and_then(toml_edit::Item::as_table_like)
4000 .and_then(|provider| provider.get("oauth_credential_generation"));
4001 let previous_generation = previous_generation_item
4002 .map(|item| {
4003 item.as_str()
4004 .context(format!(
4005 "refusing {display_name} login because the existing credential generation pointer is not a string"
4006 ))
4007 .map(ToOwned::to_owned)
4008 })
4009 .transpose()?;
4010 if let Some(previous) = previous_generation.as_deref() {
4011 provider.validate_generation(previous).with_context(|| {
4012 format!(
4013 "refusing {display_name} login because the existing credential generation pointer is invalid"
4014 )
4015 })?;
4016 }
4017
4018 let previous_owned_name = match previous_generation.as_deref() {
4019 Some(previous) => Some(previous.to_string()),
4020 None if store.read_to_string(provider.legacy_file_name())?.is_some() => {
4021 Some(provider.legacy_file_name().to_string())
4022 }
4023 None => None,
4024 };
4025 // Read the previous generation only to name the account it signed
4026 // in as. A valid pointer whose file is gone (interrupted revocation,
4027 // external cleanup) must not brick login: only a successful
4028 // activation can ever rewrite the pointer, so treat the missing
4029 // generation like a fresh start instead of failing (#5032).
4030 let mut previous_file = match previous_owned_name.as_deref() {
4031 Some(name) => load_owned_auth_file_from_store(store, name)?.unwrap_or_else(|| {
4032 tracing::warn!(
4033 target: "codewhale::oauth",
4034 generation = name,
4035 "config pointed at a missing owned OAuth generation; starting a fresh credential file"
4036 );
4037 BTreeMap::new()
4038 }),
4039 None => BTreeMap::new(),
4040 };
4041 let scope = format!("{}::{}", pending.issuer, pending.client_id);
4042 // A new login replaces the whole sign-in: the new generation holds
4043 // only this entry. Merging into the old entry would let a previous
4044 // account's refresh token, id token or account id survive whenever
4045 // the new grant omits one; carrying other scopes forward would let
4046 // an older account's entry under a differently spelled issuer
4047 // outrank this login in `select_entry` and keep its refresh token
4048 // on disk. `replaced` names the entry the runtime was actually using.
4049 let replaced =
4050 select_entry(provider, &mut previous_file).map(|(_, entry)| entry.account_label());
4051 let mut file = AuthFile::new();
4052 let mut entry = OwnedAuthEntry {
4053 access_token: None,
4054 refresh_token: None,
4055 expires_at: None,
4056 id_token: None,
4057 account_id: None,
4058 oidc_issuer: Some(pending.issuer.clone()),
4059 oidc_client_id: Some(pending.client_id.clone()),
4060 originator: None,
4061 auth_mode: Some("oidc".to_string()),
4062 extra: BTreeMap::new(),
4063 };
4064 apply_token_response(
4065 provider,
4066 &mut entry,
4067 &pending.issuer,
4068 &pending.client_id,
4069 &pending.token,
4070 )?;
4071 let access = entry
4072 .access_token
4073 .clone()
4074 .filter(|token| !token.trim().is_empty())
4075 .context(format!(
4076 "{display_name} login returned an empty access token"
4077 ))?;
4078 file.insert(scope.clone(), entry.clone());
4079 write_auth_file_to_store(store, &generation, &file, false)?;
4080 stage_written = true;
4081
4082 codewhale_config::set_config_document_value(
4083 document,
4084 &["providers", key_inside, "auth_mode"],
4085 "oauth",
4086 )?;
4087 codewhale_config::set_config_document_value(
4088 document,
4089 &["providers", key_inside, "oauth_credential_generation"],
4090 generation.clone(),
4091 )?;
4092 codewhale_config::unset_config_document_value(
4093 document,
4094 &["providers", key_inside, "external_credentials"],
4095 )?;
4096 Ok((
4097 previous_owned_name,
4098 credentials_from_entry(provider, &scope, &entry, access),
4099 entry.account_label(),
4100 replaced,
4101 ))
4102 });
4103
4104 let (previous_owned_name, credentials, account_label, replaced) = match activation {
4105 Ok(activation) => activation,
4106 Err(error) => {
4107 if stage_written && let Err(cleanup_error) = store.remove(&generation) {
4108 return Err(error).context(format!(
4109 "{display_name} login was not activated; also failed to remove unreferenced staged credentials at {}: {cleanup_error}",
4110 codewhale_config::quote_os_path(&auth_path)
4111 ));
4112 }
4113 return Err(error).context(format!(
4114 "{display_name} login was not activated; provider configuration is unchanged"
4115 ));
4116 }
4117 };
4118 if let Some(registration) = pending.token.verified_chatgpt.as_ref() {
4119 let host = ChatgptHost {
4120 host_id: registration.host_id.clone(),
4121 registration: Some(registration.clone()),
4122 };
4123 if let Err(error) = serde_json::to_vec(&host)
4124 .map_err(anyhow::Error::from)
4125 .and_then(|bytes| store.write(codewhale_config::CHATGPT_HOST_FILE_NAME, &bytes, true))
4126 {
4127 tracing::warn!(target: "codewhale::oauth", error = %error, "ChatGPT grant activated; retaining its signed-out registration failed");
4128 }
4129 }
4130
4131 if let Some(config) = live_config {
4132 match provider {
4133 OAuthProvider::Xai => config.mark_codewhale_owned_xai_oauth(generation.clone())?,
4134 OAuthProvider::Chatgpt => {
4135 config.mark_codewhale_owned_chatgpt_oauth(generation.clone())?;
4136 }
4137 }
4138 }
4139 if let Some(previous) = previous_owned_name
4140 && previous != generation
4141 && let Err(error) = store.remove(&previous)
4142 {
4143 tracing::warn!(
4144 target: "codewhale::oauth",
4145 error = %error,
4146 "new OAuth generation committed but superseded generation cleanup failed"
4147 );
4148 }
4149 Ok(OAuthActivation {
4150 credentials,
4151 config_path,
4152 auth_path,
4153 provider,
4154 account_label,
4155 replaced,
4156 })
4157 }
4158
4159 /// Remove Codewhale-owned tokens and the config pointer for one provider.
4160 ///
4161 /// ChatGPT's remote revoke is best-effort against the row's pinned revoke
4162 /// path (see [`OAuthProviderParams::revoke_path`]): a failed or unreachable
4163 /// revoke must never stop the local credentials from being removed. xAI
4164 /// revokes locally only. External CLI consent is left untouched.
4165 pub fn revoke_owned_login(
4166 provider: OAuthProvider,
4167 config_path: Option<&Path>,
4168 live_config: Option<&mut Config>,
4169 ) -> Result<()> {
4170 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
4171 revoke_owned_login_locked(provider, config_path, live_config, store)
4172 })
4173 }
4174
4175 fn revoke_owned_login_locked(
4176 provider: OAuthProvider,
4177 config_path: Option<&Path>,
4178 live_config: Option<&mut Config>,
4179 store: &codewhale_config::XaiOAuthCredentialStore,
4180 ) -> Result<()> {
4181 revoke_owned_login_locked_with(
4182 provider,
4183 config_path,
4184 live_config,
4185 store,
4186 &ReqwestOAuthFormClient,
4187 )
4188 }
4189
4190 fn revoke_owned_login_locked_with(
4191 provider: OAuthProvider,
4192 config_path: Option<&Path>,
4193 live_config: Option<&mut Config>,
4194 store: &codewhale_config::XaiOAuthCredentialStore,
4195 client: &dyn OAuthFormClient,
4196 ) -> Result<()> {
4197 let config_path = crate::config_persistence::config_toml_path(config_path)?;
4198 let key_inside = provider.config_key();
4199 let previous = codewhale_config::mutate_config_document(&config_path, |document| {
4200 let previous = document
4201 .get("providers")
4202 .and_then(toml_edit::Item::as_table_like)
4203 .and_then(|providers| providers.get(key_inside))
4204 .and_then(toml_edit::Item::as_table_like)
4205 .and_then(|provider| provider.get("oauth_credential_generation"))
4206 .and_then(toml_edit::Item::as_str)
4207 .map(ToOwned::to_owned);
4208 codewhale_config::unset_config_document_value(
4209 document,
4210 &["providers", key_inside, "oauth_credential_generation"],
4211 )?;
4212 let auth_mode_is_oauth = document
4213 .get("providers")
4214 .and_then(toml_edit::Item::as_table_like)
4215 .and_then(|providers| providers.get(key_inside))
4216 .and_then(toml_edit::Item::as_table_like)
4217 .and_then(|provider| provider.get("auth_mode"))
4218 .and_then(toml_edit::Item::as_str)
4219 == Some("oauth");
4220 if auth_mode_is_oauth {
4221 codewhale_config::unset_config_document_value(
4222 document,
4223 &["providers", key_inside, "auth_mode"],
4224 )?;
4225 }
4226 Ok(previous)
4227 })?;
4228 let live_config_clear = match live_config {
4229 Some(config) if provider == OAuthProvider::Chatgpt => {
4230 config.clear_codewhale_owned_chatgpt_oauth()
4231 }
4232 _ => Ok(()),
4233 };
4234 let names = match previous.as_deref() {
4235 Some(generation) if provider.is_valid_generation(generation) => {
4236 vec![generation.to_string()]
4237 }
4238 _ => vec![provider.legacy_file_name().to_string()],
4239 };
4240 let mut remote_unconfirmed = false;
4241 for name in names {
4242 if let Ok(Some(raw)) = store.read_to_string(&name)
4243 && let Ok(file) = parse_auth_file(&raw, &store.path_for(&name)?)
4244 {
4245 for entry in file.values() {
4246 if let Some(token) = entry
4247 .refresh_token
4248 .as_deref()
4249 .or(entry.access_token.as_deref())
4250 .filter(|token| !token.trim().is_empty())
4251 {
4252 let issuer = entry
4253 .oidc_issuer
4254 .as_deref()
4255 .unwrap_or_else(|| oauth_provider_params(provider).default_issuer);
4256 let client_id = entry
4257 .oidc_client_id
4258 .as_deref()
4259 .unwrap_or_else(|| oauth_provider_params(provider).default_client_id);
4260 if let Err(error) = revoke_remote_token_via(
4261 client,
4262 oauth_provider_params(provider),
4263 issuer,
4264 client_id,
4265 token,
4266 ) {
4267 remote_unconfirmed |= provider == OAuthProvider::Chatgpt;
4268 tracing::warn!(
4269 target: "codewhale::oauth",
4270 error = %error,
4271 "remote OAuth revoke failed; local credentials will still be removed"
4272 );
4273 }
4274 }
4275 }
4276 }
4277 store
4278 .remove(&name)
4279 .context("OAuth sign-out could not clear local credential storage")?;
4280 }
4281 if provider == OAuthProvider::Chatgpt {
4282 let host_name = codewhale_config::CHATGPT_HOST_FILE_NAME;
4283 if let Ok(Some(raw)) = store.read_to_string(host_name)
4284 && let Ok(mut host) = serde_json::from_str::<ChatgptHost>(&raw)
4285 && host.registration.is_some()
4286 {
4287 host.registration = None;
4288 let bytes = serde_json::to_vec(&host)
4289 .context("OAuth sign-out could not encode ChatGPT host metadata")?;
4290 store
4291 .write(host_name, &bytes, true)
4292 .context("OAuth sign-out could not clear local ChatGPT registration")?;
4293 }
4294 }
4295 // A refused live mirror must not leave durable tokens behind. Report it
4296 // only after local removal and preserve an unconfirmed remote outcome.
4297 if remote_unconfirmed {
4298 return live_config_clear.context(
4299 "Signed out locally, but the live route could not be refreshed and remote revocation was not confirmed.",
4300 ).and_then(|()| anyhow::bail!(
4301 "Signed out locally, but remote revocation was not confirmed. Disconnect Codewhale in ChatGPT Settings to end the renewable session."
4302 ));
4303 }
4304 live_config_clear.context("Signed out locally, but the live route could not be refreshed")?;
4305 Ok(())
4306 }
4307
4308 /// Detect the [#5032] bricked-launch state: the provider's config selects
4309 /// OAuth and points `oauth_credential_generation` at a Codewhale-owned
4310 /// credential file that no longer exists. This is a distinct, more specific
4311 /// failure than "unconfigured" — the pointer is present and authoritative,
4312 /// so [`credentials_valid`] returns false and cannot fall through to a
4313 /// legacy or external credential, which is exactly what bricked the
4314 /// dogfood machine.
4315 ///
4316 /// Returns false for any other state: OAuth not selected, no generation
4317 /// configured, a malformed generation pointer (a different, already
4318 /// fail-closed failure), or a generation whose owned file is present.
4319 ///
4320 /// [#5032]: https://github.com/codewhale-hq/CodeWhale/issues/5032
4321 #[must_use]
4322 pub fn owned_generation_is_dangling(provider: OAuthProvider, config: &Config) -> bool {
4323 let Ok(identity) = config.builtin_provider_identity(provider.api()) else {
4324 return false;
4325 };
4326 if provider == OAuthProvider::Xai
4327 && !config
4328 .provider_config_for(&identity)
4329 .and_then(|entry| entry.auth_mode.as_deref())
4330 .is_some_and(auth_mode_uses_xai_oauth)
4331 {
4332 return false;
4333 }
4334 match configured_owned_auth_file_path(provider, config) {
4335 Ok(Some(path)) => !path.exists(),
4336 // `None` => no generation configured (not a dangling pointer). `Err` =>
4337 // the generation is malformed/invalid; that is a different, already
4338 // fail-closed failure, not the missing-file state this detects.
4339 _ => false,
4340 }
4341 }
4342
4343 /// Best-effort repair for the [#5032] bricked-launch state: remove the stale
4344 /// `oauth_credential_generation` pointer from the PERSISTED config file so
4345 /// the next launch is no longer bricked. Mirrors the document edits in
4346 /// `activate_login_locked` (which replaces the pointer under the config
4347 /// lock) and [`crate::config::clear_api_key`]'s unlocked scrub.
4348 ///
4349 /// Leaves `auth_mode = "oauth"` intact: the user still wants OAuth, they
4350 /// simply need to re-authenticate. The launch-path caller must treat any
4351 /// error as non-fatal — log a warning and continue. Returns `Ok(())` when
4352 /// the stale pointer was removed (or was already absent).
4353 ///
4354 /// [#5032]: https://github.com/codewhale-hq/CodeWhale/issues/5032
4355 pub fn clear_dangling_generation(
4356 provider: OAuthProvider,
4357 config_path: Option<&Path>,
4358 ) -> Result<()> {
4359 let config_path = crate::config_persistence::config_toml_path(config_path)?;
4360 let key_inside = provider.config_key();
4361 codewhale_config::mutate_config_document(&config_path, |document| {
4362 codewhale_config::unset_config_document_value(
4363 document,
4364 &["providers", key_inside, "oauth_credential_generation"],
4365 )?;
4366 Ok(())
4367 })
4368 }
4369
4370 /// Whether `[providers.xai] auth_mode` selects the OAuth path.
4371 #[must_use]
4372 pub fn auth_mode_uses_xai_oauth(mode: &str) -> bool {
4373 matches!(
4374 normalize_auth_mode(mode).as_str(),
4375 "oauth"
4376 | "xai_oauth"
4377 | "xai"
4378 | "grok"
4379 | "grok_oauth"
4380 | "grok_cli"
4381 | "device"
4382 | "device_code"
4383 | "device_auth"
4384 )
4385 }
4386
4387 fn normalize_auth_mode(mode: &str) -> String {
4388 mode.trim().to_ascii_lowercase().replace(['-', ' '], "_")
4389 }
4390
4391 /// Resolve the Grok CLI auth file path.
4392 ///
4393 /// Priority:
4394 /// 1. `GROK_AUTH_PATH` / `XAI_AUTH_PATH`
4395 /// 2. `$GROK_HOME/auth.json`
4396 /// 3. `~/.grok/auth.json`
4397 #[must_use]
4398 pub fn grok_auth_file_path() -> PathBuf {
4399 for key in ["GROK_AUTH_PATH", "XAI_AUTH_PATH"] {
4400 if let Ok(path) = std::env::var(key) {
4401 let p = PathBuf::from(path.trim());
4402 if !p.as_os_str().is_empty() {
4403 return codewhale_config::resolve_external_credential_path(&p).unwrap_or(p);
4404 }
4405 }
4406 }
4407 if let Ok(home) = std::env::var("GROK_HOME") {
4408 let p = PathBuf::from(home.trim());
4409 if !p.as_os_str().is_empty() {
4410 let path = p.join("auth.json");
4411 return codewhale_config::resolve_external_credential_path(&path).unwrap_or(path);
4412 }
4413 }
4414 let path = codewhale_paths::user_home()
4415 .unwrap_or_else(|| PathBuf::from("."))
4416 .join(".grok")
4417 .join("auth.json");
4418 codewhale_config::resolve_external_credential_path(&path).unwrap_or(path)
4419 }
4420
4421 #[must_use]
4422 pub fn missing_auth_message(provider: OAuthProvider) -> String {
4423 match provider {
4424 OAuthProvider::Xai => format!(
4425 "xAI OAuth credentials not found.\n\
4426 Options:\n\
4427 1. Run `codewhale auth xai-device` for Codewhale-owned OAuth storage\n\
4428 2. To read an existing Grok CLI login without changing it, run \
4429 `codewhale auth external-consent --provider xai --mode read-only --path {}`\n\
4430 3. Or use API-key auth: export XAI_API_KEY=... / \
4431 codewhale auth set --provider xai",
4432 codewhale_config::quote_os_path(&grok_auth_file_path())
4433 ),
4434 OAuthProvider::Chatgpt => "Official ChatGPT credentials are unavailable.
4435 \
4436 Run `codewhale auth chatgpt` or /provider setup openai-codex.
4437 \
4438 Authorize ChatGPT plan usage to use your plan allowance.
4439 \
4440 Revoke Codewhale-owned tokens with `codewhale auth chatgpt-revoke`.
4441 \
4442 The openai API-key route uses separate API billing."
4443 .to_string(),
4444 }
4445 }
4446
4447 /// Declarative public OAuth configuration for a reviewed plugin provider.
4448 // Plugin OAuth uses the same PKCE, callback, bounded HTTP and secure-store
4449 // primitives as built-in logins. This declarative boundary intentionally does
4450 // not execute plugin callbacks, expose refresh tokens, support confidential
4451 // clients, or discover endpoints: plugins name reviewed, same-issuer endpoints.
4452 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4453 #[serde(deny_unknown_fields)]
4454 pub struct PluginOAuthConfig {
4455 pub issuer: String,
4456 pub authorization_endpoint: String,
4457 pub token_endpoint: String,
4458 pub client_id: String,
4459 #[serde(default)]
4460 pub scopes: Vec<String>,
4461 #[serde(default)]
4462 pub resource: Option<String>,
4463 #[serde(default = "plugin_callback_path")]
4464 pub callback_path: String,
4465 }
4466
4467 fn plugin_callback_path() -> String {
4468 "/oauth/callback".into()
4469 }
4470
4471 impl PluginOAuthConfig {
4472 pub fn validate(&self) -> Result<()> {
4473 let issuer = oauth_endpoint_url(&self.issuer)?;
4474 for endpoint in [&self.authorization_endpoint, &self.token_endpoint] {
4475 let url = oauth_endpoint_url(endpoint)?;
4476 anyhow::ensure!(
4477 url.origin() == issuer.origin(),
4478 "Plugin OAuth endpoints must belong to the issuer origin"
4479 );
4480 anyhow::ensure!(
4481 url.query().is_none()
4482 && url.fragment().is_none()
4483 && url.username().is_empty()
4484 && url.password().is_none(),
4485 "Plugin OAuth endpoint must not contain credentials, query or fragment"
4486 );
4487 }
4488 anyhow::ensure!(
4489 issuer.query().is_none()
4490 && issuer.fragment().is_none()
4491 && issuer.username().is_empty()
4492 && issuer.password().is_none(),
4493 "Plugin OAuth issuer must not contain credentials, query or fragment"
4494 );
4495 anyhow::ensure!(
4496 !self.client_id.trim().is_empty(),
4497 "Plugin OAuth client_id must not be empty"
4498 );
4499 anyhow::ensure!(
4500 self.callback_path.starts_with('/')
4501 && !self.callback_path.starts_with("//")
4502 && !self.callback_path.contains(['?', '#'])
4503 && !self.callback_path.chars().any(char::is_control),
4504 "Plugin OAuth callback_path must be an absolute path without query or fragment"
4505 );
4506 anyhow::ensure!(
4507 self.scopes
4508 .iter()
4509 .all(|scope| !scope.is_empty() && !scope.chars().any(char::is_whitespace)),
4510 "Plugin OAuth scopes must be nonempty individual scope names"
4511 );
4512 if let Some(resource) = &self.resource {
4513 let resource = oauth_endpoint_url(resource)?;
4514 anyhow::ensure!(
4515 resource.fragment().is_none()
4516 && resource.username().is_empty()
4517 && resource.password().is_none(),
4518 "Plugin OAuth resource must not contain credentials or a fragment"
4519 );
4520 }
4521 Ok(())
4522 }
4523
4524 pub fn callback_params(&self) -> OAuthProviderParams<'_> {
4525 OAuthProviderParams {
4526 display_name: "Plugin provider",
4527 default_issuer: &self.issuer,
4528 default_client_id: &self.client_id,
4529 default_scopes: "",
4530 env: OAuthEnvOverrides {
4531 issuer_vars: &[],
4532 client_id_vars: &[],
4533 scope_vars: &[],
4534 no_browser_var: "CODEWHALE_PLUGIN_OAUTH_NO_BROWSER",
4535 no_account_prompt_var: None,
4536 },
4537 device_code_path: None,
4538 authorize_path: None,
4539 token_path: "",
4540 discover_endpoints: false,
4541 device_poll_floor_secs: 0,
4542 authorize_extras: &[],
4543 account_choice_extras: &[],
4544 revoke_path: None,
4545 callback_path: &self.callback_path,
4546 loopback_ports: &[],
4547 relogin_hint: "codewhale auth plugin-login --provider <provider>",
4548 session_login_hint: "/connect <provider>",
4549 callback_conflict_hint: "",
4550 }
4551 }
4552
4553 pub fn authorize_url(
4554 &self,
4555 redirect_uri: &str,
4556 state: &str,
4557 pkce: &PkceChallenge,
4558 ) -> Result<String> {
4559 self.validate()?;
4560 let mut url = oauth_endpoint_url(&self.authorization_endpoint)?;
4561 url.query_pairs_mut()
4562 .append_pair("response_type", "code")
4563 .append_pair("client_id", &self.client_id)
4564 .append_pair("redirect_uri", redirect_uri)
4565 .append_pair("scope", &self.scopes.join(" "))
4566 .append_pair("state", state)
4567 .append_pair("code_challenge", &pkce.challenge)
4568 .append_pair("code_challenge_method", "S256");
4569 if let Some(resource) = &self.resource {
4570 url.query_pairs_mut().append_pair("resource", resource);
4571 }
4572 Ok(url.into())
4573 }
4574 }
4575
4576 fn validate_plugin_callback(query: &str, issuer: &str) -> Result<()> {
4577 let url = reqwest::Url::parse(&format!("http://127.0.0.1/?{query}"))?;
4578 let mut fields = BTreeMap::new();
4579 for (key, value) in url.query_pairs() {
4580 if matches!(
4581 key.as_ref(),
4582 "code" | "state" | "iss" | "error" | "error_description"
4583 ) {
4584 anyhow::ensure!(
4585 fields
4586 .insert(key.into_owned(), value.into_owned())
4587 .is_none(),
4588 "Plugin OAuth callback contains duplicate parameters"
4589 );
4590 }
4591 }
4592 anyhow::ensure!(
4593 fields.get("state").is_some_and(|state| !state.is_empty()),
4594 "Plugin OAuth callback missing state"
4595 );
4596 // RFC 9207: when an authorization server supplies `iss`, bind it exactly
4597 // to the reviewed issuer. Servers not advertising that extension still
4598 // have the single in-flight endpoint and PKCE/state binding.
4599 if let Some(actual) = fields.get("iss") {
4600 anyhow::ensure!(
4601 actual == issuer,
4602 "Plugin OAuth callback issuer does not match"
4603 );
4604 }
4605 Ok(())
4606 }
4607
4608 #[derive(Serialize, Deserialize)]
4609 pub struct PluginOAuthTokens {
4610 #[serde(default)]
4611 grant_id: Option<uuid::Uuid>,
4612 access_token: String,
4613 refresh_token: Option<String>,
4614 expires_at: u64,
4615 }
4616
4617 pub fn plugin_oauth_slot(
4618 provider: &str,
4619 base_url: &str,
4620 descriptor: &PluginOAuthConfig,
4621 ) -> Result<String> {
4622 descriptor.validate()?;
4623 oauth_endpoint_url(base_url)?;
4624 anyhow::ensure!(!provider.trim().is_empty(), "Plugin provider name is empty");
4625 let binding = serde_json::to_vec(&(provider, base_url, descriptor))?;
4626 let hash: String = Sha256::digest(binding)
4627 .iter()
4628 .map(|byte| format!("{byte:02x}"))
4629 .collect();
4630 Ok(format!("plugin-oauth:{hash}"))
4631 }
4632
4633 #[derive(Deserialize)]
4634 struct PluginTokenResponse {
4635 #[serde(flatten)]
4636 material: OAuthTokenMaterial,
4637 #[serde(default)]
4638 token_type: Option<String>,
4639 }
4640
4641 pub fn plugin_token_response(
4642 descriptor: &PluginOAuthConfig,
4643 form: &[(&str, &str)],
4644 previous_refresh: Option<String>,
4645 ) -> Result<PluginOAuthTokens> {
4646 let endpoint = oauth_endpoint_url(&descriptor.token_endpoint)?;
4647 let response = oauth_http_client(&endpoint, "plugin token exchange")?
4648 .post(endpoint)
4649 .form(form)
4650 .send()?;
4651 let (status, response): (_, PluginTokenResponse) =
4652 parse_oauth_json(response, "Plugin OAuth token exchange")?;
4653 let token = response.material;
4654 anyhow::ensure!(
4655 status.is_success() && token.error.is_none(),
4656 "Plugin OAuth token exchange failed with HTTP {}",
4657 status.as_u16()
4658 );
4659 anyhow::ensure!(
4660 response
4661 .token_type
4662 .as_deref()
4663 .is_some_and(|kind| kind.eq_ignore_ascii_case("bearer")),
4664 "Plugin OAuth token response requires Bearer token_type"
4665 );
4666 let access_token = token
4667 .access_token
4668 .filter(|token| !token.trim().is_empty())
4669 .context("Plugin OAuth token exchange returned no access token")?;
4670 let lifetime = token
4671 .expires_in
4672 .filter(|seconds| *seconds > 0)
4673 .context("Plugin OAuth token response requires a positive expires_in")?;
4674 Ok(PluginOAuthTokens {
4675 grant_id: Some(uuid::Uuid::new_v4()),
4676 access_token,
4677 refresh_token: token
4678 .refresh_token
4679 .filter(|token| !token.trim().is_empty())
4680 .or(previous_refresh),
4681 expires_at: (now_unix_secs().context("System clock before UNIX epoch")? as u64)
4682 .saturating_add(lifetime),
4683 })
4684 }
4685
4686 /// Prompt-free stored-login status. Readiness reads only this exact host-owned
4687 /// secure slot, without refreshing, migrating or contacting the issuer.
4688 pub fn plugin_oauth_credentials_present(
4689 provider: &str,
4690 base_url: &str,
4691 descriptor: &PluginOAuthConfig,
4692 ) -> Result<bool> {
4693 let slot = plugin_oauth_slot(provider, base_url, descriptor)?;
4694 let secrets = codewhale_secrets::Secrets::auto_detect_read_only();
4695 let Some(raw) = secrets.get(&slot)? else {
4696 return Ok(false);
4697 };
4698 plugin_oauth_saved_token(&raw)
4699 }
4700
4701 fn plugin_oauth_saved_token(raw: &str) -> Result<bool> {
4702 let token: PluginOAuthTokens = serde_json::from_str(raw)
4703 .map_err(|_| anyhow::anyhow!("Plugin OAuth credential store contains invalid data"))?;
4704 let now = now_unix_secs().context("System clock before UNIX epoch")? as u64;
4705 Ok(!token.access_token.trim().is_empty()
4706 && (token.expires_at > now
4707 || token
4708 .refresh_token
4709 .as_deref()
4710 .is_some_and(|token| !token.trim().is_empty())))
4711 }
4712
4713 /// Resolve only the exact provider, endpoint and descriptor-bound credential.
4714 /// Async consumers must call this sync secure-store/HTTP worker off-runtime.
4715 pub fn plugin_oauth_access_token(
4716 provider: &str,
4717 base_url: &str,
4718 descriptor: &PluginOAuthConfig,
4719 read_only: bool,
4720 ) -> Result<String> {
4721 plugin_oauth_access_token_for_grant(provider, base_url, descriptor, read_only, None)
4722 }
4723
4724 pub fn plugin_oauth_access_token_for_grant(
4725 provider: &str,
4726 base_url: &str,
4727 descriptor: &PluginOAuthConfig,
4728 read_only: bool,
4729 expected_grant: Option<uuid::Uuid>,
4730 ) -> Result<String> {
4731 let slot = plugin_oauth_slot(provider, base_url, descriptor)?;
4732 let secrets = if read_only {
4733 codewhale_secrets::Secrets::auto_detect_read_only()
4734 } else {
4735 codewhale_secrets::Secrets::auto_detect()
4736 };
4737 resolve_plugin_oauth_access_token(&slot, descriptor, read_only, &secrets, expected_grant)
4738 }
4739
4740 pub fn pin_plugin_oauth_grant(
4741 provider: &str,
4742 base_url: &str,
4743 descriptor: &PluginOAuthConfig,
4744 ) -> Result<uuid::Uuid> {
4745 let slot = plugin_oauth_slot(provider, base_url, descriptor)?;
4746 pin_plugin_oauth_grant_with_store(&slot, &codewhale_secrets::Secrets::auto_detect())
4747 }
4748
4749 fn read_plugin_oauth_grant(raw: Option<&str>) -> Result<PluginOAuthTokens> {
4750 let stored = raw.context(
4751 "Plugin OAuth login missing; use /connect <provider> in Codewhale or codewhale auth plugin-login --provider <provider> in a terminal",
4752 )?;
4753 serde_json::from_str(stored)
4754 .map_err(|_| anyhow::anyhow!("Plugin OAuth credential store contains invalid data"))
4755 }
4756
4757 fn pin_plugin_oauth_grant_with_store(
4758 slot: &str,
4759 secrets: &codewhale_secrets::Secrets,
4760 ) -> Result<uuid::Uuid> {
4761 if let Some(raw) = secrets.get(slot)?
4762 && let Some(id) = read_plugin_oauth_grant(Some(&raw))?.grant_id
4763 {
4764 return Ok(id);
4765 }
4766 secrets
4767 .with_entry_transaction(slot, |raw| {
4768 let mut token = read_plugin_oauth_grant(raw.as_deref())
4769 .map_err(|error| codewhale_secrets::SecretsError::Keyring(error.to_string()))?;
4770 let id = match token.grant_id {
4771 Some(id) => id,
4772 None => {
4773 let id = uuid::Uuid::new_v4();
4774 token.grant_id = Some(id);
4775 *raw = Some(serde_json::to_string(&token).map_err(|error| {
4776 codewhale_secrets::SecretsError::Keyring(error.to_string())
4777 })?);
4778 id
4779 }
4780 };
4781 Ok(id)
4782 })
4783 .map_err(Into::into)
4784 }
4785
4786 #[cfg(test)]
4787 fn plugin_oauth_access_token_with_store(
4788 slot: &str,
4789 descriptor: &PluginOAuthConfig,
4790 read_only: bool,
4791 secrets: &codewhale_secrets::Secrets,
4792 ) -> Result<String> {
4793 resolve_plugin_oauth_access_token(slot, descriptor, read_only, secrets, None)
4794 }
4795
4796 fn resolve_plugin_oauth_access_token(
4797 slot: &str,
4798 descriptor: &PluginOAuthConfig,
4799 read_only: bool,
4800 secrets: &codewhale_secrets::Secrets,
4801 expected_grant: Option<uuid::Uuid>,
4802 ) -> Result<String> {
4803 let resolve = |raw: &mut Option<String>| -> Result<String> {
4804 let mut token = read_plugin_oauth_grant(raw.as_deref())?;
4805 anyhow::ensure!(
4806 expected_grant.is_none_or(|expected| token.grant_id == Some(expected)),
4807 "Plugin OAuth login changed after route selection. Re-run with an explicit --provider or --model."
4808 );
4809 let now = now_unix_secs().context("System clock before UNIX epoch")? as u64;
4810 // The refresh window is not expiration. Non-refreshable grants and
4811 // read-only diagnostics may use a token for its actual valid lifetime.
4812 let expired = now >= token.expires_at;
4813 let refresh_due = !read_only
4814 && token.refresh_token.is_some()
4815 && now.saturating_add(60) >= token.expires_at;
4816 if expired || refresh_due {
4817 anyhow::ensure!(
4818 !read_only,
4819 "Plugin OAuth token expired; diagnostics never refresh credentials"
4820 );
4821 let refresh = token
4822 .refresh_token
4823 .as_ref()
4824 .context("Plugin OAuth token expired; sign in again")?;
4825 let mut form = vec![
4826 ("grant_type", "refresh_token"),
4827 ("client_id", descriptor.client_id.as_str()),
4828 ("refresh_token", refresh.as_str()),
4829 ];
4830 if let Some(resource) = &descriptor.resource {
4831 form.push(("resource", resource));
4832 }
4833 let grant_id = token.grant_id;
4834 token = plugin_token_response(descriptor, &form, Some(refresh.clone()))?;
4835 token.grant_id = grant_id.or(token.grant_id);
4836 *raw = Some(serde_json::to_string(&token)?);
4837 }
4838 Ok(token.access_token)
4839 };
4840 if read_only {
4841 return resolve(&mut secrets.get(slot)?);
4842 }
4843 // Serialize rotating refresh grants with the existing backend authority:
4844 // concurrent inference cannot replay an already consumed refresh token.
4845 secrets
4846 .with_entry_transaction(slot, |raw| {
4847 resolve(raw)
4848 .map_err(|error| codewhale_secrets::SecretsError::Keyring(error.to_string()))
4849 })
4850 .map_err(Into::into)
4851 }
4852
4853 /// Local logout is authoritative; declarative plugins do not get a remote
4854 /// revocation hook or raw refresh token.
4855 pub fn plugin_oauth_logout(
4856 provider: &str,
4857 base_url: &str,
4858 descriptor: &PluginOAuthConfig,
4859 ) -> Result<()> {
4860 let slot = plugin_oauth_slot(provider, base_url, descriptor)?;
4861 codewhale_secrets::Secrets::auto_detect().delete(&slot)?;
4862 Ok(())
4863 }
4864
4865 /// Pending-login test constructor shared by the activation tests.
4866 #[cfg(any(test, feature = "test-support"))]
4867 pub fn pending_login_for_test(
4868 provider: OAuthProvider,
4869 access_token: &str,
4870 refresh_token: &str,
4871 ) -> PendingOAuthLogin {
4872 pending_login_with_id_token_for_test(provider, access_token, refresh_token, None)
4873 }
4874
4875 #[cfg(any(test, feature = "test-support"))]
4876 pub fn pending_login_with_id_token_for_test(
4877 provider: OAuthProvider,
4878 access_token: &str,
4879 refresh_token: &str,
4880 id_token: Option<&str>,
4881 ) -> PendingOAuthLogin {
4882 let registration = (provider == OAuthProvider::Chatgpt).then(|| ChatgptRegistration {
4883 issuer: CHATGPT_OAUTH_ISSUER.to_string(),
4884 client_id: "oaiapp_codewhale_test".to_string(),
4885 subject: id_token
4886 .and_then(account_id_from_id_token)
4887 .unwrap_or_else(|| "test-sub".to_string()),
4888 email: None,
4889 host_id: format!("urn:uuid:{}", uuid::Uuid::new_v4()),
4890 });
4891 PendingOAuthLogin {
4892 provider,
4893 issuer: oauth_provider_params(provider).default_issuer.to_string(),
4894 client_id: registration.as_ref().map_or_else(
4895 || {
4896 oauth_provider_params(provider)
4897 .default_client_id
4898 .to_string()
4899 },
4900 |registration| registration.client_id.clone(),
4901 ),
4902 token: OAuthTokenMaterial {
4903 earliest_refresh_at: None,
4904 scope: registration
4905 .as_ref()
4906 .map(|_| CHATGPT_OAUTH_SCOPE.to_string()),
4907 token_type: Some("Bearer".to_string()),
4908 verified_chatgpt: registration,
4909 access_token: Some(access_token.to_string()),
4910 refresh_token: Some(refresh_token.to_string()),
4911 expires_in: Some(3600),
4912 id_token: id_token.map(ToOwned::to_owned),
4913 interval: None,
4914 error: None,
4915 error_description: None,
4916 },
4917 }
4918 }
4919
4920 /// Local stored-proof fixture only; signature verification has separate tests.
4921 /// The caller must isolate CODEWHALE_HOME before using this helper.
4922 #[cfg(any(test, feature = "test-support"))]
4923 pub fn install_test_chatgpt_registration(config: &mut Config) -> Result<String> {
4924 install_test_chatgpt_registration_for(config, "test-sub", "oaiapp_codewhale_test")
4925 }
4926
4927 #[cfg(any(test, feature = "test-support"))]
4928 pub fn install_test_chatgpt_registration_for(
4929 config: &mut Config,
4930 subject: &str,
4931 client_id: &str,
4932 ) -> Result<String> {
4933 let mut pending = pending_login_for_test(
4934 OAuthProvider::Chatgpt,
4935 "siwc-test-access",
4936 "siwc-test-refresh",
4937 );
4938 pending.client_id = client_id.to_string();
4939 let registration = pending
4940 .token
4941 .verified_chatgpt
4942 .as_mut()
4943 .expect("fixture registration");
4944 registration.subject = subject.to_string();
4945 registration.client_id = client_id.to_string();
4946 let generation = OAuthProvider::Chatgpt.new_generation();
4947 let mut entry = OwnedAuthEntry {
4948 access_token: None,
4949 refresh_token: None,
4950 expires_at: None,
4951 id_token: None,
4952 account_id: None,
4953 oidc_issuer: None,
4954 oidc_client_id: None,
4955 originator: None,
4956 auth_mode: None,
4957 extra: BTreeMap::new(),
4958 };
4959 apply_token_response(
4960 OAuthProvider::Chatgpt,
4961 &mut entry,
4962 &pending.issuer,
4963 &pending.client_id,
4964 &pending.token,
4965 )?;
4966 let file = BTreeMap::from([(format!("{}::{}", pending.issuer, pending.client_id), entry)]);
4967 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
4968 write_auth_file_to_store(store, &generation, &file, false)
4969 })?;
4970 config.mark_codewhale_owned_chatgpt_oauth(generation)?;
4971 Ok("siwc-test-access".to_string())
4972 }
4973
4974 #[cfg(test)]
4975 mod tests {
4976 use super::*;
4977 #[cfg(unix)]
4978 use std::os::unix::fs::PermissionsExt;
4979
4980 use codewhale_config::ProviderKind;
4981
4982 use std::fs;
4983
4984 // ── unified PKCE core (ported from the deleted chatgpt_oauth flow) ──
4985
4986 use std::sync::Mutex;
4987
4988 // ────────────────────────────────────────────────────────────────────
4989 // Ported from the deleted per-provider modules (§D security pins).
4990 // ────────────────────────────────────────────────────────────────────
4991
4992 use tempfile::TempDir;
4993
4994 use wiremock::matchers::method;
4995
4996 use wiremock::matchers::path;
4997
4998 use wiremock::Mock;
4999
5000 use wiremock::MockServer;
5001
5002 use super::test_support::*;
5003 use wiremock::ResponseTemplate;
5004
5005 #[test]
5006 fn oauth_endpoint_requires_https_or_parsed_loopback_http() {
5007 for raw in [
5008 "https://issuer.example/token",
5009 "http://localhost:8123/token",
5010 "http://127.0.0.1:8123/token",
5011 "http://127.0.0.2/token",
5012 "http://[::1]:8123/token",
5013 ] {
5014 assert!(oauth_endpoint_url(raw).is_ok());
5015 }
5016 for raw in [
5017 "http://issuer.example/token",
5018 "http://localhost.example/token",
5019 "http://127.0.0.1.example/token",
5020 "http://192.0.2.1/token",
5021 "https://user:example@issuer.example/token",
5022 "file:///tmp/token",
5023 "not a URL",
5024 ] {
5025 assert!(oauth_endpoint_url(raw).is_err());
5026 }
5027 }
5028
5029 #[test]
5030 fn oauth_discovery_rejects_an_initial_plaintext_remote_issuer() {
5031 let issuer = "http://issuer.example";
5032 assert!(validate_discovered_issuer(Some(issuer.into()), issuer).is_err());
5033 assert!(
5034 validate_discovered_oauth_endpoint(
5035 Some(format!("{issuer}/token")),
5036 "token_endpoint",
5037 issuer,
5038 )
5039 .is_err()
5040 );
5041 let fallback = fallback_oauth_endpoints(&XAI_OAUTH_PARAMS, issuer);
5042 assert!(oauth_endpoint_url(&fallback.token_endpoint).is_err());
5043 assert!(
5044 oauth_endpoint_url(fallback.device_authorization_endpoint.as_deref().unwrap()).is_err()
5045 );
5046 }
5047
5048 #[test]
5049 fn oauth_authorize_url_refuses_plaintext_remote_issuer_before_browser_use() {
5050 let pkce = PkceChallenge {
5051 verifier: "test-verifier".into(),
5052 challenge: "test-challenge".into(),
5053 };
5054 for issuer in [
5055 "http://issuer.example",
5056 "https://user:example@issuer.example",
5057 ] {
5058 assert!(
5059 build_authorize_url(
5060 &CHATGPT_OAUTH_PARAMS,
5061 issuer,
5062 "test-client",
5063 "openid",
5064 "http://localhost:1455/auth/callback",
5065 "test-state",
5066 &pkce,
5067 )
5068 .is_err()
5069 );
5070 }
5071 }
5072
5073 fn grant(path: &std::path::Path) -> ExternalCredentialReadGrant {
5074 codewhale_config::ExternalCredentialConsentToml::read_only(
5075 codewhale_config::ProviderKind::OpenaiCodex,
5076 codewhale_config::ExternalCredentialSource::CodexCli,
5077 path.to_path_buf(),
5078 )
5079 .read_grant(
5080 codewhale_config::ProviderKind::OpenaiCodex,
5081 codewhale_config::ExternalCredentialSource::CodexCli,
5082 path,
5083 )
5084 .expect("test read grant")
5085 }
5086
5087 #[test]
5088 fn jwt_expiry_parses_valid_token() {
5089 // A minimal JWT with {"exp": 9999999999} as payload.
5090 let payload = URL_SAFE_NO_PAD.encode(b"{\"exp\":9999999999}");
5091 let token = format!("header.{payload}.signature");
5092 assert_eq!(jwt_expiry_seconds(&token), Some(9999999999));
5093 }
5094
5095 #[test]
5096 fn jwt_expiry_returns_none_for_malformed() {
5097 assert_eq!(jwt_expiry_seconds("not.a.jwt"), None);
5098 assert_eq!(jwt_expiry_seconds(""), None);
5099 assert_eq!(jwt_expiry_seconds("x"), None);
5100 }
5101
5102 #[test]
5103 fn token_is_expired_detects_future() {
5104 // Far future — should not be expired.
5105 let payload = URL_SAFE_NO_PAD.encode(b"{\"exp\":9999999999}");
5106 let token = format!("header.{payload}.sig");
5107 assert!(!token_is_expired(&token));
5108 }
5109
5110 #[test]
5111 fn token_is_expired_detects_past() {
5112 // Way in the past.
5113 let payload = URL_SAFE_NO_PAD.encode(b"{\"exp\":1000000000}");
5114 let token = format!("header.{payload}.sig");
5115 assert!(token_is_expired(&token));
5116 }
5117
5118 #[test]
5119 fn owned_token_freshness_honors_both_expiries_and_preserves_fallbacks() {
5120 let now = now_unix_secs().expect("clock");
5121 let future = rfc3339_from_unix(now + 3600);
5122 let past = rfc3339_from_unix(now - 3600);
5123 let near = rfc3339_from_unix(now + 30);
5124 let fresh_token = jwt_with_exp((now + 3600) as u64);
5125 let expired_token = jwt_with_exp((now - 3600) as u64);
5126 let near_token = jwt_with_exp((now + 30) as u64);
5127
5128 for (stored, token, expected) in [
5129 (Some(future.as_str()), expired_token.as_str(), false),
5130 (Some(past.as_str()), fresh_token.as_str(), false),
5131 (Some(future.as_str()), fresh_token.as_str(), true),
5132 (Some(future.as_str()), near_token.as_str(), false),
5133 (Some(near.as_str()), fresh_token.as_str(), false),
5134 (None, fresh_token.as_str(), true),
5135 (None, expired_token.as_str(), false),
5136 (Some("invalid-date"), fresh_token.as_str(), true),
5137 (Some(future.as_str()), "opaque-token", true),
5138 (Some(past.as_str()), "opaque-token", false),
5139 (None, "opaque-token", false),
5140 (Some("invalid-date"), "opaque-token", false),
5141 (Some(future.as_str()), "", false),
5142 ] {
5143 let entry: OwnedAuthEntry = serde_json::from_value(serde_json::json!({
5144 "access_token": token,
5145 "expires_at": stored,
5146 }))
5147 .expect("synthetic owned entry");
5148 assert_eq!(
5149 entry_access_token_is_fresh(&entry),
5150 expected,
5151 "stored={stored:?}, JWT expiry={:?}",
5152 jwt_expiry_seconds(token),
5153 );
5154 }
5155 }
5156
5157 #[test]
5158 fn credential_presence_rejects_empty_and_malformed_files_without_refresh() {
5159 let _lock = crate::test_support::lock_test_env();
5160 let home = tempfile::tempdir().expect("temp Codex home");
5161 let auth_path = home
5162 .path()
5163 .canonicalize()
5164 .expect("canonical temp root")
5165 .join("auth.json");
5166 let _auth = crate::test_support::EnvVarGuard::set("OPENAI_CODEX_AUTH_FILE", &auth_path);
5167 let _access = crate::test_support::EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN");
5168 let _legacy_access = crate::test_support::EnvVarGuard::remove("CODEX_ACCESS_TOKEN");
5169 let grant = grant(&auth_path);
5170
5171 std::fs::write(&auth_path, "{}").expect("empty auth");
5172 crate::external_credentials::reset_side_effect_trap();
5173 assert!(!stored_credentials_present(&grant));
5174 assert_eq!(
5175 crate::external_credentials::side_effect_trap_counts(),
5176 (1, 1)
5177 );
5178 assert_eq!(
5179 crate::external_credentials::complete_side_effect_trap_counts(),
5180 (1, 1, 0, 0, 0)
5181 );
5182 std::fs::write(&auth_path, "{not-json").expect("malformed auth");
5183 crate::external_credentials::reset_side_effect_trap();
5184 assert!(!stored_credentials_present(&grant));
5185 assert_eq!(
5186 crate::external_credentials::side_effect_trap_counts(),
5187 (1, 1)
5188 );
5189
5190 let payload = URL_SAFE_NO_PAD.encode(b"{\"exp\":9999999999}");
5191 let access_token = format!("header.{payload}.signature");
5192 std::fs::write(
5193 &auth_path,
5194 serde_json::to_vec(&serde_json::json!({
5195 "tokens": {"access_token": access_token}
5196 }))
5197 .expect("valid auth json"),
5198 )
5199 .expect("valid auth");
5200 crate::external_credentials::reset_side_effect_trap();
5201 assert!(stored_credentials_present(&grant));
5202 assert_eq!(
5203 crate::external_credentials::side_effect_trap_counts(),
5204 (1, 1)
5205 );
5206 }
5207
5208 #[test]
5209 fn expired_external_token_fails_without_refresh_or_rewrite() {
5210 let _lock = crate::test_support::lock_test_env();
5211 let home = tempfile::tempdir().expect("temp Codex home");
5212 let auth_path = home
5213 .path()
5214 .canonicalize()
5215 .expect("canonical temp root")
5216 .join("auth.json");
5217 let payload = URL_SAFE_NO_PAD.encode(b"{\"exp\":1000000000}");
5218 let access_token = format!("header.{payload}.signature");
5219 let raw = serde_json::to_string_pretty(&serde_json::json!({
5220 "tokens": {
5221 "access_token": access_token,
5222 "refresh_token": "must-never-be-used",
5223 "account_id": "acct-test",
5224 "future_field": {"preserve": true}
5225 },
5226 "future_top_level": [1, 2, 3]
5227 }))
5228 .expect("auth fixture");
5229 std::fs::write(&auth_path, &raw).expect("expired auth fixture");
5230
5231 crate::external_credentials::reset_side_effect_trap();
5232 let error = get_credentials(&grant(&auth_path))
5233 .expect_err("read-only external tokens must not refresh");
5234 assert!(error.to_string().contains("never refreshes or rewrites"));
5235 assert_eq!(
5236 crate::external_credentials::side_effect_trap_counts(),
5237 (1, 1)
5238 );
5239 assert_eq!(
5240 std::fs::read_to_string(&auth_path).expect("unchanged auth file"),
5241 raw
5242 );
5243 }
5244
5245 #[test]
5246 fn auth_file_path_respects_env() {
5247 // Just verify it returns a path without panicking.
5248 let path = auth_file_path();
5249 assert!(path.to_string_lossy().contains("auth.json"));
5250 }
5251
5252 #[test]
5253 fn missing_auth_message_guides_official_sign_in() {
5254 let message = missing_auth_message(OAuthProvider::Chatgpt);
5255 assert!(message.contains("Official ChatGPT credentials"));
5256 assert!(message.contains("codewhale auth chatgpt"));
5257 assert!(message.contains("ChatGPT plan usage"));
5258 assert!(message.contains("openai API-key"));
5259 assert!(message.contains("chatgpt-revoke"));
5260 assert!(!message.contains("external-consent"));
5261 assert!(!message.contains("CODEX_ACCESS_TOKEN"));
5262 }
5263
5264 #[test]
5265 fn provider_table_separates_device_flow_from_browser_flow() {
5266 let xai = oauth_provider_params(OAuthProvider::Xai);
5267 assert_eq!(xai.device_code_path, Some("oauth2/device/code"));
5268 assert!(xai.discover_endpoints);
5269 let chatgpt = oauth_provider_params(OAuthProvider::Chatgpt);
5270 assert_eq!(chatgpt.device_code_path, None);
5271 assert!(!chatgpt.discover_endpoints);
5272 assert_ne!(xai.default_client_id, chatgpt.default_client_id);
5273 }
5274
5275 #[test]
5276 fn provider_inputs_resolve_from_defaults_without_env() {
5277 let _lock = crate::test_support::lock_test_env();
5278 let _guards: Vec<_> = [
5279 "GROK_OIDC_ISSUER",
5280 "XAI_OIDC_ISSUER",
5281 "GROK_OIDC_CLIENT_ID",
5282 "XAI_OIDC_CLIENT_ID",
5283 "GROK_OIDC_SCOPES",
5284 "XAI_OIDC_SCOPES",
5285 "CODEWHALE_XAI_OAUTH_NO_BROWSER",
5286 ]
5287 .into_iter()
5288 .map(crate::test_support::EnvVarGuard::remove)
5289 .collect();
5290 let inputs = XAI_OAUTH_PARAMS.resolve_inputs();
5291 assert_eq!(inputs.issuer, "https://auth.x.ai");
5292 assert!(inputs.scopes.contains("grok-cli:access"));
5293 assert!(inputs.open_browser);
5294 }
5295
5296 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5297 async fn request_device_grant_round_trips_a_mock_grant() {
5298 use wiremock::matchers::{method, path};
5299 use wiremock::{Mock, MockServer, ResponseTemplate};
5300 let server = MockServer::start().await;
5301 Mock::given(method("POST"))
5302 .and(path("/oauth2/device/code"))
5303 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5304 "device_code": "device-123",
5305 "user_code": "USER-456",
5306 "verification_uri": "https://example.com/device",
5307 "expires_in": 900
5308 })))
5309 .expect(1)
5310 .mount(&server)
5311 .await;
5312 let grant = tokio::task::block_in_place(|| {
5313 request_device_grant(
5314 &format!("{}/oauth2/device/code", server.uri()),
5315 "test-client",
5316 "openid",
5317 )
5318 })
5319 .expect("mock grant");
5320 assert_eq!(grant.device_code.as_deref(), Some("device-123"));
5321 assert_eq!(grant.user_code.as_deref(), Some("USER-456"));
5322 }
5323
5324 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5325 async fn request_device_grant_rejects_success_without_codes() {
5326 use wiremock::matchers::{method, path};
5327 use wiremock::{Mock, MockServer, ResponseTemplate};
5328 let server = MockServer::start().await;
5329 Mock::given(method("POST"))
5330 .and(path("/oauth2/device/code"))
5331 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
5332 .expect(1)
5333 .mount(&server)
5334 .await;
5335 let result = tokio::task::block_in_place(|| {
5336 request_device_grant(
5337 &format!("{}/oauth2/device/code", server.uri()),
5338 "test-client",
5339 "openid",
5340 )
5341 });
5342 let Err(error) = result else {
5343 panic!("a grant without codes must fail");
5344 };
5345 assert!(error.to_string().contains("without a device and user code"));
5346 }
5347
5348 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5349 async fn poll_device_grant_classifies_rfc8628_states() {
5350 use codewhale_config::device_code::DevicePollOutcome;
5351 use wiremock::matchers::{method, path};
5352 use wiremock::{Mock, MockServer, ResponseTemplate};
5353 async fn outcome(
5354 body: serde_json::Value,
5355 status: u16,
5356 ) -> Result<DevicePollOutcome<OAuthTokenMaterial>> {
5357 let server = MockServer::start().await;
5358 Mock::given(method("POST"))
5359 .and(path("/oauth2/token"))
5360 .respond_with(ResponseTemplate::new(status).set_body_json(body))
5361 .expect(1)
5362 .mount(&server)
5363 .await;
5364 tokio::task::block_in_place(|| {
5365 poll_device_grant(
5366 &format!("{}/oauth2/token", server.uri()),
5367 "test-client",
5368 "device-token",
5369 )
5370 })
5371 }
5372 assert!(matches!(
5373 outcome(serde_json::json!({ "error": "authorization_pending" }), 400).await,
5374 Ok(DevicePollOutcome::Pending)
5375 ));
5376 assert!(matches!(
5377 outcome(
5378 serde_json::json!({ "error": "slow_down", "interval": 12 }),
5379 400
5380 )
5381 .await,
5382 Ok(DevicePollOutcome::SlowDown {
5383 interval_seconds: Some(12)
5384 })
5385 ));
5386 for error in ["access_denied", "expired_token"] {
5387 let result = outcome(serde_json::json!({ "error": error }), 400).await;
5388 let Err(failure) = result else {
5389 panic!("{error} must stop polling");
5390 };
5391 assert!(failure.to_string().contains(error), "{failure}");
5392 }
5393 let result = outcome(
5394 serde_json::json!({ "access_token": "at", "expires_in": 3600 }),
5395 200,
5396 )
5397 .await;
5398 let Ok(DevicePollOutcome::Complete(material)) = result else {
5399 panic!("success must complete");
5400 };
5401 assert_eq!(material.access_token.as_deref(), Some("at"));
5402 }
5403
5404 #[test]
5405 fn oauth_challenges_require_a_terminal_and_avoid_redirected_streams() {
5406 assert_eq!(
5407 oauth_challenge_stream(true, false).unwrap(),
5408 OAuthChallengeStream::Stderr
5409 );
5410 assert_eq!(
5411 oauth_challenge_stream(true, true).unwrap(),
5412 OAuthChallengeStream::Stderr
5413 );
5414 assert_eq!(
5415 oauth_challenge_stream(false, true).unwrap(),
5416 OAuthChallengeStream::Stdout
5417 );
5418 let error = oauth_challenge_stream(false, false).unwrap_err();
5419 assert!(error.to_string().contains("requires a terminal"));
5420 assert!(!error.to_string().contains("token"));
5421 }
5422
5423 #[tokio::test]
5424 async fn device_login_without_a_device_flow_fails_before_network() {
5425 let result = device_code_login(OAuthProvider::Chatgpt).await;
5426 let Err(error) = result else {
5427 panic!("ChatGPT has no device flow");
5428 };
5429 assert!(
5430 error.to_string().contains("no device-code flow"),
5431 "{error:#}"
5432 );
5433 }
5434
5435 #[test]
5436 fn oauth_loopback_forms_bypass_ambient_proxies() {
5437 const PROBE_ENDPOINT: &str = "CODEWHALE_TEST_OAUTH_PROXY_ENDPOINT";
5438 if let Ok(endpoint) = std::env::var(PROBE_ENDPOINT) {
5439 let (status, _) = ReqwestOAuthFormClient
5440 .post_form(&endpoint, &[("refresh_token", "synthetic-refresh")])
5441 .expect("local OAuth form remains usable with an ambient proxy");
5442 assert_eq!(status, 200);
5443 return;
5444 }
5445 let runtime = tokio::runtime::Builder::new_multi_thread()
5446 .worker_threads(2)
5447 .enable_all()
5448 .build()
5449 .unwrap();
5450 runtime.block_on(async {
5451 use wiremock::matchers::{body_string_contains, method, path};
5452 use wiremock::{Mock, MockServer, ResponseTemplate};
5453 let issuer = MockServer::start().await;
5454 let proxy = MockServer::start().await;
5455 Mock::given(method("POST"))
5456 .and(path("/token"))
5457 .and(body_string_contains("refresh_token=synthetic-refresh"))
5458 .respond_with(ResponseTemplate::new(200))
5459 .expect(1)
5460 .mount(&issuer)
5461 .await;
5462 Mock::given(method("POST"))
5463 .respond_with(ResponseTemplate::new(502))
5464 .expect(0)
5465 .mount(&proxy)
5466 .await;
5467 // A fresh process gives reqwest an uncontaminated proxy cache and
5468 // keeps ambient proxy changes out of the shared test process.
5469 let mut child = std::process::Command::new(std::env::current_exe().unwrap());
5470 child
5471 .args([
5472 "--exact",
5473 "oauth::tests::oauth_loopback_forms_bypass_ambient_proxies",
5474 "--test-threads=1",
5475 ])
5476 .env(PROBE_ENDPOINT, format!("{}/token", issuer.uri()))
5477 .env_remove("NO_PROXY")
5478 .env_remove("no_proxy");
5479 for variable in [
5480 "HTTP_PROXY",
5481 "http_proxy",
5482 "HTTPS_PROXY",
5483 "https_proxy",
5484 "ALL_PROXY",
5485 "all_proxy",
5486 ] {
5487 child.env(variable, proxy.uri());
5488 }
5489 let output = tokio::task::spawn_blocking(move || child.output().unwrap())
5490 .await
5491 .unwrap();
5492 assert!(
5493 output.status.success(),
5494 "{}",
5495 String::from_utf8_lossy(&output.stderr)
5496 );
5497 assert_eq!(issuer.received_requests().await.unwrap().len(), 1);
5498 assert!(proxy.received_requests().await.unwrap().is_empty());
5499 });
5500 }
5501
5502 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5503 async fn oauth_transports_never_forward_forms_to_redirect_destinations() {
5504 use wiremock::matchers::{method, path};
5505 use wiremock::{Mock, MockServer, ResponseTemplate};
5506
5507 let issuer = MockServer::start().await;
5508 let destination = MockServer::start().await;
5509 Mock::given(method("POST"))
5510 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5511 "access_token": "synthetic-access",
5512 })))
5513 .expect(0)
5514 .mount(&destination)
5515 .await;
5516 for status in [301, 302, 303, 307, 308] {
5517 let endpoint = format!("{}/redirect-{status}", issuer.uri());
5518 Mock::given(path(format!("/redirect-{status}")))
5519 .respond_with(
5520 ResponseTemplate::new(status)
5521 .insert_header("Location", format!("{}/token", destination.uri()))
5522 .set_body_json(serde_json::json!({})),
5523 )
5524 .expect(3)
5525 .mount(&issuer)
5526 .await;
5527 tokio::task::block_in_place(|| {
5528 assert!(request_device_grant(&endpoint, "synthetic-client", "scope").is_err());
5529 assert!(
5530 poll_device_grant(&endpoint, "synthetic-client", "synthetic-device").is_err()
5531 );
5532 let (actual_status, _) = ReqwestOAuthFormClient
5533 .post_form(&endpoint, &[("refresh_token", "synthetic-refresh")])
5534 .unwrap();
5535 assert_eq!(actual_status, status);
5536 });
5537 }
5538 // An explicitly selected issuer remains usable without a redirect.
5539 Mock::given(path("/token"))
5540 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5541 "device_code": "synthetic-device",
5542 "user_code": "synthetic-user",
5543 "access_token": "synthetic-access",
5544 })))
5545 .expect(3)
5546 .mount(&issuer)
5547 .await;
5548 let endpoint = format!("{}/token", issuer.uri());
5549 tokio::task::block_in_place(|| {
5550 assert!(request_device_grant(&endpoint, "synthetic-client", "scope").is_ok());
5551 assert!(poll_device_grant(&endpoint, "synthetic-client", "synthetic-device").is_ok());
5552 assert_eq!(
5553 ReqwestOAuthFormClient
5554 .post_form(&endpoint, &[("refresh_token", "synthetic-refresh")])
5555 .unwrap()
5556 .0,
5557 200
5558 );
5559 });
5560 assert!(destination.received_requests().await.unwrap().is_empty());
5561 }
5562
5563 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5564 async fn discovery_honors_advertised_endpoints() {
5565 use wiremock::matchers::{method, path};
5566 use wiremock::{Mock, MockServer, ResponseTemplate};
5567 let server = MockServer::start().await;
5568 Mock::given(method("GET"))
5569 .and(path("/.well-known/openid-configuration"))
5570 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5571 "issuer": server.uri(),
5572 "device_authorization_endpoint": format!("{}/custom/device", server.uri()),
5573 "token_endpoint": format!("{}/custom/token", server.uri()),
5574 })))
5575 .expect(1)
5576 .mount(&server)
5577 .await;
5578 let endpoints = tokio::task::block_in_place(|| {
5579 resolve_oauth_endpoints(&XAI_OAUTH_PARAMS, &server.uri())
5580 });
5581 assert_eq!(
5582 endpoints.device_authorization_endpoint.as_deref(),
5583 Some(format!("{}/custom/device", server.uri()).as_str())
5584 );
5585 assert_eq!(
5586 endpoints.token_endpoint,
5587 format!("{}/custom/token", server.uri())
5588 );
5589 }
5590
5591 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5592 async fn discovery_issuer_mismatch_falls_back_to_documented_paths() {
5593 use wiremock::matchers::{method, path};
5594 use wiremock::{Mock, MockServer, ResponseTemplate};
5595 let server = MockServer::start().await;
5596 Mock::given(method("GET"))
5597 .and(path("/.well-known/openid-configuration"))
5598 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5599 "issuer": "https://someone-else.example",
5600 "device_authorization_endpoint": "https://someone-else.example/device",
5601 "token_endpoint": "https://someone-else.example/token",
5602 })))
5603 .expect(1)
5604 .mount(&server)
5605 .await;
5606 let endpoints = tokio::task::block_in_place(|| {
5607 resolve_oauth_endpoints(&XAI_OAUTH_PARAMS, &server.uri())
5608 });
5609 assert_eq!(
5610 endpoints.device_authorization_endpoint.as_deref(),
5611 Some(format!("{}/oauth2/device/code", server.uri()).as_str())
5612 );
5613 assert_eq!(
5614 endpoints.token_endpoint,
5615 format!("{}/oauth2/token", server.uri())
5616 );
5617 }
5618
5619 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5620 async fn device_login_aborts_on_untrusted_verification_uri() {
5621 use wiremock::matchers::{method, path};
5622 use wiremock::{Mock, MockServer, ResponseTemplate};
5623 let server = MockServer::start().await;
5624 Mock::given(method("GET"))
5625 .and(path("/.well-known/openid-configuration"))
5626 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5627 "issuer": server.uri(),
5628 "device_authorization_endpoint": format!("{}/oauth2/device-advertised", server.uri()),
5629 "token_endpoint": format!("{}/oauth2/token", server.uri()),
5630 })))
5631 .mount(&server)
5632 .await;
5633 Mock::given(method("POST"))
5634 .and(path("/oauth2/device-advertised"))
5635 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5636 "device_code": "device-token",
5637 "user_code": "CW-TEST",
5638 "verification_uri": "https://auth.x.ai/device",
5639 "verification_uri_complete": "vscode://attacker/run?code=CW-TEST",
5640 "expires_in": 60,
5641 "interval": 1
5642 })))
5643 .expect(1)
5644 .mount(&server)
5645 .await;
5646 // No token-endpoint mock: the flow must fail before it ever polls.
5647 let inputs = ResolvedOAuthInputs {
5648 issuer: server.uri(),
5649 client_id: "test-client".to_string(),
5650 scopes: "openid".to_string(),
5651 open_browser: false,
5652 };
5653 let result = tokio::task::block_in_place(|| {
5654 device_code_login_with(OAuthProvider::Xai, &inputs, &mut std::io::sink())
5655 });
5656 let Err(error) = result else {
5657 panic!("a non-web verification URI must abort login");
5658 };
5659 assert!(
5660 format!("{error:#}").contains("untrusted verification URI"),
5661 "{error:#}"
5662 );
5663 }
5664
5665 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5666 async fn device_login_refuses_terminal_controls_before_display_or_polling() {
5667 use wiremock::matchers::{method, path};
5668 use wiremock::{Mock, MockServer, ResponseTemplate};
5669 let server = MockServer::start().await;
5670 Mock::given(method("GET"))
5671 .and(path("/.well-known/openid-configuration"))
5672 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5673 "issuer": server.uri(),
5674 "device_authorization_endpoint": format!("{}/device", server.uri()),
5675 "token_endpoint": format!("{}/token", server.uri())
5676 })))
5677 .expect(1)
5678 .mount(&server)
5679 .await;
5680 Mock::given(method("POST"))
5681 .and(path("/device"))
5682 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5683 "device_code": "fixture-private-device-code",
5684 "user_code": "CW-\u{1b}]52;clipboard-payload",
5685 "verification_uri": format!("{}/verify", server.uri()),
5686 "expires_in": 60,
5687 "interval": 1
5688 })))
5689 .expect(1)
5690 .mount(&server)
5691 .await;
5692 let inputs = ResolvedOAuthInputs {
5693 issuer: server.uri(),
5694 client_id: "test-client".to_string(),
5695 scopes: "openid".to_string(),
5696 open_browser: false,
5697 };
5698 let mut challenge = Vec::new();
5699 let error = tokio::task::block_in_place(|| {
5700 device_code_login_with(OAuthProvider::Xai, &inputs, &mut challenge)
5701 })
5702 .err()
5703 .expect("terminal controls must be refused");
5704 assert!(error.to_string().contains("invalid user-code display data"));
5705 assert!(challenge.is_empty());
5706 assert!(!error.to_string().contains("clipboard-payload"));
5707 assert_eq!(server.received_requests().await.unwrap().len(), 2);
5708 }
5709
5710 /// Discovery + device grant run on the blocking worker: this fails with
5711 /// the grant refusal, never with a runtime-drop panic.
5712 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5713 async fn device_login_runs_blocking_http_off_the_executor() {
5714 use wiremock::matchers::{method, path};
5715 use wiremock::{Mock, MockServer, ResponseTemplate};
5716 let _lock = crate::test_support::lock_test_env();
5717 let server = MockServer::start().await;
5718 Mock::given(method("GET"))
5719 .and(path("/.well-known/openid-configuration"))
5720 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5721 "issuer": server.uri(),
5722 "device_authorization_endpoint": format!("{}/oauth2/device-advertised", server.uri()),
5723 "token_endpoint": format!("{}/oauth2/token-advertised", server.uri())
5724 })))
5725 .expect(1)
5726 .mount(&server)
5727 .await;
5728 Mock::given(method("POST"))
5729 .and(path("/oauth2/device-advertised"))
5730 .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
5731 "error": "invalid_scope",
5732 "error_description": "mock refusal before browser or polling"
5733 })))
5734 .expect(1)
5735 .mount(&server)
5736 .await;
5737 let _issuer =
5738 crate::test_support::EnvVarGuard::set("GROK_OIDC_ISSUER", server.uri().as_str());
5739 let _no_browser =
5740 crate::test_support::EnvVarGuard::set("CODEWHALE_XAI_OAUTH_NO_BROWSER", "1");
5741
5742 let result = device_code_login_on_worker(
5743 OAuthProvider::Xai,
5744 XAI_OAUTH_PARAMS.resolve_inputs(),
5745 Box::new(std::io::sink()),
5746 )
5747 .await;
5748 let Err(error) = result else {
5749 panic!("mock device request must fail without a runtime-drop panic");
5750 };
5751 let message = format!("{error:#}");
5752 assert!(message.contains("invalid_scope"), "{message}");
5753 assert!(message.contains("HTTP 400"), "{message}");
5754 }
5755
5756 /// Full orchestration against mocks: discovery, grant, one poll, done.
5757 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5758 async fn device_login_exchanges_and_returns_token_material() {
5759 use wiremock::matchers::{method, path};
5760 use wiremock::{Mock, MockServer, ResponseTemplate};
5761 let server = MockServer::start().await;
5762 Mock::given(method("GET"))
5763 .and(path("/.well-known/openid-configuration"))
5764 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5765 "issuer": server.uri(),
5766 "device_authorization_endpoint": format!("{}/oauth2/device-advertised", server.uri()),
5767 "token_endpoint": format!("{}/oauth2/token-advertised", server.uri())
5768 })))
5769 .expect(1)
5770 .mount(&server)
5771 .await;
5772 Mock::given(method("POST"))
5773 .and(path("/oauth2/device-advertised"))
5774 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5775 "device_code": "device-token",
5776 "user_code": "CW-TEST",
5777 "verification_uri": format!("{}/verify", server.uri()),
5778 "expires_in": 60,
5779 "interval": 1
5780 })))
5781 .expect(1)
5782 .mount(&server)
5783 .await;
5784 Mock::given(method("POST"))
5785 .and(path("/oauth2/token-advertised"))
5786 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5787 "access_token": "unified-access",
5788 "refresh_token": "unified-refresh",
5789 "expires_in": 3600
5790 })))
5791 .expect(1)
5792 .mount(&server)
5793 .await;
5794 let inputs = ResolvedOAuthInputs {
5795 issuer: server.uri(),
5796 client_id: "test-client".to_string(),
5797 scopes: "openid".to_string(),
5798 open_browser: false,
5799 };
5800 let mut challenge = Vec::new();
5801 let pending = tokio::task::block_in_place(|| {
5802 device_code_login_with(OAuthProvider::Xai, &inputs, &mut challenge)
5803 })
5804 .expect("mock login exchanges");
5805 let challenge = String::from_utf8(challenge).unwrap();
5806 assert!(challenge.contains(&format!("{}/verify", server.uri())));
5807 assert!(challenge.contains("CW-TEST"));
5808 assert!(!challenge.contains("unified-access"));
5809 assert!(!challenge.contains("unified-refresh"));
5810 assert_eq!(pending.issuer, server.uri());
5811 assert_eq!(
5812 pending.token.access_token.as_deref(),
5813 Some("unified-access")
5814 );
5815 assert_eq!(
5816 pending.token.refresh_token.as_deref(),
5817 Some("unified-refresh")
5818 );
5819 }
5820
5821 /// The shared poll loop walks pending and slow_down to completion.
5822 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5823 async fn device_login_polls_through_pending_and_slow_down() {
5824 use codewhale_config::device_code::DeviceCodePoll;
5825 use wiremock::matchers::{method, path};
5826 use wiremock::{Mock, MockServer, ResponseTemplate};
5827 let server = MockServer::start().await;
5828 // wiremock matches mocks in mount order, so mount the one-shot
5829 // transient-error responses before the terminal success response:
5830 // poll 1 -> authorization_pending, poll 2 -> slow_down, poll 3 -> ok.
5831 for (body, status) in [
5832 (serde_json::json!({ "error": "authorization_pending" }), 400),
5833 (serde_json::json!({ "error": "slow_down" }), 400),
5834 ] {
5835 Mock::given(method("POST"))
5836 .and(path("/oauth2/token"))
5837 .respond_with(ResponseTemplate::new(status).set_body_json(body))
5838 .up_to_n_times(1)
5839 .expect(1)
5840 .mount(&server)
5841 .await;
5842 }
5843 Mock::given(method("POST"))
5844 .and(path("/oauth2/token"))
5845 .respond_with(ResponseTemplate::new(200).set_body_json(
5846 serde_json::json!({ "access_token": "loop-access", "expires_in": 3600 }),
5847 ))
5848 .expect(1)
5849 .mount(&server)
5850 .await;
5851 let endpoint = format!("{}/oauth2/token", server.uri());
5852 let material = tokio::task::block_in_place(|| {
5853 DeviceCodePoll::new(
5854 std::time::Duration::from_secs(60),
5855 "mock poll must complete",
5856 )
5857 .run(
5858 |_| {},
5859 || poll_device_grant(&endpoint, "test-client", "device-token"),
5860 )
5861 })
5862 .expect("poll loop completes");
5863 assert!(matches!(
5864 material.access_token.as_deref(),
5865 Some("loop-access")
5866 ));
5867 }
5868
5869 /// A denied grant stops the full login with the server's reason.
5870 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5871 async fn device_login_surfaces_user_denial() {
5872 use wiremock::matchers::{method, path};
5873 use wiremock::{Mock, MockServer, ResponseTemplate};
5874 let server = MockServer::start().await;
5875 Mock::given(method("GET"))
5876 .and(path("/.well-known/openid-configuration"))
5877 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5878 "issuer": server.uri(),
5879 "device_authorization_endpoint": format!("{}/oauth2/device-advertised", server.uri()),
5880 "token_endpoint": format!("{}/oauth2/token-advertised", server.uri())
5881 })))
5882 .mount(&server)
5883 .await;
5884 Mock::given(method("POST"))
5885 .and(path("/oauth2/device-advertised"))
5886 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5887 "device_code": "device-token",
5888 "user_code": "CW-TEST",
5889 "verification_uri": format!("{}/verify", server.uri()),
5890 "expires_in": 60,
5891 "interval": 1
5892 })))
5893 .mount(&server)
5894 .await;
5895 Mock::given(method("POST"))
5896 .and(path("/oauth2/token-advertised"))
5897 .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
5898 "error": "access_denied",
5899 "error_description": "The user denied the authorization request"
5900 })))
5901 .expect(1)
5902 .mount(&server)
5903 .await;
5904 let inputs = ResolvedOAuthInputs {
5905 issuer: server.uri(),
5906 client_id: "test-client".to_string(),
5907 scopes: "openid".to_string(),
5908 open_browser: false,
5909 };
5910 let result = tokio::task::block_in_place(|| {
5911 device_code_login_with(OAuthProvider::Xai, &inputs, &mut std::io::sink())
5912 });
5913 let Err(error) = result else {
5914 panic!("user denial must stop the login");
5915 };
5916 let message = format!("{error:#}");
5917 assert!(message.contains("access_denied"), "{message}");
5918 assert!(message.contains("HTTP 400"), "{message}");
5919 }
5920
5921 /// Non-JSON answers disclose neither response metadata nor the body.
5922 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5923 async fn device_transport_reports_non_json_without_echoing_body() {
5924 use wiremock::matchers::{method, path};
5925 use wiremock::{Mock, MockServer, ResponseTemplate};
5926 let server = MockServer::start().await;
5927 Mock::given(method("POST"))
5928 .and(path("/oauth2/device-code"))
5929 .respond_with(
5930 ResponseTemplate::new(200)
5931 .set_body_bytes("<html>sentinel-body-bytes</html>".as_bytes())
5932 .insert_header(
5933 "content-type",
5934 "text/html; credential=sentinel-header-bytes",
5935 ),
5936 )
5937 .expect(1)
5938 .mount(&server)
5939 .await;
5940 Mock::given(method("POST"))
5941 .and(path("/oauth2/token"))
5942 .respond_with(
5943 ResponseTemplate::new(200)
5944 .set_body_bytes("<html>sentinel-body-bytes</html>".as_bytes())
5945 .insert_header(
5946 "content-type",
5947 "text/html; credential=sentinel-header-bytes",
5948 ),
5949 )
5950 .expect(1)
5951 .mount(&server)
5952 .await;
5953 let grant = tokio::task::block_in_place(|| {
5954 request_device_grant(
5955 &format!("{}/oauth2/device-code", server.uri()),
5956 "test-client",
5957 "openid",
5958 )
5959 });
5960 let Err(grant_error) = grant else {
5961 panic!("non-JSON grant must fail");
5962 };
5963 let poll = tokio::task::block_in_place(|| {
5964 poll_device_grant(
5965 &format!("{}/oauth2/token", server.uri()),
5966 "test-client",
5967 "device-token",
5968 )
5969 });
5970 let Err(poll_error) = poll else {
5971 panic!("non-JSON poll must fail");
5972 };
5973 for message in [format!("{grant_error:#}"), format!("{poll_error:#}")] {
5974 assert!(message.contains("HTTP 200"), "{message}");
5975 assert!(message.contains("expected JSON"), "{message}");
5976 assert!(!message.contains("sentinel-header-bytes"), "{message}");
5977 assert!(!message.contains("sentinel-body-bytes"), "{message}");
5978 }
5979 }
5980
5981 /// The wire format is a contract: form-encoded posts carrying the exact
5982 /// client, scope, and grant-type parameters the issuers expect.
5983 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5984 async fn device_transport_posts_exact_oauth_form_parameters() {
5985 use wiremock::matchers::{body_string_contains, header, method, path};
5986 use wiremock::{Mock, MockServer, ResponseTemplate};
5987 let server = MockServer::start().await;
5988 Mock::given(method("GET"))
5989 .and(path("/.well-known/openid-configuration"))
5990 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5991 "issuer": server.uri(),
5992 "device_authorization_endpoint": format!("{}/oauth2/device-advertised", server.uri()),
5993 "token_endpoint": format!("{}/oauth2/token-advertised", server.uri())
5994 })))
5995 .mount(&server)
5996 .await;
5997 Mock::given(method("POST"))
5998 .and(path("/oauth2/device-advertised"))
5999 .and(header("content-type", "application/x-www-form-urlencoded"))
6000 .and(body_string_contains("client_id=test-client"))
6001 .and(body_string_contains("scope=openid"))
6002 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
6003 "device_code": "device-token",
6004 "user_code": "CW-TEST",
6005 "verification_uri": format!("{}/verify", server.uri()),
6006 "expires_in": 60,
6007 "interval": 1
6008 })))
6009 .expect(1)
6010 .mount(&server)
6011 .await;
6012 Mock::given(method("POST"))
6013 .and(path("/oauth2/token-advertised"))
6014 .and(header("content-type", "application/x-www-form-urlencoded"))
6015 .and(body_string_contains(
6016 "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code",
6017 ))
6018 .and(body_string_contains("client_id=test-client"))
6019 .and(body_string_contains("device_code=device-token"))
6020 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
6021 "access_token": "form-access",
6022 "expires_in": 3600
6023 })))
6024 .expect(1)
6025 .mount(&server)
6026 .await;
6027 let inputs = ResolvedOAuthInputs {
6028 issuer: server.uri(),
6029 client_id: "test-client".to_string(),
6030 scopes: "openid".to_string(),
6031 open_browser: false,
6032 };
6033 let pending = tokio::task::block_in_place(|| {
6034 device_code_login_with(OAuthProvider::Xai, &inputs, &mut std::io::sink())
6035 })
6036 .expect("mock login exchanges");
6037 assert_eq!(pending.token.access_token.as_deref(), Some("form-access"));
6038 }
6039
6040 #[test]
6041 fn malformed_codex_credential_errors_never_echo_file_contents() {
6042 let _lock = crate::test_support::lock_test_env();
6043 let home = tempfile::tempdir().expect("temp Codex home");
6044 let path = home.path().canonicalize().unwrap().join("auth.json");
6045 let sentinel = "must-not-appear-in-diagnostics";
6046 std::fs::write(
6047 &path,
6048 format!(r#"{{"tokens":{{"access_token":{{"secret":"{sentinel}"}}}}}}"#),
6049 )
6050 .unwrap();
6051
6052 let error = load_credentials(&grant(&path)).expect_err("malformed schema");
6053 let message = format!("{error:#}");
6054 assert!(message.contains("not valid credential JSON"), "{message}");
6055 assert!(!message.contains(sentinel), "{message}");
6056 }
6057
6058 struct MockFormClient {
6059 responses: Mutex<Vec<(u16, String)>>,
6060 posts: Mutex<Vec<MockPost>>,
6061 }
6062
6063 impl MockFormClient {
6064 fn new(responses: Vec<(u16, String)>) -> Self {
6065 Self {
6066 responses: Mutex::new(responses),
6067 posts: Mutex::new(Vec::new()),
6068 }
6069 }
6070 }
6071
6072 impl OAuthFormClient for MockFormClient {
6073 fn post_form(&self, url: &str, form: &[(&str, &str)]) -> Result<(u16, String)> {
6074 self.posts.lock().expect("posts").push((
6075 url.to_string(),
6076 form.iter()
6077 .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
6078 .collect(),
6079 ));
6080 let mut responses = self.responses.lock().expect("responses");
6081 anyhow::ensure!(
6082 !responses.is_empty(),
6083 "mock issuer has no remaining responses"
6084 );
6085 Ok(responses.remove(0))
6086 }
6087 }
6088
6089 fn jwt_with_account(account: &str) -> String {
6090 let payload = URL_SAFE_NO_PAD.encode(format!(
6091 r#"{{"https://api.openai.com/auth":{{"chatgpt_account_id":"{account}"}}}}"#
6092 ));
6093 format!("header.{payload}.sig")
6094 }
6095
6096 fn chatgpt() -> &'static OAuthProviderParams<'static> {
6097 oauth_provider_params(OAuthProvider::Chatgpt)
6098 }
6099
6100 #[test]
6101 fn pkce_verifier_and_challenge_are_s256() {
6102 let pkce = generate_pkce();
6103 assert!(pkce.verifier.len() >= 43);
6104 assert_eq!(
6105 pkce.challenge,
6106 URL_SAFE_NO_PAD.encode(Sha256::digest(pkce.verifier.as_bytes()))
6107 );
6108 let other = generate_pkce();
6109 assert_ne!(pkce.verifier, other.verifier);
6110 assert_ne!(generate_state(), generate_state());
6111 }
6112
6113 #[test]
6114 fn malformed_issuer_fails_loudly_not_to_production() {
6115 let pkce = PkceChallenge {
6116 verifier: "verifier".into(),
6117 challenge: "challenge".into(),
6118 };
6119 let err = build_authorize_url(
6120 chatgpt(),
6121 "not a url \\ ",
6122 "client",
6123 "openid",
6124 "http://localhost:1455/auth/callback",
6125 "state-1",
6126 &pkce,
6127 )
6128 .expect_err("malformed issuer must not produce an authorize URL");
6129 assert!(
6130 format!("{err:#}").contains("CODEWHALE_CHATGPT_OAUTH_ISSUER"),
6131 "{err:#}"
6132 );
6133 }
6134
6135 #[test]
6136 fn authorize_url_uses_documented_chatgpt_parameters_and_pkce() {
6137 let _lock = crate::test_support::lock_test_env();
6138 let _prompt = crate::test_support::EnvVarGuard::remove("CODEWHALE_CHATGPT_OAUTH_NO_PROMPT");
6139 let pkce = PkceChallenge {
6140 verifier: "verifier".into(),
6141 challenge: "challenge".into(),
6142 };
6143 let url = build_authorize_url(
6144 chatgpt(),
6145 CHATGPT_OAUTH_ISSUER,
6146 CHATGPT_OAUTH_CLIENT_ID,
6147 CHATGPT_OAUTH_SCOPE,
6148 "http://localhost:1455/auth/callback",
6149 "state-1",
6150 &pkce,
6151 )
6152 .expect("static issuer parses");
6153 assert!(url.starts_with("https://auth.openai.com/api/accounts/authorize?"));
6154 assert!(url.contains("code_challenge=challenge"));
6155 assert!(url.contains("code_challenge_method=S256"));
6156 assert!(!url.contains("originator="), "{url}");
6157 assert!(!url.contains("codex_cli_rs"));
6158 assert!(url.contains("redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback"));
6159 assert!(url.contains("resource=https%3A%2F%2Fapi.openai.com%2Fv1"));
6160 // Account choice: the issuer must re-prompt rather than reuse the
6161 // browser's current ChatGPT session.
6162 let query: BTreeMap<String, String> = reqwest::Url::parse(&url)
6163 .expect("authorize URL parses")
6164 .query_pairs()
6165 .into_owned()
6166 .collect();
6167 assert_eq!(query.get("prompt").map(String::as_str), Some("login"));
6168 assert_eq!(url.matches("prompt=").count(), 1, "{url}");
6169
6170 // Opt-out, should the issuer ever refuse the parameter.
6171 let _opt_out =
6172 crate::test_support::EnvVarGuard::set("CODEWHALE_CHATGPT_OAUTH_NO_PROMPT", "1");
6173 let url = build_authorize_url(
6174 chatgpt(),
6175 CHATGPT_OAUTH_ISSUER,
6176 CHATGPT_OAUTH_CLIENT_ID,
6177 CHATGPT_OAUTH_SCOPE,
6178 "http://localhost:1455/auth/callback",
6179 "state-1",
6180 &pkce,
6181 )
6182 .expect("static issuer parses");
6183 assert!(!url.contains("prompt="), "{url}");
6184 assert!(
6185 url.contains("resource=https%3A%2F%2Fapi.openai.com%2Fv1"),
6186 "{url}"
6187 );
6188 }
6189
6190 fn id_token(claims: &serde_json::Value) -> String {
6191 format!(
6192 "header.{}.sig",
6193 URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).expect("claims serialize"))
6194 )
6195 }
6196
6197 #[test]
6198 fn account_label_reads_email_and_plan_claims() {
6199 let chatgpt = id_token(&serde_json::json!({
6200 "email": "a@example.com",
6201 "https://api.openai.com/auth": {"chatgpt_plan_type": "plus", "chatgpt_account_id": "acct-1"},
6202 }));
6203 assert_eq!(
6204 account_label_from_id_token(&chatgpt).as_deref(),
6205 Some("a@example.com (plus)")
6206 );
6207 // Profile-namespaced email is the fallback the ChatGPT issuer uses.
6208 let profile = id_token(&serde_json::json!({
6209 "https://api.openai.com/profile": {"email": "b@example.com"},
6210 }));
6211 assert_eq!(
6212 account_label_from_id_token(&profile).as_deref(),
6213 Some("b@example.com")
6214 );
6215 // A workspace plan names its account-id prefix: one email can hold
6216 // several workspaces, and email + plan alone would read the same.
6217 let team = id_token(&serde_json::json!({
6218 "email": "a@corp.com",
6219 "https://api.openai.com/auth": {"chatgpt_plan_type": "team", "chatgpt_account_id": "1a2b3c4d-5e6f-7081-92a3-b4c5d6e7f809"},
6220 }));
6221 assert_eq!(
6222 account_label_from_id_token(&team).as_deref(),
6223 Some("a@corp.com (team, workspace 1a2b3c4d)")
6224 );
6225 // xAI: plain OIDC email, no plan claim.
6226 let xai = id_token(&serde_json::json!({"email": "grok@example.com", "sub": "u1"}));
6227 assert_eq!(
6228 account_label_from_id_token(&xai).as_deref(),
6229 Some("grok@example.com")
6230 );
6231 }
6232
6233 #[test]
6234 fn account_label_rejects_malformed_tokens_and_missing_claims() {
6235 for token in [
6236 "",
6237 "not-a-jwt",
6238 "header.%%%.sig",
6239 &format!("header.{}.sig", URL_SAFE_NO_PAD.encode("not json")),
6240 &id_token(&serde_json::json!({"sub": "u1"})),
6241 &id_token(&serde_json::json!({"email": " "})),
6242 &id_token(&serde_json::json!({"email": 42})),
6243 // A plan alone does not identify an account.
6244 &id_token(&serde_json::json!({
6245 "https://api.openai.com/auth": {"chatgpt_plan_type": "pro"},
6246 })),
6247 ] {
6248 assert_eq!(account_label_from_id_token(token), None, "{token}");
6249 }
6250 }
6251
6252 #[test]
6253 fn account_label_strips_control_characters_and_bounds_length() {
6254 let hostile = id_token(&serde_json::json!({
6255 "email": "\u{1b}[31mevil@example.com\u{7}",
6256 "https://api.openai.com/auth": {"chatgpt_plan_type": "x".repeat(500)},
6257 }));
6258 let label = account_label_from_id_token(&hostile).expect("label");
6259 assert!(!label.chars().any(char::is_control), "{label:?}");
6260 assert!(label.starts_with("[31mevil@example.com ("), "{label}");
6261 assert!(label.len() <= ACCOUNT_EMAIL_MAX_CHARS + ACCOUNT_PLAN_MAX_CHARS + 3);
6262 }
6263
6264 #[test]
6265 fn usage_limit_guidance_names_account_and_switch_command() {
6266 let chatgpt = usage_limit_guidance(OAuthProvider::Chatgpt, Some("a@example.com (plus)"));
6267 assert!(
6268 chatgpt.contains("a@example.com (plus)"),
6269 "usage guidance must name the selected account"
6270 );
6271 assert!(
6272 chatgpt.contains("`/auth chatgpt`"),
6273 "usage guidance must name the in-session command"
6274 );
6275 assert!(
6276 chatgpt.contains("`codewhale auth chatgpt`"),
6277 "usage guidance must name the shell command"
6278 );
6279 assert!(
6280 chatgpt.contains("restart open Codewhale sessions"),
6281 "{chatgpt}"
6282 );
6283 let xai = usage_limit_guidance(OAuthProvider::Xai, None);
6284 assert!(xai.contains("`codewhale auth xai-device`"), "{xai}");
6285 assert!(xai.contains("`/auth xai-device`"), "{xai}");
6286 assert!(!xai.contains("None"), "{xai}");
6287 }
6288
6289 #[test]
6290 fn relogin_with_another_account_replaces_the_owned_entry() {
6291 let _lock = crate::test_support::lock_test_env();
6292 let home = tempfile::tempdir().expect("temp home");
6293 let root = home.path().canonicalize().expect("canonical home");
6294 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
6295 let config_path = root.join("config.toml");
6296 std::fs::write(&config_path, "").expect("empty config");
6297 let token_a = id_token(&serde_json::json!({
6298 "email": "a@example.com",
6299 "https://api.openai.com/auth": {"chatgpt_plan_type": "plus", "chatgpt_account_id": "acct-a"},
6300 }));
6301 let first = activate_login(
6302 pending_login_with_id_token_for_test(
6303 OAuthProvider::Chatgpt,
6304 "access-a",
6305 "refresh-a",
6306 Some(&token_a),
6307 ),
6308 Some(&config_path),
6309 None,
6310 )
6311 .expect("first login");
6312 assert_eq!(first.account_label.as_deref(), Some("a@example.com (plus)"));
6313 assert_eq!(first.replaced, None);
6314 assert_eq!(
6315 first.summary(codewhale_localization::Locale::En),
6316 "Signed in to ChatGPT as a@example.com (plus)."
6317 );
6318
6319 // Account B has its own offline grant and no account claim in the
6320 // display token: nothing from account A may survive into B's credential.
6321 let token_b = id_token(&serde_json::json!({"email": "b@example.com"}));
6322 let pending_b = pending_login_with_id_token_for_test(
6323 OAuthProvider::Chatgpt,
6324 "access-b",
6325 "refresh-b",
6326 Some(&token_b),
6327 );
6328 let second = activate_login(pending_b, Some(&config_path), None).expect("second login");
6329 assert_eq!(second.account_label.as_deref(), Some("b@example.com"));
6330 assert_eq!(
6331 second.replaced,
6332 Some(Some("a@example.com (plus)".to_string()))
6333 );
6334 let summary = second.summary(codewhale_localization::Locale::En);
6335 assert_eq!(
6336 summary,
6337 "Signed in to ChatGPT as b@example.com.\nReplaced the previous Codewhale ChatGPT sign-in (a@example.com (plus))."
6338 );
6339 assert!(!summary.contains("access-"), "{summary}");
6340 // The TUI transcript renders the same facts in the UI locale.
6341 let localized = second.summary(codewhale_localization::Locale::Ja);
6342 assert_ne!(localized, summary);
6343 assert!(localized.contains("b@example.com"), "{localized}");
6344 assert!(localized.contains("a@example.com (plus)"), "{localized}");
6345
6346 let persisted = std::fs::read_to_string(&second.auth_path).expect("generation");
6347 assert!(!persisted.contains("refresh-a"), "{persisted}");
6348 assert!(!persisted.contains("acct-a"), "{persisted}");
6349 assert!(!persisted.contains("access-a"), "{persisted}");
6350 let generation = second
6351 .auth_path
6352 .file_name()
6353 .and_then(|name| name.to_str())
6354 .expect("generation name");
6355 assert_eq!(
6356 owned_account_label_for_generation(OAuthProvider::Chatgpt, generation)
6357 .expect("usable sign-in")
6358 .as_deref(),
6359 Some("b@example.com")
6360 );
6361 let mut config = Config::default();
6362 config
6363 .mark_codewhale_owned_chatgpt_oauth(generation.to_string())
6364 .expect("admitted OAuth fixture");
6365 assert_eq!(
6366 usable_sign_in(OAuthProvider::Chatgpt, &config),
6367 Some(UsableSignIn {
6368 account_label: Some("b@example.com".to_string())
6369 })
6370 );
6371 // An invalid generation name never resolves to a path.
6372 assert!(
6373 owned_account_label_for_generation(OAuthProvider::Chatgpt, "../auth.json").is_err()
6374 );
6375 }
6376
6377 /// A login replaces the whole sign-in, not just its own scope: an older
6378 /// account's entry under a differently spelled issuer must neither
6379 /// outrank the new login nor keep its refresh token on disk.
6380 #[test]
6381 fn relogin_drops_other_scopes_and_names_the_account_it_replaced() {
6382 let _lock = crate::test_support::lock_test_env();
6383 let home = tempfile::tempdir().expect("temp home");
6384 let root = home.path().canonicalize().expect("canonical home");
6385 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
6386 let config_path = root.join("config.toml");
6387 std::fs::write(&config_path, "").expect("empty config");
6388 let token_a = id_token(&serde_json::json!({"email": "a@example.com"}));
6389 let mut pending_a = pending_login_with_id_token_for_test(
6390 OAuthProvider::Xai,
6391 "access-a",
6392 "refresh-a",
6393 Some(&token_a),
6394 );
6395 // '/' sorts before ':', so this scope comes first in the file.
6396 pending_a.issuer = format!("{XAI_OIDC_ISSUER}/");
6397 activate_login(pending_a, Some(&config_path), None).expect("login A");
6398
6399 let token_b = id_token(&serde_json::json!({"email": "b@example.com"}));
6400 let second = activate_login(
6401 pending_login_with_id_token_for_test(
6402 OAuthProvider::Xai,
6403 "access-b",
6404 "refresh-b",
6405 Some(&token_b),
6406 ),
6407 Some(&config_path),
6408 None,
6409 )
6410 .expect("login B");
6411 assert_eq!(second.replaced, Some(Some("a@example.com".to_string())));
6412 let persisted = std::fs::read_to_string(&second.auth_path).expect("generation");
6413 assert!(!persisted.contains("refresh-a"), "{persisted}");
6414 assert!(!persisted.contains("access-a"), "{persisted}");
6415 let generation = second
6416 .auth_path
6417 .file_name()
6418 .and_then(|name| name.to_str())
6419 .expect("generation name");
6420 let mut config = Config::default();
6421 config
6422 .mark_codewhale_owned_xai_oauth(generation.to_string())
6423 .expect("admitted OAuth fixture");
6424 assert_eq!(
6425 usable_sign_in(OAuthProvider::Xai, &config)
6426 .and_then(|sign_in| sign_in.account_label)
6427 .as_deref(),
6428 Some("b@example.com")
6429 );
6430 }
6431
6432 /// #6715 review: a login under a non-default client id (for example
6433 /// `XAI_OIDC_CLIENT_ID`) must become the account requests use.
6434 /// `select_entry` prefers the built-in client id, so an old account's
6435 /// entry under that id, carried into the new generation, would keep
6436 /// winning both the runtime credential and the displayed account.
6437 #[test]
6438 fn relogin_under_another_client_id_switches_runtime_credentials_and_label() {
6439 let _lock = crate::test_support::lock_test_env();
6440 let home = tempfile::tempdir().expect("temp home");
6441 let root = home.path().canonicalize().expect("canonical home");
6442 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
6443 let config_path = root.join("config.toml");
6444 std::fs::write(&config_path, "").expect("empty config");
6445 let mut config = {
6446 let __cw_config_init_0_0 = Some(ProviderKind::Xai.as_str().to_string());
6447 let mut __cw_config_init_0_value: Config = Config::default();
6448 __cw_config_init_0_value.provider = __cw_config_init_0_0;
6449 __cw_config_init_0_value
6450 };
6451 let token_a = id_token(&serde_json::json!({"email": "a@example.com"}));
6452 activate_login(
6453 pending_login_with_id_token_for_test(
6454 OAuthProvider::Xai,
6455 "access-a",
6456 "refresh-a",
6457 Some(&token_a),
6458 ),
6459 Some(&config_path),
6460 Some(&mut config),
6461 )
6462 .expect("login A");
6463 assert_eq!(
6464 get_xai_credentials(&config)
6465 .expect("account A")
6466 .access_token,
6467 "access-a"
6468 );
6469
6470 let token_b = id_token(&serde_json::json!({"email": "b@example.com"}));
6471 let mut pending_b = pending_login_with_id_token_for_test(
6472 OAuthProvider::Xai,
6473 "access-b",
6474 "refresh-b",
6475 Some(&token_b),
6476 );
6477 pending_b.client_id = "alternate-client".to_string();
6478 let second =
6479 activate_login(pending_b, Some(&config_path), Some(&mut config)).expect("login B");
6480 assert_eq!(second.account_label.as_deref(), Some("b@example.com"));
6481 assert_eq!(second.replaced, Some(Some("a@example.com".to_string())));
6482
6483 // Requests: the runtime credential is account B's, under B's client.
6484 let runtime = get_xai_credentials(&config).expect("account B");
6485 assert_eq!(runtime.access_token, "access-b");
6486 assert_eq!(runtime.client_id, "alternate-client");
6487 assert_eq!(runtime.account_label.as_deref(), Some("b@example.com"));
6488 // Status: readiness/picker and `auth status` name account B too.
6489 assert_eq!(
6490 usable_sign_in(OAuthProvider::Xai, &config)
6491 .and_then(|sign_in| sign_in.account_label)
6492 .as_deref(),
6493 Some("b@example.com")
6494 );
6495 let generation = second
6496 .auth_path
6497 .file_name()
6498 .and_then(|name| name.to_str())
6499 .expect("generation name");
6500 assert_eq!(
6501 owned_account_label_for_generation(OAuthProvider::Xai, generation)
6502 .expect("usable sign-in")
6503 .as_deref(),
6504 Some("b@example.com")
6505 );
6506 let persisted = std::fs::read_to_string(&second.auth_path).expect("generation");
6507 assert!(!persisted.contains("refresh-a"), "{persisted}");
6508 }
6509
6510 /// The label follows the same usability test as the runtime: an entry
6511 /// with an expired access token and no refresh token names no account.
6512 #[test]
6513 fn stale_owned_entry_names_no_account() {
6514 let _lock = crate::test_support::lock_test_env();
6515 let home = tempfile::tempdir().expect("temp home");
6516 let root = home.path().canonicalize().expect("canonical home");
6517 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
6518 let generation = "chatgpt-auth-0123456789abcdef0123456789abcdef.json";
6519 let token_a = id_token(&serde_json::json!({"email": "a@example.com"}));
6520 let file = serde_json::json!({
6521 format!("{CHATGPT_OAUTH_ISSUER}::{CHATGPT_OAUTH_CLIENT_ID}"): {
6522 "access_token": "access-stale",
6523 "expires_at": "2000-01-01T00:00:00Z",
6524 "id_token": token_a,
6525 }
6526 });
6527 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
6528 store.write(generation, file.to_string().as_bytes(), false)
6529 })
6530 .expect("seed stale generation");
6531 let mut config = Config::default();
6532 config
6533 .mark_codewhale_owned_chatgpt_oauth(generation.to_string())
6534 .expect("admitted OAuth fixture");
6535 assert!(!credentials_valid(OAuthProvider::Chatgpt, &config));
6536 assert_eq!(usable_sign_in(OAuthProvider::Chatgpt, &config), None);
6537 let reason = owned_account_label_for_generation(OAuthProvider::Chatgpt, generation)
6538 .expect_err("stale entry is unusable");
6539 assert_eq!(reason.to_string(), "sign-in file holds no usable sign-in");
6540 }
6541
6542 #[test]
6543 fn authorize_url_rejects_providers_without_a_browser_flow() {
6544 let pkce = PkceChallenge {
6545 verifier: "verifier".into(),
6546 challenge: "challenge".into(),
6547 };
6548 let err = build_authorize_url(
6549 oauth_provider_params(OAuthProvider::Xai),
6550 "https://auth.x.ai",
6551 "client",
6552 "openid",
6553 "http://localhost:1455/auth/callback",
6554 "state-1",
6555 &pkce,
6556 )
6557 .expect_err("xAI has no browser flow");
6558 assert!(
6559 format!("{err:#}").contains("no browser sign-in flow"),
6560 "{err:#}"
6561 );
6562 }
6563
6564 #[test]
6565 fn callback_success_requires_matching_state() {
6566 let ok = parse_callback_query(chatgpt(), "code=abc&state=s1").unwrap();
6567 assert_eq!(accept_callback("s1", ok).unwrap(), "abc");
6568 let mismatch = parse_callback_query(chatgpt(), "code=abc&state=other").unwrap();
6569 let err = accept_callback("s1", mismatch).unwrap_err().to_string();
6570 assert!(err.contains("state did not match"), "{err}");
6571 }
6572
6573 #[test]
6574 fn callback_error_is_user_visible_without_code() {
6575 let outcome = parse_callback_query(
6576 chatgpt(),
6577 "error=access_denied&error_description=nope&state=s1",
6578 )
6579 .unwrap();
6580 let err = accept_callback("s1", outcome).unwrap_err().to_string();
6581 assert!(err.contains("access_denied"), "{err}");
6582 assert!(!err.contains("nope"), "{err}");
6583 assert!(!err.contains("access_token"));
6584 }
6585
6586 #[test]
6587 fn callback_missing_code_fails() {
6588 let err = parse_callback_query(chatgpt(), "state=s1")
6589 .unwrap_err()
6590 .to_string();
6591 assert!(err.contains("missing authorization code"), "{err}");
6592 }
6593
6594 #[test]
6595 fn token_exchange_uses_pkce_verifier_against_mock_issuer() {
6596 let client = MockFormClient::new(vec![(
6597 200,
6598 serde_json::json!({
6599 "access_token": "at-1",
6600 "refresh_token": "rt-1",
6601 "expires_in": 3600,
6602 "id_token": jwt_with_account("acct-9")
6603 })
6604 .to_string(),
6605 )]);
6606 let token = exchange_authorization_code(
6607 &client,
6608 chatgpt(),
6609 &form_token_url(chatgpt(), CHATGPT_OAUTH_ISSUER),
6610 CHATGPT_OAUTH_CLIENT_ID,
6611 "http://localhost:1455/auth/callback",
6612 "auth-code",
6613 "verifier",
6614 )
6615 .unwrap();
6616 assert_eq!(token.access_token.as_deref(), Some("at-1"));
6617 let posts = client.posts.lock().unwrap();
6618 assert_eq!(posts.len(), 1);
6619 assert_eq!(
6620 posts[0].0,
6621 "https://auth.openai.com/api/accounts/oauth/token"
6622 );
6623 let form: std::collections::BTreeMap<_, _> = posts[0].1.iter().cloned().collect();
6624 assert_eq!(form["grant_type"], "authorization_code");
6625 assert_eq!(form["code_verifier"], "verifier");
6626 assert_eq!(form["code"], "auth-code");
6627 }
6628
6629 #[test]
6630 fn token_exchange_error_does_not_echo_body_secrets() {
6631 let client = MockFormClient::new(vec![(
6632 400,
6633 serde_json::json!({
6634 "error": "invalid_grant",
6635 "error_description": "secret-must-not-leak"
6636 })
6637 .to_string(),
6638 )]);
6639 // OAuthTokenMaterial is deliberately Debug-free; extract the error
6640 // without demanding a Debug bound on the success type.
6641 let err = match exchange_authorization_code(
6642 &client,
6643 chatgpt(),
6644 &form_token_url(chatgpt(), CHATGPT_OAUTH_ISSUER),
6645 CHATGPT_OAUTH_CLIENT_ID,
6646 "http://localhost:1455/auth/callback",
6647 "bad",
6648 "verifier",
6649 ) {
6650 Ok(_) => panic!("invalid_grant must fail"),
6651 Err(err) => err.to_string(),
6652 };
6653 assert!(err.contains("permanently"), "{err}");
6654 assert!(!err.contains("secret-must-not-leak"), "{err}");
6655 }
6656
6657 #[test]
6658 fn callback_server_handles_success_and_error_requests() {
6659 use std::io::Write as _;
6660 let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind test port");
6661 listener.set_nonblocking(false).unwrap();
6662 let addr = listener.local_addr().unwrap();
6663 let state = "state-xyz".to_string();
6664 let expected = state.clone();
6665 let params = chatgpt();
6666 let server = std::thread::spawn(move || {
6667 let (stream, _) = listener.accept().expect("accept");
6668 handle_callback_stream(stream, params, &expected)
6669 });
6670 let mut client = std::net::TcpStream::connect(addr).expect("connect");
6671 write!(
6672 client,
6673 "GET /auth/callback?code=tok&state={state} HTTP/1.1\r\nHost: localhost\r\n\r\n"
6674 )
6675 .unwrap();
6676 let code = server.join().expect("server").expect("callback ok");
6677 assert_eq!(code.0, "tok");
6678
6679 let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind error port");
6680 listener.set_nonblocking(false).unwrap();
6681 let addr = listener.local_addr().unwrap();
6682 let params = chatgpt();
6683 let server = std::thread::spawn(move || {
6684 let (stream, _) = listener.accept().expect("accept");
6685 handle_callback_stream(stream, params, "state-xyz")
6686 });
6687 let mut client = std::net::TcpStream::connect(addr).expect("connect");
6688 write!(
6689 client,
6690 "GET /auth/callback?error=access_denied&state=state-xyz HTTP/1.1\r\nHost: localhost\r\n\r\n"
6691 )
6692 .unwrap();
6693 let err = server.join().expect("server").unwrap_err().to_string();
6694 assert!(err.contains("not completed"), "{err}");
6695 }
6696
6697 /// The registered redirect URI says `localhost`, which resolves to `::1`
6698 /// as readily as `127.0.0.1`. A callback arriving on the IPv6 listener has
6699 /// to be accepted, or an IPv6-first browser hangs until the timeout.
6700 #[test]
6701 fn callback_is_accepted_on_either_loopback_family() {
6702 use std::io::Write as _;
6703 for addr in [
6704 SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
6705 SocketAddr::from((Ipv6Addr::LOCALHOST, 0)),
6706 ] {
6707 let Ok(target) = TcpListener::bind(addr) else {
6708 // A host without this stack cannot exercise it; the other arm
6709 // still covers the polling loop.
6710 continue;
6711 };
6712 target.set_nonblocking(true).unwrap();
6713 let target_addr = target.local_addr().unwrap();
6714
6715 // A second, permanently idle listener stands in for the family the
6716 // browser did not pick: `wait_for_callback` must poll past it.
6717 let idle = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
6718 .expect("bind idle listener");
6719 idle.set_nonblocking(true).unwrap();
6720
6721 let listeners = vec![idle, target];
6722 let params = chatgpt();
6723 let server =
6724 std::thread::spawn(move || wait_for_callback(&listeners, params, "state-xyz"));
6725 let mut client = std::net::TcpStream::connect(target_addr).expect("connect");
6726 write!(
6727 client,
6728 "GET /auth/callback?code=tok&state=state-xyz HTTP/1.1\r\nHost: localhost\r\n\r\n"
6729 )
6730 .unwrap();
6731 let code = server
6732 .join()
6733 .expect("server")
6734 .unwrap_or_else(|error| panic!("callback on {target_addr} rejected: {error}"));
6735 assert_eq!(code.0, "tok", "callback on {target_addr}");
6736 }
6737 }
6738
6739 #[test]
6740 fn form_refresh_and_revoke_target_the_row_endpoints() {
6741 let client = MockFormClient::new(vec![
6742 (
6743 200,
6744 serde_json::json!({"access_token": "fresh", "expires_in": 3600}).to_string(),
6745 ),
6746 (200, String::new()),
6747 ]);
6748 let refreshed = refresh_access_token_via(
6749 &client,
6750 chatgpt(),
6751 &form_token_url(chatgpt(), CHATGPT_OAUTH_ISSUER),
6752 CHATGPT_OAUTH_CLIENT_ID,
6753 "rt-1",
6754 )
6755 .expect("refresh");
6756 assert_eq!(refreshed.access_token.as_deref(), Some("fresh"));
6757 revoke_remote_token_via(
6758 &client,
6759 chatgpt(),
6760 CHATGPT_OAUTH_ISSUER,
6761 CHATGPT_OAUTH_CLIENT_ID,
6762 "rt-1",
6763 )
6764 .expect("revoke");
6765 let posts = client.posts.lock().unwrap();
6766 assert_eq!(posts.len(), 2, "{posts:?}");
6767 assert!(posts[0].0.ends_with("/oauth/token"), "{posts:?}");
6768 assert!(
6769 posts[0]
6770 .1
6771 .iter()
6772 .any(|(k, v)| k == "grant_type" && v == "refresh_token")
6773 );
6774 assert!(
6775 posts[1].0.ends_with("/api/accounts/oauth/revoke"),
6776 "{posts:?}"
6777 );
6778 }
6779
6780 #[test]
6781 fn auth_mode_accepts_oauth_aliases() {
6782 for mode in [
6783 "oauth",
6784 "xai_oauth",
6785 "XAI-OAuth",
6786 "grok",
6787 "grok_cli",
6788 "device_code",
6789 "device-auth",
6790 ] {
6791 assert!(
6792 auth_mode_uses_xai_oauth(mode),
6793 "expected oauth mode: {mode}"
6794 );
6795 }
6796 assert!(!auth_mode_uses_xai_oauth("api_key"));
6797 assert!(!auth_mode_uses_xai_oauth("keyring"));
6798 }
6799
6800 #[test]
6801 fn loads_fresh_token_from_grok_auth_json() {
6802 let _guard = crate::test_support::lock_test_env();
6803 let dir = TempDir::new().unwrap();
6804 let root = dir.path().canonicalize().expect("canonical temp root");
6805 let path = root.join("auth.json");
6806 let future = rfc3339_from_now(3600);
6807 let scope = format!("{XAI_OIDC_ISSUER}::{GROK_OIDC_CLIENT_ID}");
6808 let file = serde_json::json!({
6809 scope: {
6810 "key": "test-access-token",
6811 "refresh_token": "test-refresh",
6812 "expires_at": future,
6813 "oidc_issuer": XAI_OIDC_ISSUER,
6814 "oidc_client_id": GROK_OIDC_CLIENT_ID,
6815 "auth_mode": "oidc"
6816 }
6817 });
6818 fs::write(&path, serde_json::to_vec_pretty(&file).unwrap()).unwrap();
6819 let _home_guard = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
6820 let _path_guard = crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &path);
6821 let config = {
6822 let __cw_config_init_1_0 = Some(ProviderKind::Xai.as_str().to_string());
6823 let __cw_config_init_1_1 = Some(crate::config::ProvidersConfig {
6824 xai: crate::config::ProviderConfig {
6825 auth_mode: Some("oauth".to_string()),
6826 external_credentials: Some(
6827 codewhale_config::ExternalCredentialConsentToml::read_only(
6828 codewhale_config::ProviderKind::Xai,
6829 codewhale_config::ExternalCredentialSource::GrokCli,
6830 path.clone(),
6831 ),
6832 ),
6833 ..Default::default()
6834 },
6835 ..Default::default()
6836 });
6837 let mut __cw_config_init_1_value: Config = Default::default();
6838 __cw_config_init_1_value.provider = __cw_config_init_1_0;
6839 __cw_config_init_1_value.providers = __cw_config_init_1_1;
6840 __cw_config_init_1_value
6841 };
6842 crate::external_credentials::reset_side_effect_trap();
6843 let result = get_xai_credentials(&config);
6844 let creds = result.expect("load");
6845 assert_eq!(creds.access_token, "test-access-token");
6846 assert_eq!(creds.client_id, GROK_OIDC_CLIENT_ID);
6847 assert_eq!(
6848 crate::external_credentials::side_effect_trap_counts(),
6849 (1, 1)
6850 );
6851 }
6852
6853 #[test]
6854 fn disabled_external_grok_credentials_cause_zero_external_io() {
6855 let _guard = crate::test_support::lock_test_env();
6856 let dir = TempDir::new().unwrap();
6857 let root = dir.path().canonicalize().expect("canonical temp root");
6858 let path = root.join("external-grok-auth.json");
6859 let raw = serde_json::json!({
6860 format!("{XAI_OIDC_ISSUER}::{GROK_OIDC_CLIENT_ID}"): {
6861 "key": "must-never-be-read",
6862 "refresh_token": "must-never-be-used",
6863 "expires_at": rfc3339_from_now(3600),
6864 "future_field": {"preserve": true}
6865 }
6866 })
6867 .to_string();
6868 fs::write(&path, &raw).unwrap();
6869 let owned_home = root.join("codewhale-owned");
6870 let _home_guard = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &owned_home);
6871 let _path_guard = crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &path);
6872 let config = {
6873 let __cw_config_init_2_0 = Some(ProviderKind::Xai.as_str().to_string());
6874 let __cw_config_init_2_1 = Some(crate::config::ProvidersConfig {
6875 xai: crate::config::ProviderConfig {
6876 auth_mode: Some("oauth".to_string()),
6877 ..Default::default()
6878 },
6879 ..Default::default()
6880 });
6881 let mut __cw_config_init_2_value: Config = Default::default();
6882 __cw_config_init_2_value.provider = __cw_config_init_2_0;
6883 __cw_config_init_2_value.providers = __cw_config_init_2_1;
6884 __cw_config_init_2_value
6885 };
6886
6887 crate::external_credentials::reset_side_effect_trap();
6888 assert!(!credentials_valid(OAuthProvider::Xai, &config));
6889 let error = match get_xai_credentials(&config) {
6890 Ok(_) => panic!("external access is disabled"),
6891 Err(e) => e,
6892 };
6893 assert!(error.to_string().contains("are disabled"));
6894 assert_eq!(
6895 crate::external_credentials::side_effect_trap_counts(),
6896 (0, 0)
6897 );
6898 assert_eq!(
6899 crate::external_credentials::complete_side_effect_trap_counts(),
6900 (0, 0, 0, 0, 0),
6901 "disabled external authority must reach no credential or OAuth sink"
6902 );
6903 assert_eq!(fs::read_to_string(&path).unwrap(), raw);
6904 }
6905
6906 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6907 async fn expired_read_only_external_credentials_never_refresh_rewrite_or_network() {
6908 let _guard = crate::test_support::lock_test_env();
6909 let server = MockServer::start().await;
6910 let dir = TempDir::new().unwrap();
6911 let root = dir.path().canonicalize().expect("canonical temp root");
6912 let path = root.join("external-grok-auth.json");
6913 let scope = format!("{}::{GROK_OIDC_CLIENT_ID}", server.uri());
6914 let raw = serde_json::json!({
6915 scope: {
6916 "key": "expired-external-access",
6917 "refresh_token": "must-never-be-submitted",
6918 "expires_at": rfc3339_from_unix(now_unix_secs().unwrap_or(0) - 3600),
6919 "oidc_issuer": server.uri(),
6920 "oidc_client_id": GROK_OIDC_CLIENT_ID,
6921 "future_field": {"preserve": true}
6922 }
6923 })
6924 .to_string();
6925 fs::write(&path, &raw).unwrap();
6926 let owned_home = root.join("codewhale-owned");
6927 let _home_guard = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &owned_home);
6928 let _path_guard = crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &path);
6929 let config = {
6930 let __cw_config_init_3_0 = Some(ProviderKind::Xai.as_str().to_string());
6931 let __cw_config_init_3_1 = Some(crate::config::ProvidersConfig {
6932 xai: crate::config::ProviderConfig {
6933 auth_mode: Some("oauth".to_string()),
6934 external_credentials: Some(
6935 codewhale_config::ExternalCredentialConsentToml::read_only(
6936 codewhale_config::ProviderKind::Xai,
6937 codewhale_config::ExternalCredentialSource::GrokCli,
6938 path.clone(),
6939 ),
6940 ),
6941 ..Default::default()
6942 },
6943 ..Default::default()
6944 });
6945 let mut __cw_config_init_3_value: Config = Default::default();
6946 __cw_config_init_3_value.provider = __cw_config_init_3_0;
6947 __cw_config_init_3_value.providers = __cw_config_init_3_1;
6948 __cw_config_init_3_value
6949 };
6950
6951 crate::external_credentials::reset_side_effect_trap();
6952 let error = match tokio::task::block_in_place(|| get_xai_credentials(&config)) {
6953 Ok(_) => panic!("read-only external credentials must fail instead of refreshing"),
6954 Err(e) => e,
6955 };
6956 assert!(
6957 error
6958 .to_string()
6959 .contains("Read-only consent never refreshes")
6960 );
6961 assert_eq!(
6962 crate::external_credentials::side_effect_trap_counts(),
6963 (1, 1)
6964 );
6965 assert_eq!(
6966 crate::external_credentials::complete_side_effect_trap_counts(),
6967 (1, 1, 0, 0, 0),
6968 "read-only external expiry must not reach write, refresh, or network sinks"
6969 );
6970 assert_eq!(fs::read_to_string(&path).unwrap(), raw);
6971 assert!(!owned_home.join("credentials/xai-auth.json").exists());
6972 assert!(
6973 server
6974 .received_requests()
6975 .await
6976 .expect("recorded requests")
6977 .is_empty(),
6978 "external refresh tokens must never be sent over the network"
6979 );
6980 }
6981
6982 #[test]
6983 fn native_login_storage_is_codewhale_owned() {
6984 let _guard = crate::test_support::lock_test_env();
6985 let dir = TempDir::new().unwrap();
6986 let grok_path = dir.path().join("external-grok-auth.json");
6987 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", dir.path());
6988 let _grok = crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &grok_path);
6989
6990 let owned = codewhale_config::legacy_xai_oauth_path().expect("Codewhale-owned auth path");
6991 assert_eq!(owned, dir.path().join("credentials/xai-auth.json"));
6992 assert_ne!(owned, grok_auth_file_path());
6993 }
6994
6995 /// #4257 storage contract: the on-disk credential file is a JSON object
6996 /// keyed `{issuer}::{client_id}` whose entries use the Grok CLI's field
6997 /// names. Consolidating the device-code poller must not touch it, so pin
6998 /// the format with literal bytes rather than a round-trip through the
6999 /// writer — a round-trip would follow the code if the code drifted.
7000 #[test]
7001 fn a_token_stored_in_the_current_on_disk_format_still_loads() {
7002 let _guard = crate::test_support::lock_test_env();
7003 let dir = TempDir::new().unwrap();
7004 let home = dir
7005 .path()
7006 .canonicalize()
7007 .expect("canonical temp root")
7008 .join("owned-home");
7009 fs::create_dir_all(&home).unwrap();
7010 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7011
7012 let generation = "xai-auth-fedcba9876543210fedcba9876543210.json";
7013 let expires_at = rfc3339_from_now(3600);
7014 let stored = format!(
7015 r#"{{
7016 "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828": {{
7017 "key": "stored-access-token",
7018 "refresh_token": "stored-refresh-token",
7019 "expires_at": "{expires_at}",
7020 "oidc_issuer": "https://auth.x.ai",
7021 "oidc_client_id": "b1a00492-073a-47ea-816f-4c329264a828",
7022 "auth_mode": "oidc",
7023 "unknown_cli_field": "preserved"
7024 }}
7025 }}"#
7026 );
7027
7028 let credentials = codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
7029 store.write(generation, stored.as_bytes(), false)?;
7030 // A fresh stored token must be used as-is: refreshing here would
7031 // mean an existing login stopped working offline.
7032 get_owned_credentials_locked(
7033 OAuthProvider::Xai,
7034 store,
7035 generation,
7036 &ReqwestOAuthFormClient,
7037 |_, _, _| panic!("a fresh stored token must not be refreshed"),
7038 )
7039 })
7040 .expect("read back a credential stored in the current format");
7041
7042 assert_eq!(credentials.access_token, "stored-access-token");
7043 assert_eq!(
7044 credentials.refresh_token.as_deref(),
7045 Some("stored-refresh-token")
7046 );
7047 assert_eq!(credentials.issuer, XAI_OIDC_ISSUER);
7048 assert_eq!(credentials.client_id, GROK_OIDC_CLIENT_ID);
7049 }
7050
7051 /// `Debug` reaches production through tracing's `?` sigil, anyhow context,
7052 /// and panic messages. Nothing that holds bearer material may print it.
7053 #[test]
7054 fn debug_output_never_contains_bearer_material() {
7055 let entry = OwnedAuthEntry {
7056 access_token: Some("secret-access-token".to_string()),
7057 refresh_token: Some("secret-refresh-token".to_string()),
7058 expires_at: Some("2030-01-01T00:00:00.000Z".to_string()),
7059 id_token: None,
7060 account_id: None,
7061 oidc_issuer: Some(XAI_OIDC_ISSUER.to_string()),
7062 oidc_client_id: Some(GROK_OIDC_CLIENT_ID.to_string()),
7063 originator: None,
7064 auth_mode: Some("oidc".to_string()),
7065 extra: BTreeMap::new(),
7066 };
7067 let credentials = credentials_from_entry(
7068 OAuthProvider::Xai,
7069 &format!("{XAI_OIDC_ISSUER}::{GROK_OIDC_CLIENT_ID}"),
7070 &entry,
7071 "secret-access-token".to_string(),
7072 );
7073 let activation = OAuthActivation {
7074 credentials: credentials.clone(),
7075 config_path: PathBuf::from("/tmp/config.toml"),
7076 auth_path: PathBuf::from("/tmp/auth.json"),
7077 provider: OAuthProvider::Xai,
7078 account_label: None,
7079 replaced: None,
7080 };
7081
7082 let rendered = format!("{entry:?} {activation:?}");
7083 for secret in ["secret-access-token", "secret-refresh-token"] {
7084 assert!(!rendered.contains(secret), "{secret} leaked: {rendered}");
7085 }
7086 // The shape stays useful for diagnosis.
7087 assert!(rendered.contains("<redacted>"), "{rendered}");
7088 assert!(rendered.contains(GROK_OIDC_CLIENT_ID), "{rendered}");
7089 }
7090
7091 fn pending_login(access: &str, refresh: &str) -> PendingOAuthLogin {
7092 pending_login_for_test(OAuthProvider::Xai, access, refresh)
7093 }
7094
7095 fn seed_expired_owned_generation() -> String {
7096 let generation = "xai-auth-0123456789abcdef0123456789abcdef.json".to_string();
7097 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
7098 let scope = format!("{}::{}", XAI_OIDC_ISSUER, GROK_OIDC_CLIENT_ID);
7099 let mut file = AuthFile::new();
7100 file.insert(
7101 scope,
7102 OwnedAuthEntry {
7103 access_token: Some("expired-access".to_string()),
7104 refresh_token: Some("initial-refresh".to_string()),
7105 expires_at: Some("1970-01-01T00:00:00.000Z".to_string()),
7106 id_token: None,
7107 account_id: None,
7108 oidc_issuer: Some(XAI_OIDC_ISSUER.to_string()),
7109 oidc_client_id: Some(GROK_OIDC_CLIENT_ID.to_string()),
7110 originator: None,
7111 auth_mode: Some("oidc".to_string()),
7112 extra: BTreeMap::new(),
7113 },
7114 );
7115 write_auth_file_to_store(store, &generation, &file, false)
7116 })
7117 .expect("seed expired owned generation");
7118 generation
7119 }
7120
7121 fn seed_legacy_owned_credentials() -> PathBuf {
7122 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
7123 let scope = format!("{}::{}", XAI_OIDC_ISSUER, GROK_OIDC_CLIENT_ID);
7124 let mut legacy = AuthFile::new();
7125 legacy.insert(
7126 scope,
7127 OwnedAuthEntry {
7128 access_token: Some("legacy-access".to_string()),
7129 refresh_token: Some("legacy-refresh".to_string()),
7130 expires_at: Some(rfc3339_from_now(3600)),
7131 id_token: None,
7132 account_id: None,
7133 oidc_issuer: Some(XAI_OIDC_ISSUER.to_string()),
7134 oidc_client_id: Some(GROK_OIDC_CLIENT_ID.to_string()),
7135 originator: None,
7136 auth_mode: Some("oidc".to_string()),
7137 extra: BTreeMap::new(),
7138 },
7139 );
7140 write_auth_file_to_store(
7141 store,
7142 codewhale_config::LEGACY_XAI_OAUTH_FILE_NAME,
7143 &legacy,
7144 false,
7145 )?;
7146 store.path_for(codewhale_config::LEGACY_XAI_OAUTH_FILE_NAME)
7147 })
7148 .expect("seed legacy credentials")
7149 }
7150
7151 #[test]
7152 fn concurrent_refreshes_share_one_rotated_epoch() {
7153 let _guard = crate::test_support::lock_test_env();
7154 let dir = TempDir::new().unwrap();
7155 let home = dir
7156 .path()
7157 .canonicalize()
7158 .expect("canonical temp root")
7159 .join("owned-home");
7160 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7161 let generation = seed_expired_owned_generation();
7162 let refreshes = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
7163 let (entered_tx, entered_rx) = std::sync::mpsc::channel();
7164 let (release_tx, release_rx) = std::sync::mpsc::channel();
7165
7166 let first_generation = generation.clone();
7167 let first_refreshes = refreshes.clone();
7168 let first = std::thread::spawn(move || {
7169 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
7170 get_owned_credentials_locked(
7171 OAuthProvider::Xai,
7172 store,
7173 &first_generation,
7174 &ReqwestOAuthFormClient,
7175 |_, _, refresh| {
7176 assert_eq!(refresh, "initial-refresh");
7177 first_refreshes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7178 entered_tx.send(()).unwrap();
7179 release_rx.recv().unwrap();
7180 Ok(OAuthTokenMaterial {
7181 earliest_refresh_at: None,
7182 scope: None,
7183 token_type: None,
7184 verified_chatgpt: None,
7185 id_token: None,
7186 access_token: Some("rotated-access".to_string()),
7187 refresh_token: Some("rotated-refresh".to_string()),
7188 expires_in: Some(3600),
7189 error: None,
7190 error_description: None,
7191 interval: None,
7192 })
7193 },
7194 )
7195 })
7196 });
7197 entered_rx.recv().expect("first refresh reached barrier");
7198
7199 let second_generation = generation.clone();
7200 let second_refreshes = refreshes.clone();
7201 let (attempt_tx, attempt_rx) = std::sync::mpsc::channel();
7202 let second = std::thread::spawn(move || {
7203 attempt_tx.send(()).unwrap();
7204 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
7205 get_owned_credentials_locked(
7206 OAuthProvider::Xai,
7207 store,
7208 &second_generation,
7209 &ReqwestOAuthFormClient,
7210 |_, _, _| {
7211 second_refreshes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7212 bail!("second refresh must observe the first thread's committed token")
7213 },
7214 )
7215 })
7216 });
7217 attempt_rx.recv().expect("second refresh attempted lock");
7218 release_tx.send(()).expect("release first refresh");
7219
7220 let first = first.join().unwrap().expect("first refresh");
7221 let second = second.join().unwrap().expect("second refresh");
7222 assert_eq!(first.access_token, "rotated-access");
7223 assert_eq!(second.access_token, "rotated-access");
7224 assert_eq!(refreshes.load(std::sync::atomic::Ordering::SeqCst), 1);
7225 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
7226 let mut file = load_owned_auth_file_from_store(store, &generation)?
7227 .context("generation must remain active")?;
7228 let (_, entry) = select_entry(OAuthProvider::Xai, &mut file).context("stored entry")?;
7229 assert_eq!(entry.refresh_token.as_deref(), Some("rotated-refresh"));
7230 Ok(())
7231 })
7232 .unwrap();
7233 }
7234
7235 #[test]
7236 fn logout_waits_for_refresh_then_revokes_the_committed_epoch() {
7237 let _guard = crate::test_support::lock_test_env();
7238 let dir = TempDir::new().unwrap();
7239 let home = dir
7240 .path()
7241 .canonicalize()
7242 .expect("canonical temp root")
7243 .join("owned-home");
7244 fs::create_dir_all(&home).unwrap();
7245 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7246 let generation = seed_expired_owned_generation();
7247 fs::write(
7248 home.join("config.toml"),
7249 format!(
7250 "[providers.xai]\nauth_mode = \"oauth\"\noauth_credential_generation = \"{generation}\"\n"
7251 ),
7252 )
7253 .unwrap();
7254 let (entered_tx, entered_rx) = std::sync::mpsc::channel();
7255 let (release_tx, release_rx) = std::sync::mpsc::channel();
7256
7257 let refresh_generation = generation.clone();
7258 let refresh = std::thread::spawn(move || {
7259 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
7260 get_owned_credentials_locked(
7261 OAuthProvider::Xai,
7262 store,
7263 &refresh_generation,
7264 &ReqwestOAuthFormClient,
7265 |_, _, _| {
7266 entered_tx.send(()).unwrap();
7267 release_rx.recv().unwrap();
7268 Ok(OAuthTokenMaterial {
7269 earliest_refresh_at: None,
7270 scope: None,
7271 token_type: None,
7272 verified_chatgpt: None,
7273 id_token: None,
7274 access_token: Some("last-refresh-access".to_string()),
7275 refresh_token: Some("last-refresh-rotation".to_string()),
7276 expires_in: Some(3600),
7277 error: None,
7278 error_description: None,
7279 interval: None,
7280 })
7281 },
7282 )
7283 })
7284 });
7285 entered_rx.recv().expect("refresh reached barrier");
7286
7287 let (attempt_tx, attempt_rx) = std::sync::mpsc::channel();
7288 let config_path = home.join("config.toml");
7289 let logout = std::thread::spawn(move || {
7290 attempt_tx.send(()).unwrap();
7291 codewhale_config::with_xai_oauth_revocation_transaction(|| {
7292 codewhale_config::mutate_config_document(&config_path, |document| {
7293 codewhale_config::unset_config_document_value(
7294 document,
7295 &["providers", "xai", "oauth_credential_generation"],
7296 )?;
7297 codewhale_config::unset_config_document_value(
7298 document,
7299 &["providers", "xai", "auth_mode"],
7300 )?;
7301 Ok(())
7302 })
7303 })
7304 });
7305 attempt_rx.recv().expect("logout attempted lifecycle lock");
7306 release_tx.send(()).expect("release refresh");
7307
7308 assert_eq!(
7309 refresh.join().unwrap().expect("refresh").access_token,
7310 "last-refresh-access"
7311 );
7312 logout.join().unwrap().expect("logout");
7313 let auth_path = home.join("credentials").join(&generation);
7314 assert!(
7315 !auth_path.exists(),
7316 "logout must retire the generation written by the preceding refresh"
7317 );
7318 let config = fs::read_to_string(home.join("config.toml")).unwrap();
7319 assert!(!config.contains("oauth_credential_generation"));
7320 assert!(!config.contains("auth_mode"));
7321 }
7322
7323 #[test]
7324 fn activation_commits_unique_generation_pointer_and_revokes_external_consent() {
7325 let _guard = crate::test_support::lock_test_env();
7326 let dir = TempDir::new().unwrap();
7327 let home = dir
7328 .path()
7329 .canonicalize()
7330 .expect("canonical temp root")
7331 .join("owned-home");
7332 let config_path = dir.path().join("config.toml");
7333 let external_path = dir.path().join("grok-external.json");
7334 fs::write(&external_path, "external owner bytes").unwrap();
7335 fs::write(
7336 &config_path,
7337 format!(
7338 r#"# operator note
7339 [providers.xai]
7340 model = "grok-code-fast-1" # model note
7341 future_setting = "preserve"
7342
7343 [providers.xai.external_credentials]
7344 access = "read_only"
7345 provider = "xai"
7346 source = "grok_cli"
7347 path = {}
7348 consent_version = 1
7349 "#,
7350 toml::Value::String(external_path.display().to_string())
7351 ),
7352 )
7353 .unwrap();
7354 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7355 let consent = codewhale_config::ExternalCredentialConsentToml::read_only(
7356 codewhale_config::ProviderKind::Xai,
7357 codewhale_config::ExternalCredentialSource::GrokCli,
7358 external_path.clone(),
7359 );
7360 let mut live = {
7361 let __cw_config_init_4_0 = Some(crate::config::ProvidersConfig {
7362 xai: crate::config::ProviderConfig {
7363 model: Some("grok-code-fast-1".to_string()),
7364 external_credentials: Some(consent),
7365 ..Default::default()
7366 },
7367 ..Default::default()
7368 });
7369 let mut __cw_config_init_4_value: Config = Default::default();
7370 __cw_config_init_4_value.providers = __cw_config_init_4_0;
7371 __cw_config_init_4_value
7372 };
7373
7374 crate::external_credentials::reset_side_effect_trap();
7375 let activation = activate_login(
7376 pending_login("activation-access", "activation-refresh"),
7377 Some(&config_path),
7378 Some(&mut live),
7379 )
7380 .expect("activate login");
7381
7382 assert_eq!(activation.config_path, config_path);
7383 let generation = activation
7384 .auth_path
7385 .file_name()
7386 .and_then(|name| name.to_str())
7387 .expect("generation basename");
7388 assert!(codewhale_config::is_valid_xai_oauth_generation(generation));
7389 let persisted = fs::read_to_string(&config_path).unwrap();
7390 assert!(persisted.contains("# operator note"));
7391 assert!(persisted.contains("model = \"grok-code-fast-1\" # model note"));
7392 assert!(persisted.contains("future_setting = \"preserve\""));
7393 assert!(persisted.contains("auth_mode = \"oauth\""));
7394 assert!(persisted.contains(&format!("oauth_credential_generation = \"{generation}\"")));
7395 assert!(!persisted.contains("external_credentials"));
7396 assert_eq!(
7397 fs::read_to_string(&external_path).unwrap(),
7398 "external owner bytes"
7399 );
7400 let owned = fs::read_to_string(&activation.auth_path).unwrap();
7401 assert!(owned.contains("activation-access"));
7402 assert!(owned.contains("activation-refresh"));
7403 #[cfg(unix)]
7404 assert_eq!(
7405 fs::metadata(&activation.auth_path)
7406 .unwrap()
7407 .permissions()
7408 .mode()
7409 & 0o777,
7410 0o600
7411 );
7412 let live_xai = live
7413 .provider_config_for(&live.test_identity_for_kind(ProviderKind::Xai))
7414 .unwrap();
7415 assert_eq!(live_xai.auth_mode.as_deref(), Some("oauth"));
7416 assert_eq!(
7417 live_xai.oauth_credential_generation.as_deref(),
7418 Some(generation)
7419 );
7420 assert!(live_xai.external_credentials.is_none());
7421 assert_eq!(
7422 crate::external_credentials::complete_side_effect_trap_counts(),
7423 (0, 0, 1, 0, 0),
7424 "activation must reach exactly the owned write sink"
7425 );
7426 }
7427
7428 #[test]
7429 fn activation_retires_legacy_owned_file_only_after_config_commit() {
7430 let _guard = crate::test_support::lock_test_env();
7431 let dir = TempDir::new().unwrap();
7432 let home = dir
7433 .path()
7434 .canonicalize()
7435 .expect("canonical temp root")
7436 .join("owned-home");
7437 let config_path = dir.path().join("config.toml");
7438 fs::write(&config_path, "[providers.xai]\nmodel = \"grok-4.5\"\n").unwrap();
7439 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7440 let legacy_path = seed_legacy_owned_credentials();
7441 assert!(legacy_path.exists());
7442
7443 let activation = activate_login(
7444 pending_login("new-access", "new-refresh"),
7445 Some(&config_path),
7446 None,
7447 )
7448 .expect("activate replacement generation");
7449
7450 assert!(activation.auth_path.exists());
7451 assert!(
7452 !legacy_path.exists(),
7453 "legacy duplicate must be removed after the generation pointer commits"
7454 );
7455 let persisted = fs::read_to_string(config_path).unwrap();
7456 assert!(persisted.contains(activation.auth_path.file_name().unwrap().to_str().unwrap()));
7457 }
7458
7459 #[test]
7460 fn activation_rotation_cleans_only_the_superseded_generation_after_commit() {
7461 let _guard = crate::test_support::lock_test_env();
7462 let dir = TempDir::new().unwrap();
7463 let home = dir
7464 .path()
7465 .canonicalize()
7466 .expect("canonical temp root")
7467 .join("owned-home");
7468 let config_path = dir.path().join("config.toml");
7469 fs::write(&config_path, "[providers.xai]\nmodel = \"grok-4.5\"\n").unwrap();
7470 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7471 let mut live = Config::default();
7472
7473 let first = activate_login(
7474 pending_login("first-access", "first-refresh"),
7475 Some(&config_path),
7476 Some(&mut live),
7477 )
7478 .expect("first activation");
7479 assert!(first.auth_path.exists());
7480 let first_name = first
7481 .auth_path
7482 .file_name()
7483 .unwrap()
7484 .to_str()
7485 .unwrap()
7486 .to_string();
7487
7488 let second = activate_login(
7489 pending_login("second-access", "second-refresh"),
7490 Some(&config_path),
7491 Some(&mut live),
7492 )
7493 .expect("second activation");
7494 assert_ne!(first.auth_path, second.auth_path);
7495 assert!(second.auth_path.exists());
7496 assert!(
7497 !first.auth_path.exists(),
7498 "superseded generation must be removed only after the new pointer commits"
7499 );
7500 let persisted = fs::read_to_string(&config_path).unwrap();
7501 assert!(!persisted.contains(&first_name));
7502 assert!(persisted.contains(second.auth_path.file_name().unwrap().to_str().unwrap()));
7503 assert!(
7504 fs::read_to_string(second.auth_path)
7505 .unwrap()
7506 .contains("second-access")
7507 );
7508 }
7509
7510 #[test]
7511 fn activation_recovers_from_a_dangling_generation_pointer() {
7512 let _guard = crate::test_support::lock_test_env();
7513 let dir = TempDir::new().unwrap();
7514 let home = dir
7515 .path()
7516 .canonicalize()
7517 .expect("canonical temp root")
7518 .join("owned-home");
7519 let config_path = dir.path().join("config.toml");
7520 // A valid-looking generation pointer whose credential file does not
7521 // exist: the state Hunter's dogfood machine was bricked in (#5032).
7522 let stale = "xai-auth-0123456789abcdef0123456789abcdef.json";
7523 fs::write(
7524 &config_path,
7525 format!(
7526 "[providers.xai]\nauth_mode = \"oauth\"\noauth_credential_generation = \"{stale}\"\n"
7527 ),
7528 )
7529 .unwrap();
7530 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7531 let mut live = Config::default();
7532
7533 let activation = activate_login(
7534 pending_login("recovered-access", "recovered-refresh"),
7535 Some(&config_path),
7536 Some(&mut live),
7537 )
7538 .expect("a dangling generation pointer must not brick login");
7539 assert!(activation.auth_path.exists());
7540 assert!(
7541 fs::read_to_string(&activation.auth_path)
7542 .unwrap()
7543 .contains("recovered-access")
7544 );
7545 let persisted = fs::read_to_string(&config_path).unwrap();
7546 assert!(
7547 !persisted.contains(stale),
7548 "stale pointer must be replaced: {persisted}"
7549 );
7550 assert!(persisted.contains(activation.auth_path.file_name().unwrap().to_str().unwrap()));
7551 assert!(persisted.contains("auth_mode = \"oauth\""));
7552 }
7553
7554 #[test]
7555 fn dangling_generation_pointer_is_detected_and_repaired() {
7556 let _guard = crate::test_support::lock_test_env();
7557 let dir = TempDir::new().unwrap();
7558 let home = dir
7559 .path()
7560 .canonicalize()
7561 .expect("canonical temp root")
7562 .join("owned-home");
7563 let config_path = dir.path().join("config.toml");
7564 // A valid-looking generation pointer whose credential file does not
7565 // exist: the state Hunter's dogfood machine was bricked in (#5032).
7566 let stale = "xai-auth-0123456789abcdef0123456789abcdef.json";
7567 fs::write(
7568 &config_path,
7569 format!(
7570 "[providers.xai]\nauth_mode = \"oauth\"\noauth_credential_generation = \"{stale}\"\n"
7571 ),
7572 )
7573 .unwrap();
7574 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7575
7576 let config = {
7577 let __cw_config_init_5_0 = Some(ProviderKind::Xai.as_str().to_string());
7578 let __cw_config_init_5_1 = Some(crate::config::ProvidersConfig {
7579 xai: crate::config::ProviderConfig {
7580 auth_mode: Some("oauth".to_string()),
7581 oauth_credential_generation: Some(stale.to_string()),
7582 ..Default::default()
7583 },
7584 ..Default::default()
7585 });
7586 let mut __cw_config_init_5_value: Config = Default::default();
7587 __cw_config_init_5_value.provider = __cw_config_init_5_0;
7588 __cw_config_init_5_value.providers = __cw_config_init_5_1;
7589 __cw_config_init_5_value
7590 };
7591
7592 assert!(
7593 owned_generation_is_dangling(OAuthProvider::Xai, &config),
7594 "OAuth mode pointing at a missing owned file is the #5032 bricked state"
7595 );
7596 // Specificity: OAuth selected but no generation configured is the normal
7597 // "needs auth" state, not a dangling pointer.
7598 let unconfigured = {
7599 let __cw_config_init_6_0 = Some(ProviderKind::Xai.as_str().to_string());
7600 let __cw_config_init_6_1 = Some(crate::config::ProvidersConfig {
7601 xai: crate::config::ProviderConfig {
7602 auth_mode: Some("oauth".to_string()),
7603 ..Default::default()
7604 },
7605 ..Default::default()
7606 });
7607 let mut __cw_config_init_6_value: Config = Default::default();
7608 __cw_config_init_6_value.provider = __cw_config_init_6_0;
7609 __cw_config_init_6_value.providers = __cw_config_init_6_1;
7610 __cw_config_init_6_value
7611 };
7612 assert!(
7613 !owned_generation_is_dangling(OAuthProvider::Xai, &unconfigured),
7614 "an unconfigured OAuth mode must not be reported as dangling"
7615 );
7616
7617 clear_dangling_generation(OAuthProvider::Xai, Some(&config_path))
7618 .expect("best-effort repair must clear the stale pointer");
7619
7620 let persisted = fs::read_to_string(&config_path).unwrap();
7621 assert!(
7622 !persisted.contains(stale),
7623 "stale generation pointer must be cleared: {persisted}"
7624 );
7625 assert!(
7626 persisted.contains("auth_mode = \"oauth\""),
7627 "the user's OAuth mode selection must be preserved: {persisted}"
7628 );
7629 }
7630
7631 #[test]
7632 fn activation_rejects_a_non_string_generation_pointer_without_staging_credentials() {
7633 let _guard = crate::test_support::lock_test_env();
7634 let dir = TempDir::new().unwrap();
7635 let home = dir
7636 .path()
7637 .canonicalize()
7638 .expect("canonical temp root")
7639 .join("owned-home");
7640 let config_path = dir.path().join("config.toml");
7641 let original = "[providers.xai]\noauth_credential_generation = { path = \"attacker\" }\n";
7642 fs::write(&config_path, original).unwrap();
7643 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7644
7645 let error = activate_login(
7646 pending_login("must-not-stage", "must-not-persist"),
7647 Some(&config_path),
7648 None,
7649 )
7650 .expect_err("non-string generation pointers must fail closed");
7651 assert!(error.to_string().contains("not activated"), "{error:#}");
7652 assert_eq!(fs::read_to_string(&config_path).unwrap(), original);
7653 let credentials = home.join("credentials");
7654 assert!(credentials.exists(), "lifecycle lock directory is durable");
7655 assert!(fs::read_dir(credentials).unwrap().all(|entry| {
7656 let name = entry.unwrap().file_name();
7657 let name = name.to_string_lossy();
7658 name != codewhale_config::LEGACY_XAI_OAUTH_FILE_NAME
7659 && !codewhale_config::is_valid_xai_oauth_generation(&name)
7660 }));
7661 }
7662
7663 #[cfg(unix)]
7664 #[test]
7665 fn activation_failure_cleans_unreferenced_stage_and_keeps_live_config_inert() {
7666 let _guard = crate::test_support::lock_test_env();
7667 let dir = TempDir::new().unwrap();
7668 let home = dir
7669 .path()
7670 .canonicalize()
7671 .expect("canonical temp root")
7672 .join("owned-home");
7673 let config_dir = dir.path().join("config-parent");
7674 fs::create_dir(&config_dir).unwrap();
7675 let config_path = config_dir.join("config.toml");
7676 fs::write(&config_path, "[providers.xai]\nauth_mode = \"api_key\"\n").unwrap();
7677 fs::create_dir(config_dir.join("config.toml.bak")).unwrap();
7678 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7679 let legacy_path = seed_legacy_owned_credentials();
7680 let legacy_before = fs::read(&legacy_path).unwrap();
7681 let mut live = {
7682 let __cw_config_init_7_0 = Some(crate::config::ProvidersConfig {
7683 xai: crate::config::ProviderConfig {
7684 auth_mode: Some("api_key".to_string()),
7685 api_key: Some("still-selected".to_string()),
7686 ..Default::default()
7687 },
7688 ..Default::default()
7689 });
7690 let mut __cw_config_init_7_value: Config = Default::default();
7691 __cw_config_init_7_value.providers = __cw_config_init_7_0;
7692 __cw_config_init_7_value
7693 };
7694
7695 let result = activate_login(
7696 pending_login("must-be-cleaned", "must-not-persist"),
7697 Some(&config_path),
7698 Some(&mut live),
7699 );
7700 let error = result.expect_err("invalid backup path must fail activation");
7701 assert!(error.to_string().contains("not activated"), "{error:#}");
7702 let live_xai = live
7703 .provider_config_for(&live.test_identity_for_kind(ProviderKind::Xai))
7704 .unwrap();
7705 assert_eq!(live_xai.auth_mode.as_deref(), Some("api_key"));
7706 assert!(live_xai.oauth_credential_generation.is_none());
7707 assert_eq!(
7708 fs::read(&legacy_path).unwrap(),
7709 legacy_before,
7710 "legacy owned credentials must remain byte-identical until activation commits"
7711 );
7712 let credentials = home.join("credentials");
7713 if credentials.exists() {
7714 assert!(
7715 fs::read_dir(credentials).unwrap().all(|entry| {
7716 let name = entry.unwrap().file_name();
7717 let name = name.to_string_lossy();
7718 name == codewhale_config::LEGACY_XAI_OAUTH_FILE_NAME
7719 || !codewhale_config::is_valid_xai_oauth_generation(&name)
7720 }),
7721 "failed activation must remove every unreferenced generation but retain legacy"
7722 );
7723 }
7724 assert!(
7725 !fs::read_to_string(config_path)
7726 .unwrap()
7727 .contains("must-be-cleaned")
7728 );
7729 }
7730
7731 #[test]
7732 fn missing_file_message_mentions_oauth_paths() {
7733 let _guard = crate::test_support::lock_test_env();
7734 let msg = missing_auth_message(OAuthProvider::Xai);
7735 assert!(msg.contains("xAI OAuth credentials not found"), "{msg}");
7736 assert!(msg.contains("external-consent"), "{msg}");
7737 assert!(msg.contains("Codewhale-owned OAuth storage"), "{msg}");
7738 assert!(msg.contains("XAI_API_KEY"), "{msg}");
7739 }
7740
7741 #[test]
7742 fn parse_rfc3339_accepts_zulu() {
7743 let ts = parse_rfc3339_secs("2026-07-09T12:00:00.000Z").expect("parse");
7744 assert!(ts > 0);
7745 }
7746
7747 #[test]
7748 fn device_code_constants_match_discovery_shape() {
7749 assert_eq!(
7750 DEFAULT_SCOPES.split_whitespace().collect::<Vec<_>>(),
7751 [
7752 "openid",
7753 "profile",
7754 "email",
7755 "offline_access",
7756 "api:access",
7757 "grok-cli:access",
7758 ]
7759 );
7760 assert_eq!(XAI_OIDC_ISSUER, "https://auth.x.ai");
7761 assert_eq!(GROK_OIDC_CLIENT_ID.len(), 36);
7762 }
7763
7764 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7765 async fn discovery_binds_to_advertised_endpoints() {
7766 let server = MockServer::start().await;
7767 Mock::given(method("GET"))
7768 .and(path("/.well-known/openid-configuration"))
7769 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
7770 "issuer": server.uri(),
7771 "device_authorization_endpoint": format!("{}/oauth2/device-advertised", server.uri()),
7772 "token_endpoint": format!("{}/oauth2/token-advertised", server.uri())
7773 })))
7774 .expect(1)
7775 .mount(&server)
7776 .await;
7777
7778 let endpoints = tokio::task::block_in_place(|| {
7779 discover_oauth_endpoints(&XAI_OAUTH_PARAMS, &server.uri()).expect("discover endpoints")
7780 });
7781
7782 assert_eq!(
7783 endpoints,
7784 OAuthEndpoints {
7785 device_authorization_endpoint: Some(format!(
7786 "{}/oauth2/device-advertised",
7787 server.uri()
7788 )),
7789 token_endpoint: format!("{}/oauth2/token-advertised", server.uri()),
7790 }
7791 );
7792 }
7793
7794 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7795 async fn refresh_uses_discovered_token_endpoint() {
7796 let server = MockServer::start().await;
7797 Mock::given(method("GET"))
7798 .and(path("/.well-known/openid-configuration"))
7799 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
7800 "issuer": server.uri(),
7801 "device_authorization_endpoint": format!("{}/oauth2/device-advertised", server.uri()),
7802 "token_endpoint": format!("{}/oauth2/token-advertised", server.uri())
7803 })))
7804 .expect(1)
7805 .mount(&server)
7806 .await;
7807 Mock::given(method("POST"))
7808 .and(path("/oauth2/token-advertised"))
7809 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
7810 "access_token": "refreshed-access",
7811 "refresh_token": "rotated-refresh",
7812 "expires_in": 3600
7813 })))
7814 .expect(1)
7815 .mount(&server)
7816 .await;
7817
7818 let token = tokio::task::block_in_place(|| {
7819 refresh_for_provider(
7820 OAuthProvider::Xai,
7821 &ReqwestOAuthFormClient,
7822 &server.uri(),
7823 GROK_OIDC_CLIENT_ID,
7824 "refresh-secret",
7825 )
7826 .expect("refresh token")
7827 });
7828
7829 assert_eq!(token.access_token.as_deref(), Some("refreshed-access"));
7830 assert_eq!(token.refresh_token.as_deref(), Some("rotated-refresh"));
7831 }
7832
7833 #[test]
7834 fn https_discovery_rejects_plaintext_endpoint_downgrade() {
7835 let error = validate_discovered_oauth_endpoint(
7836 Some("http://auth.x.ai/oauth2/device/code".to_string()),
7837 "device_authorization_endpoint",
7838 XAI_OIDC_ISSUER,
7839 )
7840 .expect_err("HTTPS issuer must reject an HTTP endpoint");
7841
7842 assert!(error.to_string().contains("downgrade"), "{error}");
7843 }
7844
7845 #[test]
7846 fn https_discovery_accepts_same_origin_with_explicit_default_port() {
7847 let endpoint = "https://auth.x.ai:443/oauth2/token";
7848 let validated = validate_discovered_oauth_endpoint(
7849 Some(endpoint.to_string()),
7850 "token_endpoint",
7851 XAI_OIDC_ISSUER,
7852 )
7853 .expect("URL origins normalize the explicit default HTTPS port");
7854
7855 assert_eq!(validated, endpoint);
7856 }
7857
7858 #[test]
7859 fn https_discovery_rejects_cross_origin_endpoint() {
7860 let error = validate_discovered_oauth_endpoint(
7861 Some("https://oauth.attacker.example/oauth2/token".to_string()),
7862 "token_endpoint",
7863 XAI_OIDC_ISSUER,
7864 )
7865 .expect_err("discovered OAuth endpoints must stay on the issuer origin");
7866
7867 assert!(error.to_string().contains("different origin"), "{error}");
7868 }
7869
7870 #[test]
7871 fn discovery_rejects_mismatched_issuer() {
7872 let error = validate_discovered_issuer(
7873 Some("https://attacker.example".to_string()),
7874 XAI_OIDC_ISSUER,
7875 )
7876 .expect_err("discovery issuer must bind to the request issuer");
7877
7878 assert!(error.to_string().contains("does not match"), "{error}");
7879 }
7880
7881 #[test]
7882 fn oauth_error_details_collapse_control_whitespace() {
7883 let detail = oauth_failure_detail(
7884 Some("invalid_scope\nforged"),
7885 Some("bad\t scope\r\nnext line"),
7886 reqwest::StatusCode::BAD_REQUEST,
7887 );
7888
7889 assert!(
7890 !detail
7891 .chars()
7892 .any(|character| matches!(character, '\n' | '\r' | '\t')),
7893 "{detail}"
7894 );
7895 assert!(detail.contains("invalid_scope forged"), "{detail}");
7896 assert!(detail.contains("bad scope next line"), "{detail}");
7897 }
7898
7899 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7900 async fn discovery_failure_uses_documented_endpoint_fallback() {
7901 let server = MockServer::start().await;
7902 Mock::given(method("GET"))
7903 .and(path("/.well-known/openid-configuration"))
7904 .respond_with(
7905 ResponseTemplate::new(503)
7906 .set_body_raw("<html>temporarily unavailable</html>", "text/html"),
7907 )
7908 .expect(1)
7909 .mount(&server)
7910 .await;
7911
7912 let endpoints = tokio::task::block_in_place(|| {
7913 resolve_oauth_endpoints(&XAI_OAUTH_PARAMS, &server.uri())
7914 });
7915
7916 assert_eq!(
7917 endpoints,
7918 OAuthEndpoints {
7919 device_authorization_endpoint: Some(format!("{}/oauth2/device/code", server.uri())),
7920 token_endpoint: format!("{}/oauth2/token", server.uri()),
7921 }
7922 );
7923 }
7924
7925 /// End-to-end regression for the v0.9.4 dogfood failure (#5032): starting
7926 /// from the exact state the dogfood machine was bricked in — a
7927 /// `providers.xai.oauth_credential_generation` pointer whose credential
7928 /// file no longer exists — the full device flow (discovery, device-code
7929 /// request, token poll, activation) must succeed and replace the stale
7930 /// pointer instead of dying with "xAI login was not activated; provider
7931 /// configuration is unchanged".
7932 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7933 async fn device_login_end_to_end_recovers_from_dangling_generation_pointer() {
7934 let _guard = crate::test_support::lock_test_env();
7935 let server = MockServer::start().await;
7936 Mock::given(method("GET"))
7937 .and(path("/.well-known/openid-configuration"))
7938 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
7939 "issuer": server.uri(),
7940 "device_authorization_endpoint": format!("{}/oauth2/device-advertised", server.uri()),
7941 "token_endpoint": format!("{}/oauth2/token-advertised", server.uri())
7942 })))
7943 .expect(1)
7944 .mount(&server)
7945 .await;
7946 Mock::given(method("POST"))
7947 .and(path("/oauth2/device-advertised"))
7948 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
7949 "device_code": "device-token",
7950 "user_code": "CW-TEST",
7951 "verification_uri": format!("{}/verify", server.uri()),
7952 "expires_in": 60,
7953 "interval": 1
7954 })))
7955 .expect(1)
7956 .mount(&server)
7957 .await;
7958 Mock::given(method("POST"))
7959 .and(path("/oauth2/token-advertised"))
7960 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
7961 "access_token": "e2e-xai-access",
7962 "refresh_token": "e2e-xai-refresh",
7963 "expires_in": 3600,
7964 "token_type": "Bearer"
7965 })))
7966 .expect(1)
7967 .mount(&server)
7968 .await;
7969
7970 let dir = TempDir::new().unwrap();
7971 let home = dir
7972 .path()
7973 .canonicalize()
7974 .expect("canonical temp root")
7975 .join("owned-home");
7976 let config_path = dir.path().join("config.toml");
7977 // The exact dogfood-machine state: valid-looking generation pointer,
7978 // missing credential file.
7979 let stale = "xai-auth-39a2f3e766ab47f89490002cd04fe187.json";
7980 fs::write(
7981 &config_path,
7982 format!(
7983 "[providers.xai]\nauth_mode = \"oauth\"\noauth_credential_generation = \"{stale}\"\n"
7984 ),
7985 )
7986 .unwrap();
7987 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
7988
7989 // The login half runs through the unified flow; only activation is
7990 // still legacy here (3b-ii unifies it).
7991 let inputs = crate::oauth::ResolvedOAuthInputs {
7992 issuer: server.uri(),
7993 client_id: GROK_OIDC_CLIENT_ID.to_string(),
7994 scopes: DEFAULT_SCOPES.to_string(),
7995 open_browser: false,
7996 };
7997 let unified = tokio::task::block_in_place(|| {
7998 crate::oauth::device_code_login_with(
7999 crate::oauth::OAuthProvider::Xai,
8000 &inputs,
8001 &mut std::io::sink(),
8002 )
8003 })
8004 .expect("device login against mock xAI");
8005 let pending = unified;
8006 let mut live = Config::default();
8007 let activation = activate_login(pending, Some(&config_path), Some(&mut live))
8008 .expect("dangling pointer must not brick activation");
8009
8010 assert!(activation.auth_path.exists());
8011 let owned = fs::read_to_string(&activation.auth_path).unwrap();
8012 assert!(owned.contains("e2e-xai-access"));
8013 assert!(owned.contains("e2e-xai-refresh"));
8014 let persisted = fs::read_to_string(&config_path).unwrap();
8015 assert!(
8016 !persisted.contains(stale),
8017 "stale pointer must be replaced: {persisted}"
8018 );
8019 assert!(persisted.contains(activation.auth_path.file_name().unwrap().to_str().unwrap()));
8020 assert!(persisted.contains("auth_mode = \"oauth\""));
8021 assert!(
8022 credentials_valid(OAuthProvider::Xai, &live),
8023 "activated login must be usable"
8024 );
8025 }
8026
8027 #[test]
8028 fn apply_token_response_sets_expiry_from_expires_in() {
8029 let mut entry = OwnedAuthEntry {
8030 access_token: None,
8031 refresh_token: None,
8032 expires_at: None,
8033 id_token: None,
8034 account_id: None,
8035 oidc_issuer: None,
8036 oidc_client_id: None,
8037 originator: None,
8038 auth_mode: None,
8039 extra: BTreeMap::new(),
8040 };
8041 let token = OAuthTokenMaterial {
8042 earliest_refresh_at: None,
8043 scope: None,
8044 token_type: None,
8045 verified_chatgpt: None,
8046 id_token: None,
8047 access_token: Some("fresh-access".to_string()),
8048 refresh_token: Some("fresh-refresh".to_string()),
8049 expires_in: Some(3600),
8050 error: None,
8051 error_description: None,
8052 interval: None,
8053 };
8054 let before = now_unix_secs().expect("clock");
8055
8056 apply_token_response(
8057 OAuthProvider::Xai,
8058 &mut entry,
8059 XAI_OIDC_ISSUER,
8060 GROK_OIDC_CLIENT_ID,
8061 &token,
8062 )
8063 .expect("apply token");
8064
8065 assert_eq!(entry.access_token.as_deref(), Some("fresh-access"));
8066 assert_eq!(entry.refresh_token.as_deref(), Some("fresh-refresh"));
8067 let expires_at = entry
8068 .expires_at
8069 .as_deref()
8070 .and_then(parse_rfc3339_secs)
8071 .expect("expires_at set from expires_in");
8072 let after = now_unix_secs().expect("clock");
8073 assert!(
8074 expires_at >= before + 3600,
8075 "{expires_at} < {before} + 3600"
8076 );
8077 assert!(expires_at <= after + 3600, "{expires_at} > {after} + 3600");
8078 }
8079
8080 #[test]
8081 fn apply_token_response_rejects_missing_access_token() {
8082 let mut entry = OwnedAuthEntry {
8083 access_token: None,
8084 refresh_token: None,
8085 expires_at: None,
8086 id_token: None,
8087 account_id: None,
8088 oidc_issuer: None,
8089 oidc_client_id: None,
8090 originator: None,
8091 auth_mode: None,
8092 extra: BTreeMap::new(),
8093 };
8094 let token = OAuthTokenMaterial {
8095 earliest_refresh_at: None,
8096 scope: None,
8097 token_type: None,
8098 verified_chatgpt: None,
8099 id_token: None,
8100 access_token: None,
8101 refresh_token: None,
8102 expires_in: None,
8103 error: None,
8104 error_description: None,
8105 interval: None,
8106 };
8107
8108 let error = apply_token_response(
8109 OAuthProvider::Xai,
8110 &mut entry,
8111 XAI_OIDC_ISSUER,
8112 GROK_OIDC_CLIENT_ID,
8113 &token,
8114 )
8115 .expect_err("missing access_token must fail");
8116
8117 assert!(
8118 error.to_string().contains("missing access_token"),
8119 "{error}"
8120 );
8121 }
8122
8123 struct MockTokenClient {
8124 responses: Mutex<Vec<(u16, String)>>,
8125 posts: Mutex<Vec<MockPost>>,
8126 }
8127
8128 impl MockTokenClient {
8129 fn new(responses: Vec<(u16, String)>) -> Self {
8130 Self {
8131 responses: Mutex::new(responses),
8132 posts: Mutex::new(Vec::new()),
8133 }
8134 }
8135 }
8136
8137 impl crate::oauth::OAuthFormClient for MockTokenClient {
8138 fn post_form(&self, url: &str, form: &[(&str, &str)]) -> Result<(u16, String)> {
8139 self.posts.lock().expect("posts").push((
8140 url.to_string(),
8141 form.iter()
8142 .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
8143 .collect(),
8144 ));
8145 let mut responses = self.responses.lock().expect("responses");
8146 anyhow::ensure!(
8147 !responses.is_empty(),
8148 "mock issuer has no remaining responses"
8149 );
8150 Ok(responses.remove(0))
8151 }
8152 }
8153
8154 fn jwt_with_exp(exp: u64) -> String {
8155 let payload = URL_SAFE_NO_PAD.encode(format!(r#"{{"exp":{exp}}}"#));
8156 format!("header.{payload}.sig")
8157 }
8158
8159 #[test]
8160 fn siwc_legacy_credentials_require_reauthorization_and_revoke_retains_host() {
8161 let _lock = crate::test_support::lock_test_env();
8162 let home = tempfile::tempdir().expect("temp home");
8163 let root = home.path().canonicalize().expect("canonical home");
8164 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
8165 let config_path = root.join("config.toml");
8166 std::fs::write(&config_path, "").expect("empty config");
8167
8168 let pending = pending_login_with_id_token_for_test(
8169 OAuthProvider::Chatgpt,
8170 "access-1",
8171 "refresh-1",
8172 Some(&jwt_with_account("acct-7")),
8173 );
8174 let activation = activate_login(pending, Some(&config_path), None).expect("activate");
8175 assert!(activation.auth_path.exists());
8176 let persisted = std::fs::read_to_string(root.join("config.toml")).expect("config");
8177 assert!(persisted.contains("chatgpt-auth-"));
8178 assert!(persisted.contains("auth_mode = \"oauth\""));
8179 assert!(!persisted.contains("access-1"), "{persisted}");
8180
8181 let generation = toml::from_str::<toml::Value>(&persisted)
8182 .unwrap()["providers"]["openai_codex"]["oauth_credential_generation"]
8183 .as_str()
8184 .unwrap()
8185 .to_string();
8186 let mut config = {
8187 let __cw_config_init_8_0 = Some(ProviderKind::OpenaiCodex.as_str().to_string());
8188 let mut __cw_config_init_8_value: Config = Config::default();
8189 __cw_config_init_8_value.provider = __cw_config_init_8_0;
8190 __cw_config_init_8_value
8191 };
8192 config
8193 .mark_codewhale_owned_chatgpt_oauth(generation.clone())
8194 .expect("admitted OAuth fixture");
8195 assert!(credentials_valid(OAuthProvider::Chatgpt, &config));
8196
8197 let stale = jwt_with_exp(1_000_000_000);
8198 let scope = format!("{CHATGPT_OAUTH_ISSUER}::{CHATGPT_OAUTH_CLIENT_ID}");
8199 let raw = serde_json::json!({
8200 &scope: {
8201 "access_token": stale,
8202 "refresh_token": "refresh-old",
8203 // Conflicting metadata must not suppress the existing refresh.
8204 "expires_at": rfc3339_from_now(3600),
8205 "oidc_issuer": CHATGPT_OAUTH_ISSUER,
8206 "oidc_client_id": CHATGPT_OAUTH_CLIENT_ID,
8207 "originator": "codewhale"
8208 }
8209 });
8210 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
8211 store.write(
8212 &generation,
8213 serde_json::to_vec_pretty(&raw).unwrap().as_slice(),
8214 true,
8215 )
8216 })
8217 .unwrap();
8218
8219 let mock = MockTokenClient::new(vec![(
8220 200,
8221 serde_json::json!({
8222 "access_token": "access-2",
8223 "refresh_token": "refresh-2",
8224 "expires_in": 3600
8225 })
8226 .to_string(),
8227 )]);
8228 let error = match get_owned_credentials_with(OAuthProvider::Chatgpt, &config, &mock) {
8229 Ok(_) => panic!("legacy credentials must not be sent to the official API"),
8230 Err(error) => error.to_string(),
8231 };
8232 assert!(error.contains("reauthorization"), "{error}");
8233 assert!(
8234 mock.posts.lock().unwrap().is_empty(),
8235 "legacy tokens must not be refreshed"
8236 );
8237
8238 let revoke_mock = MockTokenClient::new(vec![(200, String::new())]);
8239 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
8240 revoke_owned_login_locked_with(
8241 OAuthProvider::Chatgpt,
8242 Some(&config_path),
8243 None,
8244 store,
8245 &revoke_mock,
8246 )
8247 })
8248 .expect("revoke");
8249 let after = std::fs::read_to_string(&config_path).expect("config after revoke");
8250 assert!(!after.contains("chatgpt-auth-"), "{after}");
8251 let host_path = root
8252 .join("credentials")
8253 .join(codewhale_config::CHATGPT_HOST_FILE_NAME);
8254 assert!(host_path.exists(), "signout retains host metadata");
8255 let host_after: ChatgptHost = serde_json::from_str(
8256 &std::fs::read_to_string(&host_path).expect("read host after revoke"),
8257 )
8258 .expect("parse host after revoke");
8259 assert!(
8260 host_after.host_id.starts_with("urn:uuid:"),
8261 "signout preserves host_id"
8262 );
8263 assert_eq!(
8264 host_after.registration, None,
8265 "signout clears sticky ChatGPT registration"
8266 );
8267 let posts = revoke_mock.posts.lock().unwrap();
8268 assert!(
8269 posts.iter().any(|(url, _)| url.contains("/oauth/revoke")),
8270 "{posts:?}"
8271 );
8272 }
8273
8274 #[test]
8275 fn chatgpt_revoke_removes_durable_tokens_when_live_mirror_refuses() {
8276 let _lock = crate::test_support::lock_test_env();
8277 let home = tempfile::tempdir().expect("temp home");
8278 let root = home.path().canonicalize().expect("canonical home");
8279 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
8280 let config_path = root.join("config.toml");
8281 std::fs::write(&config_path, "").expect("empty config");
8282 let pending = pending_login_with_id_token_for_test(
8283 OAuthProvider::Chatgpt,
8284 "access-1",
8285 "refresh-1",
8286 Some(&jwt_with_account("acct-7")),
8287 );
8288 let activation = activate_login(pending, Some(&config_path), None).expect("activate");
8289 assert!(activation.auth_path.exists());
8290 let mut live = Config::default();
8291 live.providers
8292 .get_or_insert_with(Default::default)
8293 .custom
8294 .insert(
8295 ProviderKind::OpenaiCodex.as_str().to_string(),
8296 crate::config::ProviderConfig {
8297 kind: Some("openai-compatible".to_string()),
8298 base_url: Some("http://localhost:1234/v1".to_string()),
8299 ..Default::default()
8300 },
8301 );
8302 assert!(live.clear_codewhale_owned_chatgpt_oauth().is_err());
8303 let mock = MockTokenClient::new(vec![(200, String::new())]);
8304 let error = codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
8305 revoke_owned_login_locked_with(
8306 OAuthProvider::Chatgpt,
8307 Some(&config_path),
8308 Some(&mut live),
8309 store,
8310 &mock,
8311 )
8312 })
8313 .expect_err("live mirror refusal remains visible");
8314 assert!(error.to_string().contains("Signed out locally"));
8315 assert!(
8316 !activation.auth_path.exists(),
8317 "local tokens cannot survive a refused mirror"
8318 );
8319 let after = std::fs::read_to_string(&config_path).expect("config after revoke");
8320 assert!(
8321 !after.contains("chatgpt-auth-"),
8322 "durable generation pointer removed"
8323 );
8324 assert_eq!(
8325 mock.posts.lock().unwrap().len(),
8326 1,
8327 "one captured remote revoke"
8328 );
8329 }
8330
8331 #[test]
8332 fn chatgpt_login_mode_fresh_account_omits_login_hint_and_reauth_pins_registration() {
8333 let _lock = crate::test_support::lock_test_env();
8334 let home = tempfile::tempdir().expect("temp home");
8335 let root = home.path().canonicalize().expect("canonical home");
8336 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
8337
8338 let initial_host =
8339 prepare_chatgpt_host_for_mode(ChatgptLoginMode::FreshAccount).expect("initial host");
8340 assert_eq!(initial_host.registration, None);
8341 let host_id = initial_host.host_id.clone();
8342
8343 let saved_reg = ChatgptRegistration {
8344 issuer: CHATGPT_OAUTH_ISSUER.to_string(),
8345 client_id: "oaiapp_saved_client".to_string(),
8346 subject: "sub-old".to_string(),
8347 email: Some("old@example.com".to_string()),
8348 host_id: host_id.clone(),
8349 };
8350 codewhale_config::with_xai_oauth_lifecycle_lock(|store| {
8351 let bytes = serde_json::to_vec(&ChatgptHost {
8352 host_id: host_id.clone(),
8353 registration: Some(saved_reg.clone()),
8354 })?;
8355 store.write(codewhale_config::CHATGPT_HOST_FILE_NAME, &bytes, true)
8356 })
8357 .expect("persist saved registration");
8358
8359 let fresh_host =
8360 prepare_chatgpt_host_for_mode(ChatgptLoginMode::FreshAccount).expect("fresh host");
8361 assert_eq!(fresh_host.host_id, host_id);
8362 assert_eq!(fresh_host.registration, None);
8363 let fresh_url = apply_chatgpt_host_to_authorize_url(
8364 "https://auth.openai.com/oauth/authorize",
8365 &fresh_host,
8366 )
8367 .expect("fresh authorize url");
8368 assert!(fresh_url.contains("ext_agent_host_id="), "{fresh_url}");
8369 assert!(!fresh_url.contains("login_hint="), "{fresh_url}");
8370
8371 let reauth_host = prepare_chatgpt_host_for_mode(ChatgptLoginMode::ReauthorizeCurrent)
8372 .expect("reauth host");
8373 assert_eq!(reauth_host.host_id, host_id);
8374 assert_eq!(reauth_host.registration.as_ref(), Some(&saved_reg));
8375 let reauth_url = apply_chatgpt_host_to_authorize_url(
8376 "https://auth.openai.com/oauth/authorize",
8377 &reauth_host,
8378 )
8379 .expect("reauth authorize url");
8380 assert!(reauth_url.contains("ext_agent_host_id="), "{reauth_url}");
8381 assert!(
8382 reauth_url.contains("login_hint=old%40example.com"),
8383 "{reauth_url}"
8384 );
8385
8386 let _override = crate::test_support::EnvVarGuard::set("CODEWHALE_CHATGPT_NEW_ACCOUNT", "1");
8387 let overridden_host = prepare_chatgpt_host_for_mode(ChatgptLoginMode::ReauthorizeCurrent)
8388 .expect("overridden host");
8389 assert_eq!(overridden_host.host_id, host_id);
8390 assert_eq!(overridden_host.registration, None);
8391 }
8392
8393 #[test]
8394 fn debug_impls_redact_secrets() {
8395 let file = CodexAuthFile {
8396 tokens: Some(AuthTokens {
8397 access_token: Some("synthetic-codex-bearer".into()),
8398 }),
8399 };
8400 let credentials = CodexCredentials {
8401 access_token: "synthetic-codex-bearer".into(),
8402 };
8403 for rendered in [format!("{file:?}"), format!("{credentials:?}")] {
8404 assert!(rendered.contains("<redacted>"));
8405 assert!(!rendered.contains("synthetic-codex-bearer"));
8406 }
8407 let entry = OwnedAuthEntry {
8408 access_token: Some("secret-access".into()),
8409 refresh_token: Some("secret-refresh".into()),
8410 expires_at: None,
8411 id_token: Some("secret-id".into()),
8412 account_id: None,
8413 oidc_issuer: None,
8414 oidc_client_id: None,
8415 originator: None,
8416 auth_mode: None,
8417 extra: BTreeMap::new(),
8418 };
8419 let rendered = format!("{entry:?}");
8420 assert!(rendered.contains("<redacted>"));
8421 assert!(!rendered.contains("secret-access"));
8422 assert!(!rendered.contains("secret-refresh"));
8423 assert!(!rendered.contains("secret-id"));
8424
8425 let activation = OAuthActivation {
8426 credentials: OwnedOAuthCredentials {
8427 access_token: "secret-access".into(),
8428 account_id: None,
8429 account_label: None,
8430 refresh_token: Some("secret-refresh".into()),
8431 expires_at: None,
8432 issuer: "issuer".into(),
8433 client_id: "client".into(),
8434 },
8435 config_path: PathBuf::from("/tmp/config.toml"),
8436 auth_path: PathBuf::from("/tmp/auth.json"),
8437 provider: OAuthProvider::Chatgpt,
8438 account_label: Some("a@example.com (plus)".into()),
8439 replaced: None,
8440 };
8441 let rendered = format!("{activation:?}");
8442 assert!(rendered.contains("<redacted>"));
8443 assert!(!rendered.contains("secret-access"));
8444 }
8445
8446 #[test]
8447 fn siwc_signed_identity_requires_signature_issuer_audience_expiry_nonce_and_account() {
8448 let signer = SiwcSigningFixture::new();
8449 let verify = |token: &str| {
8450 verify_chatgpt_id_token(
8451 token,
8452 &signer.keys,
8453 CHATGPT_OAUTH_ISSUER,
8454 "oaiapp_codewhale_test",
8455 Some("pending-nonce"),
8456 Some("test-sub"),
8457 "urn:uuid:00000000-0000-4000-8000-000000000001",
8458 )
8459 };
8460 let claims = signer.id_claims();
8461 let signed = signer.token(claims.clone());
8462 assert_eq!(verify(&signed).unwrap().subject, "test-sub");
8463 let mut other_sub_claims = claims.clone();
8464 other_sub_claims["sub"] = Value::from("another-subject");
8465 let fresh_verified = verify_chatgpt_id_token(
8466 &signer.token(other_sub_claims),
8467 &signer.keys,
8468 CHATGPT_OAUTH_ISSUER,
8469 CHATGPT_OAUTH_CLIENT_ID,
8470 Some("pending-nonce"),
8471 None,
8472 "urn:uuid:00000000-0000-4000-8000-000000000001",
8473 );
8474 assert!(
8475 fresh_verified.is_err(),
8476 "audience mismatch still fails even without expected_subject"
8477 );
8478 let mut fresh_claims = claims.clone();
8479 fresh_claims["sub"] = Value::from("another-subject");
8480 fresh_claims["aud"] = Value::from("oaiapp_fresh_client");
8481 assert_eq!(
8482 verify_chatgpt_id_token(
8483 &signer.token(fresh_claims),
8484 &signer.keys,
8485 CHATGPT_OAUTH_ISSUER,
8486 "oaiapp_fresh_client",
8487 Some("pending-nonce"),
8488 None,
8489 "urn:uuid:00000000-0000-4000-8000-000000000001",
8490 )
8491 .unwrap()
8492 .subject,
8493 "another-subject"
8494 );
8495 for (field, wrong, expected) in [
8496 ("iss", Value::from("https://other.invalid"), "issuer"),
8497 ("aud", Value::from("oaiapp_other"), "audience"),
8498 (
8499 "aud",
8500 serde_json::json!(["oaiapp_codewhale_test", "another-audience"]),
8501 "audience",
8502 ),
8503 ("exp", Value::from(1), "expired"),
8504 (
8505 "nbf",
8506 Value::from(now_unix_secs().unwrap() + 3600),
8507 "not valid yet",
8508 ),
8509 ("nonce", Value::from("another-nonce"), "nonce"),
8510 ("sub", Value::from("another-subject"), "different account"),
8511 ("sub", Value::from(""), "no subject"),
8512 ] {
8513 let mut changed = claims.clone();
8514 changed[field] = wrong;
8515 let error = verify(&signer.token(changed)).unwrap_err().to_string();
8516 assert!(error.contains(expected), "invalid {field}: {error}");
8517 }
8518 let mut skewed = claims.clone();
8519 skewed["nbf"] = Value::from(now_unix_secs().unwrap() + 15);
8520 assert!(
8521 verify(&signer.token(skewed)).is_ok(),
8522 "a small clock skew must not reject a valid identity token"
8523 );
8524 let verify_with = |keys: &ChatgptKeys, token: &str| {
8525 verify_chatgpt_id_token(
8526 token,
8527 keys,
8528 CHATGPT_OAUTH_ISSUER,
8529 "oaiapp_codewhale_test",
8530 Some("pending-nonce"),
8531 Some("test-sub"),
8532 "urn:uuid:00000000-0000-4000-8000-000000000001",
8533 )
8534 };
8535 let local_now = now_unix_secs().unwrap();
8536 for (issuer_offset, field, value, accepted) in [
8537 (None, "nbf", local_now + 15, true),
8538 (None, "exp", local_now - 15, true),
8539 (None, "nbf", local_now + 90, false),
8540 (None, "exp", local_now - 90, false),
8541 (Some(90), "nbf", local_now + 90, true),
8542 (Some(90), "exp", local_now - 15, false),
8543 (Some(-90), "exp", local_now - 75, true),
8544 (Some(-90), "nbf", local_now + 90, false),
8545 ] {
8546 let mut changed = claims.clone();
8547 changed[field] = Value::from(value);
8548 let keys = ChatgptKeys {
8549 issuer_clock_offset: issuer_offset,
8550 ..signer.keys.clone()
8551 };
8552 assert_eq!(
8553 verify_with(&keys, &signer.token(changed)).is_ok(),
8554 accepted,
8555 "{field}={value} with issuer clock offset {issuer_offset:?}"
8556 );
8557 }
8558 let mut future = claims.clone();
8559 future["nbf"] = Value::from(local_now + 2 * 3600);
8560 let issuer_ahead = ChatgptKeys {
8561 issuer_clock_offset: Some(900),
8562 ..signer.keys.clone()
8563 };
8564 let error = verify_with(&issuer_ahead, &signer.token(future))
8565 .unwrap_err()
8566 .to_string();
8567 assert!(
8568 error.contains("not valid yet by the issuer's clock") && error.contains("900 s behind"),
8569 "{error}"
8570 );
8571 let stale = ChatgptKeys::from(JwkSet { keys: Vec::new() });
8572 let fetches = std::cell::Cell::new(0);
8573 let rotated = chatgpt_keys_covering(&[&signed], || {
8574 fetches.set(fetches.get() + 1);
8575 Ok(if fetches.get() == 1 {
8576 stale.clone()
8577 } else {
8578 signer.keys.clone()
8579 })
8580 })
8581 .unwrap();
8582 assert_eq!(fetches.get(), 2, "an unknown key id refetches once");
8583 assert!(verify_with(&rotated, &signed).is_ok());
8584 fetches.set(0);
8585 let still_stale = chatgpt_keys_covering(&[&signed], || {
8586 fetches.set(fetches.get() + 1);
8587 Ok(stale.clone())
8588 })
8589 .unwrap();
8590 assert_eq!(fetches.get(), 2, "the refetch happens only once");
8591 assert!(
8592 verify_with(&still_stale, &signed)
8593 .unwrap_err()
8594 .to_string()
8595 .contains("verification key is unknown")
8596 );
8597 fetches.set(0);
8598 chatgpt_keys_covering(&[&signed], || {
8599 fetches.set(fetches.get() + 1);
8600 Ok(signer.keys.clone())
8601 })
8602 .unwrap();
8603 assert_eq!(fetches.get(), 1, "known keys are fetched once");
8604 for required in ["iss", "aud", "exp", "sub", "nonce"] {
8605 let mut changed = claims.clone();
8606 changed.as_object_mut().unwrap().remove(required);
8607 let error = verify(&signer.token(changed)).unwrap_err().to_string();
8608 let expected = if required == "nonce" {
8609 "nonce did not match".to_string()
8610 } else {
8611 format!("missing required {required} claim")
8612 };
8613 assert!(error.contains(&expected), "missing {required}: {error}");
8614 }
8615 let other_signer = SiwcSigningFixture::new();
8616 assert!(
8617 verify(&other_signer.token(claims.clone()))
8618 .unwrap_err()
8619 .to_string()
8620 .contains("signature verification failed")
8621 );
8622 let parts: Vec<_> = signed.split('.').collect();
8623 let bad_payload = URL_SAFE_NO_PAD.encode(br#"{"sub":"attacker"}"#);
8624 assert!(verify(&format!("{}.{}.{}", parts[0], bad_payload, parts[2])).is_err());
8625 let symmetric_header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","kid":"siwc-fixture"}"#);
8626 assert!(verify(&format!("{}.{}.{}", symmetric_header, parts[1], parts[2])).is_err());
8627 }
8628
8629 #[test]
8630 fn siwc_callback_and_grant_guards_reject_registration_substitution() {
8631 assert!(issued_callback_client_id(CHATGPT_OAUTH_CLIENT_ID, None).is_err());
8632 assert!(
8633 issued_callback_client_id(CHATGPT_OAUTH_CLIENT_ID, Some(CHATGPT_OAUTH_CLIENT_ID))
8634 .is_err()
8635 );
8636 assert_eq!(
8637 issued_callback_client_id(CHATGPT_OAUTH_CLIENT_ID, Some("oaiapp_first")).unwrap(),
8638 "oaiapp_first"
8639 );
8640 assert_eq!(
8641 issued_callback_client_id("oaiapp_first", None).unwrap(),
8642 "oaiapp_first"
8643 );
8644 assert!(issued_callback_client_id("oaiapp_first", Some("oaiapp_other")).is_err());
8645 assert!(require_chatgpt_scopes(Some("openid resource.invoke")).is_err());
8646 assert!(require_chatgpt_scopes(Some("chatgpt.tokens.use.direct")).is_err());
8647 assert!(require_chatgpt_scopes(Some(CHATGPT_OAUTH_SCOPE)).is_ok());
8648 assert!(parse_callback_query(&CHATGPT_OAUTH_PARAMS, "code=x&state=a&state=b").is_err());
8649 assert!(
8650 parse_callback_query(&CHATGPT_OAUTH_PARAMS, "code=x&state=a&error=denied").is_err()
8651 );
8652 let error = parse_callback_query(&CHATGPT_OAUTH_PARAMS, "error=access_denied").unwrap();
8653 assert!(accept_callback("pending", error).is_err());
8654 let success = parse_callback_query(
8655 &CHATGPT_OAUTH_PARAMS,
8656 "code=secret-code&state=a&client_id=oaiapp_first",
8657 )
8658 .unwrap();
8659 assert!(!format!("{success:?}").contains("secret-code"));
8660 }
8661
8662 #[test]
8663 fn siwc_signed_access_requires_resource_account_registration_and_plan_scope() {
8664 let signer = SiwcSigningFixture::new();
8665 let registration = verify_chatgpt_id_token(
8666 &signer.token(signer.id_claims()),
8667 &signer.keys,
8668 CHATGPT_OAUTH_ISSUER,
8669 "oaiapp_codewhale_test",
8670 Some("pending-nonce"),
8671 None,
8672 "host",
8673 )
8674 .unwrap();
8675 assert!(
8676 verify_chatgpt_access_token(&signer.access("test-sub"), &signer.keys, &registration)
8677 .is_ok()
8678 );
8679 assert!(
8680 verify_chatgpt_access_token(
8681 &signer.access("another-subject"),
8682 &signer.keys,
8683 &registration
8684 )
8685 .is_err()
8686 );
8687 for (field, wrong) in [
8688 ("aud", CHATGPT_OAUTH_ISSUER),
8689 ("client_id", "oaiapp_other"),
8690 ("scope", "openid resource.invoke"),
8691 ] {
8692 let mut claims = serde_json::json!({"iss": CHATGPT_OAUTH_ISSUER, "aud": CHATGPT_OAUTH_RESOURCE, "sub": "test-sub", "client_id": "oaiapp_codewhale_test", "scope": CHATGPT_OAUTH_SCOPE, "exp": now_unix_secs().unwrap() + 3600});
8693 claims[field] = Value::from(wrong);
8694 let token = signer.token(claims);
8695 assert!(
8696 verify_chatgpt_access_token(&token, &signer.keys, &registration).is_err(),
8697 "accepted invalid {field}"
8698 );
8699 }
8700 for (claim, broken, expected) in [
8701 ("client_id", None, "missing required client_id claim"),
8702 ("scope", None, "missing required scope claim"),
8703 (
8704 "scope",
8705 Some(serde_json::json!(["resource.invoke"])),
8706 "invalid scope claim format",
8707 ),
8708 ] {
8709 let mut claims = serde_json::json!({"iss": CHATGPT_OAUTH_ISSUER, "aud": CHATGPT_OAUTH_RESOURCE, "sub": "test-sub", "client_id": "oaiapp_codewhale_test", "scope": CHATGPT_OAUTH_SCOPE, "exp": now_unix_secs().unwrap() + 3600});
8710 match broken {
8711 Some(value) => claims[claim] = value,
8712 None => {
8713 claims.as_object_mut().unwrap().remove(claim);
8714 }
8715 }
8716 let error =
8717 verify_chatgpt_access_token(&signer.token(claims), &signer.keys, &registration)
8718 .unwrap_err()
8719 .to_string();
8720 assert!(error.contains(expected), "{claim}: {error}");
8721 }
8722 }
8723
8724 #[test]
8725 fn siwc_replacing_account_drops_previous_registration_and_token() {
8726 let _lock = crate::test_support::lock_test_env();
8727 let home = tempfile::tempdir().unwrap();
8728 let root = home.path().canonicalize().unwrap();
8729 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
8730 let config_path = root.join("config.toml");
8731 std::fs::write(&config_path, "").unwrap();
8732 let mut config = Config::default();
8733 let first = pending_login_for_test(OAuthProvider::Chatgpt, "first-access", "first-refresh");
8734 activate_login(first, Some(&config_path), Some(&mut config)).unwrap();
8735 let mut next =
8736 pending_login_for_test(OAuthProvider::Chatgpt, "next-access", "next-refresh");
8737 next.client_id = "oaiapp_next".to_string();
8738 let registration = next.token.verified_chatgpt.as_mut().unwrap();
8739 registration.client_id = "oaiapp_next".to_string();
8740 registration.subject = "next-sub".to_string();
8741 let activated = activate_login(next, Some(&config_path), Some(&mut config)).unwrap();
8742 let registration = official_chatgpt_registration(&config).unwrap();
8743 assert_eq!(registration.subject, "next-sub");
8744 assert_eq!(registration.client_id, "oaiapp_next");
8745 let raw = std::fs::read_to_string(activated.auth_path).unwrap();
8746 assert!(!raw.contains("first-access"));
8747 assert!(!raw.contains("first-refresh"));
8748 let mut file: AuthFile = serde_json::from_str(&raw).unwrap();
8749 assert_eq!(file.len(), 1);
8750 let (_, mut entry) = select_entry(OAuthProvider::Chatgpt, &mut file).unwrap();
8751 entry.account_id = Some("unverified-account".to_string());
8752 assert!(registration_from_entry(&entry).is_err());
8753 entry.account_id = Some("next-sub".to_string());
8754 entry.access_token = Some("unverified-replacement".to_string());
8755 assert!(registration_from_entry(&entry).is_err());
8756 }
8757
8758 // === OrcaRouter: API-key + PKCE adapters over one credential seam =======
8759
8760 fn orca_inputs(auth_base: &str) -> OrcaLoginInputs {
8761 OrcaLoginInputs {
8762 auth_base: auth_base.to_string(),
8763 api_base: "https://api.orcarouter.ai/v1".to_string(),
8764 app_name: ORCAROUTER_APP_NAME.to_string(),
8765 open_browser: false,
8766 }
8767 }
8768
8769 const ORCA_FAKE_KEY: &str = "sk-orca-test-key-not-a-real-credential";
8770
8771 #[test]
8772 fn orcarouter_api_key_adapter_shapes_and_rejects() {
8773 let from_key = OrcaCredential::from_api_key(&format!(" {ORCA_FAKE_KEY} ")).unwrap();
8774 assert_eq!(
8775 from_key.expose(),
8776 ORCA_FAKE_KEY,
8777 "outer whitespace is trimmed"
8778 );
8779 assert_eq!(from_key.source(), OrcaCredentialSource::ApiKey);
8780 assert_eq!(from_key.granted_scope(), ORCAROUTER_SCOPE);
8781 assert!(from_key.scope_satisfies_purpose());
8782
8783 for bad in ["", " ", "sk-openai-not-orca", "orca-key"] {
8784 let err = match OrcaCredential::from_api_key(bad) {
8785 Ok(_) => panic!("non-OrcaRouter key must be refused: {bad:?}"),
8786 Err(err) => err.to_string(),
8787 };
8788 assert!(!err.contains(bad) || bad.trim().is_empty(), "{err}");
8789 }
8790 }
8791
8792 /// Both adapters must produce the same credential type, and nothing about
8793 /// the adapter may be observable downstream beyond the presentation label.
8794 #[test]
8795 fn orcarouter_adapters_produce_the_same_credential_result() {
8796 let api_key = OrcaCredential::from_api_key(ORCA_FAKE_KEY).unwrap();
8797 let exchanged = exchange_orcarouter_code(
8798 &MockFormClient::new(vec![(
8799 200,
8800 serde_json::json!({"key": ORCA_FAKE_KEY, "user_id": "u-1", "scope": "api"})
8801 .to_string(),
8802 )]),
8803 ORCAROUTER_AUTH_BASE,
8804 "auth-code",
8805 "verifier-value",
8806 )
8807 .unwrap();
8808 assert_eq!(api_key.expose(), exchanged.expose());
8809 assert_eq!(api_key.granted_scope(), exchanged.granted_scope());
8810 assert!(api_key.scope_satisfies_purpose() && exchanged.scope_satisfies_purpose());
8811 assert_ne!(
8812 api_key.source(),
8813 exchanged.source(),
8814 "the source is presentation only and never changes the key"
8815 );
8816 assert_eq!(exchanged.source(), OrcaCredentialSource::Pkce);
8817 assert_eq!(api_key.source().as_str(), "api_key");
8818 assert_eq!(exchanged.source().as_str(), "pkce");
8819 }
8820
8821 #[test]
8822 fn orcarouter_authorize_url_is_the_documented_contract() {
8823 let inputs = orca_inputs("https://www.orcarouter.ai");
8824 let pkce = PkceChallenge {
8825 verifier: "verifier".into(),
8826 challenge: "challenge-abc".into(),
8827 };
8828 let url = build_orcarouter_authorize_url(
8829 &inputs,
8830 "http://127.0.0.1:41234/callback",
8831 "state-1",
8832 &pkce,
8833 )
8834 .unwrap();
8835 assert!(
8836 url.starts_with("https://www.orcarouter.ai/auth?"),
8837 "authorize path is fixed at /auth: {url}"
8838 );
8839 let parsed = reqwest::Url::parse(&url).unwrap();
8840 let form: std::collections::BTreeMap<_, _> = parsed.query_pairs().collect();
8841 assert_eq!(form["callback_url"], "http://127.0.0.1:41234/callback");
8842 assert_eq!(form["code_challenge"], "challenge-abc");
8843 assert_eq!(form["code_challenge_method"], "S256");
8844 assert_eq!(form["state"], "state-1");
8845 assert_eq!(form["app_name"], ORCAROUTER_APP_NAME);
8846 assert_eq!(form["scope"], ORCAROUTER_SCOPE);
8847 assert_eq!(form["ref"], ORCAROUTER_REF);
8848 assert_eq!(form.get("app_id").map(|value| &**value), ORCAROUTER_APP_ID);
8849 assert!(!form.contains_key("client_id"), "no client id in the URL");
8850 assert!(
8851 !form.contains_key("client_secret"),
8852 "PKCE never carries a client secret"
8853 );
8854 assert!(!form.contains_key("response_type"));
8855 assert!(
8856 !url.contains(&pkce.verifier),
8857 "the verifier must never reach the browser"
8858 );
8859 }
8860
8861 #[test]
8862 fn orcarouter_exchange_uses_the_auth_origin_path_and_body() {
8863 let client = MockFormClient::new(vec![(
8864 200,
8865 serde_json::json!({"key": ORCA_FAKE_KEY, "user_id": "u", "scope": "api"}).to_string(),
8866 )]);
8867 exchange_orcarouter_code(&client, ORCAROUTER_AUTH_BASE, "code-1", "verifier-1").unwrap();
8868 let posts = client.posts.lock().unwrap();
8869 assert_eq!(posts.len(), 1);
8870 assert_eq!(
8871 posts[0].0, "https://www.orcarouter.ai/api/v1/auth/keys",
8872 "the exchange is on the auth origin at /api/v1/auth/keys"
8873 );
8874 assert!(
8875 !posts[0].0.contains("api.orcarouter.ai"),
8876 "the exchange must never target the inference origin"
8877 );
8878 let form: std::collections::BTreeMap<_, _> = posts[0].1.iter().cloned().collect();
8879 assert_eq!(form["code"], "code-1");
8880 assert_eq!(form["code_verifier"], "verifier-1");
8881 assert_eq!(form["code_challenge_method"], "S256");
8882 assert!(
8883 !form.contains_key("client_secret"),
8884 "no client secret is ever sent"
8885 );
8886 }
8887
8888 #[test]
8889 fn orcarouter_exchange_error_does_not_echo_the_response_body() {
8890 let client = MockFormClient::new(vec![(
8891 403,
8892 serde_json::json!({
8893 "error": "invalid_grant",
8894 "error_description": "secret-must-not-leak"
8895 })
8896 .to_string(),
8897 )]);
8898 let err = match exchange_orcarouter_code(&client, ORCAROUTER_AUTH_BASE, "used", "verifier")
8899 {
8900 Ok(_) => panic!("a rejected code must fail"),
8901 Err(err) => err.to_string(),
8902 };
8903 assert!(err.contains("invalid_grant"), "{err}");
8904 assert!(err.contains("codewhale auth orcarouter"), "{err}");
8905 assert!(!err.contains("secret-must-not-leak"), "{err}");
8906 assert!(!err.contains(ORCA_FAKE_KEY), "{err}");
8907 }
8908
8909 #[test]
8910 fn orcarouter_exchange_error_field_never_discloses_untrusted_text() {
8911 let code = "authorization-code-sentinel";
8912 let verifier = "verifier-sentinel";
8913 for server_error in [
8914 ORCA_FAKE_KEY.to_string(),
8915 format!("invalid_grant\r\n{code} {verifier}\u{1b}[2J"),
8916 ] {
8917 let client = MockFormClient::new(vec![(
8918 403,
8919 serde_json::json!({"error": server_error, "key": ORCA_FAKE_KEY}).to_string(),
8920 )]);
8921 let error = exchange_orcarouter_code(&client, ORCAROUTER_AUTH_BASE, code, verifier)
8922 .err()
8923 .expect("a rejected exchange must fail")
8924 .to_string();
8925 assert!(!error.contains(ORCA_FAKE_KEY));
8926 assert!(!error.contains(code));
8927 assert!(!error.contains(verifier));
8928 assert!(!error.chars().any(char::is_control));
8929 assert!(error.contains("HTTP 403"));
8930 assert!(error.contains("exchange_failed"));
8931 assert_eq!(client.posts.lock().unwrap().len(), 1);
8932 }
8933 }
8934
8935 /// 400 is the method-mismatch / downgrade defence; it is terminal for the
8936 /// attempt, never retried, and never prints the code or verifier.
8937 #[test]
8938 fn orcarouter_exchange_400_is_terminal_and_leaks_nothing() {
8939 let client = MockFormClient::new(vec![(
8940 400,
8941 serde_json::json!({"error": "invalid_request", "error_description": "downgrade"})
8942 .to_string(),
8943 )]);
8944 let err = match exchange_orcarouter_code(&client, ORCAROUTER_AUTH_BASE, "c", "v") {
8945 Ok(_) => panic!("400 must fail"),
8946 Err(err) => err.to_string(),
8947 };
8948 assert!(err.contains("invalid_request"), "{err}");
8949 assert!(!err.contains("downgrade"), "{err}");
8950 assert_eq!(client.posts.lock().unwrap().len(), 1, "no retry");
8951 }
8952
8953 /// A granted scope other than the requested one is surfaced, not assumed.
8954 #[test]
8955 fn orcarouter_exchange_records_the_granted_scope_not_the_requested_one() {
8956 let narrowed = exchange_orcarouter_code(
8957 &MockFormClient::new(vec![(
8958 200,
8959 serde_json::json!({"key": ORCA_FAKE_KEY, "scope": "read"}).to_string(),
8960 )]),
8961 ORCAROUTER_AUTH_BASE,
8962 "c",
8963 "v",
8964 )
8965 .unwrap();
8966 assert_eq!(narrowed.granted_scope(), "read");
8967 assert!(
8968 !narrowed.scope_satisfies_purpose(),
8969 "a downgraded grant must not be treated as satisfying the purpose"
8970 );
8971
8972 let silent = exchange_orcarouter_code(
8973 &MockFormClient::new(vec![(
8974 200,
8975 serde_json::json!({"key": ORCA_FAKE_KEY}).to_string(),
8976 )]),
8977 ORCAROUTER_AUTH_BASE,
8978 "c",
8979 "v",
8980 )
8981 .unwrap();
8982 assert_eq!(silent.granted_scope(), ORCAROUTER_SCOPE);
8983 }
8984
8985 #[test]
8986 fn orcarouter_exchange_rejects_non_orca_and_empty_keys() {
8987 for body in [
8988 serde_json::json!({"key": "sk-not-orca", "scope": "api"}),
8989 serde_json::json!({"key": " ", "scope": "api"}),
8990 serde_json::json!({"user_id": "u", "scope": "api"}),
8991 ] {
8992 assert!(
8993 exchange_orcarouter_code(
8994 &MockFormClient::new(vec![(200, body.to_string())]),
8995 ORCAROUTER_AUTH_BASE,
8996 "c",
8997 "v",
8998 )
8999 .is_err(),
9000 "a key this client cannot use must be refused"
9001 );
9002 }
9003 }
9004
9005 /// Flow A state handling: the callback state is compared before the code is
9006 /// accepted, a denial is terminal, and a reused code is not retried.
9007 #[test]
9008 fn orcarouter_callback_state_mismatch_and_denial_are_terminal() {
9009 let params = &ORCAROUTER_OAUTH_PARAMS;
9010
9011 let success = parse_callback_query(params, "code=code-1&state=state-1").unwrap();
9012 assert_eq!(
9013 accept_callback_with_client("state-1", success).unwrap().0,
9014 "code-1"
9015 );
9016
9017 let mismatched = parse_callback_query(params, "code=code-1&state=other").unwrap();
9018 let err = accept_callback_with_client("state-1", mismatched)
9019 .expect_err("state mismatch must be refused")
9020 .to_string();
9021 assert!(err.contains("state did not match"), "{err}");
9022
9023 let denied = parse_callback_query(
9024 params,
9025 "error=access_denied&error_description=nope&state=state-1",
9026 )
9027 .unwrap();
9028 let err = accept_callback_with_client("state-1", denied)
9029 .expect_err("a denial must be terminal")
9030 .to_string();
9031 assert!(err.contains("access_denied"), "{err}");
9032 assert!(
9033 !err.contains("nope"),
9034 "the description is not echoed: {err}"
9035 );
9036
9037 let duplicated = parse_callback_query(params, "code=a&code=b&state=s");
9038 assert!(duplicated.is_err(), "a duplicate code is refused");
9039 }
9040
9041 #[test]
9042 fn orcarouter_pkce_pair_is_s256_and_ephemeral() {
9043 let pkce = generate_pkce();
9044 assert!(pkce.verifier.len() >= 43);
9045 assert_eq!(
9046 pkce.challenge,
9047 URL_SAFE_NO_PAD.encode(Sha256::digest(pkce.verifier.as_bytes()))
9048 );
9049 assert!(!pkce.challenge.contains('='), "challenge is unpadded");
9050 assert_ne!(generate_state(), generate_state());
9051 }
9052
9053 /// Both origins are explicit and independently overridable; a remote plain
9054 /// HTTP auth origin is refused because PKCE must not run in the clear.
9055 #[test]
9056 fn orcarouter_origins_are_separate_and_enforce_https() {
9057 assert_eq!(ORCAROUTER_AUTH_BASE, "https://www.orcarouter.ai");
9058 assert_eq!(ORCAROUTER_API_BASE, "https://api.orcarouter.ai/v1");
9059 assert!(
9060 !ORCAROUTER_API_BASE.contains("www.orcarouter.ai"),
9061 "the inference origin is not derived from the auth origin"
9062 );
9063 assert_eq!(
9064 orcarouter_exchange_url("https://www.orcarouter.ai/"),
9065 "https://www.orcarouter.ai/api/v1/auth/keys"
9066 );
9067 let exchange = orcarouter_exchange_url(ORCAROUTER_AUTH_BASE);
9068 assert_eq!(exchange, "https://www.orcarouter.ai/api/v1/auth/keys");
9069 assert!(
9070 !exchange.starts_with("https://api.orcarouter.ai"),
9071 "the exchange runs on the auth origin, not the inference origin"
9072 );
9073 let inputs = orca_inputs("http://evil.example");
9074 let pkce = PkceChallenge {
9075 verifier: "v".into(),
9076 challenge: "c".into(),
9077 };
9078 assert!(
9079 build_orcarouter_authorize_url(&inputs, "http://127.0.0.1:1/callback", "s", &pkce)
9080 .is_err(),
9081 "a remote plain-HTTP auth origin must be refused"
9082 );
9083 }
9084
9085 /// OrcaRouter has no owned OAuth generation: PKCE hands back a durable API
9086 /// key, not refreshable token material. It therefore never appears in
9087 /// `OAuthProvider` and is driven by its own [`orcarouter_pkce_login`] path.
9088 #[test]
9089 fn orcarouter_is_not_an_owned_generation_provider() {
9090 for provider in [OAuthProvider::Xai, OAuthProvider::Chatgpt] {
9091 assert!(provider.is_valid_generation(&provider.new_generation()));
9092 }
9093 assert_eq!(ORCAROUTER_EXCHANGE_PATH, "/api/v1/auth/keys");
9094 assert!(
9095 !ORCAROUTER_EXCHANGE_PATH.starts_with("/v1/auth/keys"),
9096 "the exchange path is not the relay model route"
9097 );
9098 }
9099
9100 /// The loopback listener binds an ephemeral port on 127.0.0.1 and the
9101 /// authorize URL's callback matches that exact port.
9102 #[test]
9103 fn orcarouter_loopback_request_matches_the_bound_port() {
9104 let listeners = bind_orcarouter_callback().unwrap();
9105 let inputs = orca_inputs(ORCAROUTER_AUTH_BASE);
9106 let request = start_orcarouter_auth_request(&listeners, &inputs).unwrap();
9107 assert!(request.redirect_uri.starts_with("http://127.0.0.1:"));
9108 assert!(request.redirect_uri.ends_with("/callback"));
9109 let port = listeners[0].local_addr().unwrap().port();
9110 assert!(request.redirect_uri.contains(&port.to_string()));
9111 assert!(request.authorize_url.contains(&request.state));
9112 assert!(request.authorize_url.contains(&request.pkce.challenge));
9113 assert!(!request.authorize_url.contains(&request.pkce.verifier));
9114 assert!(
9115 !format!("{request:?}").contains(&request.pkce.verifier),
9116 "Debug output must not print the verifier"
9117 );
9118 }
9119
9120 #[test]
9121 fn orcarouter_credential_debug_never_prints_the_key() {
9122 let credential = OrcaCredential::from_api_key(ORCA_FAKE_KEY).unwrap();
9123 // OrcaCredential is deliberately Debug-free; prove the key does not
9124 // leak through the presentation label or the scope accessors.
9125 assert!(!credential.source().as_str().contains(ORCA_FAKE_KEY));
9126 assert!(!credential.granted_scope().contains(ORCA_FAKE_KEY));
9127 assert_eq!(credential.source().as_str(), "api_key");
9128 }
9129
9130 /// One local fake auth server that plays both the browser and the
9131 /// exchange endpoint over real sockets. It answers `GET {auth}/auth` with a
9132 /// 302 to the `callback_url` the client sent — carrying the client's own
9133 /// `state`, which is the only way the callback is accepted — and answers
9134 /// `POST {auth}/api/v1/auth/keys` with the minted key. The PKCE verifier
9135 /// never reaches this server: only the S256 challenge does.
9136 struct FakeOrcaAuthServer {
9137 port: u16,
9138 requests: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
9139 }
9140
9141 impl FakeOrcaAuthServer {
9142 fn start() -> Self {
9143 let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
9144 listener.set_nonblocking(true).unwrap();
9145 let port = listener.local_addr().unwrap().port();
9146 let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
9147 let seen = requests.clone();
9148 std::thread::spawn(move || {
9149 let deadline = std::time::Instant::now() + Duration::from_secs(25);
9150 while std::time::Instant::now() < deadline {
9151 match listener.accept() {
9152 Ok((mut stream, _)) => {
9153 let head = read_fixture_request(&mut stream);
9154 seen.lock().unwrap().push(head.clone());
9155 let request_line = head.lines().next().unwrap_or_default();
9156 let mut parts = request_line.split_whitespace();
9157 let method = parts.next().unwrap_or("");
9158 let target = parts.next().unwrap_or("");
9159 let url = reqwest::Url::parse("http://127.0.0.1")
9160 .and_then(|base| base.join(target))
9161 .ok();
9162 let query = |name: &str| -> Option<String> {
9163 url.as_ref().and_then(|url| {
9164 url.query_pairs()
9165 .find(|(key, _)| key == name)
9166 .map(|(_, value)| value.into_owned())
9167 })
9168 };
9169 let reply = if method == "GET" {
9170 match (query("callback_url"), query("state")) {
9171 (Some(callback), Some(state)) => format!(
9172 "HTTP/1.1 302 Found\r\nLocation: {callback}?code=local-flows-code&state={state}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
9173 ),
9174 _ => "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
9175 .to_string(),
9176 }
9177 } else if method == "POST"
9178 && url
9179 .as_ref()
9180 .is_some_and(|url| url.path() == ORCAROUTER_EXCHANGE_PATH)
9181 {
9182 let body = serde_json::json!({
9183 "key": ORCA_FAKE_KEY,
9184 "user_id": "u",
9185 "scope": "api"
9186 })
9187 .to_string();
9188 format!(
9189 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
9190 body.len()
9191 )
9192 } else {
9193 "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
9194 .to_string()
9195 };
9196 let _ = stream.write_all(reply.as_bytes());
9197 }
9198 Err(ref error) if error.kind() == std::io::ErrorKind::WouldBlock => {
9199 std::thread::sleep(Duration::from_millis(10));
9200 }
9201 Err(_) => break,
9202 }
9203 }
9204 });
9205 Self { port, requests }
9206 }
9207
9208 fn port(&self) -> u16 {
9209 self.port
9210 }
9211
9212 fn urls(&self) -> String {
9213 self.requests
9214 .lock()
9215 .unwrap()
9216 .iter()
9217 .filter_map(|head| head.lines().next().map(str::to_string))
9218 .collect::<Vec<_>>()
9219 .join("\n")
9220 }
9221 }
9222
9223 /// Read one whole request for the fake auth server: the head, then the
9224 /// `Content-Length` bytes of body. The fixture's listener is non-blocking
9225 /// and Windows and BSD sockets hand that mode to the accepted stream, so a
9226 /// single `read` can return `WouldBlock` before the client has written a
9227 /// byte. Answering that empty read puts a response on the wire ahead of
9228 /// the request, which the client reports as "received unexpected message
9229 /// from connection"; closing with the body still unread resets the
9230 /// connection under the reply.
9231 fn read_fixture_request(stream: &mut TcpStream) -> String {
9232 let _ = stream.set_nonblocking(false);
9233 let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
9234 let mut raw = Vec::new();
9235 let mut chunk = [0u8; 4096];
9236 while raw.len() < 64 * 1024 {
9237 if let Some(head_end) = raw.windows(4).position(|window| window == b"\r\n\r\n") {
9238 let head = String::from_utf8_lossy(&raw[..head_end]);
9239 let body_len = header_value(&head, "content-length")
9240 .and_then(|value| value.parse::<usize>().ok())
9241 .unwrap_or(0);
9242 if raw.len() >= head_end + 4 + body_len {
9243 break;
9244 }
9245 }
9246 match stream.read(&mut chunk) {
9247 Ok(0) | Err(_) => break,
9248 Ok(read) => raw.extend_from_slice(&chunk[..read]),
9249 }
9250 }
9251 String::from_utf8_lossy(&raw).to_string()
9252 }
9253
9254 /// The full connect adapter over a local fake auth server: the adapter
9255 /// binds its own loopback callback, the fake server redirects the code to
9256 /// exactly that callback with the adapter's own state, and the exchange
9257 /// POST returns the key. Nothing here fakes the flow for the adapter — it
9258 /// runs `orcarouter_pkce_login` end to end over real sockets.
9259 /// Captures the `Open: <url>` line the login prints, so the test can play
9260 /// the browser leg. The PKCE verifier is never part of that line.
9261 struct AuthorizeUrlCapture {
9262 seen: String,
9263 sent: std::sync::mpsc::Sender<String>,
9264 done: bool,
9265 }
9266
9267 impl std::io::Write for AuthorizeUrlCapture {
9268 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
9269 self.seen.push_str(&String::from_utf8_lossy(buf));
9270 if !self.done
9271 && let Some(start) = self.seen.find("http")
9272 {
9273 let url: String = self.seen[start..]
9274 .chars()
9275 .take_while(|c| !c.is_whitespace())
9276 .collect();
9277 if url.contains("/auth?") {
9278 self.done = true;
9279 let _ = self.sent.send(url);
9280 }
9281 }
9282 Ok(buf.len())
9283 }
9284 fn flush(&mut self) -> std::io::Result<()> {
9285 Ok(())
9286 }
9287 }
9288
9289 /// One raw HTTP/1.1 GET over a fresh socket. The fake server speaks plain
9290 /// loopback HTTP, so the browser leg needs no client library.
9291 fn raw_get(url: &str) -> String {
9292 let parsed = reqwest::Url::parse(url).expect("callback url");
9293 let host = parsed.host_str().expect("host").to_string();
9294 let port = parsed.port_or_known_default().expect("port");
9295 let target = match parsed.query() {
9296 Some(query) => format!("{}?{query}", parsed.path()),
9297 None => parsed.path().to_string(),
9298 };
9299 let mut stream = TcpStream::connect((host.as_str(), port)).expect("connect");
9300 write!(
9301 stream,
9302 "GET {target} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"
9303 )
9304 .expect("write request");
9305 let mut response = String::new();
9306 stream.read_to_string(&mut response).expect("read response");
9307 response
9308 }
9309
9310 fn header_value(response: &str, name: &str) -> Option<String> {
9311 response.lines().find_map(|line| {
9312 let (key, value) = line.split_once(':')?;
9313 key.trim()
9314 .eq_ignore_ascii_case(name)
9315 .then(|| value.trim().to_string())
9316 })
9317 }
9318
9319 /// The fake auth server must answer the request, not the accept: a client
9320 /// that connects, pauses, and then sends its head and body in separate
9321 /// segments still gets the exchange reply, and the server saw the body.
9322 #[test]
9323 fn fake_orca_auth_server_waits_for_a_late_fragmented_request() {
9324 let auth = FakeOrcaAuthServer::start();
9325 let mut stream = TcpStream::connect(("127.0.0.1", auth.port())).expect("connect");
9326 // Longer than the fixture's accept poll, so it accepts an empty socket.
9327 std::thread::sleep(Duration::from_millis(100));
9328 let body = r#"{"code":"late-fragment"}"#;
9329 write!(
9330 stream,
9331 "POST {ORCAROUTER_EXCHANGE_PATH} HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
9332 body.len()
9333 )
9334 .expect("write head");
9335 std::thread::sleep(Duration::from_millis(100));
9336 stream.write_all(body.as_bytes()).expect("write body");
9337 let mut response = String::new();
9338 stream.read_to_string(&mut response).expect("read response");
9339 assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}");
9340 let recorded = auth.requests.lock().unwrap().join("\n");
9341 assert!(recorded.contains("late-fragment"), "{recorded}");
9342 }
9343
9344 #[test]
9345 fn orcarouter_connect_adapter_runs_authorize_callback_exchange_end_to_end() {
9346 let auth = FakeOrcaAuthServer::start();
9347 let auth_base = format!("http://127.0.0.1:{}", auth.port());
9348 let inputs = OrcaLoginInputs {
9349 auth_base: auth_base.clone(),
9350 api_base: ORCAROUTER_API_BASE.to_string(),
9351 app_name: ORCAROUTER_APP_NAME.to_string(),
9352 open_browser: false,
9353 };
9354 let (url_tx, url_rx) = std::sync::mpsc::channel();
9355 let login = std::thread::spawn(move || {
9356 let mut capture = AuthorizeUrlCapture {
9357 seen: String::new(),
9358 sent: url_tx,
9359 done: false,
9360 };
9361 orcarouter_pkce_login(&inputs, &mut capture)
9362 });
9363
9364 let authorize_url = url_rx
9365 .recv_timeout(Duration::from_secs(20))
9366 .expect("the adapter prints the authorize URL before it waits for the callback");
9367 assert!(
9368 authorize_url.starts_with(&format!("{auth_base}/auth?")),
9369 "{authorize_url}"
9370 );
9371
9372 // Browser leg 1: the authorize endpoint redirects to the adapter's own
9373 // loopback callback, carrying the code and the adapter's own state.
9374 let redirect = raw_get(&authorize_url);
9375 let callback = header_value(&redirect, "location")
9376 .expect("the authorize endpoint returns a loopback redirect");
9377 assert!(callback.starts_with("http://127.0.0.1:"), "{callback}");
9378
9379 // Browser leg 2: the loopback callback receives it; the login thread
9380 // then POSTs the code and the S256 verifier to the exchange endpoint.
9381 let _ = raw_get(&callback);
9382
9383 let credential = login.join().expect("login worker").expect("login");
9384 assert_eq!(credential.expose(), ORCA_FAKE_KEY);
9385 assert_eq!(credential.source(), OrcaCredentialSource::Pkce);
9386 assert!(credential.scope_satisfies_purpose());
9387
9388 // The auth server saw the authorize GET and the exchange POST, both on
9389 // the auth origin, and never the verifier or the minted key.
9390 let seen = auth.urls();
9391 let expected_post = format!("POST {ORCAROUTER_EXCHANGE_PATH}");
9392 assert!(seen.contains("GET /auth?"), "{seen}");
9393 assert!(seen.contains(&expected_post), "{seen}");
9394 assert!(!seen.contains("code_verifier"), "{seen}");
9395 assert!(!seen.contains(ORCA_FAKE_KEY), "{seen}");
9396 }
9397 }
9398
9399 #[cfg(test)]
9400 mod plugin_oauth_tests {
9401 use super::test_support::*;
9402 use super::*;
9403
9404 #[test]
9405 fn plugin_oauth_rejects_insecure_or_cross_origin_endpoints() {
9406 let mut config = descriptor();
9407 assert!(config.validate().is_ok());
9408 config.token_endpoint = "https://attacker.example/token".into();
9409 assert!(config.validate().is_err());
9410 config.token_endpoint = "http://issuer.example/token".into();
9411 assert!(config.validate().is_err());
9412 config.token_endpoint = "https://issuer.example/token?secret=value".into();
9413 assert!(config.validate().is_err());
9414 }
9415
9416 #[test]
9417 fn plugin_oauth_callback_rejects_duplicate_state_and_issuer_mixup() {
9418 assert!(
9419 validate_plugin_callback(
9420 "code=x&state=s&iss=https%3A%2F%2Fissuer.example",
9421 "https://issuer.example"
9422 )
9423 .is_ok()
9424 );
9425 assert!(
9426 validate_plugin_callback("code=x&state=s&state=other", "https://issuer.example")
9427 .is_err()
9428 );
9429 assert!(
9430 validate_plugin_callback(
9431 "code=x&state=s&iss=https%3A%2F%2Fattacker.example",
9432 "https://issuer.example"
9433 )
9434 .is_err()
9435 );
9436 assert!(validate_plugin_callback("error=access_denied", "https://issuer.example").is_err());
9437 }
9438
9439 #[test]
9440 fn plugin_callback_preserves_client_identity_and_rejects_issuer_mixup() {
9441 fn callback(query: &str) -> Result<(String, Option<String>)> {
9442 let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
9443 let address = listener.local_addr()?;
9444 let server = std::thread::spawn(move || {
9445 let config = descriptor();
9446 let (stream, _) = listener.accept()?;
9447 let outcome = handle_callback_stream_validated(
9448 stream,
9449 &config.callback_params(),
9450 "expected-state",
9451 Some(&config.issuer),
9452 Instant::now() + CALLBACK_TIMEOUT,
9453 )?;
9454 accept_callback_with_client("expected-state", outcome)
9455 });
9456 let mut client = TcpStream::connect(address)?;
9457 write!(
9458 client,
9459 "GET /oauth/callback?{query} HTTP/1.1\r\nHost: localhost\r\n\r\n"
9460 )?;
9461 server.join().expect("callback worker")
9462 }
9463 let (code, client_id) = callback(
9464 "code=code-sentinel&state=expected-state&client_id=oaiapp_callback_fixture&iss=https%3A%2F%2Fissuer.example",
9465 ).unwrap();
9466 assert_eq!(code, "code-sentinel");
9467 assert_eq!(client_id.as_deref(), Some("oaiapp_callback_fixture"));
9468 assert!(
9469 callback("code=code-sentinel&state=expected-state&iss=https%3A%2F%2Fother.example",)
9470 .is_err()
9471 );
9472 }
9473
9474 #[test]
9475 fn plugin_oauth_binding_is_exact_and_authorization_uses_pkce_resource() {
9476 let config = descriptor();
9477 let slot = plugin_oauth_slot("example", "https://api.example/v1", &config).unwrap();
9478 assert_ne!(
9479 slot,
9480 plugin_oauth_slot("other", "https://api.example/v1", &config).unwrap()
9481 );
9482 assert_ne!(
9483 slot,
9484 plugin_oauth_slot("example", "https://other.example/v1", &config).unwrap()
9485 );
9486 let mut changed = config.clone();
9487 changed.scopes.push("balance:read".into());
9488 assert_ne!(
9489 slot,
9490 plugin_oauth_slot("example", "https://api.example/v1", &changed).unwrap()
9491 );
9492 let pkce = generate_pkce();
9493 let url = reqwest::Url::parse(
9494 &config
9495 .authorize_url("http://127.0.0.1:1234/oauth/callback", "state", &pkce)
9496 .unwrap(),
9497 )
9498 .unwrap();
9499 let pairs: BTreeMap<_, _> = url.query_pairs().collect();
9500 assert_eq!(pairs.get("code_challenge_method").unwrap(), "S256");
9501 assert_eq!(pairs.get("resource").unwrap(), "https://api.example/oauth");
9502 assert!(!url.as_str().contains(&pkce.verifier));
9503 }
9504
9505 #[test]
9506 fn plugin_oauth_diagnostics_do_not_refresh_or_mutate_expired_credentials() {
9507 let secrets = codewhale_secrets::Secrets::new(std::sync::Arc::new(
9508 codewhale_secrets::InMemoryKeyringStore::default(),
9509 ));
9510 let config = descriptor();
9511 let raw = serde_json::to_string(&PluginOAuthTokens {
9512 grant_id: None,
9513 access_token: "expired".into(),
9514 refresh_token: Some("refresh".into()),
9515 expires_at: 1,
9516 })
9517 .unwrap();
9518 secrets.set("test-slot", &raw).unwrap();
9519 assert!(plugin_oauth_saved_token(&raw).unwrap());
9520 let unusable = serde_json::to_string(&PluginOAuthTokens {
9521 grant_id: None,
9522 access_token: "expired".into(),
9523 refresh_token: None,
9524 expires_at: 1,
9525 })
9526 .unwrap();
9527 assert!(!plugin_oauth_saved_token(&unusable).unwrap());
9528 let error =
9529 plugin_oauth_access_token_with_store("test-slot", &config, true, &secrets).unwrap_err();
9530 assert!(error.to_string().contains("diagnostics never refresh"));
9531 assert_eq!(
9532 secrets.get("test-slot").unwrap().as_deref(),
9533 Some(raw.as_str())
9534 );
9535 }
9536 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
9537 async fn plugin_oauth_short_lived_nonrefreshable_token_uses_its_actual_lifetime() -> Result<()>
9538 {
9539 use wiremock::matchers::{body_string_contains, method, path};
9540 use wiremock::{Mock, MockServer, ResponseTemplate};
9541
9542 let server = MockServer::start().await;
9543 Mock::given(method("POST"))
9544 .and(path("/token"))
9545 .and(body_string_contains("grant_type=authorization_code"))
9546 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
9547 "access_token": "short-lived",
9548 "expires_in": 30,
9549 "token_type": "Bearer"
9550 })))
9551 .expect(1)
9552 .mount(&server)
9553 .await;
9554 let mut config = descriptor();
9555 config.issuer = server.uri();
9556 config.authorization_endpoint = format!("{}/authorize", server.uri());
9557 config.token_endpoint = format!("{}/token", server.uri());
9558 tokio::task::spawn_blocking(move || -> Result<()> {
9559 let mut token = plugin_token_response(
9560 &config,
9561 &[("grant_type", "authorization_code"), ("code", "test-code")],
9562 None,
9563 )?;
9564 assert!(token.refresh_token.is_none());
9565 assert!(
9566 token.expires_at > now_unix_secs().context("test clock before UNIX epoch")? as u64
9567 );
9568 let secrets = codewhale_secrets::Secrets::new(std::sync::Arc::new(
9569 codewhale_secrets::InMemoryKeyringStore::default(),
9570 ));
9571 let raw = serde_json::to_string(&token)?;
9572 secrets.set("short-lifetime", &raw)?;
9573 for read_only in [true, false] {
9574 assert_eq!(
9575 plugin_oauth_access_token_with_store(
9576 "short-lifetime",
9577 &config,
9578 read_only,
9579 &secrets,
9580 )?,
9581 "short-lived"
9582 );
9583 assert_eq!(
9584 secrets.get("short-lifetime")?.as_deref(),
9585 Some(raw.as_str())
9586 );
9587 }
9588 // Read-only use also preserves a still-valid refreshable grant.
9589 token.refresh_token = Some("unused-refresh".into());
9590 let refreshable = serde_json::to_string(&token)?;
9591 secrets.set("short-lifetime", &refreshable)?;
9592 assert_eq!(
9593 plugin_oauth_access_token_with_store("short-lifetime", &config, true, &secrets)?,
9594 "short-lived"
9595 );
9596 assert_eq!(
9597 secrets.get("short-lifetime")?.as_deref(),
9598 Some(refreshable.as_str())
9599 );
9600 // Model the actual expiry boundary without a wall-clock sleep.
9601 token.refresh_token = None;
9602 token.expires_at = now_unix_secs().context("test clock before UNIX epoch")? as u64;
9603 let expired = serde_json::to_string(&token)?;
9604 secrets.set("short-lifetime", &expired)?;
9605 for read_only in [true, false] {
9606 let error = plugin_oauth_access_token_with_store(
9607 "short-lifetime",
9608 &config,
9609 read_only,
9610 &secrets,
9611 )
9612 .expect_err("an actually expired token must be refused");
9613 assert!(error.to_string().contains("expired"));
9614 assert_eq!(
9615 secrets.get("short-lifetime")?.as_deref(),
9616 Some(expired.as_str())
9617 );
9618 }
9619 Ok(())
9620 })
9621 .await??;
9622 assert_eq!(server.received_requests().await.unwrap().len(), 1);
9623 server.verify().await;
9624 Ok(())
9625 }
9626
9627 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
9628 async fn plugin_oauth_refresh_rotation_serializes_concurrent_requests() {
9629 use wiremock::matchers::{body_string_contains, method, path};
9630 use wiremock::{Mock, MockServer, ResponseTemplate};
9631 let server = MockServer::start().await;
9632 Mock::given(method("POST")).and(path("/token"))
9633 .and(body_string_contains("grant_type=refresh_token"))
9634 .and(body_string_contains("refresh_token=old-refresh"))
9635 .and(body_string_contains("resource=https%3A%2F%2Fapi.example%2Foauth"))
9636 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"access_token":"fresh", "refresh_token":"rotated", "expires_in":3600, "token_type":"Bearer"})))
9637 .expect(1).mount(&server).await;
9638 let mut config = descriptor();
9639 config.issuer = server.uri();
9640 config.authorization_endpoint = format!("{}/authorize", server.uri());
9641 config.token_endpoint = format!("{}/token", server.uri());
9642 let secrets = std::sync::Arc::new(codewhale_secrets::Secrets::new(std::sync::Arc::new(
9643 codewhale_secrets::InMemoryKeyringStore::default(),
9644 )));
9645 secrets
9646 .set(
9647 "rotation",
9648 &serde_json::to_string(&PluginOAuthTokens {
9649 grant_id: None,
9650 access_token: "expired".into(),
9651 refresh_token: Some("old-refresh".into()),
9652 expires_at: 1,
9653 })
9654 .unwrap(),
9655 )
9656 .unwrap();
9657 let grant = pin_plugin_oauth_grant_with_store("rotation", &secrets).unwrap();
9658 let mut workers = Vec::new();
9659 for _ in 0..2 {
9660 let config = config.clone();
9661 let secrets = secrets.clone();
9662 workers.push(tokio::task::spawn_blocking(move || {
9663 resolve_plugin_oauth_access_token("rotation", &config, false, &secrets, Some(grant))
9664 }));
9665 }
9666 for worker in workers {
9667 assert_eq!(worker.await.unwrap().unwrap(), "fresh");
9668 }
9669 let stored: PluginOAuthTokens =
9670 serde_json::from_str(&secrets.get("rotation").unwrap().unwrap()).unwrap();
9671 assert_eq!(stored.refresh_token.as_deref(), Some("rotated"));
9672 assert_eq!(stored.grant_id, Some(grant));
9673 let new_grant = PluginOAuthTokens {
9674 grant_id: Some(uuid::Uuid::new_v4()),
9675 ..stored
9676 };
9677 secrets
9678 .set("rotation", &serde_json::to_string(&new_grant).unwrap())
9679 .unwrap();
9680 assert!(
9681 resolve_plugin_oauth_access_token("rotation", &config, false, &secrets, Some(grant))
9682 .unwrap_err()
9683 .to_string()
9684 .contains("login changed")
9685 );
9686 secrets.delete("rotation").unwrap();
9687 assert!(
9688 plugin_oauth_access_token_with_store("rotation", &config, false, &secrets).is_err()
9689 );
9690 server.verify().await;
9691 }
9692
9693 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
9694 async fn plugin_oauth_failed_refresh_preserves_secret_without_exposing_response() {
9695 use wiremock::matchers::{method, path};
9696 use wiremock::{Mock, MockServer, ResponseTemplate};
9697 let responses = [
9698 ResponseTemplate::new(400).set_body_json(serde_json::json!({
9699 "error": "invalid_grant",
9700 "error_description": "secret-response-material"
9701 })),
9702 ResponseTemplate::new(400)
9703 .set_body_bytes(b"secret-response-material")
9704 .insert_header(
9705 "content-type",
9706 "text/html; credential=secret-header-material",
9707 ),
9708 ];
9709 for response in responses {
9710 let server = MockServer::start().await;
9711 Mock::given(method("POST"))
9712 .and(path("/token"))
9713 .respond_with(response)
9714 .expect(1)
9715 .mount(&server)
9716 .await;
9717 let mut config = descriptor();
9718 config.issuer = server.uri();
9719 config.authorization_endpoint = format!("{}/authorize", server.uri());
9720 config.token_endpoint = format!("{}/token", server.uri());
9721 let secrets = codewhale_secrets::Secrets::new(std::sync::Arc::new(
9722 codewhale_secrets::InMemoryKeyringStore::default(),
9723 ));
9724 let raw = serde_json::to_string(&PluginOAuthTokens {
9725 grant_id: None,
9726 access_token: "still-valid".into(),
9727 refresh_token: Some("refresh".into()),
9728 expires_at: (now_unix_secs().unwrap() as u64).saturating_add(30),
9729 })
9730 .unwrap();
9731 secrets.set("denied", &raw).unwrap();
9732 let (error, unchanged) = tokio::task::spawn_blocking(move || {
9733 let error =
9734 plugin_oauth_access_token_with_store("denied", &config, false, &secrets)
9735 .unwrap_err();
9736 (error.to_string(), secrets.get("denied").unwrap().unwrap())
9737 })
9738 .await
9739 .unwrap();
9740 assert!(error.contains("HTTP 400"));
9741 assert!(!error.contains("secret-response-material"));
9742 assert!(!error.contains("secret-header-material"));
9743 assert_eq!(unchanged, raw);
9744 server.verify().await;
9745 }
9746 }
9747 }
9748
9749 /// Non-secret account label (email, plan) of the Codewhale-owned
9750 /// subscription sign-in stored in `generation`, for `codewhale auth status`
9751 /// and `auth list`. Reads only that Codewhale-owned file: no refresh, no
9752 /// network, no external CLI file. `Err` carries a fixed, token-free reason
9753 /// the sign-in is unusable (missing, unreadable, no usable entry).
9754 pub fn owned_oauth_account_label(
9755 provider: codewhale_config::ProviderKind,
9756 generation: &str,
9757 ) -> Result<Option<String>> {
9758 let provider = match provider {
9759 codewhale_config::ProviderKind::OpenaiCodex => OAuthProvider::Chatgpt,
9760 codewhale_config::ProviderKind::Xai => OAuthProvider::Xai,
9761 _ => bail!("provider has no subscription sign-in"),
9762 };
9763 owned_account_label_for_generation(provider, generation)
9764 }
9765
9766 #[cfg(any(test, feature = "test-support"))]
9767 pub mod test_support;
9768
9768 lines RUST