modelbridge 0.5.2

One provider-neutral Rust client for OpenAI, Anthropic, Gemini, Groq, Ollama and friends: streaming, tool calling, an agent loop, usage accounting, and subscription sign-in
Documentation
//! One-shot loopback listener that catches the OAuth redirect.
//!
//! The port is bound before the browser opens, so a port already in use fails
//! immediately rather than after the password has been typed.

use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use crate::Error;

use super::pkce;

pub struct Catcher {
    listener: TcpListener,
    app: String,
}

impl Catcher {
    pub fn bind(port: u16, app: impl Into<String>) -> crate::Result<Self> {
        let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|error| {
            Error::Config(format!(
                "cannot bind 127.0.0.1:{port} ({error}). Close whatever is using it and retry."
            ))
        })?;
        listener
            .set_nonblocking(true)
            .map_err(|error| Error::Config(error.to_string()))?;
        Ok(Self {
            listener,
            app: app.into(),
        })
    }

    /// The port actually bound, which matters when the caller asked for zero.
    pub fn port(&self) -> u16 {
        self.listener
            .local_addr()
            .map(|address| address.port())
            .unwrap_or_default()
    }

    /// Wait for the browser to hit the callback. `cancel` lets an interface
    /// abandon a sign-in the user has walked away from.
    pub fn wait(
        &self,
        timeout: Duration,
        cancel: &AtomicBool,
    ) -> crate::Result<HashMap<String, String>> {
        let deadline = Instant::now() + timeout;
        while Instant::now() < deadline {
            if cancel.load(Ordering::Relaxed) {
                return Err(Error::Cancelled);
            }
            match self.listener.accept() {
                Ok((stream, _)) => {
                    if let Some(params) = handle(stream, &self.app) {
                        // Ignore stray hits (favicon, preflight) carrying no code.
                        if params.contains_key("code") || params.contains_key("error") {
                            return Ok(params);
                        }
                    }
                }
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    std::thread::sleep(Duration::from_millis(150));
                }
                Err(error) => return Err(Error::Network(format!("accept: {error}"))),
            }
        }
        Err(Error::Network(
            "timed out waiting for the browser redirect".into(),
        ))
    }
}

fn handle(mut stream: TcpStream, app: &str) -> Option<HashMap<String, String>> {
    let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
    let mut reader = BufReader::new(stream.try_clone().ok()?);
    let mut request_line = String::new();
    reader.read_line(&mut request_line).ok()?;

    let params = parse_query(&request_line);
    let body = page(app, params.contains_key("code"), params.get("error"));
    let response = format!(
        "HTTP/1.1 200 OK\r\ncontent-type: text/html; charset=utf-8\r\n\
         content-length: {}\r\nconnection: close\r\n\r\n{body}",
        body.len()
    );
    let _ = stream.write_all(response.as_bytes());
    let _ = stream.flush();
    Some(params)
}

/// `GET /callback?code=abc&state=xyz HTTP/1.1`
fn parse_query(request_line: &str) -> HashMap<String, String> {
    let mut out = HashMap::new();
    let Some((_, query)) = request_line
        .split_whitespace()
        .nth(1)
        .and_then(|path| path.split_once('?'))
    else {
        return out;
    };
    for pair in query.split('&') {
        if let Some((key, value)) = pair.split_once('=') {
            out.insert(pkce::decode(key), pkce::decode(value));
        }
    }
    out
}

fn page(app: &str, ok: bool, error: Option<&String>) -> String {
    let app = escape(app);
    let (title, message) = if ok {
        ("Signed in", format!("Close this tab and go back to {app}."))
    } else {
        (
            "Sign-in failed",
            error
                .map(|error| escape(error))
                .unwrap_or_else(|| "No authorization code came back.".into()),
        )
    };
    format!(
        "<!doctype html><meta charset=\"utf-8\"><title>{app}</title>\
         <body style=\"font:16px/1.6 system-ui;margin:20vh auto;max-width:32rem;\
         text-align:center;color:#e8e8e8;background:#111\">\
         <h1 style=\"font-weight:600\">{title}</h1>\
         <p style=\"opacity:.75\">{message}</p></body>"
    )
}

/// The error text comes off the wire, so it never reaches the page as markup.
fn escape(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_callback_query_is_decoded() {
        let params = parse_query("GET /callback?code=a%20b&state=xyz&x=1 HTTP/1.1");
        assert_eq!(params.get("code").unwrap(), "a b");
        assert_eq!(params.get("state").unwrap(), "xyz");
    }

    #[test]
    fn a_request_without_a_query_yields_nothing() {
        assert!(parse_query("GET /callback HTTP/1.1").is_empty());
        assert!(parse_query("nonsense").is_empty());
    }

    #[test]
    fn the_success_page_names_the_application() {
        assert!(page("Notebook", true, None).contains("go back to Notebook"));
        assert!(page("x", false, Some(&"access_denied".into())).contains("access_denied"));
    }

    #[test]
    fn redirect_text_cannot_inject_markup_into_the_page() {
        let rendered = page("x", false, Some(&"<script>alert(1)</script>".into()));
        assert!(!rendered.contains("<script>"));
        assert!(rendered.contains("&lt;script&gt;"));
    }

    #[test]
    fn a_bound_port_reports_the_conflict_rather_than_panicking() {
        let first = Catcher::bind(0, "test").unwrap();
        assert!(Catcher::bind(first.port(), "test").is_err());
    }
}