Skip to main content

cpa_exec/
xai_auth.rs

1//! xAI RFC 8628 device login with OIDC discovery, token refresh and credential files
2//! (internal/auth/xai, sdk/auth/xai.go, internal/runtime/executor/xai_executor_auth.go).
3//!
4//! Discovered endpoints must be HTTPS on `x.ai` or a subdomain, decided with Go's
5//! `net/url` rules (Go `ValidateOAuthEndpoint`, see xai_url.rs). The discovered token
6//! endpoint is saved with the credential and reused for refresh.
7
8use std::collections::{BTreeMap, HashMap};
9use std::path::{Path, PathBuf};
10use std::sync::{LazyLock, Mutex};
11use std::time::Duration;
12
13use base64::Engine;
14use bytes::Bytes;
15use chrono::{DateTime, SecondsFormat, Utc};
16use cpa_common::gostr::{GoStr, quote};
17use cpa_common::json::{self as gj, GoValue, Kind};
18use cpa_core::config::Config;
19use cpa_core::credential::{Credential, MetadataPatch};
20use cpa_core::exec::{ExecError, FailureScope};
21use futures_util::FutureExt;
22use futures_util::future::{BoxFuture, Shared};
23use serde_json::{Value, json};
24
25use crate::proxy::{GoClients, GoHeaders, Proxy};
26use crate::xai_url;
27
28pub const DEFAULT_API_BASE_URL: &str = "https://api.x.ai/v1";
29pub const CLI_CHAT_PROXY_BASE_URL: &str = "https://cli-chat-proxy.grok.com/v1";
30pub const ISSUER: &str = "https://auth.x.ai";
31pub const DISCOVERY_URL: &str = "https://auth.x.ai/.well-known/openid-configuration";
32pub const CLIENT_ID: &str = "b1a00492-073a-47ea-816f-4c329264a828";
33pub const SCOPE: &str = "openid profile email offline_access grok-cli:access api:access";
34const DEVICE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
35const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(5);
36const HTTP_TIMEOUT: Duration = Duration::from_secs(30);
37pub const MAX_POLL_DURATION: Duration = Duration::from_secs(30 * 60);
38/// SDK refresh lead (`xaiauth.RefreshLead`).
39pub const REFRESH_LEAD: Duration = Duration::from_secs(300);
40
41/// A control-plane failure. Messages never carry tokens.
42fn auth_error(status: u16, message: impl Into<String>) -> ExecError {
43    ExecError::local(status, FailureScope::Credential, message)
44}
45
46/// Go `time.Time.UTC().Format(time.RFC3339)`.
47fn rfc3339_utc(time: DateTime<Utc>) -> String {
48    time.to_rfc3339_opts(SecondsFormat::Secs, true)
49}
50
51/// `ValidateOAuthEndpoint`: HTTPS on `x.ai` or a subdomain. Returns the trimmed input.
52pub fn validate_endpoint(raw: &str, field: &str) -> Result<String, String> {
53    let raw = raw.trim();
54    if raw.is_empty() {
55        return Err(format!("xai discovery {field} is empty"));
56    }
57    let parsed = xai_url::parse(raw).map_err(|e| format!("xai discovery {field} is invalid: {e}"))?;
58    if parsed.scheme != "https" {
59        return Err(format!("xai discovery {field} must use https: {}", quote(raw)));
60    }
61    let host = parsed.hostname.trim().go_lower();
62    if host != "x.ai" && !host.ends_with(".x.ai") {
63        return Err(format!("xai discovery {field} host {} is not on x.ai", quote(&host)));
64    }
65    Ok(raw.to_owned())
66}
67
68/// Go `url.QueryEscape`.
69fn query_escape(s: &str) -> String {
70    let mut out = String::with_capacity(s.len());
71    for b in s.bytes() {
72        match b {
73            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
74            b' ' => out.push('+'),
75            _ => out.push_str(&format!("%{b:02X}")),
76        }
77    }
78    out
79}
80
81/// Go `url.Values.Encode`: keys sorted.
82fn form(pairs: &[(&str, &str)]) -> String {
83    let mut pairs = pairs.to_vec();
84    pairs.sort_by(|a, b| a.0.cmp(b.0));
85    pairs
86        .iter()
87        .map(|(k, v)| format!("{}={}", query_escape(k), query_escape(v)))
88        .collect::<Vec<_>>()
89        .join("&")
90}
91
92#[derive(Clone, Copy, PartialEq, Eq)]
93enum Field {
94    Str,
95    Int,
96}
97
98/// The result of decoding a flat Go struct of string and int fields.
99#[derive(Default)]
100struct Decoded {
101    strs: HashMap<&'static str, String>,
102    ints: HashMap<&'static str, i64>,
103}
104
105impl Decoded {
106    fn s(&self, key: &str) -> String {
107        self.strs.get(key).cloned().unwrap_or_default()
108    }
109
110    fn i(&self, key: &str) -> i64 {
111        self.ints.get(key).copied().unwrap_or_default()
112    }
113}
114
115/// `json.Unmarshal` into a struct whose fields are strings and ints: keys match the
116/// field name exactly or case-insensitively, the last occurrence wins, null leaves a
117/// field unset, and the first type mismatch is the error (Go keeps decoding, then
118/// returns it). `go_type` is the struct as Go prints it; `field_prefix` its name in
119/// field errors (empty for anonymous structs).
120// ponytail: syntax errors report a fixed text instead of Go's scanner message (for
121// example "invalid character 'o' in literal null"); only CLI login output and refresh
122// error messages differ.
123fn go_unmarshal(
124    body: &[u8],
125    fields: &[(&'static str, Field)],
126    go_type: &str,
127    field_prefix: &str,
128) -> Result<Decoded, String> {
129    if !gj::valid(body) {
130        return Err("invalid JSON input".into());
131    }
132    let root = gj::parse(body);
133    let kind_name = |r: &gj::Res<'_>| match r.kind {
134        Kind::String => "string",
135        Kind::Number => "number",
136        Kind::True | Kind::False => "bool",
137        Kind::Json if r.is_array() => "array",
138        Kind::Json => "object",
139        Kind::Null => "null",
140    };
141    match root.kind {
142        Kind::Null => return Ok(Decoded::default()),
143        Kind::Json if root.is_object() => {}
144        _ => {
145            return Err(format!(
146                "json: cannot unmarshal {} into Go value of type {go_type}",
147                kind_name(&root)
148            ));
149        }
150    }
151    let mut out = Decoded::default();
152    let mut first_error: Option<String> = None;
153    root.each(|key, value| {
154        let key = key.str();
155        let field = fields
156            .iter()
157            .find(|(name, _)| *name == key)
158            .or_else(|| fields.iter().find(|(name, _)| name.go_eq_fold(&key)));
159        let Some(&(name, kind)) = field else { return true };
160        let mismatch = |what: &str| {
161            let ty = if kind == Field::Str { "string" } else { "int" };
162            format!("json: cannot unmarshal {what} into Go struct field {field_prefix}.{name} of type {ty}")
163        };
164        match (kind, value.kind) {
165            (_, Kind::Null) => {}
166            (Field::Str, Kind::String) => {
167                out.strs.insert(name, gj::go_unquote(value.raw()).unwrap_or_default());
168            }
169            (Field::Int, Kind::Number) => match std::str::from_utf8(value.raw())
170                .ok()
171                .and_then(|n| n.parse::<i64>().ok())
172            {
173                Some(n) => {
174                    out.ints.insert(name, n);
175                }
176                // ponytail: Go quotes the number ("number 1.5 into ..."); the value is
177                // response data that reaches logs and returned errors, so the message
178                // names only its kind.
179                None => {
180                    first_error.get_or_insert_with(|| mismatch("number"));
181                }
182            },
183            _ => {
184                first_error.get_or_insert_with(|| mismatch(kind_name(&value)));
185            }
186        }
187        true
188    });
189    match first_error {
190        Some(error) => Err(error),
191        None => Ok(out),
192    }
193}
194
195const DISCOVERY_TYPE: &str = r#"struct { DeviceAuthorizationEndpoint string "json:\"device_authorization_endpoint\""; TokenEndpoint string "json:\"token_endpoint\"" }"#;
196const TOKEN_TYPE: &str = r#"struct { Error string "json:\"error\""; ErrorDescription string "json:\"error_description\""; AccessToken string "json:\"access_token\""; RefreshToken string "json:\"refresh_token\""; IDToken string "json:\"id_token\""; TokenType string "json:\"token_type\""; ExpiresIn int "json:\"expires_in\"" }"#;
197const REFRESH_TYPE: &str = r#"struct { AccessToken string "json:\"access_token\""; RefreshToken string "json:\"refresh_token\""; IDToken string "json:\"id_token\""; TokenType string "json:\"token_type\""; ExpiresIn int "json:\"expires_in\"" }"#;
198const TOKEN_FIELDS: [(&str, Field); 7] = [
199    ("error", Field::Str),
200    ("error_description", Field::Str),
201    ("access_token", Field::Str),
202    ("refresh_token", Field::Str),
203    ("id_token", Field::Str),
204    ("token_type", Field::Str),
205    ("expires_in", Field::Int),
206];
207
208/// Discovered OAuth endpoints.
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct Discovery {
211    pub device_authorization_endpoint: String,
212    pub token_endpoint: String,
213}
214
215/// RFC 8628 device authorization response, plus the token endpoint to poll.
216#[derive(Debug, Clone, Default, PartialEq, Eq)]
217pub struct DeviceCode {
218    pub device_code: String,
219    pub user_code: String,
220    pub verification_uri: String,
221    pub verification_uri_complete: String,
222    pub expires_in: i64,
223    pub interval: i64,
224    pub token_endpoint: String,
225}
226
227/// Go `TokenData`. `expire` is RFC 3339 UTC, empty when the server sent no lifetime.
228#[derive(Debug, Clone, Default, PartialEq, Eq)]
229pub struct TokenData {
230    pub access_token: String,
231    pub refresh_token: String,
232    pub id_token: String,
233    pub token_type: String,
234    pub expires_in: i64,
235    pub expire: String,
236    pub email: String,
237    pub subject: String,
238}
239
240/// `parseJWTIdentity`: email and subject claims from an ID token, unverified.
241pub fn parse_jwt_identity(token: &str) -> (String, String) {
242    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
243    // base64.URLEncoding: padded, discarded bits may be non-zero, CR and LF are skipped.
244    const GO_URL_ENCODING: GeneralPurpose = GeneralPurpose::new(
245        &base64::alphabet::URL_SAFE,
246        GeneralPurposeConfig::new()
247            .with_decode_allow_trailing_bits(true)
248            .with_decode_padding_mode(DecodePaddingMode::RequireCanonical),
249    );
250    let mut parts = token.split('.');
251    let (Some(_), Some(payload)) = (parts.next(), parts.next()) else {
252        return Default::default();
253    };
254    let padded = format!("{payload}{}", "=".repeat((4 - payload.len() % 4) % 4));
255    let padded: String = padded.chars().filter(|c| !matches!(c, '\r' | '\n')).collect();
256    let Ok(raw) = GO_URL_ENCODING.decode(padded) else {
257        return Default::default();
258    };
259    let Some(Ok(claims)) = GoValue::parse_f64(&raw).map(GoValue::into_object) else {
260        return Default::default();
261    };
262    let claim = |k: &str| match claims.get(k) {
263        Some(GoValue::String(s)) => s.trim().to_owned(),
264        _ => String::new(),
265    };
266    (claim("email"), claim("sub"))
267}
268
269/// `time.Duration(seconds) * time.Second` in nanoseconds, wrapping like Go's int64.
270fn go_seconds(seconds: i64) -> i64 {
271    seconds.wrapping_mul(1_000_000_000)
272}
273
274/// `buildTokenData`. Identity comes from the untrimmed ID token, as in Go.
275fn token_data(decoded: &Decoded, now: DateTime<Utc>) -> TokenData {
276    let (email, subject) = parse_jwt_identity(&decoded.s("id_token"));
277    let expires_in = decoded.i("expires_in");
278    let expire = (expires_in > 0).then(|| {
279        let at = now
280            .checked_add_signed(chrono::Duration::nanoseconds(go_seconds(expires_in)))
281            .unwrap_or(now);
282        rfc3339_utc(at)
283    });
284    TokenData {
285        access_token: decoded.s("access_token").trim().to_owned(),
286        refresh_token: decoded.s("refresh_token").trim().to_owned(),
287        id_token: decoded.s("id_token").trim().to_owned(),
288        token_type: decoded.s("token_type").trim().to_owned(),
289        expires_in,
290        expire: expire.unwrap_or_default(),
291        email,
292        subject,
293    }
294}
295
296/// The poll interval Go starts with (`PollForToken`).
297fn initial_interval(device_interval: i64, min_poll: Option<Duration>) -> Duration {
298    let min = min_poll.unwrap_or(DEFAULT_POLL_INTERVAL);
299    let interval = go_seconds(device_interval);
300    if (min_poll.is_some() && device_interval <= 0) || interval < min.as_nanos() as i64 {
301        min
302    } else {
303        Duration::from_nanos(interval as u64)
304    }
305}
306
307/// When polling stops, in nanoseconds after the first poll: 30 minutes, or the device
308/// code lifetime when that is earlier (Go's wrapped duration can lie in the past).
309fn poll_deadline(expires_in: i64) -> i64 {
310    let max = MAX_POLL_DURATION.as_nanos() as i64;
311    if expires_in > 0 {
312        go_seconds(expires_in).min(max)
313    } else {
314        max
315    }
316}
317
318/// One xAI OAuth client.
319#[derive(Clone)]
320pub struct XaiAuth {
321    client: wreq::Client,
322    discovery_url: String,
323    min_poll_interval: Option<Duration>,
324    /// Test seam: requests to `https://auth.x.ai` go to this origin instead, after
325    /// validation (the Go goldens use the same rewrite in their transport).
326    issuer_origin: Option<String>,
327}
328
329impl XaiAuth {
330    pub fn new(client: wreq::Client) -> Self {
331        Self {
332            client,
333            discovery_url: DISCOVERY_URL.into(),
334            min_poll_interval: None,
335            issuer_origin: None,
336        }
337    }
338
339    pub fn with_issuer_origin(mut self, origin: &str) -> Self {
340        self.issuer_origin = Some(origin.into());
341        self
342    }
343
344    /// Where a request for `url` goes. Fails closed when the HTTP client would contact a
345    /// different host than Go's `net/url` reads from the same string.
346    // ponytail: the request target is the WHATWG form of the URL, so dot segments and
347    // backslashes in an accepted path are normalized where Go sends them as given.
348    fn target(&self, url: &str) -> Result<String, ()> {
349        if !crate::xai_url::same_authority(url) {
350            return Err(());
351        }
352        Ok(match (&self.issuer_origin, url.strip_prefix(ISSUER)) {
353            (Some(origin), Some(rest)) => format!("{origin}{rest}"),
354            _ => url.to_owned(),
355        })
356    }
357
358    /// Go's `minPollInterval` test knob.
359    pub fn with_min_poll_interval(mut self, interval: Duration) -> Self {
360        self.min_poll_interval = Some(interval);
361        self
362    }
363
364    /// `http.Client.Do` of a form POST: status and the whole body.
365    async fn post_form(&self, url: &str, body: String) -> Result<(u16, Bytes), ()> {
366        let mut headers = GoHeaders::new();
367        headers.set("User-Agent", "Go-http-client/1.1");
368        headers.set("Content-Type", "application/x-www-form-urlencoded");
369        headers.set("Accept", "application/json");
370        let upstream = crate::proxy::send(&self.client, &self.target(url)?, headers, body, Some(HTTP_TIMEOUT))
371            .await
372            .map_err(|_| ())?;
373        let status = upstream.status;
374        let body = crate::proxy::read_all(upstream.body, crate::proxy::MAX_ERROR_BODY, false)
375            .await
376            .map_err(|_| ())?;
377        Ok((status, body))
378    }
379
380    /// `http.Client.Do` of the discovery GET, following redirects as Go does.
381    async fn get(&self, url: &str) -> Result<(u16, Bytes), ()> {
382        let mut headers = GoHeaders::new();
383        headers.set("User-Agent", "Go-http-client/1.1");
384        headers.set("Accept", "application/json");
385        let upstream = crate::proxy::request(
386            &self.client,
387            wreq::Method::GET,
388            &self.target(url)?,
389            headers,
390            None,
391            Some(HTTP_TIMEOUT),
392        )
393        .await
394        .map_err(|_| ())?;
395        let status = upstream.status;
396        let body = crate::proxy::read_all(upstream.body, crate::proxy::MAX_ERROR_BODY, false)
397            .await
398            .map_err(|_| ())?;
399        Ok((status, body))
400    }
401
402    /// `Discover`.
403    pub async fn discover(&self) -> Result<Discovery, ExecError> {
404        let fail = |m: String| auth_error(502, m);
405        let (status, body) = self
406            .get(&self.discovery_url)
407            .await
408            .map_err(|_| fail("xai discovery: request failed".into()))?;
409        if status != 200 {
410            return Err(fail(format!(
411                "xai discovery failed with status {status}: {}",
412                String::from_utf8_lossy(&body).trim()
413            )));
414        }
415        let wire = go_unmarshal(
416            &body,
417            &[
418                ("device_authorization_endpoint", Field::Str),
419                ("token_endpoint", Field::Str),
420            ],
421            DISCOVERY_TYPE,
422            "",
423        )
424        .map_err(|e| fail(format!("xai discovery: parse response: {e}")))?;
425        let device = validate_endpoint(
426            &wire.s("device_authorization_endpoint"),
427            "device_authorization_endpoint",
428        )
429        .map_err(fail)?;
430        let token = validate_endpoint(&wire.s("token_endpoint"), "token_endpoint").map_err(fail)?;
431        Ok(Discovery {
432            device_authorization_endpoint: device,
433            token_endpoint: token,
434        })
435    }
436
437    /// `StartDeviceFlow`.
438    pub async fn start_device_flow(&self) -> Result<DeviceCode, ExecError> {
439        let discovery = self.discover().await?;
440        self.request_device_code(&discovery.device_authorization_endpoint, &discovery.token_endpoint)
441            .await
442    }
443
444    /// `RequestDeviceCode`.
445    pub async fn request_device_code(
446        &self,
447        device_endpoint: &str,
448        token_endpoint: &str,
449    ) -> Result<DeviceCode, ExecError> {
450        let fail = |m: String| auth_error(502, m);
451        let device_endpoint = device_endpoint.trim();
452        if device_endpoint.is_empty() {
453            return Err(fail(
454                "xai device code: device authorization endpoint is required".into(),
455            ));
456        }
457        let (status, body) = self
458            .post_form(device_endpoint, form(&[("client_id", CLIENT_ID), ("scope", SCOPE)]))
459            .await
460            .map_err(|_| fail("xai device code request failed".into()))?;
461        if status != 200 {
462            return Err(fail(format!(
463                "xai device code request failed with status {status}: {}",
464                String::from_utf8_lossy(&body).trim()
465            )));
466        }
467        let wire = go_unmarshal(
468            &body,
469            &[
470                ("device_code", Field::Str),
471                ("user_code", Field::Str),
472                ("verification_uri", Field::Str),
473                ("verification_uri_complete", Field::Str),
474                ("expires_in", Field::Int),
475                ("interval", Field::Int),
476            ],
477            "xai.DeviceCodeResponse",
478            "DeviceCodeResponse",
479        )
480        .map_err(|e| fail(format!("xai device code: parse response: {e}")))?;
481        let code = DeviceCode {
482            device_code: wire.s("device_code"),
483            user_code: wire.s("user_code"),
484            verification_uri: wire.s("verification_uri"),
485            verification_uri_complete: wire.s("verification_uri_complete"),
486            expires_in: wire.i("expires_in"),
487            interval: wire.i("interval"),
488            token_endpoint: token_endpoint.trim().to_owned(),
489        };
490        if code.device_code.trim().is_empty() {
491            return Err(fail("xai device code: response missing device_code".into()));
492        }
493        if code.user_code.trim().is_empty() {
494            return Err(fail("xai device code: response missing user_code".into()));
495        }
496        if code.verification_uri.trim().is_empty() && code.verification_uri_complete.trim().is_empty() {
497            return Err(fail("xai device code: response missing verification URI".into()));
498        }
499        Ok(code)
500    }
501
502    /// One `exchangeDeviceCode`: `Ok(Some)` tokens, `Ok(None)` keep polling after
503    /// `interval`, `Err` stop.
504    async fn exchange(
505        &self,
506        token_endpoint: &str,
507        device_code: &str,
508        interval: &mut Duration,
509    ) -> Result<Option<TokenData>, ExecError> {
510        let fail = |m: String| auth_error(400, m);
511        let body = form(&[
512            ("client_id", CLIENT_ID),
513            ("device_code", device_code.trim()),
514            ("grant_type", DEVICE_GRANT),
515        ]);
516        let (status, body) = self
517            .post_form(token_endpoint.trim(), body)
518            .await
519            .map_err(|_| auth_error(502, "xai device token request failed"))?;
520        let wire = go_unmarshal(&body, &TOKEN_FIELDS, TOKEN_TYPE, "")
521            .map_err(|e| auth_error(502, format!("xai device token: parse response: {e}")))?;
522        match wire.s("error").as_str() {
523            "" => {}
524            "authorization_pending" => return Ok(None),
525            "slow_down" => {
526                *interval = interval.saturating_add(self.min_poll_interval.unwrap_or(DEFAULT_POLL_INTERVAL));
527                return Ok(None);
528            }
529            "expired_token" => return Err(fail("xai device code expired".into())),
530            "access_denied" => return Err(auth_error(403, "xai device authorization denied")),
531            other => {
532                let description = wire.s("error_description");
533                let description = description.trim();
534                return Err(fail(if description.is_empty() {
535                    format!("xai device token error: {other}")
536                } else {
537                    format!("xai device token error: {other}: {description}")
538                }));
539            }
540        }
541        if status != 200 {
542            return Err(auth_error(
543                502,
544                format!(
545                    "xai device token request failed with status {status}: {}",
546                    String::from_utf8_lossy(&body).trim()
547                ),
548            ));
549        }
550        if wire.s("access_token").trim().is_empty() {
551            return Err(auth_error(502, "xai device token response missing access_token"));
552        }
553        Ok(Some(token_data(&wire, Utc::now())))
554    }
555
556    /// `PollForToken`: the first poll is immediate, then at the device interval (at least
557    /// 5s), slower on `slow_down`, until the code or 30 minutes expire.
558    pub async fn poll(&self, code: &DeviceCode) -> Result<TokenData, ExecError> {
559        let mut token_endpoint = code.token_endpoint.trim().to_owned();
560        if token_endpoint.is_empty() {
561            token_endpoint = self.discover().await?.token_endpoint;
562        }
563        let mut interval = initial_interval(code.interval, self.min_poll_interval);
564        let start = tokio::time::Instant::now();
565        let deadline = poll_deadline(code.expires_in);
566        let mut first = true;
567        loop {
568            if !first {
569                tokio::time::sleep(interval).await;
570                if start.elapsed().as_nanos() as i64 > deadline {
571                    return Err(auth_error(400, "xai device code expired"));
572                }
573            }
574            first = false;
575            if let Some(tokens) = self.exchange(&token_endpoint, &code.device_code, &mut interval).await? {
576                return Ok(tokens);
577            }
578        }
579    }
580
581    /// `RefreshTokens`, single-flighted per refresh token across the process
582    /// (xaiRefreshGroup). Callers that go away do not cancel it.
583    pub async fn refresh(&self, refresh_token: &str, token_endpoint: &str) -> Result<TokenData, ExecError> {
584        if refresh_token.trim().is_empty() {
585            return Err(auth_error(400, "xai token refresh: refresh token is required"));
586        }
587        let refresh_token = refresh_token.trim().to_owned();
588        let mut token_endpoint = token_endpoint.trim().to_owned();
589        if token_endpoint.is_empty() {
590            token_endpoint = self.discover().await?.token_endpoint;
591        }
592        type Flight = Shared<BoxFuture<'static, Result<TokenData, ExecError>>>;
593        static FLIGHTS: LazyLock<Mutex<HashMap<String, Flight>>> = LazyLock::new(Mutex::default);
594        let flight = {
595            let mut flights = FLIGHTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
596            match flights.get(&refresh_token) {
597                Some(flight) => flight.clone(),
598                None => {
599                    let auth = self.clone();
600                    let key = refresh_token.clone();
601                    let task = tokio::spawn(async move {
602                        let result = auth.refresh_once(&key, &token_endpoint).await;
603                        FLIGHTS
604                            .lock()
605                            .unwrap_or_else(std::sync::PoisonError::into_inner)
606                            .remove(&key);
607                        result
608                    });
609                    let flight = async move {
610                        task.await
611                            .map_err(|_| auth_error(502, "xai token refresh task failed"))?
612                    }
613                    .boxed()
614                    .shared();
615                    flights.insert(refresh_token, flight.clone());
616                    flight
617                }
618            }
619        };
620        flight.await
621    }
622
623    /// `refreshTokensSingleFlight` + `postTokenForm`.
624    async fn refresh_once(&self, refresh_token: &str, token_endpoint: &str) -> Result<TokenData, ExecError> {
625        let body = form(&[
626            ("client_id", CLIENT_ID),
627            ("grant_type", "refresh_token"),
628            ("refresh_token", refresh_token),
629        ]);
630        let (status, body) = self
631            .post_form(token_endpoint, body)
632            .await
633            .map_err(|_| auth_error(502, "xai token request failed"))?;
634        if status != 200 {
635            // ponytail: Go appends the response body; it is withheld because token
636            // endpoints may echo credentials and the message reaches management clients
637            // (same choice as the Kimi refresh).
638            return Err(auth_error(
639                status,
640                format!("xai token request failed with status {status}"),
641            ));
642        }
643        let wire = go_unmarshal(&body, &TOKEN_FIELDS[2..], REFRESH_TYPE, "")
644            .map_err(|e| auth_error(502, format!("xai token response: parse body: {e}")))?;
645        if wire.s("access_token").trim().is_empty() {
646            return Err(auth_error(502, "xai token response missing access_token"));
647        }
648        Ok(token_data(&wire, Utc::now()))
649    }
650}
651
652/// `sanitizeFileSegment`.
653fn sanitize_segment(value: &str) -> String {
654    value
655        .trim()
656        .chars()
657        .map(|c| {
658            if c.is_ascii_alphanumeric() || matches!(c, '@' | '.' | '_' | '-') {
659                c
660            } else {
661                '-'
662            }
663        })
664        .collect::<String>()
665        .trim_matches('-')
666        .to_owned()
667}
668
669/// `CredentialFileName`.
670pub fn credential_file_name(email: &str, subject: &str, now_ms: i64) -> String {
671    let email = sanitize_segment(email);
672    if !email.is_empty() {
673        return format!("xai-{email}.json");
674    }
675    let subject = sanitize_segment(subject);
676    if !subject.is_empty() {
677        return format!("xai-{subject}.json");
678    }
679    format!("xai-{now_ms}.json")
680}
681
682/// A finished login: file name, the saved document and label.
683pub struct LoginRecord {
684    pub file_name: String,
685    pub metadata: BTreeMap<String, GoValue>,
686    pub label: String,
687}
688
689fn go_str(s: &str) -> GoValue {
690    GoValue::String(s.to_owned())
691}
692
693/// The credential Go's login saves before any existing file is merged: `TokenStorage`
694/// fields (omitempty) overlaid by the login metadata (sdk/auth/xai.go).
695pub fn login_record(tokens: &TokenData, last_refresh: &str, token_endpoint: &str, now_ms: i64) -> LoginRecord {
696    let email = tokens.email.trim();
697    let mut out = BTreeMap::new();
698    // TokenStorage with omitempty.
699    for (k, v) in [
700        ("id_token", tokens.id_token.as_str()),
701        ("token_type", &tokens.token_type),
702        ("expired", &tokens.expire),
703        ("last_refresh", last_refresh),
704        ("email", email),
705        ("sub", &tokens.subject),
706        ("base_url", DEFAULT_API_BASE_URL),
707        ("token_endpoint", token_endpoint),
708    ] {
709        if !v.is_empty() {
710            out.insert(k.to_owned(), go_str(v));
711        }
712    }
713    if tokens.expires_in != 0 {
714        out.insert("expires_in".into(), GoValue::Number(tokens.expires_in.to_string()));
715    }
716    // Login metadata, always present.
717    for (k, v) in [
718        ("type", "xai"),
719        ("access_token", tokens.access_token.as_str()),
720        ("refresh_token", &tokens.refresh_token),
721        ("id_token", &tokens.id_token),
722        ("token_type", &tokens.token_type),
723        ("expired", &tokens.expire),
724        ("last_refresh", last_refresh),
725        ("base_url", DEFAULT_API_BASE_URL),
726        ("token_endpoint", token_endpoint),
727        ("auth_kind", "oauth"),
728    ] {
729        out.insert(k.to_owned(), go_str(v));
730    }
731    out.insert("expires_in".into(), GoValue::Number(tokens.expires_in.to_string()));
732    if !email.is_empty() {
733        out.insert("email".into(), go_str(email));
734    }
735    if !tokens.subject.is_empty() {
736        out.insert("sub".into(), go_str(&tokens.subject));
737    }
738    LoginRecord {
739        file_name: credential_file_name(email, &tokens.subject, now_ms),
740        metadata: out,
741        label: if email.is_empty() { "xAI".into() } else { email.into() },
742    }
743}
744
745/// `IsAuthTokenPayloadKey`.
746fn is_token_key(key: &str) -> bool {
747    matches!(
748        key.trim().go_lower().as_str(),
749        "access_token"
750            | "refresh_token"
751            | "id_token"
752            | "session_id"
753            | "expired"
754            | "last_refresh"
755            | "expires_in"
756            | "timestamp"
757            | "token_type"
758            | "user_code"
759            | "verification_uri"
760            | "verification_uri_complete"
761    )
762}
763
764/// `CanonicalCredentialMetadataKey`.
765fn canonical_key(key: &str) -> &str {
766    match key {
767        "api-key" => "api_key",
768        "base-url" => "base_url",
769        "disable-cooling" => "disable_cooling",
770        "excluded-models" => "excluded_models",
771        "fingerprint-profile" => "fingerprint_profile",
772        "model-aliases" => "model_aliases",
773        "openapi-location" => "openapi_location",
774        "openapi-models" => "openapi_models",
775        "proxy-url" => "proxy_url",
776        "request-retry" => "request_retry",
777        "request-scoped-errors" => "request_scoped_errors",
778        "tool-prefix-disabled" => "tool_prefix_disabled",
779        other => other,
780    }
781}
782
783/// The file `Manager.Login` + `FileTokenStore.Save` write: non-token fields of an
784/// existing file are kept (`MergeExistingAuthMetadata`), legacy keys are renamed
785/// (`NormalizeCredentialMetadata`), `disabled` is the existing boolean or false, and a
786/// merged `weight` must be valid (`ValidateAuthWeight`) or nothing is written.
787pub fn saved_document(
788    mut record: BTreeMap<String, GoValue>,
789    existing: Option<&[u8]>,
790) -> Result<BTreeMap<String, GoValue>, String> {
791    let existing = existing
792        .and_then(GoValue::parse_f64)
793        .and_then(|v| v.into_object().ok())
794        .filter(|map| !map.is_empty());
795    let mut disabled = false;
796    if let Some(existing) = existing {
797        if let Some(GoValue::Bool(b)) = existing.get("disabled") {
798            disabled = *b;
799        }
800        for (k, v) in existing {
801            if !is_token_key(&k) {
802                record.entry(k).or_insert(v);
803            }
804        }
805    }
806    let legacy: Vec<String> = record
807        .keys()
808        .filter(|k| canonical_key(k) != k.as_str())
809        .cloned()
810        .collect();
811    for key in legacy {
812        let value = record.remove(&key).expect("present");
813        record.entry(canonical_key(&key).to_owned()).or_insert(value);
814    }
815    if let Some(weight) = record.get("weight") {
816        let json = match weight {
817            GoValue::Number(n) => serde_json::from_str(n).unwrap_or(Value::Null),
818            GoValue::String(s) => Value::String(s.clone()),
819            _ => Value::Null,
820        };
821        cpa_core::config::credentials::parse_weight(&json)
822            .map_err(|e| format!("auth filestore: invalid metadata weight: {e}"))?;
823    }
824    record.insert("disabled".into(), GoValue::Bool(disabled));
825    Ok(record)
826}
827
828/// `xaiMetadataString`: a metadata value as `fmt.Sprint` prints it (JSON numbers are
829/// float64 in Go's decoded auth files), trimmed; missing and null are empty.
830pub(crate) fn metadata_string(credential: &Credential, key: &str) -> String {
831    match credential.metadata.get(key) {
832        None | Some(Value::Null) => String::new(),
833        Some(value) => go_sprint(value).trim().to_owned(),
834    }
835}
836
837/// `fmt.Sprint` of a value decoded by `encoding/json` into `any`.
838fn go_sprint(value: &Value) -> String {
839    match value {
840        Value::Null => "<nil>".into(),
841        Value::Bool(b) => b.to_string(),
842        Value::String(s) => s.clone(),
843        Value::Number(n) => go_float_v(n.as_f64().unwrap_or(f64::NAN)),
844        Value::Array(items) => format!("[{}]", items.iter().map(go_sprint).collect::<Vec<_>>().join(" ")),
845        Value::Object(map) => {
846            let mut keys: Vec<&String> = map.keys().collect();
847            keys.sort();
848            let items: Vec<String> = keys.iter().map(|k| format!("{k}:{}", go_sprint(&map[*k]))).collect();
849            format!("map[{}]", items.join(" "))
850        }
851    }
852}
853
854/// `%v` of a float64: `strconv.FormatFloat(f, 'g', -1, 64)`, the shortest digits in
855/// exponent form when the decimal exponent is below -4 or at least 6.
856pub(crate) fn go_float_v(f: f64) -> String {
857    if f.is_nan() {
858        return "NaN".into();
859    }
860    if f.is_infinite() {
861        return if f > 0.0 { "+Inf".into() } else { "-Inf".into() };
862    }
863    if f == 0.0 {
864        return if f.is_sign_negative() { "-0".into() } else { "0".into() };
865    }
866    let sci = format!("{f:e}");
867    let (mantissa, exp) = sci.split_once('e').expect("exponent form");
868    let exp: i32 = exp.parse().expect("exponent");
869    if !(-4..6).contains(&exp) {
870        let sign = if exp < 0 { '-' } else { '+' };
871        return format!("{mantissa}e{sign}{:02}", exp.abs());
872    }
873    format!("{f}")
874}
875
876/// Metadata change for a successful refresh (`XAIExecutor.Refresh`).
877pub fn refresh_patch(
878    credential: &Credential,
879    tokens: &TokenData,
880    token_endpoint: &str,
881    now: DateTime<Utc>,
882) -> MetadataPatch {
883    let mut patch = MetadataPatch::default();
884    let mut set = |k: &str, v: Value| {
885        patch.set.insert(k.into(), v);
886    };
887    set("type", json!("xai"));
888    set("auth_kind", json!("oauth"));
889    set("access_token", json!(tokens.access_token));
890    for (key, value) in [
891        ("refresh_token", &tokens.refresh_token),
892        ("id_token", &tokens.id_token),
893        ("token_type", &tokens.token_type),
894        ("expired", &tokens.expire),
895        ("email", &tokens.email),
896        ("sub", &tokens.subject),
897    ] {
898        if !value.is_empty() {
899            set(key, json!(value));
900        }
901    }
902    if tokens.expires_in > 0 {
903        set("expires_in", json!(tokens.expires_in));
904    }
905    if !token_endpoint.is_empty() {
906        set("token_endpoint", json!(token_endpoint));
907    }
908    if metadata_string(credential, "base_url").is_empty() {
909        set("base_url", json!(DEFAULT_API_BASE_URL));
910    }
911    set("last_refresh", json!(rfc3339_utc(now)));
912    patch
913}
914
915/// Whether the background loop should refresh: a refresh token and expiry within the
916/// SDK lead (`RefreshSoon`; requests keep the current token).
917pub fn needs_refresh(credential: &Credential, now: DateTime<Utc>) -> bool {
918    !metadata_string(credential, "refresh_token").is_empty()
919        && crate::kimi_http::refresh_due(
920            credential,
921            Some(chrono::Duration::from_std(REFRESH_LEAD).expect("lead fits")),
922            now,
923        )
924}
925
926/// `XAIExecutor.Refresh`: nothing to do without a refresh token.
927pub async fn refresh(auth: &XaiAuth, credential: &Credential) -> Result<MetadataPatch, ExecError> {
928    let refresh_token = metadata_string(credential, "refresh_token");
929    if refresh_token.is_empty() {
930        return Ok(MetadataPatch::default());
931    }
932    let token_endpoint = metadata_string(credential, "token_endpoint");
933    let tokens = auth.refresh(&refresh_token, &token_endpoint).await?;
934    Ok(refresh_patch(credential, &tokens, &token_endpoint, Utc::now()))
935}
936
937/// `--xai-login`: device flow through `requests.proxy-url`, then the credential file.
938pub async fn login(cfg: &Config, no_browser: bool) -> Result<PathBuf, ExecError> {
939    let proxy = cfg
940        .document
941        .get("requests")
942        .and_then(|r| r.get("proxy-url"))
943        .and_then(|v| v.as_str())
944        .unwrap_or_default();
945    let client = GoClients::new(Default::default()).get(&Proxy::parse(proxy));
946    login_with(XaiAuth::new(client), &cfg.auth_dir, no_browser).await
947}
948
949pub(crate) async fn login_with(auth: XaiAuth, auth_dir: &Path, no_browser: bool) -> Result<PathBuf, ExecError> {
950    println!("Starting xAI authentication...");
951    let code = auth.start_device_flow().await.map_err(|e| {
952        auth_error(
953            e.status,
954            format!("xai: failed to start device flow: {}", String::from_utf8_lossy(&e.body)),
955        )
956    })?;
957    let url = if code.verification_uri_complete.trim().is_empty() {
958        code.verification_uri.trim()
959    } else {
960        code.verification_uri_complete.trim()
961    };
962    print!("\nTo authenticate, please visit:\n{url}\n\n");
963    if !code.user_code.is_empty() {
964        print!("Then enter this code: {}\n\n", code.user_code);
965    }
966    if !no_browser && crate::kimi_auth::open_browser(url) {
967        println!("Browser opened automatically.");
968    }
969    println!("Waiting for authorization...");
970    if code.expires_in > 0 {
971        println!("(This will timeout in {} seconds if not authorized)", code.expires_in);
972    }
973    let tokens = auth
974        .poll(&code)
975        .await
976        .map_err(|e| auth_error(e.status, format!("xai: {}", String::from_utf8_lossy(&e.body))))?;
977    if tokens.access_token.trim().is_empty() {
978        return Err(auth_error(502, "xai token storage missing access token"));
979    }
980    println!("xAI authentication successful");
981    let record = login_record(
982        &tokens,
983        &rfc3339_utc(Utc::now()),
984        &code.token_endpoint,
985        Utc::now().timestamp_millis(),
986    );
987    let path = auth_dir.join(&record.file_name);
988    let target = path.clone();
989    let metadata = record.metadata;
990    tokio::task::spawn_blocking(move || {
991        let existing = std::fs::read(&target).ok().filter(|raw| !raw.is_empty());
992        let document = GoValue::Object(saved_document(metadata, existing.as_deref()).map_err(|e| auth_error(500, e))?);
993        crate::kimi_auth::write_private(&target, &document.encode_indented())
994            .map_err(|_| auth_error(500, "xai: cannot write credential file"))
995    })
996    .await
997    .map_err(|_| auth_error(500, "xai: credential publication failed"))??;
998    println!("Authentication saved to {}", path.display());
999    println!("Authenticated as {}", record.label);
1000    println!("xAI authentication successful!");
1001    Ok(path)
1002}
1003
1004#[cfg(test)]
1005#[path = "xai_auth_tests.rs"]
1006mod tests;