Skip to main content

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