Skip to main content

artifactize_provider/auth/codex/
interactive.rs

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