Skip to main content

artifactize_core/auth/
antigravity.rs

1//! Antigravity's native Google sign-in. URLs and a single pasted code are relayed to the
2//! official CLI; its credentials and vendor files never pass through Artifactize.
3use std::{path::PathBuf, time::Duration};
4
5use tokio::{
6    io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader},
7    sync::oneshot,
8    time::Instant,
9};
10use tokio_util::sync::CancellationToken;
11
12use crate::{
13    agent::error::Failure,
14    llm::{
15        antigravity::{self, Acp, PROBE_TIMEOUT, Problem},
16        models::ListedModel,
17    },
18    platform, process,
19};
20
21/// A person may need to confirm the account in a browser before pasting the code.
22const LOGIN_TIMEOUT: Duration = Duration::from_secs(10 * 60);
23/// Enough room for a Google authorization URL or a full callback URL, not unbounded output.
24const LOGIN_LINE_BYTES: u64 = 8192;
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum State {
28    Missing,
29    TooOld { error: String },
30    SignedOut,
31    SignedIn { account: Option<String> },
32    Quota { error: String },
33    RateLimited { error: String },
34    Failed { error: String },
35}
36
37impl From<Problem> for State {
38    fn from(problem: Problem) -> Self {
39        match problem {
40            Problem::Missing => Self::Missing,
41            Problem::SignedOut => Self::SignedOut,
42            Problem::TooOld { .. } => Self::TooOld {
43                error: Failure::from(problem).message,
44            },
45            Problem::Quota => Self::Quota {
46                error: Failure::from(problem).message,
47            },
48            Problem::RateLimit => Self::RateLimited {
49                error: Failure::from(problem).message,
50            },
51            Problem::Failed(error) => Self::Failed { error },
52        }
53    }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Status {
58    pub path: Option<PathBuf>,
59    pub version: Option<semver::Version>,
60    pub required_version: semver::Version,
61    pub state: State,
62}
63
64/// The check never authenticates or sends a prompt. A `session/new` distinguishes available
65/// accounts; Antigravity ACP does not report a Google account identity for the session.
66pub async fn status() -> Status {
67    let deadline = Instant::now() + PROBE_TIMEOUT;
68    let cancel = CancellationToken::new();
69    let mut path = None;
70    let mut version = None;
71    let result = async {
72        let directory = antigravity::workspace()?;
73        let executable = antigravity::executable(directory.path())?;
74        let executable = path.insert(executable);
75        let detected =
76            antigravity::version(executable, directory.path(), deadline, &cancel).await?;
77        antigravity::supported(version.insert(detected))?;
78        let acp = Acp::start_checked(directory, executable, deadline, &cancel).await?;
79        probe_started(acp, deadline, Acp::inspect).await
80    }
81    .await;
82    Status {
83        path,
84        version,
85        required_version: antigravity::MINIMUM,
86        state: match result {
87            Ok(_) => State::SignedIn { account: None },
88            Err(problem) => problem.into(),
89        },
90    }
91}
92
93pub async fn models() -> Result<Vec<ListedModel>, String> {
94    models_checked().await.map_err(message)
95}
96
97pub(crate) async fn models_checked() -> Result<Vec<ListedModel>, Problem> {
98    probe(Acp::inspect).await
99}
100
101pub async fn logout() -> Result<(), String> {
102    probe(Acp::logout).await.map_err(message)
103}
104
105async fn probe<T>(
106    ask: impl for<'a> AsyncFnOnce(&'a mut Acp) -> Result<T, Problem>,
107) -> Result<T, Problem> {
108    let deadline = Instant::now() + PROBE_TIMEOUT;
109    let cancel = CancellationToken::new();
110    let acp = Acp::start(deadline, &cancel).await?;
111    probe_started(acp, deadline, ask).await
112}
113
114async fn probe_started<T>(
115    mut acp: Acp,
116    deadline: Instant,
117    ask: impl for<'a> AsyncFnOnce(&'a mut Acp) -> Result<T, Problem>,
118) -> Result<T, Problem> {
119    let result = tokio::time::timeout_at(deadline, ask(&mut acp))
120        .await
121        .unwrap_or_else(|_| {
122            Err(Problem::Failed(
123                "Antigravity did not answer the ACP probe in time.".into(),
124            ))
125        });
126    let diagnostic = acp.stop().await;
127    result.map_err(|problem| match problem {
128        Problem::Failed(_) => diagnostic.unwrap_or(problem),
129        _ => problem,
130    })
131}
132
133fn message(problem: Problem) -> String {
134    Failure::from(problem).message
135}
136
137#[derive(Debug, Clone)]
138pub struct Prompt {
139    pub url: url::Url,
140}
141
142/// Run the native manual sign-in with a URL relay and a one-time stdin paste. Dropping the
143/// future stops the owned CLI; finishing successfully leaves its native login in place.
144pub async fn login_with(
145    pasted: oneshot::Receiver<String>,
146    show: impl FnOnce(&Prompt),
147) -> Result<(), String> {
148    let deadline = Instant::now() + LOGIN_TIMEOUT;
149    let directory = antigravity::workspace().map_err(message)?;
150    let executable =
151        antigravity::check_version(directory.path(), deadline, &CancellationToken::new())
152            .await
153            .map_err(message)?;
154    let mut command = antigravity::command(&["acp", "--login"], directory.path(), deadline);
155    command.program = executable.into_os_string();
156    let mut cli = process::spawn_handoff(&command)
157        .await
158        .map_err(antigravity::start_problem)
159        .map_err(message)?;
160    let mut input = cli.stdin().take().expect("sign-in stdin is piped");
161    let mut output = BufReader::new(cli.stdout().take().expect("sign-in stdout is piped"));
162    let mut errors = BufReader::new(cli.stderr().take().expect("sign-in stderr is piped"));
163    let mut read_output = true;
164    let mut read_errors = true;
165    let mut output_line = Vec::new();
166    let mut error_line = Vec::new();
167    let sign_in = async {
168        let url = loop {
169            let line = tokio::select! {
170                result = url_line(&mut output, &mut output_line), if read_output => {
171                    let (open, url) = result?;
172                    read_output = open;
173                    url
174                }
175                result = url_line(&mut errors, &mut error_line), if read_errors => {
176                    let (open, url) = result?;
177                    read_errors = open;
178                    url
179                }
180                else => break None,
181            };
182            if line.is_some() {
183                break line;
184            }
185        };
186        if let Some(url) = url {
187            show(&Prompt { url });
188            let paste = async {
189                let pasted = pasted
190                    .await
191                    .map_err(|_| "Antigravity sign-in was cancelled.")?;
192                let code = pasted.trim();
193                if code.is_empty()
194                    || code.len() as u64 > LOGIN_LINE_BYTES
195                    || code.chars().any(char::is_control)
196                {
197                    return Err("Paste the Antigravity sign-in code on one line.");
198                }
199                let _ = input.write_all(format!("{code}\n").as_bytes()).await;
200                drop(input);
201                std::future::pending::<Result<(), &str>>().await
202            };
203            let exited = finish_login(&mut cli, output, errors);
204            tokio::select! {
205                result = exited => result,
206                result = paste => result,
207            }
208        } else {
209            finish_login(&mut cli, output, errors).await
210        }
211    };
212    let result = tokio::time::timeout_at(deadline, sign_in)
213        .await
214        .map_err(|_| "Antigravity sign-in timed out. Start sign-in again.")?;
215    result?;
216    cli.release()
217        .map_err(|_| "Cannot release the finished Antigravity sign-in.".to_owned())
218}
219
220async fn finish_login(
221    cli: &mut platform::Child,
222    mut output: impl AsyncRead + Unpin,
223    mut errors: impl AsyncRead + Unpin,
224) -> Result<(), &'static str> {
225    // Drain both pipes while waiting; never include sign-in output or the code in a diagnostic.
226    let (mut discard_output, mut discard_errors) = (tokio::io::sink(), tokio::io::sink());
227    let (ended, _, _) = tokio::join!(
228        cli.wait_leader(),
229        tokio::io::copy(&mut output, &mut discard_output),
230        tokio::io::copy(&mut errors, &mut discard_errors)
231    );
232    if ended.is_ok_and(|ended| ended.success()) {
233        Ok(())
234    } else {
235        Err(
236            "Antigravity could not sign in. Start again, or sign in directly in the Antigravity CLI.",
237        )
238    }
239}
240
241async fn url_line(
242    reader: &mut (impl AsyncBufReadExt + Unpin),
243    line: &mut Vec<u8>,
244) -> Result<(bool, Option<url::Url>), &'static str> {
245    let remaining = LOGIN_LINE_BYTES.saturating_sub(line.len() as u64);
246    let read = reader
247        .take(remaining + 1)
248        .read_until(b'\n', line)
249        .await
250        .map_err(|_| "Cannot read the Antigravity sign-in prompt.")?;
251    if line.len() as u64 > LOGIN_LINE_BYTES {
252        return Err("Antigravity wrote an oversized sign-in prompt.");
253    }
254    let text = platform::output_text(line);
255    let url = text
256        .split_whitespace()
257        .filter_map(|word| url::Url::parse(word).ok())
258        .find(|url| {
259            url.scheme() == "https"
260                && url.host_str() == Some("accounts.google.com")
261                && url.port().is_none()
262                && url.username().is_empty()
263                && url.password().is_none()
264                && url.fragment().is_none()
265                && matches!(url.path(), "/o/oauth2/auth" | "/o/oauth2/v2/auth")
266                && url.query_pairs().any(|(key, value)| {
267                    key == "redirect_uri" && value == "https://antigravity.google/oauth-callback"
268                })
269        });
270    line.clear();
271    Ok((read != 0, url))
272}