Skip to main content

cpa_exec/
antigravity_auth.rs

1//! Antigravity OAuth (internal/auth/antigravity, sdk/auth/antigravity.go) and the
2//! executor's credential preparation (antigravity_executor_auth.go).
3//!
4//! An Antigravity credential is a Google OAuth token plus the Cloud Code project it
5//! works in. Requests wait for the project ID (Go's `RequestAuthPreparer`): it comes from
6//! `loadCodeAssist`, else from onboarding the user to the default tier. Tokens refresh in
7//! the background 30 minutes before they expire, and before a project lookup when less
8//! than five minutes remain.
9
10use std::path::{Path, PathBuf};
11use std::sync::LazyLock;
12use std::time::Duration;
13
14use bytes::Bytes;
15use chrono::{DateTime, Utc};
16use cpa_common::gostr::{GoStr, values_encode};
17use cpa_common::json::{self as gj, GoValue};
18use cpa_core::config::Config;
19use cpa_core::credential::{Credential, MetadataPatch};
20use cpa_core::exec::{ExecError, FailureScope};
21use serde_json::{Map, Value};
22
23use crate::antigravity_version as version;
24use crate::meta_wire::{self, Slot};
25use crate::proxy::{self, GoClients, GoHeaders, Proxy, Upstream};
26
27pub const PROVIDER: &str = "antigravity";
28/// The Antigravity desktop app's OAuth client (internal/auth/antigravity/constants.go).
29pub const CLIENT_ID: &str = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
30pub const CLIENT_SECRET: &str = "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";
31pub const DEFAULT_CALLBACK_PORT: u16 = 51121;
32pub const SCOPES: [&str; 5] = [
33    "https://www.googleapis.com/auth/cloud-platform",
34    "https://www.googleapis.com/auth/userinfo.email",
35    "https://www.googleapis.com/auth/userinfo.profile",
36    "https://www.googleapis.com/auth/cclog",
37    "https://www.googleapis.com/auth/experimentsandconfigs",
38];
39pub const TOKEN_ENDPOINT: &str = "https://oauth2.googleapis.com/token";
40pub const AUTH_ENDPOINT: &str = "https://accounts.google.com/o/oauth2/v2/auth";
41pub const USERINFO_ENDPOINT: &str = "https://www.googleapis.com/oauth2/v2/userinfo?alt=json";
42pub const API_ENDPOINT: &str = "https://cloudcode-pa.googleapis.com";
43pub const DAILY_API_ENDPOINT: &str = "https://daily-cloudcode-pa.googleapis.com";
44pub const API_VERSION: &str = "v1internal";
45/// `AntigravityAuthenticator.RefreshLead`.
46pub const REFRESH_LEAD: chrono::TimeDelta = chrono::TimeDelta::minutes(30);
47/// `antigravityRequestTokenSafetyWindow`.
48const TOKEN_SAFETY_WINDOW: chrono::TimeDelta = chrono::TimeDelta::minutes(5);
49/// `antigravityCredentialAcquisitionTimeout`.
50pub(crate) const ACQUISITION_TIMEOUT: Duration = Duration::from_secs(30);
51const ONBOARD_ATTEMPTS: u32 = 5;
52const ONBOARD_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(30);
53
54/// A failed auth step: Go's error text, and the status of an `HTTPStatusError` (or a
55/// `statusErr`), with its retry hint.
56#[derive(Debug, Clone, PartialEq)]
57pub struct AuthError {
58    pub status: Option<u16>,
59    pub message: String,
60    pub retry_after: Option<Duration>,
61}
62
63impl AuthError {
64    fn plain(message: impl Into<String>) -> Self {
65        Self {
66            status: None,
67            message: message.into(),
68            retry_after: None,
69        }
70    }
71
72    fn http(status: u16, message: impl Into<String>) -> Self {
73        Self {
74            status: Some(status),
75            message: message.into(),
76            retry_after: None,
77        }
78    }
79
80    /// Go's `fmt.Errorf("%s: %w", prefix, err)`: the status survives wrapping.
81    fn wrap(self, prefix: &str) -> Self {
82        Self {
83            message: format!("{prefix}: {}", self.message),
84            ..self
85        }
86    }
87}
88
89impl std::fmt::Display for AuthError {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.write_str(&self.message)
92    }
93}
94
95fn transport_text(error: &ExecError) -> String {
96    String::from_utf8_lossy(&error.body).into_owned()
97}
98
99/// `CredentialFileName`.
100pub fn credential_file_name(email: &str) -> String {
101    match email.trim() {
102        "" => "antigravity.json".into(),
103        email => format!("antigravity-{}.json", crate::file_name_email(email)),
104    }
105}
106
107/// `AntigravityDefaultCallbackURI` for a callback port.
108pub fn redirect_uri(port: u16) -> String {
109    format!("http://localhost:{port}/oauth-callback")
110}
111
112/// `BuildAuthURL`.
113pub fn auth_url(state: &str, redirect_uri: &str) -> String {
114    let redirect = if redirect_uri.trim().is_empty() {
115        self::redirect_uri(DEFAULT_CALLBACK_PORT)
116    } else {
117        redirect_uri.to_owned()
118    };
119    let scope = SCOPES.join(" ");
120    let query = values_encode(&[
121        ("access_type", "offline"),
122        ("client_id", CLIENT_ID),
123        ("prompt", "consent"),
124        ("redirect_uri", &redirect),
125        ("response_type", "code"),
126        ("scope", &scope),
127        ("state", state),
128    ]);
129    format!("{AUTH_ENDPOINT}?{query}")
130}
131
132/// A token endpoint answer (`TokenResponse`, `antigravityTokenRefreshData`).
133#[derive(Debug, Clone, Default, PartialEq)]
134pub struct Tokens {
135    pub access_token: String,
136    pub refresh_token: String,
137    pub expires_in: i64,
138    pub token_type: String,
139}
140
141impl Tokens {
142    /// `json.Unmarshal` (`first_value`: `json.NewDecoder(...).Decode`, which reads only
143    /// the first JSON value) into the token struct.
144    fn decode(data: &[u8], first_value: bool, name: &str) -> Result<Self, String> {
145        let mut tokens = Self::default();
146        let mut fields = [
147            ("access_token", Slot::Str(&mut tokens.access_token)),
148            ("refresh_token", Slot::Str(&mut tokens.refresh_token)),
149            ("expires_in", Slot::Int(&mut tokens.expires_in, "int64")),
150            ("token_type", Slot::Str(&mut tokens.token_type)),
151        ];
152        let data = if first_value { first_json_value(data)? } else { data };
153        meta_wire::unmarshal(data, "antigravity", name, &mut fields)?;
154        Ok(tokens)
155    }
156}
157
158/// What `json.Decoder.Decode` reads: the object at the start of `data` (after white
159/// space), or the whole input for anything else, whose decoding fails either way.
160fn first_json_value(data: &[u8]) -> Result<&[u8], String> {
161    let start = data
162        .iter()
163        .position(|c| !matches!(c, b' ' | b'\t' | b'\r' | b'\n'))
164        .ok_or("EOF")?;
165    let value = &data[start..];
166    if value.starts_with(b"{") {
167        return meta_wire::object_end(value)
168            .map(|end| &value[..end])
169            .ok_or_else(|| "unexpected EOF".to_owned());
170    }
171    Ok(value)
172}
173
174/// `json.Unmarshal(body, &map[string]any)`: `None` for `null`.
175fn decode_map(data: &[u8]) -> Result<Option<std::collections::BTreeMap<String, GoValue>>, String> {
176    meta_wire::check_valid(data)?;
177    let value = GoValue::parse_f64(data).map(GoValue::into_object);
178    match value {
179        Some(Ok(map)) => Ok(Some(map)),
180        Some(Err(GoValue::Null)) => Ok(None),
181        Some(Err(GoValue::Array(_))) => {
182            Err("json: cannot unmarshal array into Go value of type map[string]interface {}".into())
183        }
184        Some(Err(GoValue::String(_))) => {
185            Err("json: cannot unmarshal string into Go value of type map[string]interface {}".into())
186        }
187        Some(Err(GoValue::Bool(_))) => {
188            Err("json: cannot unmarshal bool into Go value of type map[string]interface {}".into())
189        }
190        Some(Err(_)) => Err("json: cannot unmarshal number into Go value of type map[string]interface {}".into()),
191        None => Err("json: cannot unmarshal number into Go value of type float64".into()),
192    }
193}
194
195type GoMap = std::collections::BTreeMap<String, GoValue>;
196
197fn go_str<'a>(map: &'a GoMap, key: &str) -> Option<&'a str> {
198    match map.get(key) {
199        Some(GoValue::String(s)) => Some(s),
200        _ => None,
201    }
202}
203
204/// `extractCloudaicompanionProject`.
205fn extract_project(data: Option<&GoMap>) -> String {
206    let Some(data) = data else {
207        return String::new();
208    };
209    for key in ["cloudaicompanionProject", "projectId", "project"] {
210        let found = match data.get(key) {
211            Some(GoValue::String(s)) => s.trim(),
212            Some(GoValue::Object(inner)) => go_str(inner, "id").map(str::trim).unwrap_or_default(),
213            _ => "",
214        };
215        if !found.is_empty() {
216            return found.to_owned();
217        }
218    }
219    String::new()
220}
221
222/// `defaultAntigravityTierID`: the default allowed tier, else the current tier, else
223/// `free-tier`.
224fn default_tier(load: Option<&GoMap>) -> String {
225    let Some(load) = load else {
226        return "free-tier".into();
227    };
228    if let Some(GoValue::Array(tiers)) = load.get("allowedTiers") {
229        for tier in tiers {
230            let GoValue::Object(tier) = tier else { continue };
231            if !matches!(tier.get("isDefault"), Some(GoValue::Bool(true))) {
232                continue;
233            }
234            if let Some(id) = go_str(tier, "id").map(str::trim).filter(|id| !id.is_empty()) {
235                return id.to_owned();
236            }
237        }
238    }
239    if let Some(GoValue::Object(current)) = load.get("currentTier")
240        && let Some(id) = go_str(current, "id").map(str::trim).filter(|id| !id.is_empty())
241    {
242        return id.to_owned();
243    }
244    "free-tier".into()
245}
246
247/// The OAuth and Cloud Code calls of `AntigravityAuth`, over one client.
248pub struct OAuth {
249    client: wreq::Client,
250    token_endpoint: String,
251    userinfo_endpoint: String,
252    api_endpoint: String,
253    daily_api_endpoint: String,
254    /// Pause between onboarding polls (two seconds; tests shorten it).
255    poll_delay: Duration,
256}
257
258impl OAuth {
259    pub fn new(client: wreq::Client) -> Self {
260        Self::with_endpoints(
261            client,
262            TOKEN_ENDPOINT,
263            USERINFO_ENDPOINT,
264            API_ENDPOINT,
265            DAILY_API_ENDPOINT,
266        )
267    }
268
269    /// Redirects OAuth traffic to local mocks without changing the login flow.
270    pub fn with_endpoints(client: wreq::Client, token: &str, userinfo: &str, api: &str, daily_api: &str) -> Self {
271        Self {
272            client,
273            token_endpoint: token.into(),
274            userinfo_endpoint: userinfo.into(),
275            api_endpoint: api.into(),
276            daily_api_endpoint: daily_api.into(),
277            poll_delay: Duration::from_secs(2),
278        }
279    }
280
281    #[cfg(test)]
282    pub(crate) fn with_poll_delay(mut self, delay: Duration) -> Self {
283        self.poll_delay = delay;
284        self
285    }
286
287    async fn post(
288        &self,
289        url: &str,
290        headers: GoHeaders,
291        body: Vec<u8>,
292        timeout: Option<Duration>,
293    ) -> Result<Upstream, ExecError> {
294        proxy::request(
295            &self.client,
296            wreq::Method::POST,
297            url,
298            headers,
299            Some(Bytes::from(body)),
300            timeout,
301        )
302        .await
303    }
304
305    /// `ExchangeCodeForTokens`.
306    pub async fn exchange_code(&self, code: &str, redirect_uri: &str) -> Result<Tokens, AuthError> {
307        const STEP: &str = "antigravity token exchange";
308        let form = values_encode(&[
309            ("code", code),
310            ("client_id", CLIENT_ID),
311            ("client_secret", CLIENT_SECRET),
312            ("redirect_uri", redirect_uri),
313            ("grant_type", "authorization_code"),
314        ]);
315        let mut headers = GoHeaders::new();
316        headers.set("Content-Type", "application/x-www-form-urlencoded");
317        let upstream = self
318            .post(&self.token_endpoint, headers, form.into_bytes(), None)
319            .await
320            .map_err(|e| AuthError::plain(format!("{STEP}: execute request: {}", transport_text(&e))))?;
321        let status = upstream.status;
322        if !(200..300).contains(&status) {
323            let body = proxy::read_all(upstream.body, 8 << 10, false)
324                .await
325                .map_err(|e| AuthError::plain(format!("{STEP}: read response: {}", transport_text(&e))))?;
326            return Err(AuthError::http(
327                status,
328                status_message(STEP, status, &token_error_code(&body)),
329            ));
330        }
331        let body = proxy::read_all(upstream.body, usize::MAX, false)
332            .await
333            .map_err(|e| AuthError::plain(format!("{STEP}: decode response: {}", transport_text(&e))))?;
334        Tokens::decode(&body, true, "TokenResponse")
335            .map_err(|e| AuthError::plain(format!("{STEP}: decode response: {e}")))
336    }
337
338    /// `FetchUserInfo`: the account email.
339    pub async fn user_info(&self, access_token: &str) -> Result<String, AuthError> {
340        const STEP: &str = "antigravity userinfo";
341        let access_token = access_token.trim();
342        if access_token.is_empty() {
343            return Err(AuthError::plain(format!("{STEP}: missing access token")));
344        }
345        let mut headers = GoHeaders::new();
346        headers.set("Authorization", format!("Bearer {access_token}"));
347        headers.set("User-Agent", version::request_user_agent(""));
348        let upstream = proxy::request(
349            &self.client,
350            wreq::Method::GET,
351            &self.userinfo_endpoint,
352            headers,
353            None,
354            None,
355        )
356        .await
357        .map_err(|e| AuthError::plain(format!("{STEP}: execute request: {}", transport_text(&e))))?;
358        let status = upstream.status;
359        if !(200..300).contains(&status) {
360            let body = proxy::read_all(upstream.body, 8 << 10, false)
361                .await
362                .map_err(|e| AuthError::plain(format!("{STEP}: read response: {}", transport_text(&e))))?;
363            return Err(AuthError::http(status, status_message(STEP, status, &body)));
364        }
365        let body = proxy::read_all(upstream.body, usize::MAX, false)
366            .await
367            .map_err(|e| AuthError::plain(format!("{STEP}: decode response: {}", transport_text(&e))))?;
368        let mut email = String::new();
369        let mut fields = [("email", Slot::Str(&mut email))];
370        first_json_value(&body)
371            .and_then(|value| meta_wire::unmarshal(value, "antigravity", "userInfo", &mut fields))
372            .map_err(|e| AuthError::plain(format!("{STEP}: decode response: {e}")))?;
373        let email = email.trim();
374        if email.is_empty() {
375            return Err(AuthError::plain(format!("{STEP}: response missing email")));
376        }
377        Ok(email.to_owned())
378    }
379
380    /// `FetchProjectID`: `loadCodeAssist`'s project, else onboarding to its default tier.
381    pub async fn project_id(&self, access_token: &str) -> Result<String, AuthError> {
382        let body = br#"{"metadata":{"ideType":"ANTIGRAVITY"}}"#.to_vec();
383        let mut headers = GoHeaders::new();
384        headers.set("Authorization", format!("Bearer {access_token}"));
385        headers.set("Accept", "*/*");
386        headers.set("Content-Type", "application/json");
387        headers.set("User-Agent", version::request_user_agent(""));
388        let url = format!("{}/{API_VERSION}:loadCodeAssist", self.api_endpoint);
389        let upstream = self
390            .post(&url, headers, body, None)
391            .await
392            .map_err(|e| AuthError::plain(format!("execute request: {}", transport_text(&e))))?;
393        let status = upstream.status;
394        let data = proxy::read_all(upstream.body, usize::MAX, false)
395            .await
396            .map_err(|e| AuthError::plain(format!("read response: {}", transport_text(&e))))?;
397        if !(200..300).contains(&status) {
398            return Err(AuthError::http(
399                status,
400                format!(
401                    "request failed with status {status}: {}",
402                    String::from_utf8_lossy(cpa_common::gostr::trim_space(&data))
403                ),
404            ));
405        }
406        let load = decode_map(&data).map_err(|e| AuthError::plain(format!("decode response: {e}")))?;
407        let project = extract_project(load.as_ref());
408        if !project.is_empty() {
409            return Ok(project);
410        }
411        let project = self.onboard(access_token, &default_tier(load.as_ref())).await?;
412        if project.is_empty() {
413            return Err(AuthError::plain(
414                "project id not found in loadCodeAssist or onboardUser response",
415            ));
416        }
417        Ok(project)
418    }
419
420    /// `OnboardUser`: polls `onboardUser` until the operation is done, five times at most.
421    pub async fn onboard(&self, access_token: &str, tier: &str) -> Result<String, AuthError> {
422        tracing::info!("Antigravity: onboarding user with tier: {tier}");
423        let user_agent = version::onboard_user_user_agent("");
424        let s = |v: &str| GoValue::String(v.to_owned());
425        let metadata = GoMap::from([
426            ("ide_type".to_owned(), s("ANTIGRAVITY")),
427            (
428                "ide_version".to_owned(),
429                s(&version::version_from_user_agent(&user_agent)),
430            ),
431            ("ide_name".to_owned(), s("antigravity")),
432        ]);
433        let body = GoValue::Object(GoMap::from([
434            ("tier_id".to_owned(), s(tier)),
435            ("metadata".to_owned(), GoValue::Object(metadata)),
436        ]))
437        .marshal();
438        let url = format!("{}/{API_VERSION}:onboardUser", self.daily_api_endpoint);
439        for attempt in 1..=ONBOARD_ATTEMPTS {
440            tracing::debug!("Polling attempt {attempt}/{ONBOARD_ATTEMPTS}");
441            let mut headers = GoHeaders::new();
442            headers.set("Authorization", format!("Bearer {access_token}"));
443            headers.set("Accept", "*/*");
444            headers.set("Content-Type", "application/json");
445            headers.set("User-Agent", user_agent.clone());
446            headers.set("X-Goog-Api-Client", version::GOOG_API_CLIENT_UA);
447            let read = async {
448                let upstream = self
449                    .post(&url, headers, body.clone(), None)
450                    .await
451                    .map_err(|e| AuthError::plain(format!("execute request: {}", transport_text(&e))))?;
452                let status = upstream.status;
453                let data = proxy::read_all(upstream.body, usize::MAX, false)
454                    .await
455                    .map_err(|e| AuthError::plain(format!("read response: {}", transport_text(&e))))?;
456                Ok::<_, AuthError>((status, data))
457            };
458            let (status, data) = tokio::time::timeout(ONBOARD_ATTEMPT_TIMEOUT, read)
459                .await
460                .map_err(|_| AuthError::plain("execute request: context deadline exceeded"))??;
461            if status == 200 {
462                let response = decode_map(&data).map_err(|e| AuthError::plain(format!("decode response: {e}")))?;
463                let response = response.unwrap_or_default();
464                if matches!(response.get("done"), Some(GoValue::Bool(true))) {
465                    let project = match response.get("response") {
466                        Some(GoValue::Object(inner)) => extract_project(Some(inner)),
467                        _ => String::new(),
468                    };
469                    if project.is_empty() {
470                        return Err(AuthError::plain("no project_id in response"));
471                    }
472                    tracing::info!("Successfully fetched project_id: {}", hide(&project));
473                    return Ok(project);
474                }
475                tokio::time::sleep(self.poll_delay).await;
476                continue;
477            }
478            // Go cuts the body to 500 bytes for its preview, then to 200 for the error.
479            let preview = cpa_common::gostr::trim_space(&data);
480            let preview = &preview[..preview.len().min(500)];
481            let preview = &preview[..preview.len().min(200)];
482            return Err(AuthError::http(
483                status,
484                format!("http {status}: {}", String::from_utf8_lossy(preview)),
485            ));
486        }
487        Err(AuthError::plain(format!(
488            "onboard user did not complete after {ONBOARD_ATTEMPTS} attempts"
489        )))
490    }
491
492    /// The executor's `refreshTokenSingleFlight`: a refresh grant with Go's fixed Host
493    /// and user agent. A 429 carries Google's retry hint.
494    pub async fn refresh(&self, refresh_token: &str) -> Result<Tokens, ExecError> {
495        let form = values_encode(&[
496            ("client_id", CLIENT_ID),
497            ("client_secret", CLIENT_SECRET),
498            ("grant_type", "refresh_token"),
499            ("refresh_token", refresh_token),
500        ]);
501        let mut headers = GoHeaders::new();
502        headers.set("Host", "oauth2.googleapis.com");
503        headers.set("Content-Type", "application/x-www-form-urlencoded");
504        headers.set("User-Agent", "Go-http-client/2.0");
505        let upstream = self
506            .post(&self.token_endpoint, headers, form.into_bytes(), None)
507            .await?;
508        let status = upstream.status;
509        let data = proxy::read_all(upstream.body, usize::MAX, false).await?;
510        if !(200..300).contains(&status) {
511            let code = token_error_code(&data);
512            let message = if code.is_empty() {
513                format!("token refresh failed with status {status}")
514            } else {
515                format!(
516                    "token refresh failed with status {status}: {}",
517                    String::from_utf8_lossy(&code)
518                )
519            };
520            let mut error = crate::gemini::status_err(status, message);
521            if status == 429 {
522                error.retry_after = parse_retry_delay(&data);
523            }
524            return Err(error);
525        }
526        Tokens::decode(&data, false, "antigravityTokenRefreshData")
527            .map_err(|e| ExecError::local(500, FailureScope::Credential, e))
528    }
529}
530
531/// What a failed token endpoint answer may show: its OAuth `error` code (or a Google
532/// API error's `status`) when it is a short plain token, else nothing. Go shows the whole
533/// body; a token endpoint is sent the authorization code, the refresh token and the
534/// client secret, so its body stays out of errors, logs and client answers, as for the
535/// other providers' sign-ins (docs/DIFFERENCES-FROM-GO.md).
536fn token_error_code(body: &[u8]) -> Vec<u8> {
537    let error = gj::get(body, "error");
538    let code = if error.kind == gj::Kind::String {
539        error.bytes().into_owned()
540    } else {
541        error.get("status").bytes().into_owned()
542    };
543    if code.len() <= 64
544        && code
545            .iter()
546            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.'))
547    {
548        code
549    } else {
550        Vec::new()
551    }
552}
553
554/// `HTTPStatusError` texts of the token exchange and user info calls.
555fn status_message(step: &str, status: u16, body: &[u8]) -> String {
556    let body = String::from_utf8_lossy(cpa_common::gostr::trim_space(body)).into_owned();
557    if body.is_empty() {
558        format!("{step}: request failed: status {status}")
559    } else {
560        format!("{step}: request failed: status {status}: {body}")
561    }
562}
563
564/// `util.HideAPIKey` (on bytes, as Go): four bytes at each end of a value longer than
565/// eight, two above four, one above two.
566fn hide(value: &str) -> String {
567    let bytes = value.as_bytes();
568    let keep = match bytes.len() {
569        9.. => 4,
570        5.. => 2,
571        3.. => 1,
572        _ => return value.to_owned(),
573    };
574    String::from_utf8_lossy(&[&bytes[..keep], b"...", &bytes[bytes.len() - keep..]].concat()).into_owned()
575}
576
577/// `helps.ParseRetryDelay`: Google's `RetryInfo.retryDelay`, then
578/// `ErrorInfo.metadata.quotaResetDelay`, then "after Ns" in the message, then a
579/// positive "after 1h2m3s" in the lowercased message.
580pub(crate) fn parse_retry_delay(body: &[u8]) -> Option<Duration> {
581    let details = gj::get(body, "error.details");
582    if details.exists() && details.is_array() {
583        for detail in details.array() {
584            if detail.get("@type").str() != "type.googleapis.com/google.rpc.RetryInfo" {
585                continue;
586            }
587            let delay = detail.get("retryDelay").str().into_owned();
588            if delay.is_empty() {
589                continue;
590            }
591            // Go returns an error (no hint) when the first RetryInfo delay is malformed.
592            return cpa_core::config::parse_duration(&delay).map(nanos);
593        }
594        for detail in details.array() {
595            if detail.get("@type").str() != "type.googleapis.com/google.rpc.ErrorInfo" {
596                continue;
597            }
598            let delay = detail.get("metadata.quotaResetDelay").str().into_owned();
599            if delay.is_empty() {
600                continue;
601            }
602            if let Some(parsed) = cpa_core::config::parse_duration(&delay) {
603                return Some(nanos(parsed));
604            }
605        }
606    }
607    let message = gj::get(body, "error.message").str().into_owned();
608    if message.is_empty() {
609        return None;
610    }
611    static SECONDS: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(r"after\s+(\d+)s\.?").unwrap());
612    static HUMAN: LazyLock<regex::Regex> =
613        LazyLock::new(|| regex::Regex::new(r"after\s+((?:\d+h)?(?:\d+m)?(?:\d+s)?)\.?").unwrap());
614    // strconv.Atoi, then time.Duration(seconds) * time.Second (wrapping like Go).
615    if let Some(seconds) = SECONDS.captures(&message).and_then(|c| c[1].parse::<i64>().ok()) {
616        return Some(nanos(seconds.wrapping_mul(1_000_000_000)));
617    }
618    let lower = message.go_lower();
619    let human = HUMAN.captures(&lower)?;
620    cpa_core::config::parse_duration(&human[1])
621        .filter(|d| *d > 0)
622        .map(nanos)
623}
624
625/// A Go `time.Duration` (nanoseconds); negative durations clamp to zero.
626fn nanos(value: i64) -> Duration {
627    Duration::from_nanos(value.max(0) as u64)
628}
629
630/// `antigravityProjectIDFromAuth`.
631pub(crate) fn project_id(credential: &Credential) -> &str {
632    credential.str("project_id").map(str::trim).unwrap_or_default()
633}
634
635/// `metaStringValue(auth.Metadata, key)`.
636fn meta_string<'a>(credential: &'a Credential, key: &str) -> &'a str {
637    credential.str(key).map(str::trim).unwrap_or_default()
638}
639
640/// Whether requests must wait for preparation: a missing project
641/// (`ShouldPrepareRequestAuth`), or an access token Go's `ensureAccessToken` would
642/// refresh before sending (empty, without an expiry, or inside five minutes of it).
643pub(crate) fn must_prepare(credential: &Credential) -> bool {
644    project_id(credential).is_empty() || !token_fresh(credential, Utc::now())
645}
646
647/// `ensureAccessToken`'s fast path: a token valid beyond the safety window.
648fn token_fresh(credential: &Credential, now: DateTime<Utc>) -> bool {
649    !meta_string(credential, "access_token").is_empty()
650        && crate::kimi_http::expiration(credential).is_some_and(|e| e > now + TOKEN_SAFETY_WINDOW)
651}
652
653/// Whether the credential needs preparation at `now`: a missing project, a token Go's
654/// `ensureAccessToken` would refresh, or a token inside the 30-minute refresh lead (the
655/// background loop's `shouldRefresh`).
656pub(crate) fn needs_prepare(credential: &Credential, now: DateTime<Utc>) -> bool {
657    project_id(credential).is_empty()
658        || !token_fresh(credential, now)
659        || (!meta_string(credential, "refresh_token").is_empty()
660            && crate::kimi_http::refresh_due(credential, Some(REFRESH_LEAD), now))
661}
662
663/// `refreshToken`'s metadata after a refresh grant at `now`.
664fn refresh_patch(tokens: &Tokens, now: DateTime<Utc>) -> MetadataPatch {
665    let mut set = Map::new();
666    set.insert("access_token".into(), Value::String(tokens.access_token.clone()));
667    if !tokens.refresh_token.is_empty() {
668        set.insert("refresh_token".into(), Value::String(tokens.refresh_token.clone()));
669    }
670    set.insert("expires_in".into(), Value::from(tokens.expires_in));
671    set.insert("timestamp".into(), Value::from(now.timestamp_millis()));
672    let expired = now.with_timezone(&chrono::Local) + chrono::TimeDelta::seconds(tokens.expires_in);
673    set.insert(
674        "expired".into(),
675        Value::String(expired.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
676    );
677    set.insert("type".into(), Value::String(PROVIDER.into()));
678    MetadataPatch {
679        set,
680        remove: Vec::new(),
681    }
682}
683
684/// `missingAntigravityProjectIDError`: 400 unless the cause carried a status.
685fn missing_project(cause: Option<AuthError>) -> ExecError {
686    let Some(cause) = cause else {
687        return ExecError::local(400, FailureScope::Credential, "antigravity auth missing project_id");
688    };
689    let mut error = ExecError::local(
690        cause.status.filter(|s| *s > 0).unwrap_or(400),
691        FailureScope::Credential,
692        format!("antigravity auth missing project_id: {}", cause.message),
693    );
694    error.retry_after = cause.retry_after;
695    error
696}
697
698/// Credential preparation: `PrepareRequestAuth` for a credential without a project
699/// (fresh access token, then the project lookup, whose failure blocks requests), else
700/// the background `Refresh` (refresh grant; a project lookup failure only logs).
701// ponytail: Go shares one refresh per refresh token across credentials (singleflight);
702// the runtime's per-credential prepare lock covers the usual one-file-per-token case.
703// Credits hints and refresh queues (antigravity_executor_credits.go) come with the
704// executor.
705pub(crate) async fn prepare(
706    clients: &GoClients,
707    credential: &Credential,
708    cfg: &Config,
709) -> Result<MetadataPatch, ExecError> {
710    let oauth = OAuth::new(clients.get(&Proxy::effective(credential, cfg)));
711    let now = Utc::now();
712    let mut patch = MetadataPatch::default();
713    let mut access = meta_string(credential, "access_token").to_owned();
714    let fresh = token_fresh(credential, now);
715    let missing = project_id(credential).is_empty();
716    let lookup = |access: String| {
717        let oauth = &oauth;
718        async move {
719            if access.trim().is_empty() {
720                return Ok(String::new());
721            }
722            match tokio::time::timeout(ACQUISITION_TIMEOUT, oauth.project_id(&access)).await {
723                Ok(result) => result,
724                Err(_) => Err(AuthError::plain("context deadline exceeded")),
725            }
726        }
727    };
728    let refreshed = !missing || access.is_empty() || !fresh;
729    if refreshed {
730        let refresh = meta_string(credential, "refresh_token");
731        if refresh.is_empty() {
732            return Err(ExecError::local(401, FailureScope::Credential, "missing refresh token"));
733        }
734        let tokens = tokio::time::timeout(ACQUISITION_TIMEOUT, oauth.refresh(refresh))
735            .await
736            .map_err(|_| ExecError::local(500, FailureScope::Credential, "context deadline exceeded"))??;
737        patch = refresh_patch(&tokens, now);
738        access = tokens.access_token;
739    }
740    if !missing {
741        return Ok(patch);
742    }
743    // A refresh already tried the lookup (ensureAntigravityProjectID, failure logged);
744    // PrepareRequestAuth then looks again and reports its own outcome.
745    let mut project = lookup(access.clone()).await;
746    if refreshed {
747        match &project {
748            Ok(found) if !found.is_empty() => {}
749            Ok(_) => project = lookup(access.clone()).await,
750            Err(error) => {
751                tracing::warn!("antigravity executor: ensure project id failed: {error}");
752                project = lookup(access.clone()).await;
753            }
754        }
755    }
756    match project {
757        Ok(project) if !project.is_empty() => {
758            patch.set.insert("project_id".into(), Value::String(project));
759            Ok(patch)
760        }
761        Ok(_) => Err(missing_project(None)),
762        Err(cause) => Err(missing_project(Some(cause))),
763    }
764}
765
766/// `-antigravity-login` options.
767pub struct LoginOptions {
768    pub no_browser: bool,
769    pub callback_port: u16,
770}
771
772impl Default for LoginOptions {
773    fn default() -> Self {
774        Self {
775            no_browser: false,
776            callback_port: DEFAULT_CALLBACK_PORT,
777        }
778    }
779}
780
781/// `CompleteAntigravityOAuth`: the code exchange, the account email and the project,
782/// as the credential file's name and metadata (`BuildAntigravityAuth`).
783pub async fn complete(
784    oauth: &OAuth,
785    code: &str,
786    redirect_uri: &str,
787    now: DateTime<Utc>,
788) -> Result<(String, Map<String, Value>), AuthError> {
789    let tokens = oauth
790        .exchange_code(code, redirect_uri)
791        .await
792        .map_err(|e| e.wrap("antigravity: token exchange failed"))?;
793    let access = tokens.access_token.trim();
794    if access.is_empty() {
795        return Err(AuthError::plain(
796            "antigravity: token exchange returned empty access token",
797        ));
798    }
799    let email = oauth
800        .user_info(access)
801        .await
802        .map_err(|e| e.wrap("antigravity: fetch user info failed"))?;
803    let project = oauth
804        .project_id(access)
805        .await
806        .map_err(|e| e.wrap("antigravity: failed to fetch project ID"))?;
807    let project = project.trim();
808    if project.is_empty() {
809        return Err(AuthError::plain(
810            "antigravity: project ID discovery returned empty project",
811        ));
812    }
813    Ok(build_auth(&tokens, &email, project, now))
814}
815
816/// `BuildAntigravityAuth`: file name and metadata of a new credential.
817pub fn build_auth(tokens: &Tokens, email: &str, project: &str, now: DateTime<Utc>) -> (String, Map<String, Value>) {
818    let mut metadata = refresh_patch(tokens, now).set;
819    // A login keeps the refresh token as returned, even when empty.
820    metadata.insert("refresh_token".into(), Value::String(tokens.refresh_token.clone()));
821    let email = email.trim();
822    if !email.is_empty() {
823        metadata.insert("email".into(), Value::String(email.into()));
824    }
825    let project = project.trim();
826    if !project.is_empty() {
827        metadata.insert("project_id".into(), Value::String(project.into()));
828    }
829    (credential_file_name(email), metadata)
830}
831
832/// Saves a CLI or management login through the shared file-token store.
833pub fn write_login(auth_dir: &Path, file_name: &str, metadata: &Map<String, Value>) -> Result<PathBuf, String> {
834    let email = metadata.get("email").and_then(Value::as_str).unwrap_or_default();
835    if crate::other_account_file(&auth_dir.join(file_name), email, &[]) {
836        return Err(crate::OTHER_ACCOUNT_FILE.into());
837    }
838    crate::devin_auth::save_metadata_file(auth_dir, file_name, metadata, PROVIDER)
839}
840
841/// One OAuth callback (`callbackResult`).
842#[derive(Debug, Default)]
843struct Callback {
844    code: String,
845    error: String,
846    state: String,
847}
848
849/// `startAntigravityCallbackServer`: `/oauth-callback` (any method) answers with Go's
850/// pages and hands the trimmed parameters to the login; other paths get Go's 404.
851async fn serve_callbacks(listener: tokio::net::TcpListener, results: tokio::sync::mpsc::Sender<Callback>) {
852    loop {
853        let Ok((socket, _)) = listener.accept().await else {
854            continue;
855        };
856        let results = results.clone();
857        tokio::spawn(async move {
858            let _ = tokio::time::timeout(Duration::from_secs(10), respond(socket, results)).await;
859        });
860    }
861}
862
863async fn respond(
864    mut socket: tokio::net::TcpStream,
865    results: tokio::sync::mpsc::Sender<Callback>,
866) -> std::io::Result<()> {
867    use tokio::io::{AsyncReadExt, AsyncWriteExt};
868    let mut head = Vec::new();
869    let mut byte = [0];
870    while head.len() < 8192 && !head.ends_with(b"\r\n\r\n") {
871        if socket.read(&mut byte).await? == 0 {
872            return Ok(());
873        }
874        head.push(byte[0]);
875    }
876    let text = String::from_utf8_lossy(&head);
877    let target = text
878        .lines()
879        .next()
880        .unwrap_or_default()
881        .split_whitespace()
882        .nth(1)
883        .unwrap_or_default();
884    let (path, query) = target.split_once('?').unwrap_or((target, ""));
885    let (content_type, extra, body) = if path == "/oauth-callback" {
886        // url.Values.Get: the first value of each parameter.
887        let first = |key: &str| {
888            url::form_urlencoded::parse(query.as_bytes())
889                .find(|(k, _)| k == key)
890                .map(|(_, v)| v.trim().to_owned())
891                .unwrap_or_default()
892        };
893        let callback = Callback {
894            code: first("code"),
895            error: first("error"),
896            state: first("state"),
897        };
898        let ok = !callback.code.is_empty() && callback.error.is_empty();
899        let _ = results.try_send(callback);
900        let body = if ok {
901            "<h1>Login successful</h1><p>You can close this window.</p>"
902        } else {
903            "<h1>Login failed</h1><p>Please check the CLI output.</p>"
904        };
905        ("text/html; charset=utf-8", "", body)
906    } else {
907        (
908            "text/plain; charset=utf-8",
909            "X-Content-Type-Options: nosniff\r\n",
910            "404 page not found\n",
911        )
912    };
913    let status = if path == "/oauth-callback" {
914        "200 OK"
915    } else {
916        "404 Not Found"
917    };
918    let response = format!(
919        "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
920        body.len()
921    );
922    socket.write_all(response.as_bytes()).await?;
923    socket.shutdown().await
924}
925
926/// `-antigravity-login`: the browser flow, then `Manager.Login`'s save. Returns the
927/// credential path and the account label.
928pub async fn login(auth_dir: &Path, cfg: &Config, options: &LoginOptions) -> Result<(PathBuf, String), String> {
929    let port = if options.callback_port == 0 {
930        DEFAULT_CALLBACK_PORT
931    } else {
932        options.callback_port
933    };
934    let state = crate::oauth::random_hex(16).map_err(|e| transport_text(&e))?;
935    let listener = match crate::claude_login::listen_any(port) {
936        Ok(listener) => listener,
937        Err(_) => tokio::net::TcpListener::bind(("0.0.0.0", port))
938            .await
939            .map_err(|e| format!("antigravity: failed to start callback server: listen tcp :{port}: {e}"))?,
940    };
941    let (tx, mut callbacks) = tokio::sync::mpsc::channel(1);
942    let server = tokio::spawn(serve_callbacks(listener, tx));
943    let redirect = redirect_uri(port);
944    let url = auth_url(&state, &redirect);
945    let show_manual = || {
946        crate::claude_login::print_ssh_tunnel_instructions(port);
947        println!("Visit the following URL to continue authentication:\n{url}");
948    };
949    if options.no_browser {
950        show_manual();
951    } else {
952        println!("Opening browser for antigravity authentication");
953        if !open_browser(&url) {
954            tracing::warn!("No browser available; please open the URL manually");
955            show_manual();
956        }
957    }
958    println!("Waiting for antigravity authentication callback...");
959    let result = async {
960        let callback = wait_for_callback(&mut callbacks).await?;
961        if !callback.error.is_empty() {
962            return Err(format!("antigravity: authentication failed: {}", callback.error));
963        }
964        if callback.state != state {
965            return Err("antigravity: invalid state".to_owned());
966        }
967        if callback.code.is_empty() {
968            return Err("antigravity: missing authorization code".to_owned());
969        }
970        // NewAntigravityAuth(cfg, nil): the global proxy (util.SetProxy).
971        let proxy = Proxy::parse(
972            cfg.document
973                .get("requests")
974                .and_then(|r| r.get("proxy-url"))
975                .and_then(serde_yaml_ng::Value::as_str)
976                .unwrap_or_default(),
977        );
978        let oauth = OAuth::new(GoClients::new(Default::default()).get(&proxy));
979        let (file_name, metadata) = complete(&oauth, &callback.code, &redirect, Utc::now())
980            .await
981            .map_err(|e| e.message)?;
982        if let Some(project) = metadata.get("project_id").and_then(Value::as_str) {
983            tracing::info!("antigravity: obtained project ID {}", hide(project));
984            println!("Antigravity authentication successful");
985            println!("Using GCP project: {}", hide(project));
986        }
987        let label = metadata
988            .get("email")
989            .and_then(Value::as_str)
990            .unwrap_or("antigravity")
991            .to_owned();
992        let path = write_login(auth_dir, &file_name, &metadata)?;
993        Ok((path, label))
994    }
995    .await;
996    server.abort();
997    result
998}
999
1000/// The wait: the first callback, a pasted callback URL after 15 seconds, or the
1001/// five-minute timeout.
1002async fn wait_for_callback(callbacks: &mut tokio::sync::mpsc::Receiver<Callback>) -> Result<Callback, String> {
1003    let deadline = tokio::time::sleep(Duration::from_secs(300));
1004    tokio::pin!(deadline);
1005    let manual = async {
1006        tokio::time::sleep(Duration::from_secs(15)).await;
1007        let (tx, rx) = tokio::sync::oneshot::channel();
1008        std::thread::spawn(move || {
1009            use std::io::Write;
1010            print!("Paste the antigravity callback URL (or press Enter to keep waiting): ");
1011            let _ = std::io::stdout().flush();
1012            let mut line = String::new();
1013            let _ = tx.send(std::io::stdin().read_line(&mut line).map(|_| line));
1014        });
1015        rx.await
1016            .unwrap_or_else(|_| Err(std::io::Error::other("prompt thread ended")))
1017    };
1018    tokio::pin!(manual);
1019    let mut prompted = false;
1020    loop {
1021        tokio::select! {
1022            biased;
1023            Some(callback) = callbacks.recv() => return Ok(callback),
1024            () = &mut deadline => return Err("antigravity: authentication timed out".into()),
1025            input = &mut manual, if !prompted => {
1026                prompted = true;
1027                let input = input.map_err(|e| e.to_string())?;
1028                match crate::claude_login::parse_callback_input(&input)? {
1029                    Some(parsed) => {
1030                        return Ok(Callback {
1031                            code: parsed.code,
1032                            error: parsed.error,
1033                            state: parsed.state,
1034                        })
1035                    }
1036                    None => continue,
1037                }
1038            }
1039        }
1040    }
1041}
1042
1043/// Opens `url` in the desktop browser; `false` when none is available.
1044fn open_browser(url: &str) -> bool {
1045    #[cfg(target_os = "linux")]
1046    let command = std::process::Command::new("xdg-open")
1047        .arg(url)
1048        .stdout(std::process::Stdio::null())
1049        .stderr(std::process::Stdio::null())
1050        .spawn();
1051    #[cfg(target_os = "macos")]
1052    let command = std::process::Command::new("open").arg(url).spawn();
1053    #[cfg(target_os = "windows")]
1054    let command = std::process::Command::new("rundll32")
1055        .args(["url.dll,FileProtocolHandler", url])
1056        .spawn();
1057    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
1058    let command: std::io::Result<std::process::Child> = Err(std::io::Error::other("no browser"));
1059    command.is_ok()
1060}
1061
1062#[cfg(test)]
1063#[path = "antigravity_auth_tests.rs"]
1064mod tests;