Skip to main content

subspace_github_auth/
browser.rs

1//! The browser flow: GitHub's authorize page, then a one-shot listener on
2//! `127.0.0.1` for its redirect to `/callback`. For an OAuth App with a
3//! loopback callback GitHub accepts any port, so the listener takes a free
4//! one. The listener uses `std::net`: it reads one request line on
5//! loopback, which needs no HTTP server dependency.
6
7use std::io::{BufRead as _, BufReader, Write as _};
8use std::net::{TcpListener, TcpStream};
9use std::sync::mpsc::{self, RecvTimeoutError, Sender};
10use std::time::{Duration, Instant};
11
12use subspace_core::Secret;
13use subspace_core::http::status::{BAD_REQUEST, NOT_FOUND, OK};
14
15use crate::pkce::{self, Pkce};
16use crate::token::{self, Reply};
17use crate::{AuthError, Cancel, Endpoints, Pending, Prompt, SignedIn, Started};
18
19pub const AUTHORIZE_PATH: &str = "/login/oauth/authorize";
20pub const CALLBACK_PATH: &str = "/callback";
21/// How often the listener checks for a connection, a cancel or the limit.
22const POLL: Duration = Duration::from_millis(100);
23/// How long one browser connection may take to send its request.
24const READ_LIMIT: Duration = Duration::from_secs(10);
25/// The longest request line and header line read.
26const LINE_LIMIT: usize = 8 * 1024;
27const MAX_HEADER_LINES: usize = 100;
28
29/// What the authorize URL carries.
30pub struct Authorize<'a> {
31    pub oauth: &'a str,
32    pub client_id: &'a str,
33    pub redirect_uri: &'a str,
34    pub state: &'a str,
35    pub challenge: &'a str,
36}
37
38/// GitHub's authorize page. `prompt=select_account` lets a person with
39/// several GitHub accounts choose one.
40pub fn authorize_url(request: &Authorize<'_>) -> String {
41    let query = url::form_urlencoded::Serializer::new(String::new())
42        .append_pair("client_id", request.client_id)
43        .append_pair("redirect_uri", request.redirect_uri)
44        .append_pair("scope", crate::config::SCOPES)
45        .append_pair("state", request.state)
46        .append_pair("code_challenge", request.challenge)
47        .append_pair("code_challenge_method", "S256")
48        .append_pair("prompt", "select_account")
49        .finish();
50    format!("{}{AUTHORIZE_PATH}?{query}", request.oauth)
51}
52
53/// What the browser's request means.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum Callback {
56    /// Not the callback, such as `/favicon.ico`.
57    Other,
58    Code(Secret),
59    Failed(AuthError),
60}
61
62/// Reads `GET /callback?code=…&state=…` against the `expected` state.
63pub fn parse_callback(target: &str, expected: &str) -> Callback {
64    let Ok(url) = url::Url::parse(&format!("http://127.0.0.1{target}")) else {
65        return Callback::Other;
66    };
67    if url.path() != CALLBACK_PATH {
68        return Callback::Other;
69    }
70    let value = |name: &str| {
71        url.query_pairs()
72            .find(|(key, _)| key == name)
73            .map(|(_, value)| value.into_owned())
74    };
75    if value("state").as_deref() != Some(expected) {
76        return Callback::Failed(AuthError::StateMismatch);
77    }
78    match (value("code"), value("error")) {
79        (Some(code), None) if !code.is_empty() => Callback::Code(Secret::new(code)),
80        (_, error) => Callback::Failed(token::failure(error.as_deref(), None)),
81    }
82}
83
84/// The request target of an HTTP request line, for `GET` only.
85pub fn request_target(line: &str) -> Option<&str> {
86    let mut parts = line.split_whitespace();
87    let (Some("GET"), Some(target)) = (parts.next(), parts.next()) else {
88        return None;
89    };
90    Some(target)
91}
92
93/// The small page the browser shows after its redirect.
94pub fn page(callback: &Callback) -> (u16, String) {
95    use subspace_auth_return::State;
96    let (status, state) = match callback {
97        Callback::Code(_) => (OK, State::Succeeded),
98        Callback::Failed(_) => (BAD_REQUEST, State::Failed),
99        Callback::Other => (NOT_FOUND, State::NotFound),
100    };
101    let html = subspace_auth_return::page(state);
102    (status, html)
103}
104
105/// Starts the browser flow: a listener on a free loopback port and the
106/// authorize URL that redirects to it.
107pub(crate) fn start(
108    client_id: &str,
109    secret: &Secret,
110    endpoints: &Endpoints,
111    time_limit: Duration,
112) -> Result<Started, AuthError> {
113    let listener = TcpListener::bind(("127.0.0.1", 0)).map_err(listener_error)?;
114    let port = listener.local_addr().map_err(listener_error)?.port();
115    let redirect_uri = format!("http://127.0.0.1:{port}{CALLBACK_PATH}");
116    let pkce = Pkce::generate();
117    let state = pkce::state();
118    let url = authorize_url(&Authorize {
119        oauth: &endpoints.oauth,
120        client_id,
121        redirect_uri: &redirect_uri,
122        state: &state,
123        challenge: &pkce.challenge,
124    });
125    let pending = BrowserPending {
126        listener,
127        exchange: Exchange {
128            endpoints: endpoints.clone(),
129            client_id: client_id.to_owned(),
130            secret: secret.clone(),
131            redirect_uri,
132            verifier: pkce.verifier,
133        },
134        state,
135        deadline: Instant::now() + time_limit,
136    };
137    Ok(Started {
138        prompt: Prompt::Browser { url },
139        pending: Box::new(pending),
140    })
141}
142
143fn listener_error(error: std::io::Error) -> AuthError {
144    AuthError::Listener(error.to_string())
145}
146
147/// What the code exchange sends.
148struct Exchange {
149    endpoints: Endpoints,
150    client_id: String,
151    secret: Secret,
152    redirect_uri: String,
153    verifier: Secret,
154}
155
156impl Exchange {
157    fn token(&self, code: &Secret) -> Result<SignedIn, AuthError> {
158        let form = [
159            ("client_id", self.client_id.as_str()),
160            ("client_secret", self.secret.expose()),
161            ("code", code.expose()),
162            ("redirect_uri", self.redirect_uri.as_str()),
163            ("code_verifier", self.verifier.expose()),
164        ];
165        match token::request(&self.endpoints.oauth, &form)? {
166            Reply::Token(granted) => crate::signed_in(&self.endpoints, granted),
167            Reply::Failed(error) => Err(error),
168            Reply::Pending | Reply::SlowDown(_) => Err(token::failure(None, None)),
169        }
170    }
171}
172
173struct BrowserPending {
174    listener: TcpListener,
175    exchange: Exchange,
176    state: String,
177    deadline: Instant,
178}
179
180impl Pending for BrowserPending {
181    fn finish(self: Box<Self>, cancel: &Cancel) -> Result<SignedIn, AuthError> {
182        let code = wait_for_code(&self.listener, &self.state, self.deadline, cancel)?;
183        drop(self.listener);
184        self.exchange.token(&code)
185    }
186}
187
188/// Answers browser connections until one brings the callback, the time
189/// limit passes or the sign-in is cancelled.
190fn wait_for_code(
191    listener: &TcpListener,
192    state: &str,
193    deadline: Instant,
194    cancel: &Cancel,
195) -> Result<Secret, AuthError> {
196    listener.set_nonblocking(true).map_err(listener_error)?;
197    let (sender, receiver) = mpsc::channel();
198    loop {
199        if cancel.is_cancelled() {
200            return Err(AuthError::Cancelled);
201        }
202        if Instant::now() >= deadline {
203            return Err(AuthError::TimedOut);
204        }
205        accept_one(listener, state, &sender)?;
206        match receiver.recv_timeout(POLL) {
207            Ok(Callback::Code(code)) => return Ok(code),
208            Ok(Callback::Failed(error)) => return Err(error),
209            Ok(Callback::Other) | Err(RecvTimeoutError::Timeout) => {}
210            Err(RecvTimeoutError::Disconnected) => return Err(AuthError::Cancelled),
211        }
212    }
213}
214
215/// Hands a waiting connection to its own thread, so a browser's idle
216/// speculative connection cannot hold up the real one.
217fn accept_one(
218    listener: &TcpListener,
219    state: &str,
220    sender: &Sender<Callback>,
221) -> Result<(), AuthError> {
222    match listener.accept() {
223        Ok((stream, _)) => {
224            let (state, sender) = (state.to_owned(), sender.clone());
225            std::thread::spawn(move || {
226                if let Some(callback) = answer(stream, &state) {
227                    let _ = sender.send(callback);
228                }
229            });
230            Ok(())
231        }
232        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(()),
233        Err(error) => Err(listener_error(error)),
234    }
235}
236
237/// Reads one request, answers it with a page and gives what it meant.
238fn answer(stream: TcpStream, state: &str) -> Option<Callback> {
239    stream.set_nonblocking(false).ok()?;
240    stream.set_read_timeout(Some(READ_LIMIT)).ok()?;
241    let mut reader = BufReader::new(stream.try_clone().ok()?);
242    let line = read_line(&mut reader)?;
243    skip_headers(&mut reader)?;
244    let callback =
245        request_target(&line).map_or(Callback::Other, |target| parse_callback(target, state));
246    write_page(stream, &callback);
247    Some(callback)
248}
249
250fn read_line(reader: &mut BufReader<TcpStream>) -> Option<String> {
251    let mut line = String::new();
252    let read = std::io::Read::take(reader, LINE_LIMIT as u64)
253        .read_line(&mut line)
254        .ok()?;
255    (read > 0).then_some(line)
256}
257
258fn skip_headers(reader: &mut BufReader<TcpStream>) -> Option<()> {
259    for _ in 0..MAX_HEADER_LINES {
260        if read_line(reader)?.trim().is_empty() {
261            return Some(());
262        }
263    }
264    None
265}
266
267fn write_page(mut stream: TcpStream, callback: &Callback) {
268    let (status, html) = page(callback);
269    let reason = match status {
270        OK => "OK",
271        BAD_REQUEST => "Bad Request",
272        _ => "Not Found",
273    };
274    let head = format!(
275        "HTTP/1.1 {status} {reason}\r\nContent-Type: text/html; charset=utf-8\r\n\
276         Content-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
277        html.len()
278    );
279    let _ = stream.write_all(head.as_bytes());
280    let _ = stream.write_all(html.as_bytes());
281    let _ = stream.flush();
282}
283
284#[cfg(test)]
285mod tests {
286    use super::{Authorize, Callback, authorize_url, page, parse_callback, request_target};
287    use crate::AuthError;
288    use subspace_core::Secret;
289
290    #[test]
291    fn the_authorize_url_asks_for_pkce_scopes_and_an_account_choice() {
292        let url = authorize_url(&Authorize {
293            oauth: "https://github.com",
294            client_id: "client",
295            redirect_uri: "http://127.0.0.1:5000/callback",
296            state: "state-value",
297            challenge: "challenge-value",
298        });
299        let parsed = url::Url::parse(&url).unwrap();
300        assert_eq!(parsed.path(), "/login/oauth/authorize");
301        let pairs: Vec<(String, String)> = parsed.query_pairs().into_owned().collect();
302        let expected = [
303            ("client_id", "client"),
304            ("redirect_uri", "http://127.0.0.1:5000/callback"),
305            ("scope", "repo read:org"),
306            ("state", "state-value"),
307            ("code_challenge", "challenge-value"),
308            ("code_challenge_method", "S256"),
309            ("prompt", "select_account"),
310        ];
311        assert_eq!(
312            pairs,
313            expected.map(|(key, value)| (key.to_owned(), value.to_owned()))
314        );
315    }
316
317    #[test]
318    fn the_callback_needs_the_expected_state() {
319        assert_eq!(
320            parse_callback("/callback?code=abc&state=good", "good"),
321            Callback::Code(Secret::new("abc"))
322        );
323        assert_eq!(
324            parse_callback("/callback?code=abc&state=bad", "good"),
325            Callback::Failed(AuthError::StateMismatch)
326        );
327        assert_eq!(
328            parse_callback("/callback?code=abc", "good"),
329            Callback::Failed(AuthError::StateMismatch)
330        );
331        assert_eq!(
332            parse_callback("/callback?error=access_denied&state=good", "good"),
333            Callback::Failed(AuthError::Denied)
334        );
335        assert_eq!(parse_callback("/favicon.ico", "good"), Callback::Other);
336        assert_eq!(
337            request_target("GET /callback?x=1 HTTP/1.1\r\n"),
338            Some("/callback?x=1")
339        );
340        assert_eq!(request_target("POST /callback HTTP/1.1"), None);
341    }
342
343    #[test]
344    fn pages_say_what_happened_without_echoing_the_request() {
345        let (status, html) = page(&Callback::Code(Secret::new("code-value")));
346        assert_eq!(status, 200);
347        assert!(html.contains("Signed in to Subspace") && html.contains("close this tab"));
348        assert!(!html.contains("code-value"));
349        let (status, html) = page(&Callback::Failed(AuthError::StateMismatch));
350        assert_eq!(status, 400);
351        assert!(html.contains("Sign-in did not finish"));
352        assert_eq!(page(&Callback::Other).0, 404);
353        for callback in [
354            Callback::Code(Secret::new("code-value")),
355            Callback::Failed(AuthError::StateMismatch),
356            Callback::Other,
357        ] {
358            let (_, html) = page(&callback);
359            assert!(html.contains("alt=\"Subspace\""));
360            assert_eq!(html.matches("src=\"data:image/svg+xml;base64,").count(), 1);
361            assert!(!html.contains("src=\"http") && !html.contains("{{"));
362        }
363    }
364}