Skip to main content

artifactize_core/auth/codex/
interactive.rs

1//! Interactive OAuth, from the request state through the authorization-code exchange.
2use super::*;
3use sha2::{Digest, Sha256};
4use std::{
5    collections::BTreeMap,
6    ffi::OsStr,
7    io::{self, Write},
8};
9use tokio::{
10    io::{AsyncReadExt, AsyncWriteExt},
11    net::TcpListener,
12    sync::oneshot,
13};
14
15/// A stalled browser must not hold up a completed callback while receiving its short reply.
16pub(super) const CALLBACK_WRITE_TIMEOUT: Duration = Duration::from_secs(2);
17
18/// Release the callback listener from a client that stops sending its request headers.
19pub(super) const CALLBACK_READ_TIMEOUT: Duration = Duration::from_secs(5);
20
21/// Give a person five minutes to finish browser or pasted-redirect sign-in,
22/// without leaving an unattended callback listener alive indefinitely.
23pub(super) const LOGIN_TIMEOUT: Duration = Duration::from_secs(300);
24
25/// Choose 128 unpredictable bits for OAuth state/CSRF correlation, encoded as 32 hex
26/// characters. This is this client's chosen size, not an OAuth-mandated exact length.
27pub(super) const OAUTH_STATE_BYTES: usize = 16;
28
29/// 32 random bytes give 256 bits and 43 unpadded base64url characters, within RFC 7636's
30/// permitted 43–128-character code_verifier length; the S256 challenge hashes that text.
31pub(super) const PKCE_VERIFIER_BYTES: usize = 32;
32
33pub(super) const SCOPE: &str = "openid profile email offline_access";
34
35pub(super) const CALLBACK_PATH: &str = "/auth/callback";
36
37/// Match the localhost callback convention of the Codex public-client flow that Pi
38/// also uses; listener and OAuth redirect must agree for browser/pasted-URL interoperability.
39pub(super) const CALLBACK_PORT: u16 = 1455;
40
41/// The registered redirect, or a private loopback redirect for a test provider.
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub enum CallbackPort {
44    #[default]
45    Registered,
46    Ephemeral,
47}
48
49impl CallbackPort {
50    pub(super) fn bind(self) -> Result<Option<Callback>, String> {
51        let port = match self {
52            Self::Registered => CALLBACK_PORT,
53            Self::Ephemeral => 0,
54        };
55        Callback::bind(port).map_err(|error| format!("Cannot bind Codex sign-in callback: {error}"))
56    }
57
58    pub(super) fn redirect(self, listener: Option<&Callback>) -> Result<String, String> {
59        let port = match self {
60            Self::Registered => CALLBACK_PORT,
61            Self::Ephemeral => listener
62                .and_then(|listener| listener.ipv4.local_addr().ok())
63                .map(|address| address.port())
64                .filter(|port| *port != 0)
65                .ok_or("Cannot reserve a private Codex sign-in callback port.")?,
66        };
67        Ok(format!("http://localhost:{port}{CALLBACK_PATH}"))
68    }
69}
70
71pub(super) fn random(bytes: usize) -> Result<Vec<u8>, String> {
72    let mut value = vec![0; bytes];
73    getrandom::fill(&mut value).map_err(|_| "Cannot obtain secure randomness.".to_owned())?;
74    Ok(value)
75}
76
77/// One sign-in attempt: PKCE verifier, its S256 challenge and the `state` it expects.
78pub(super) struct Pending {
79    pub(super) verifier: String,
80    pub(super) state: crate::types::OAuthState,
81}
82
83impl Pending {
84    pub(super) fn new() -> Result<Self, String> {
85        let state: String = random(OAUTH_STATE_BYTES)?
86            .iter()
87            .map(|byte| format!("{byte:02x}"))
88            .collect();
89        Ok(Self {
90            verifier: URL_SAFE_NO_PAD.encode(random(PKCE_VERIFIER_BYTES)?),
91            state: state.parse().expect("generated OAuth state is valid"),
92        })
93    }
94
95    pub(super) fn challenge(&self) -> String {
96        URL_SAFE_NO_PAD.encode(Sha256::digest(self.verifier.as_bytes()))
97    }
98
99    pub(super) fn authorize_url(&self, root: &Url, redirect_uri: &str) -> Result<Url, String> {
100        let mut url = endpoint(root, "authorize")?;
101        url.query_pairs_mut().extend_pairs([
102            ("response_type", "code"),
103            ("client_id", CLIENT_ID),
104            ("redirect_uri", redirect_uri),
105            ("scope", SCOPE),
106            ("code_challenge", &self.challenge()),
107            ("code_challenge_method", "S256"),
108            ("state", &self.state),
109            ("id_token_add_organizations", "true"),
110            ("codex_cli_simplified_flow", "true"),
111            ("originator", ORIGINATOR),
112        ]);
113        Ok(url)
114    }
115
116    /// The code from a pasted redirect URL, `code#state`, a query string or a bare code,
117    /// as Pi accepts them. A pasted state must match.
118    pub(super) fn pasted(&self, input: &str) -> Result<String, String> {
119        let input = input.trim();
120        let (code, state) = if let Ok(url) = Url::parse(input) {
121            let pairs: BTreeMap<_, _> = url.query_pairs().into_owned().collect();
122            (pairs.get("code").cloned(), pairs.get("state").cloned())
123        } else if let Some((code, state)) = input.split_once('#') {
124            (Some(code.to_owned()), Some(state.to_owned()))
125        } else if input.contains("code=") {
126            let pairs: BTreeMap<_, _> = url::form_urlencoded::parse(input.as_bytes())
127                .into_owned()
128                .collect();
129            (pairs.get("code").cloned(), pairs.get("state").cloned())
130        } else {
131            (Some(input.to_owned()), None)
132        };
133        if state.is_some_and(|state| state != self.state) {
134            return Err("Codex sign-in state mismatch.".into());
135        }
136        code.filter(|code| !code.is_empty())
137            .ok_or_else(|| "The pasted input has no authorization code.".into())
138    }
139
140    /// Answer one callback request. `Some` ends the sign-in; `None` keeps waiting.
141    pub(super) fn callback(
142        &self,
143        target: &str,
144    ) -> (&'static str, &'static str, Option<Result<String, String>>) {
145        let Ok(url) = Url::parse(&format!("http://localhost{target}")) else {
146            return ("400 Bad Request", "Invalid callback.", None);
147        };
148        if url.path() != CALLBACK_PATH {
149            return ("404 Not Found", "Not found.", None);
150        }
151        let mut parameters = BTreeMap::new();
152        for (key, value) in url.query_pairs().into_owned() {
153            if parameters.insert(key, value).is_some() {
154                return ("400 Bad Request", "Duplicate callback parameter.", None);
155            }
156        }
157        if parameters.get("state").map(String::as_str) != Some(self.state.as_str()) {
158            return ("400 Bad Request", "State mismatch.", None);
159        }
160        if let Some(error) = parameters.get("error") {
161            let error: String = error
162                .chars()
163                .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
164                .take(MAX_OAUTH_ERROR_CHARS)
165                .collect();
166            return (
167                "400 Bad Request",
168                "Codex sign-in was not completed. Return to artifactize.",
169                Some(Err(format!("Codex sign-in failed ({error})."))),
170            );
171        }
172        match parameters.get("code").filter(|code| !code.is_empty()) {
173            Some(code) => (
174                "200 OK",
175                "Signed in to Codex. Return to artifactize; you can close this page.",
176                Some(Ok(code.clone())),
177            ),
178            None => ("400 Bad Request", "Missing authorization code.", None),
179        }
180    }
181
182    /// Serve the loopback callback until one completes the sign-in. Requests must be
183    /// `GET` with a loopback `Host` matching the reserved port.
184    pub(super) async fn serve(&self, listener: TcpListener) -> Result<String, String> {
185        // Allow browser callback headers and the authorization URL while bounding
186        // memory consumed by an untrusted loopback client before HTTP validation.
187        const MAX_CALLBACK_HEADER_BYTES: usize = 16 * 1024;
188        let port = listener.local_addr().map_err(|e| e.to_string())?.port();
189        let hosts = [
190            format!("localhost:{port}"),
191            format!("127.0.0.1:{port}"),
192            format!("[::1]:{port}"),
193        ];
194        loop {
195            let (mut stream, _) = listener.accept().await.map_err(|e| e.to_string())?;
196            let head = tokio::time::timeout(CALLBACK_READ_TIMEOUT, async {
197                let mut head = Vec::new();
198                let mut byte = [0];
199                while !head.ends_with(b"\r\n\r\n") && head.len() < MAX_CALLBACK_HEADER_BYTES {
200                    if stream.read(&mut byte).await? == 0 {
201                        break;
202                    }
203                    head.push(byte[0]);
204                }
205                Ok::<_, std::io::Error>(head)
206            })
207            .await;
208            let Ok(Ok(head)) = head else { continue };
209            let head = String::from_utf8_lossy(&head);
210            let line: Vec<_> = head
211                .lines()
212                .next()
213                .unwrap_or("")
214                .split_whitespace()
215                .collect();
216            let host: Vec<_> = head
217                .lines()
218                .skip(1)
219                .filter_map(|line| line.split_once(':'))
220                .filter(|(name, _)| name.eq_ignore_ascii_case("host"))
221                .map(|(_, value)| value.trim())
222                .collect();
223            let valid = head.ends_with("\r\n\r\n")
224                && line.len() == 3
225                && line[0] == "GET"
226                && matches!(line[2], "HTTP/1.0" | "HTTP/1.1")
227                && host.len() == 1
228                && hosts.iter().any(|expected| expected == host[0])
229                && line[1].starts_with('/')
230                && !line[1].starts_with("//");
231            let (status, body, result) = if valid {
232                self.callback(line[1])
233            } else {
234                ("400 Bad Request", "Invalid callback.", None)
235            };
236            let response = format!(
237                "HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{body}",
238                body.len()
239            );
240            let _ = tokio::time::timeout(
241                CALLBACK_WRITE_TIMEOUT,
242                stream.write_all(response.as_bytes()),
243            )
244            .await;
245            if let Some(result) = result {
246                return result;
247            }
248        }
249    }
250
251    /// The authorization code from the callback or a pasted redirect, whichever is first.
252    pub(super) async fn wait(
253        &self,
254        listener: Option<Callback>,
255        pasted: Option<oneshot::Receiver<String>>,
256    ) -> Result<String, String> {
257        let callback = async {
258            match listener {
259                Some(listener) => listener.wait(self).await,
260                None => std::future::pending().await,
261            }
262        };
263        let pasted = async {
264            match pasted {
265                Some(receiver) => match receiver.await {
266                    Ok(input) => self.pasted(&input),
267                    Err(_) => std::future::pending().await,
268                },
269                None => std::future::pending().await,
270            }
271        };
272        tokio::time::timeout(LOGIN_TIMEOUT, async {
273            tokio::select! {
274                result = callback => result,
275                result = pasted => result,
276            }
277        })
278        .await
279        .map_err(|_| "Codex sign-in timed out; run `artifactize login codex` again.".to_owned())?
280    }
281}
282
283/// What a sign-in asks the person to do: open `url`, and whether the browser can return to
284/// this machine's callback (when the port is taken, only a pasted redirect URL finishes it).
285#[derive(Debug, Clone, Serialize)]
286#[serde(rename_all = "camelCase")]
287pub struct Prompt {
288    pub url: String,
289    pub callback: bool,
290}
291
292/// Sign in interactively and save artifactize's own tokens. The sign-in URL goes to
293/// stderr, also with --json.
294pub async fn login(state: Option<&Path>, repo: Option<&Path>) -> Result<(), String> {
295    // Refuse before reading the terminal: where the tokens go and the sign-in root.
296    Storage::new(state, repo, Tokens::Codex)?;
297    auth_root()?;
298    let terminal = crate::platform::stdin_is_terminal();
299    let pasted = if terminal {
300        let (send, receive) = oneshot::channel();
301        // Detached: a sign-in finished in the browser leaves this read unanswered.
302        std::thread::Builder::new()
303            .name("codex-login-input".into())
304            .spawn(move || {
305                for line in std::io::stdin().lines() {
306                    match line {
307                        Ok(line) if line.trim().is_empty() => continue,
308                        Ok(line) => {
309                            let _ = send.send(line);
310                        }
311                        Err(_) => {}
312                    }
313                    break;
314                }
315            })
316            .map_err(|error| format!("Cannot start Codex sign-in input: {error}"))?;
317        Some(receive)
318    } else {
319        None
320    };
321    login_with(state, repo, pasted, true, CallbackPort::Registered, |prompt| {
322        let mut err = std::io::stderr().lock();
323        let _ = writeln!(err, "Open this URL to sign in with Codex:\n{}", prompt.url);
324        if !prompt.callback {
325            let _ = writeln!(
326                err,
327                "Port {CALLBACK_PORT} is in use (another sign-in, such as the Codex CLI or app, may hold it), so the browser cannot return here."
328            );
329        }
330        if terminal {
331            let _ = writeln!(
332                err,
333                "When the browser cannot return here, paste the full URL it was sent to (starting http://localhost:{CALLBACK_PORT}{CALLBACK_PATH}?code=) and press Enter. Find it in the browser's address bar after the failed load, or in DevTools → Network if the page keeps loading."
334            );
335        }
336    })
337    .await
338}
339
340/// The sign-in behind `login codex` for any interface: `show` receives the prompt once the
341/// callback listener is up, `pasted` may deliver the redirect URL the browser was sent to,
342/// and `browser` hands the URL to the desktop's opener. It ends when the tokens are saved, the
343/// sign-in fails, or after five minutes; dropping the future stops it and frees the port.
344pub async fn login_with(
345    state: Option<&Path>,
346    repo: Option<&Path>,
347    pasted: Option<oneshot::Receiver<String>>,
348    browser: bool,
349    callback_port: CallbackPort,
350    show: impl FnOnce(&Prompt),
351) -> Result<(), String> {
352    // Check where the tokens will go before anyone signs in.
353    let storage = Storage::new(state, repo, Tokens::Codex)?;
354    let root = auth_root()?;
355    let listener = callback_port.bind()?;
356    let redirect_uri = callback_port.redirect(listener.as_ref())?;
357    sign_in(
358        &storage,
359        &root,
360        listener,
361        &redirect_uri,
362        pasted,
363        browser,
364        |url, callback| {
365            show(&Prompt {
366                url: url.to_string(),
367                callback,
368            })
369        },
370    )
371    .await
372}
373
374pub(super) async fn sign_in(
375    storage: &Storage,
376    root: &Url,
377    listener: Option<Callback>,
378    redirect_uri: &str,
379    pasted: Option<oneshot::Receiver<String>>,
380    browser: bool,
381    show: impl FnOnce(&Url, bool),
382) -> Result<(), String> {
383    let open = browser.then_some(crate::platform::program::open_desktop);
384    sign_in_opening(storage, root, listener, redirect_uri, pasted, open, show).await
385}
386
387/// [`sign_in`] that hands the sign-in URL to `open`, when given, as the browser's opener.
388pub(super) async fn sign_in_opening(
389    storage: &Storage,
390    root: &Url,
391    listener: Option<Callback>,
392    redirect_uri: &str,
393    pasted: Option<oneshot::Receiver<String>>,
394    open: Option<impl AsyncFnOnce(&OsStr) -> io::Result<()>>,
395    show: impl FnOnce(&Url, bool),
396) -> Result<(), String> {
397    if listener.is_none() && pasted.is_none() {
398        return Err(format!(
399            "Port {CALLBACK_PORT} is in use and there is no terminal to paste the redirect URL into; finish the other sign-in and try again."
400        ));
401    }
402    let pending = Pending::new()?;
403    let url = pending.authorize_url(root, redirect_uri)?;
404    show(&url, listener.is_some());
405    let opened = async {
406        if let Some(open) = open {
407            open_browser(&url, open).await;
408        }
409    };
410    // The callback answers while the opener hands the URL off: the browser may come back
411    // before the opener returns, as when the opener waits for what it opened.
412    let (code, ()) = tokio::join!(pending.wait(listener, pasted), opened);
413    let code = code?;
414    let tokens = token_request(
415        root,
416        &[
417            ("grant_type", "authorization_code"),
418            ("client_id", CLIENT_ID),
419            ("code", &code),
420            ("code_verifier", &pending.verifier),
421            ("redirect_uri", redirect_uri),
422        ],
423        None,
424    )
425    .await
426    .map_err(|error| error.message)?;
427    let credentials = credentials(tokens, now()?)?;
428    let _lock = storage.lock(LOCK).await?;
429    storage.save(CREDENTIALS, &credentials)
430}
431
432pub(super) async fn open_browser(url: &Url, open: impl AsyncFnOnce(&OsStr) -> io::Result<()>) {
433    // The printed authorization URL remains available if desktop handoff fails.
434    let _ = open(OsStr::new(url.as_str())).await;
435}