Skip to main content

rig_core/providers/auth/
loopback.rs

1//! A one-shot loopback listener for an OAuth authorization-code sign-in in
2//! the browser. It binds a local port, reports the redirect address to send
3//! to the provider, and hands back the code the browser returns, checked
4//! against the sign-in's state. The page the browser lands on names the
5//! provider and the app to return to. Native only.
6//!
7//! ```no_run
8//! use rig_core::providers::auth::loopback::{Loopback, LoopbackHost};
9//! use std::time::{Duration, Instant};
10//!
11//! # async fn sign_in() -> Result<(), rig_core::providers::auth::loopback::LoopbackError> {
12//! let listener = Loopback::new("Example", LoopbackHost::Localhost, [0], "/callback")
13//!     .listen("state".into(), Instant::now() + Duration::from_secs(300))?;
14//! // Send the user to the provider with `listener.redirect_uri()`, then:
15//! let received = listener.code().await?;
16//! // Exchange `received.code()` for tokens, then tell the browser:
17//! received.succeeded();
18//! # Ok(())
19//! # }
20//! ```
21
22use futures::channel::oneshot;
23use std::io::{self, Read, Write};
24use std::net::{Ipv4Addr, Ipv6Addr, TcpListener, TcpStream};
25use std::sync::mpsc;
26use std::time::{Duration, Instant};
27
28/// How often the listener checks whether its waiter is gone.
29const ACCEPT_POLL: Duration = Duration::from_millis(100);
30/// Reading one request head, or writing a page, gives up after this.
31const STREAM_TIMEOUT: Duration = Duration::from_secs(10);
32/// How long the browser waits for the token exchange before its page.
33const EXCHANGE_WAIT: Duration = Duration::from_secs(120);
34const MAX_REQUEST_BYTES: usize = 16 * 1024;
35/// How many times a port the system picks is picked again when its IPv6
36/// side is taken.
37const ANY_PORT_ATTEMPTS: usize = 6;
38
39/// The host the redirect address names. The listener binds loopback only.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum LoopbackHost {
42    /// `127.0.0.1`, listening on IPv4.
43    Ipv4,
44    /// `localhost`, listening on IPv4 and, where the system has it, on the
45    /// same port on IPv6, since a browser may resolve `localhost` to either.
46    Localhost,
47}
48
49/// Why a loopback sign-in ended without a code.
50#[derive(Debug, thiserror::Error)]
51pub enum LoopbackError {
52    /// None of the ports could be bound. Of kind
53    /// [`io::ErrorKind::AddrInUse`] when every port was taken.
54    #[error(transparent)]
55    Bind(io::Error),
56    /// The listener failed after binding.
57    #[error(transparent)]
58    Io(io::Error),
59    /// The deadline passed before the browser came back.
60    #[error("timed out waiting for the sign-in in the browser")]
61    TimedOut,
62    /// The provider refused or failed the sign-in; the message says why.
63    #[error("{0}")]
64    Refused(String),
65    /// The listener's thread ended without an answer.
66    #[error("the sign-in listener stopped unexpectedly")]
67    Stopped,
68}
69
70/// Where a browser sign-in returns: the provider and app its pages name,
71/// the host, the ports to try in order (`0` lets the system pick one), and
72/// the callback path.
73#[derive(Clone, Debug)]
74pub struct Loopback {
75    provider: String,
76    app: String,
77    host: LoopbackHost,
78    ports: Vec<u16>,
79    path: String,
80}
81
82impl Loopback {
83    /// A listener for `provider`'s sign-in on `host` at the first free port
84    /// of `ports`, taking callbacks on `path`, such as `/callback`. Its
85    /// pages tell the user to return to `rig` until
86    /// [`Self::with_app_name`] says otherwise.
87    pub fn new(
88        provider: impl Into<String>,
89        host: LoopbackHost,
90        ports: impl IntoIterator<Item = u16>,
91        path: impl Into<String>,
92    ) -> Self {
93        Self {
94            provider: provider.into(),
95            app: "rig".into(),
96            host,
97            ports: ports.into_iter().collect(),
98            path: path.into(),
99        }
100    }
101
102    /// This listener's pages telling the user to return to `app`.
103    #[must_use]
104    pub fn with_app_name(mut self, app: impl Into<String>) -> Self {
105        self.app = app.into();
106        self
107    }
108
109    /// Binds the first free port and serves it on a thread of its own until
110    /// a callback with `state` arrives, `deadline` passes, or the returned
111    /// [`Listener`] is dropped, which the thread notices within a fraction
112    /// of a second. The port is freed when the thread ends.
113    ///
114    /// # Errors
115    ///
116    /// [`LoopbackError::Bind`] when no port could be bound, of kind
117    /// [`io::ErrorKind::AddrInUse`] when every one was taken, and
118    /// [`LoopbackError::Io`] when the thread cannot start.
119    pub fn listen(&self, state: String, deadline: Instant) -> Result<Listener, LoopbackError> {
120        let (listeners, port) = self.bind()?;
121        for listener in &listeners {
122            listener.set_nonblocking(true).map_err(LoopbackError::Io)?;
123        }
124        let host = match self.host {
125            LoopbackHost::Ipv4 => "127.0.0.1",
126            LoopbackHost::Localhost => "localhost",
127        };
128        let redirect_uri = format!("http://{host}:{port}{}", self.path);
129        let (sender, callback) = oneshot::channel();
130        let serving = Serving {
131            pages: Pages {
132                provider: escape_html(&self.provider),
133                app: escape_html(&self.app),
134            },
135            path: self.path.clone(),
136            state,
137            deadline,
138        };
139        std::thread::Builder::new()
140            .name("sign-in-listener".into())
141            .spawn(move || serving.serve(&listeners, sender))
142            .map_err(LoopbackError::Io)?;
143        Ok(Listener {
144            redirect_uri,
145            callback,
146        })
147    }
148
149    /// The listeners on the first port of [`Self::ports`] free on every
150    /// address the host needs, and that port.
151    fn bind(&self) -> Result<(Vec<TcpListener>, u16), LoopbackError> {
152        for &port in &self.ports {
153            let attempts = if port == 0 { ANY_PORT_ATTEMPTS } else { 1 };
154            for _ in 0..attempts {
155                if let Some(bound) = self.bind_port(port)? {
156                    return Ok(bound);
157                }
158            }
159        }
160        let ports: Vec<String> = self.ports.iter().map(u16::to_string).collect();
161        Err(LoopbackError::Bind(io::Error::new(
162            io::ErrorKind::AddrInUse,
163            format!(
164                "the sign-in callback ports {} on the loopback address are in use",
165                ports.join(", ")
166            ),
167        )))
168    }
169
170    /// The listeners on `port`, or `None` when it is taken.
171    fn bind_port(&self, port: u16) -> Result<Option<(Vec<TcpListener>, u16)>, LoopbackError> {
172        let ipv4 = match TcpListener::bind((Ipv4Addr::LOCALHOST, port)) {
173            Ok(listener) => listener,
174            Err(error) if taken(&error) => return Ok(None),
175            Err(error) => return Err(LoopbackError::Bind(error)),
176        };
177        let port = ipv4.local_addr().map_err(LoopbackError::Bind)?.port();
178        if self.host == LoopbackHost::Ipv4 {
179            return Ok(Some((vec![ipv4], port)));
180        }
181        match TcpListener::bind((Ipv6Addr::LOCALHOST, port)) {
182            Ok(ipv6) => Ok(Some((vec![ipv4, ipv6], port))),
183            Err(error) if taken(&error) => Ok(None),
184            // No IPv6 loopback here, so `localhost` resolves to IPv4.
185            Err(_) => Ok(Some((vec![ipv4], port))),
186        }
187    }
188}
189
190/// Windows reports a reserved or taken port as access denied.
191fn taken(error: &io::Error) -> bool {
192    matches!(
193        error.kind(),
194        io::ErrorKind::AddrInUse | io::ErrorKind::PermissionDenied
195    )
196}
197
198/// A listening sign-in: the redirect address to send to the provider, and
199/// the code to wait for. Dropping it stops the listener.
200pub struct Listener {
201    redirect_uri: String,
202    callback: oneshot::Receiver<Result<Received, LoopbackError>>,
203}
204
205impl Listener {
206    /// The address the provider sends the browser back to, such as
207    /// `http://localhost:54545/callback`.
208    pub fn redirect_uri(&self) -> &str {
209        &self.redirect_uri
210    }
211
212    /// Waits for the browser to come back with the code.
213    ///
214    /// # Errors
215    ///
216    /// [`LoopbackError::Refused`] when the provider refused the sign-in,
217    /// [`LoopbackError::TimedOut`] when the deadline passed,
218    /// [`LoopbackError::Io`] when the listener failed, and
219    /// [`LoopbackError::Stopped`] when its thread ended without an answer.
220    pub async fn code(self) -> Result<Received, LoopbackError> {
221        self.callback.await.map_err(|_| LoopbackError::Stopped)?
222    }
223}
224
225/// The code the browser brought back, its state checked. The browser waits
226/// for [`Self::succeeded`] or [`Self::failed`] before showing its page;
227/// dropping this tells it the sign-in was cancelled.
228pub struct Received {
229    code: String,
230    outcome: mpsc::Sender<Result<(), String>>,
231}
232
233impl Received {
234    /// The authorization code.
235    pub fn code(&self) -> &str {
236        &self.code
237    }
238
239    /// Tells the browser the sign-in is done.
240    pub fn succeeded(self) {
241        self.outcome.send(Ok(())).ok();
242    }
243
244    /// Tells the browser the sign-in failed, for `reason`.
245    pub fn failed(self, reason: &str) {
246        self.outcome.send(Err(reason.to_owned())).ok();
247    }
248}
249
250/// What one request to the listener asked for.
251#[derive(Debug, PartialEq, Eq)]
252enum Callback {
253    /// The authorization code, its state checked.
254    Code(String),
255    /// The sign-in failed or was refused; the message says why.
256    Failed(String),
257    /// A callback whose state is not this sign-in's, such as a stale tab.
258    StateMismatch,
259    /// This sign-in's callback without exactly one non-empty code.
260    NoCode,
261    /// Anything else, such as `/favicon.ico`.
262    Other,
263}
264
265/// Reads the request line of a request to the listener, whose callback is
266/// on `path`. A repeated state is a mismatch and a repeated code no code,
267/// so no copy is picked over another.
268fn parse_callback(request_line: &str, path: &str, expected_state: &str) -> Callback {
269    let mut parts = request_line.split_whitespace();
270    let (Some("GET"), Some(target)) = (parts.next(), parts.next()) else {
271        return Callback::Other;
272    };
273    let (target_path, query) = target.split_once('?').unwrap_or((target, ""));
274    if target_path != path {
275        return Callback::Other;
276    }
277    let (mut code, mut state, mut error, mut description) = (Vec::new(), Vec::new(), None, None);
278    for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
279        match key.as_ref() {
280            "code" => code.push(value.into_owned()),
281            "state" => state.push(value.into_owned()),
282            "error" => error = Some(value.into_owned()),
283            "error_description" => description = Some(value.into_owned()),
284            _ => {}
285        }
286    }
287    if state.as_slice() != [expected_state] {
288        return Callback::StateMismatch;
289    }
290    if let Some(error) = error {
291        return Callback::Failed(match description.filter(|text| !text.trim().is_empty()) {
292            Some(description) => format!("the browser sign-in returned {error} ({description})"),
293            None => format!("the browser sign-in returned {error}"),
294        });
295    }
296    match code.as_slice() {
297        [code] if !code.is_empty() => Callback::Code(code.clone()),
298        _ => Callback::NoCode,
299    }
300}
301
302/// What the listener's thread needs.
303struct Serving {
304    pages: Pages,
305    path: String,
306    state: String,
307    deadline: Instant,
308}
309
310impl Serving {
311    fn serve(
312        &self,
313        listeners: &[TcpListener],
314        sender: oneshot::Sender<Result<Received, LoopbackError>>,
315    ) {
316        let pages = &self.pages;
317        let result = 'serve: loop {
318            if sender.is_canceled() {
319                return;
320            }
321            if Instant::now() >= self.deadline {
322                break Err(LoopbackError::TimedOut);
323            }
324            let mut accepted = None;
325            for listener in listeners {
326                match listener.accept() {
327                    Ok((stream, _)) => {
328                        accepted = Some(stream);
329                        break;
330                    }
331                    Err(error)
332                        if matches!(
333                            error.kind(),
334                            io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
335                        ) => {}
336                    Err(error) => break 'serve Err(LoopbackError::Io(error)),
337                }
338            }
339            let Some(mut stream) = accepted else {
340                std::thread::sleep(ACCEPT_POLL);
341                continue;
342            };
343            // A browser that stalls or sends garbage only loses its own request.
344            let until = (Instant::now() + STREAM_TIMEOUT).min(self.deadline);
345            let Ok(line) = read_request_line(&mut stream, until, || sender.is_canceled()) else {
346                continue;
347            };
348            match parse_callback(&line, &self.path, &self.state) {
349                Callback::Other => respond(&mut stream, "404 Not Found", "Not found."),
350                Callback::StateMismatch => {
351                    respond(&mut stream, "400 Bad Request", &pages.state_mismatch())
352                }
353                Callback::NoCode => respond(&mut stream, "400 Bad Request", &pages.no_code()),
354                Callback::Failed(message) => {
355                    respond(&mut stream, "200 OK", &pages.failed(&message));
356                    break Err(LoopbackError::Refused(message));
357                }
358                Callback::Code(code) => {
359                    let (outcome, wait) = mpsc::channel();
360                    if sender.send(Ok(Received { code, outcome })).is_err() {
361                        respond(&mut stream, "200 OK", &pages.cancelled());
362                        return;
363                    }
364                    let body = match wait.recv_timeout(EXCHANGE_WAIT) {
365                        Ok(Ok(())) => pages.signed_in(),
366                        Ok(Err(message)) => pages.failed(&message),
367                        Err(_) => pages.cancelled(),
368                    };
369                    respond(&mut stream, "200 OK", &body);
370                    return;
371                }
372            }
373        };
374        sender.send(result).ok();
375    }
376}
377
378/// Reads the request head and returns its first line, giving up at `until`
379/// or once `stopped` says the waiter is gone. The whole head is read so that
380/// closing the connection does not reset it before the page.
381fn read_request_line(
382    stream: &mut TcpStream,
383    until: Instant,
384    stopped: impl Fn() -> bool,
385) -> io::Result<String> {
386    // Accepted sockets inherit non-blocking mode on some platforms.
387    stream.set_nonblocking(false)?;
388    stream.set_write_timeout(Some(STREAM_TIMEOUT))?;
389    let mut head = Vec::new();
390    let mut chunk = [0u8; 1024];
391    while !head.windows(4).any(|window| window == b"\r\n\r\n") {
392        if head.len() >= MAX_REQUEST_BYTES {
393            return Err(io::Error::new(
394                io::ErrorKind::InvalidData,
395                "request head too large",
396            ));
397        }
398        let left = until.saturating_duration_since(Instant::now());
399        if left.is_zero() || stopped() {
400            return Err(io::ErrorKind::TimedOut.into());
401        }
402        // Short reads, so a client trickling bytes cannot outlast `until`.
403        stream.set_read_timeout(Some(left.min(ACCEPT_POLL)))?;
404        match stream.read(&mut chunk) {
405            Ok(0) => break,
406            Ok(read) => head.extend(chunk.iter().take(read)),
407            Err(error)
408                if matches!(
409                    error.kind(),
410                    io::ErrorKind::WouldBlock
411                        | io::ErrorKind::TimedOut
412                        | io::ErrorKind::Interrupted
413                ) => {}
414            Err(error) => return Err(error),
415        }
416    }
417    let head = String::from_utf8_lossy(&head);
418    Ok(head.lines().next().unwrap_or_default().to_owned())
419}
420
421fn respond(stream: &mut TcpStream, status: &str, body: &str) {
422    let response = format!(
423        "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\n\
424         Content-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{body}",
425        body.len()
426    );
427    stream.write_all(response.as_bytes()).ok();
428    stream.flush().ok();
429}
430
431/// The listener's pages, with the provider and app names HTML-escaped.
432struct Pages {
433    provider: String,
434    app: String,
435}
436
437impl Pages {
438    fn signed_in(&self) -> String {
439        let Self { provider, app } = self;
440        page(
441            &format!("Signed in to {provider}"),
442            &format!("You can close this tab and return to {app}."),
443        )
444    }
445
446    fn failed(&self, message: &str) -> String {
447        let message = escape_html(message);
448        page(
449            "Sign-in failed",
450            &format!("Sign-in failed: {message}. Return to {}.", self.app),
451        )
452    }
453
454    fn state_mismatch(&self) -> String {
455        let app = &self.app;
456        page(
457            "Sign-in not recognised",
458            &format!(
459                "This sign-in link is not the one {app} is waiting for. Start it again from {app}."
460            ),
461        )
462    }
463
464    fn no_code(&self) -> String {
465        let app = &self.app;
466        page(
467            "No sign-in code",
468            &format!(
469                "This page brought back no sign-in code. {app} is still waiting: finish signing in from the provider's page."
470            ),
471        )
472    }
473
474    fn cancelled(&self) -> String {
475        let app = &self.app;
476        page(
477            "Sign-in cancelled",
478            &format!("{app} stopped waiting for this sign-in. Start it again from {app}."),
479        )
480    }
481}
482
483/// A page from an escaped `title` and `message`.
484fn page(title: &str, message: &str) -> String {
485    format!(
486        "<!doctype html><html><head><meta charset=\"utf-8\"><title>{title}</title></head>\
487         <body style=\"font-family: system-ui, sans-serif; margin: 4rem auto; max-width: 32rem\">\
488         <h1>{title}</h1><p>{message}</p></body></html>"
489    )
490}
491
492fn escape_html(text: &str) -> String {
493    let mut escaped = String::with_capacity(text.len());
494    for character in text.chars() {
495        match character {
496            '&' => escaped.push_str("&amp;"),
497            '<' => escaped.push_str("&lt;"),
498            '>' => escaped.push_str("&gt;"),
499            '"' => escaped.push_str("&quot;"),
500            '\'' => escaped.push_str("&#39;"),
501            other => escaped.push(other),
502        }
503    }
504    escaped
505}
506
507#[cfg(test)]
508mod tests;