Skip to main content

cpa_exec/
codex_siwc_bind.rs

1//! `-siwc-bind` (Go internal/cmd/siwc_bind.go, 7b0319fb): runs the Sign in with
2//! ChatGPT browser flow from the command line and writes the `siwc` token partition and
3//! `use_siwc` into an existing Codex OAuth credential file in `auth-dir`, under Go's
4//! credential lock file (internal/auth/codex/token.go `WithFileLock`).
5
6use std::collections::BTreeMap;
7use std::path::{Path, PathBuf};
8use std::time::Duration;
9
10use cpa_common::json::GoValue;
11use cpa_core::config::Config;
12use cpa_core::gostr::GoStr;
13
14use crate::claude_login::{Interaction, parse_callback_input};
15use crate::codex_oauth::{CodexOAuth, LoginOptions};
16use crate::codex_siwc::Tokens;
17
18/// Go `SIWCCallbackPort`, unless `-oauth-callback-port` is set.
19pub const CALLBACK_PORT: u16 = 1455;
20
21/// How `-siwc-bind` failed, as Go reports it.
22#[derive(Debug, PartialEq, Eq)]
23pub enum BindError {
24    /// Go `log.Errorf`, before the browser flow.
25    Log(String),
26    /// Go `fmt.Printf`, once the flow started: the whole line.
27    Print(String),
28    /// The callback port cannot be bound: Go logs `ErrPortInUse`'s message and exits
29    /// with 13.
30    PortInUse,
31}
32
33type GoMap = BTreeMap<String, GoValue>;
34
35/// Go `json.Unmarshal(data, &map[string]any)`: `Ok(None)` for `null` (a nil map),
36/// numbers through float64. The error is the cause Go wraps.
37fn decode(data: &[u8]) -> Result<Option<GoMap>, String> {
38    match GoValue::parse_f64(data).map(GoValue::into_object) {
39        Some(Ok(map)) => Ok(Some(map)),
40        Some(Err(GoValue::Null)) => Ok(None),
41        Some(Err(_)) => Err("json: cannot unmarshal into Go value of type map[string]interface {}".into()),
42        None => Err("invalid JSON".into()),
43    }
44}
45
46fn go_str<'a>(map: Option<&'a GoMap>, key: &str) -> &'a str {
47    match map.and_then(|m| m.get(key)) {
48        Some(GoValue::String(s)) => s,
49        _ => "",
50    }
51}
52
53/// Go `validateSIWCBindCredential`.
54fn validate(meta: Option<&GoMap>) -> Result<(), String> {
55    if !go_str(meta, "type").trim().go_eq_fold("codex") {
56        return Err("siwc-bind: credential type must be codex".into());
57    }
58    for key in ["access_token", "refresh_token"] {
59        if go_str(meta, key).trim().is_empty() {
60            return Err(format!("siwc-bind: codex credential requires a non-empty {key}"));
61        }
62    }
63    Ok(())
64}
65
66/// Go `ResolveSIWCBindPath`: an absolute path or a bare file name in `auth_dir`, whose
67/// real path (symlinks resolved) is a regular Codex OAuth file inside the real
68/// `auth_dir`. Returns that real path.
69pub fn resolve(auth_dir: &Path, target: &str) -> Result<PathBuf, String> {
70    let raw = target.trim();
71    if raw.is_empty() {
72        return Err("siwc-bind: missing codex credential file path".into());
73    }
74    if auth_dir.to_string_lossy().trim().is_empty() {
75        return Err("siwc-bind: auth-dir is not configured".into());
76    }
77    // Go `util.ResolveAuthDir` cleans lexically and `filepath.Abs` joins the working
78    // directory before `EvalSymlinks`: `link/../auth` is a sibling of `link`, never the
79    // parent of its target.
80    let dir = go_abs(auth_dir)
81        .and_then(std::fs::canonicalize)
82        .map(plain_path)
83        .map_err(|e| format!("siwc-bind: failed to resolve real auth-dir: {e}"))?;
84    let candidate = if Path::new(raw).is_absolute() {
85        PathBuf::from(raw)
86    } else if raw.contains(['/', '\\']) || raw == "." || raw == ".." {
87        return Err("siwc-bind: expected an absolute path or bare filename".into());
88    } else {
89        dir.join(raw)
90    };
91    let candidate = std::fs::canonicalize(candidate)
92        .map(plain_path)
93        .map_err(|e| format!("siwc-bind: failed to resolve credential file: {e}"))?;
94    if candidate
95        .strip_prefix(&dir)
96        .map_or(true, |rel| rel.as_os_str().is_empty())
97    {
98        return Err("siwc-bind: credential file must belong to auth-dir".into());
99    }
100    if !std::fs::metadata(&candidate).is_ok_and(|m| m.is_file()) {
101        return Err("siwc-bind: credential target must be an existing regular file".into());
102    }
103    let data = std::fs::read(&candidate)
104        .map_err(|e| format!("siwc-bind: failed to read credential file {}: {e}", candidate.display()))?;
105    let meta = decode(&data).map_err(|_| format!("siwc-bind: invalid credential JSON in {}", candidate.display()))?;
106    validate(meta.as_ref())?;
107    Ok(candidate)
108}
109
110/// Go `ensureSIWCDeviceIDFromFile`: the file's valid `siwc.device_id`, lower-cased, else a
111/// new UUID.
112pub fn device_id(path: &Path) -> Result<String, String> {
113    let data = std::fs::read(path).map_err(|e| format!("failed to read credential file: {e}"))?;
114    let meta = decode(&data).map_err(|e| format!("invalid credential JSON: {e}"))?;
115    if let Some(GoValue::Object(siwc)) = meta.as_ref().and_then(|m| m.get("siwc"))
116        && let Some(GoValue::String(id)) = siwc.get("device_id")
117        && crate::codex_siwc::is_valid_uuid(id)
118    {
119        return Ok(id.trim().go_lower());
120    }
121    Ok(uuid::Uuid::new_v4().to_string())
122}
123
124/// Go `saveSIWCToCodexCredentialFile` after its log line: under the credential lock, the
125/// current file with `use_siwc` set and `siwc` replaced, encoded as Go's `json.Marshal`
126/// of the decoded map (sorted keys, numbers through float64), written atomically.
127/// Blocking.
128pub fn save(path: &Path, tokens: &Tokens) -> Result<(), String> {
129    with_file_lock(path, || {
130        let data = std::fs::read(path).map_err(|e| format!("failed to read existing credential file: {e}"))?;
131        let meta = decode(&data).map_err(|e| format!("failed to parse existing credential file: {e}"))?;
132        validate(meta.as_ref())?;
133        let mut meta = meta.unwrap_or_default();
134        // Binding is an explicit SIWC replacement, not a stale snapshot merge.
135        meta.insert("use_siwc".into(), GoValue::Bool(true));
136        meta.insert(
137            "siwc".into(),
138            GoValue::from_json(&serde_json::Value::Object(tokens.to_map())),
139        );
140        let bytes = GoValue::Object(meta).marshal();
141        let dir = path.parent().unwrap_or(Path::new("."));
142        crate::codex_oauth::publish(dir, path, &bytes).map_err(|e| format!("failed to replace credential file: {e}"))
143    })
144}
145
146/// Go `WithFileLock`'s inter-process half: an exclusive lock on `<path>.lock` for the
147/// duration of `f` (`flock`, or `LockFileEx` on Windows), so a Go or Rust process
148/// refreshing the same file waits.
149// ponytail: Go also serializes callers in one process with a mutex per path; here the
150// server's refresh holds its per-credential preparation lock around [`lock_file`].
151pub fn with_file_lock<T>(path: &Path, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
152    let file = lock_file(path)?;
153    let result = f();
154    drop(file);
155    result
156}
157
158/// The lock of [`with_file_lock`], held until the returned file is dropped (closing it
159/// releases the lock). Blocking.
160pub fn lock_file(path: &Path) -> Result<std::fs::File, String> {
161    let (file, lock_path) = open_lock(path)?;
162    lock(&file, true).map_err(|e| format!("failed to acquire flock on {}: {e}", lock_path.display()))?;
163    Ok(file)
164}
165
166/// The lock file of [`lock_file`], open but not yet locked; [`try_lock`] takes it.
167pub fn open_lock_file(path: &Path) -> Result<std::fs::File, String> {
168    open_lock(path).map(|(file, _)| file)
169}
170
171/// Takes the lock on a file [`open_lock_file`] opened, if no one holds it: `false`
172/// when another holder has it. Never blocks.
173pub fn try_lock(file: &std::fs::File) -> Result<bool, String> {
174    match lock(file, false) {
175        Ok(()) => Ok(true),
176        Err(e) if would_block(&e) => Ok(false),
177        Err(e) => Err(format!("failed to acquire credential lock: {e}")),
178    }
179}
180
181fn open_lock(path: &Path) -> Result<(std::fs::File, PathBuf), String> {
182    let mut lock_path = lock_base(path).into_os_string();
183    lock_path.push(".lock");
184    let lock_path = PathBuf::from(lock_path);
185    let mut options = std::fs::OpenOptions::new();
186    options.read(true).write(true).create(true).truncate(false);
187    #[cfg(unix)]
188    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
189    let file = options
190        .open(&lock_path)
191        .map_err(|e| format!("failed to open credential lock file {}: {e}", lock_path.display()))?;
192    Ok((file, lock_path))
193}
194
195#[cfg(unix)]
196fn lock(file: &std::fs::File, wait: bool) -> std::io::Result<()> {
197    use std::os::fd::AsRawFd;
198    let operation = if wait {
199        libc::LOCK_EX
200    } else {
201        libc::LOCK_EX | libc::LOCK_NB
202    };
203    loop {
204        // SAFETY: a valid open descriptor; flock touches no memory.
205        if unsafe { libc::flock(file.as_raw_fd(), operation) } == 0 {
206            return Ok(());
207        }
208        let error = std::io::Error::last_os_error();
209        if error.kind() != std::io::ErrorKind::Interrupted {
210            return Err(error);
211        }
212    }
213}
214
215#[cfg(unix)]
216fn would_block(error: &std::io::Error) -> bool {
217    error.kind() == std::io::ErrorKind::WouldBlock
218}
219
220#[cfg(windows)]
221fn lock(file: &std::fs::File, wait: bool) -> std::io::Result<()> {
222    use std::os::windows::io::AsRawHandle;
223    use windows_sys::Win32::Storage::FileSystem::{LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx};
224    let flags = if wait {
225        LOCKFILE_EXCLUSIVE_LOCK
226    } else {
227        LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY
228    };
229    // Go locks the first byte; overlapping ranges conflict, so the two interoperate.
230    // SAFETY: a valid open handle and a zeroed OVERLAPPED that outlives the call.
231    let ok = unsafe {
232        let mut overlapped: windows_sys::Win32::System::IO::OVERLAPPED = std::mem::zeroed();
233        LockFileEx(file.as_raw_handle() as _, flags, 0, 1, 0, &mut overlapped)
234    };
235    if ok == 0 {
236        Err(std::io::Error::last_os_error())
237    } else {
238        Ok(())
239    }
240}
241
242#[cfg(windows)]
243fn would_block(error: &std::io::Error) -> bool {
244    // ERROR_LOCK_VIOLATION
245    error.raw_os_error() == Some(33)
246}
247
248#[cfg(not(any(unix, windows)))]
249fn lock(_: &std::fs::File, _: bool) -> std::io::Result<()> {
250    Ok(())
251}
252
253#[cfg(not(any(unix, windows)))]
254fn would_block(_: &std::io::Error) -> bool {
255    false
256}
257
258/// Go `filepath.Clean`, lexically.
259fn go_clean(path: &Path) -> PathBuf {
260    use std::path::Component;
261    let mut out: Vec<Component<'_>> = Vec::new();
262    for component in path.components() {
263        match component {
264            Component::CurDir => {}
265            Component::ParentDir => match out.last() {
266                Some(Component::Normal(_)) => {
267                    out.pop();
268                }
269                Some(Component::RootDir | Component::Prefix(_)) => {}
270                _ => out.push(component),
271            },
272            other => out.push(other),
273        }
274    }
275    if out.is_empty() {
276        return PathBuf::from(".");
277    }
278    out.iter().collect()
279}
280
281/// A canonical path spelled as Go's `filepath.EvalSymlinks` spells it. On Windows,
282/// `std::fs::canonicalize` answers with a verbatim path: `\\?\C:\x` becomes `C:\x`
283/// and `\\?\UNC\server\share\x` becomes `\\server\share\x`; other verbatim
284/// forms stay. Other platforms return the path as it is.
285#[cfg(windows)]
286pub fn plain_path(path: PathBuf) -> PathBuf {
287    use std::os::windows::ffi::{OsStrExt, OsStringExt};
288    use std::path::{Component, Prefix};
289    let wide: Vec<u16> = path.as_os_str().encode_wide().collect();
290    let plain = match path.components().next() {
291        Some(Component::Prefix(p)) => match p.kind() {
292            // `\\?\` is four UTF-16 units, `\\?\UNC\` eight.
293            Prefix::VerbatimDisk(_) => wide[4..].to_vec(),
294            Prefix::VerbatimUNC(..) => [&[u16::from(b'\\'); 2][..], &wide[8..]].concat(),
295            _ => return path,
296        },
297        _ => return path,
298    };
299    PathBuf::from(std::ffi::OsString::from_wide(&plain))
300}
301
302/// The path as it is: only Windows spells canonical paths verbatim.
303#[cfg(not(windows))]
304pub fn plain_path(path: PathBuf) -> PathBuf {
305    path
306}
307
308/// Go `filepath.Abs` of a cleaned path: joined with the working directory, cleaned.
309fn go_abs(path: &Path) -> std::io::Result<PathBuf> {
310    std::path::absolute(go_clean(path)).map(|p| go_clean(&p))
311}
312
313/// Go `canonicalLockPath`: the path trimmed of surrounding white space, cleaned and made
314/// absolute. The lock file is this plus `.lock`, so a file named with trailing spaces
315/// shares its lock with Go's.
316fn lock_base(path: &Path) -> PathBuf {
317    let trimmed = path.to_str().map_or(path, |s| Path::new(s.trim()));
318    go_abs(trimmed).unwrap_or_else(|_| go_clean(trimmed))
319}
320
321/// `-siwc-bind <file>`: the browser flow on the callback port (`-oauth-callback-port`,
322/// else 1455), then [`save`]. Returns the bound file.
323pub async fn bind(cfg: &Config, target: &str, options: &LoginOptions) -> Result<PathBuf, BindError> {
324    let port = match options.callback_port {
325        0 => CALLBACK_PORT,
326        port => port,
327    };
328    let no_browser = options.no_browser;
329    let interaction = Interaction {
330        manual_delay: Duration::from_secs(15),
331        prompt: Some(Box::new(|| {
332            Box::pin(async {
333                use std::io::Write;
334                print!("Paste the callback URL (or press Enter to keep waiting): ");
335                let _ = std::io::stdout().flush();
336                // misc.AsyncPrompt: a detached reader never keeps the process alive.
337                let (tx, rx) = tokio::sync::oneshot::channel();
338                std::thread::spawn(move || {
339                    let mut line = String::new();
340                    let _ = tx.send(std::io::stdin().read_line(&mut line).map(|_| line));
341                });
342                rx.await.map_err(std::io::Error::other)?
343            })
344        })),
345        show_url: Box::new(move |url| show_url(url, port, no_browser)),
346    };
347    // Go `NewCodexAuth(cfg)`: `requests.proxy-url` on a standard client.
348    let proxy = cfg
349        .document
350        .get("requests")
351        .and_then(|r| r.get("proxy-url"))
352        .and_then(|v| v.as_str())
353        .unwrap_or_default();
354    let client = crate::proxy::GoClients::new(Default::default()).get(&crate::proxy::Proxy::parse(proxy));
355    bind_with(cfg, target, port, CodexOAuth::new(client), interaction).await
356}
357
358fn show_url(url: &str, port: u16, no_browser: bool) {
359    if !no_browser {
360        println!("Opening browser for OpenAI Sign in with ChatGPT authentication");
361        if crate::claude_login::open_browser(url) {
362            println!("Waiting for Sign in with ChatGPT authentication callback...");
363            return;
364        }
365        tracing::warn!("No browser available; please open the URL manually");
366    }
367    crate::claude_login::print_ssh_tunnel_instructions(port);
368    println!("Visit the following URL to continue authentication:\n{url}");
369    println!("Waiting for Sign in with ChatGPT authentication callback...");
370}
371
372/// [`bind`] through `oauth` and `interaction` (tests use local endpoints).
373pub(crate) async fn bind_with(
374    cfg: &Config,
375    target: &str,
376    port: u16,
377    oauth: CodexOAuth,
378    interaction: Interaction,
379) -> Result<PathBuf, BindError> {
380    let path = resolve(&cfg.auth_dir, target).map_err(BindError::Log)?;
381    let device = {
382        let path = path.clone();
383        tokio::task::spawn_blocking(move || device_id(&path))
384            .await
385            .map_err(|e| BindError::Log(format!("siwc-bind: {e}")))?
386            .map_err(|e| BindError::Log(format!("siwc-bind: {e}")))?
387    };
388    let redirect = format!("http://127.0.0.1:{port}/auth/callback");
389    let (verifier, challenge) =
390        crate::oauth::pkce().map_err(|_| BindError::Log("siwc-bind: PKCE generation failed".into()))?;
391    let random = |what: &str| {
392        crate::codex_siwc::random_base64url()
393            .map_err(|_| BindError::Log(format!("siwc-bind: {what} generation failed")))
394    };
395    let (state, nonce) = (random("state")?, random("nonce")?);
396    // Go reports any failure to listen as the port being in use. The redirect is
397    // loopback, so loopback is all that has to listen (Go takes every interface).
398    let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
399        .await
400        .map_err(|_| BindError::PortInUse)?;
401    let identifier = crate::codex_siwc::identifier(cfg);
402    let url =
403        crate::codex_siwc::authorize_url(&state, &nonce, &device, &redirect, &challenge, &identifier).map_err(|e| {
404            BindError::Log(format!(
405                "siwc-bind: failed to generate authorization URL: {}",
406                String::from_utf8_lossy(&e.body)
407            ))
408        })?;
409    // Go's callback server runs until the command returns, so the browser's redirect
410    // to /success is answered; the first callback wins.
411    let (results, mut callbacks) = tokio::sync::mpsc::channel(1);
412    let server = tokio::spawn(async move {
413        while let Ok(callback) = crate::codex_oauth::callback(&listener).await {
414            let _ = results.try_send(callback);
415        }
416    });
417    (interaction.show_url)(&url);
418    let result = async {
419        let failed = |e: String| BindError::Print(format!("Sign in with ChatGPT authentication failed: {e}"));
420        let (code, got_state, client_id, error, description) =
421            wait(&mut callbacks, interaction.manual_delay, interaction.prompt)
422                .await
423                .map_err(failed)?;
424        if !error.is_empty() {
425            // Go `OAuthError.Error`.
426            return Err(failed(if description.is_empty() {
427                format!("OAuth error: {error}")
428            } else {
429                format!("OAuth error {error}: {description}")
430            }));
431        }
432        if got_state != state {
433            return Err(failed("state mismatch".into()));
434        }
435        if client_id.trim().is_empty() {
436            return Err(failed("callback did not contain an issued client ID".into()));
437        }
438        let tokens = oauth
439            .exchange_siwc(&code, &client_id, &redirect, &device, &verifier)
440            .await
441            .map_err(|e| {
442                BindError::Print(format!(
443                    "Sign in with ChatGPT token exchange failed: {}",
444                    String::from_utf8_lossy(&e.body)
445                ))
446            })?;
447        // Go `misc.LogSavingCredentials`.
448        println!("Saving credentials to {}", path.display());
449        let target = path.clone();
450        tokio::task::spawn_blocking(move || save(&target, &tokens))
451            .await
452            .map_err(|e| e.to_string())
453            .and_then(|r| r)
454            .map_err(|e| BindError::Print(format!("Failed to save SIWC credentials: {e}")))?;
455        Ok(path)
456    }
457    .await;
458    // Give the browser's /success a moment before the listener closes.
459    tokio::time::sleep(Duration::from_millis(200)).await;
460    server.abort();
461    result
462}
463
464/// The callback (code, state, client ID, error, description): the local server's
465/// first, a pasted URL after `delay`, or Go's 5-minute timeout. An empty paste keeps
466/// waiting without asking again.
467async fn wait(
468    callbacks: &mut tokio::sync::mpsc::Receiver<crate::codex_oauth::Callback>,
469    delay: Duration,
470    prompt: Option<crate::claude_login::Prompt>,
471) -> Result<(String, String, String, String, String), String> {
472    let deadline = tokio::time::sleep(Duration::from_secs(300));
473    tokio::pin!(deadline);
474    let manual = async {
475        let prompt = prompt?;
476        tokio::time::sleep(delay).await;
477        Some(prompt().await)
478    };
479    tokio::pin!(manual);
480    let mut manual_done = false;
481    loop {
482        tokio::select! {
483            biased;
484            Some(c) = callbacks.recv() => {
485                return Ok((c.code, c.state, c.client_id, c.error.unwrap_or_default(), String::new()));
486            }
487            () = &mut deadline => return Err("timeout waiting for OAuth callback".into()),
488            input = &mut manual, if !manual_done => {
489                manual_done = true;
490                let Some(input) = input else { continue };
491                let input = input.map_err(|e| e.to_string())?;
492                if let Some(c) = parse_callback_input(&input)? {
493                    return Ok((c.code, c.state, c.client_id, c.error, c.description));
494                }
495            }
496        }
497    }
498}
499
500#[cfg(test)]
501#[path = "codex_siwc_bind_tests.rs"]
502mod tests;