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    let (status, title, message) = match callback {
96        Callback::Code(_) => (
97            OK,
98            "Signed in to Subspace",
99            "You can close this tab and return to Subspace.",
100        ),
101        Callback::Failed(_) => (
102            BAD_REQUEST,
103            "Sign-in did not finish",
104            "Return to Subspace to see why and try again.",
105        ),
106        Callback::Other => (
107            NOT_FOUND,
108            "Not found",
109            "This address only completes a Subspace sign-in.",
110        ),
111    };
112    let html = format!(
113        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>{title}</title>\
114         <meta name=\"color-scheme\" content=\"light dark\"><style>body{{font:16px -apple-system,\
115         system-ui,sans-serif;margin:20vh auto;max-width:28em;text-align:center}}</style></head>\
116         <body><h1>{title}</h1><p>{message}</p></body></html>"
117    );
118    (status, html)
119}
120
121/// Starts the browser flow: a listener on a free loopback port and the
122/// authorize URL that redirects to it.
123pub(crate) fn start(
124    client_id: &str,
125    secret: &Secret,
126    endpoints: &Endpoints,
127    time_limit: Duration,
128) -> Result<Started, AuthError> {
129    let listener = TcpListener::bind(("127.0.0.1", 0)).map_err(listener_error)?;
130    let port = listener.local_addr().map_err(listener_error)?.port();
131    let redirect_uri = format!("http://127.0.0.1:{port}{CALLBACK_PATH}");
132    let pkce = Pkce::generate();
133    let state = pkce::state();
134    let url = authorize_url(&Authorize {
135        oauth: &endpoints.oauth,
136        client_id,
137        redirect_uri: &redirect_uri,
138        state: &state,
139        challenge: &pkce.challenge,
140    });
141    let pending = BrowserPending {
142        listener,
143        exchange: Exchange {
144            endpoints: endpoints.clone(),
145            client_id: client_id.to_owned(),
146            secret: secret.clone(),
147            redirect_uri,
148            verifier: pkce.verifier,
149        },
150        state,
151        deadline: Instant::now() + time_limit,
152    };
153    Ok(Started {
154        prompt: Prompt::Browser { url },
155        pending: Box::new(pending),
156    })
157}
158
159fn listener_error(error: std::io::Error) -> AuthError {
160    AuthError::Listener(error.to_string())
161}
162
163/// What the code exchange sends.
164struct Exchange {
165    endpoints: Endpoints,
166    client_id: String,
167    secret: Secret,
168    redirect_uri: String,
169    verifier: Secret,
170}
171
172impl Exchange {
173    fn token(&self, code: &Secret) -> Result<SignedIn, AuthError> {
174        let form = [
175            ("client_id", self.client_id.as_str()),
176            ("client_secret", self.secret.expose()),
177            ("code", code.expose()),
178            ("redirect_uri", self.redirect_uri.as_str()),
179            ("code_verifier", self.verifier.expose()),
180        ];
181        match token::request(&self.endpoints.oauth, &form)? {
182            Reply::Token(granted) => crate::signed_in(&self.endpoints, granted),
183            Reply::Failed(error) => Err(error),
184            Reply::Pending | Reply::SlowDown(_) => Err(token::failure(None, None)),
185        }
186    }
187}
188
189struct BrowserPending {
190    listener: TcpListener,
191    exchange: Exchange,
192    state: String,
193    deadline: Instant,
194}
195
196impl Pending for BrowserPending {
197    fn finish(self: Box<Self>, cancel: &Cancel) -> Result<SignedIn, AuthError> {
198        let code = wait_for_code(&self.listener, &self.state, self.deadline, cancel)?;
199        drop(self.listener);
200        self.exchange.token(&code)
201    }
202}
203
204/// Answers browser connections until one brings the callback, the time
205/// limit passes or the sign-in is cancelled.
206fn wait_for_code(
207    listener: &TcpListener,
208    state: &str,
209    deadline: Instant,
210    cancel: &Cancel,
211) -> Result<Secret, AuthError> {
212    listener.set_nonblocking(true).map_err(listener_error)?;
213    let (sender, receiver) = mpsc::channel();
214    loop {
215        if cancel.is_cancelled() {
216            return Err(AuthError::Cancelled);
217        }
218        if Instant::now() >= deadline {
219            return Err(AuthError::TimedOut);
220        }
221        accept_one(listener, state, &sender)?;
222        match receiver.recv_timeout(POLL) {
223            Ok(Callback::Code(code)) => return Ok(code),
224            Ok(Callback::Failed(error)) => return Err(error),
225            Ok(Callback::Other) | Err(RecvTimeoutError::Timeout) => {}
226            Err(RecvTimeoutError::Disconnected) => return Err(AuthError::Cancelled),
227        }
228    }
229}
230
231/// Hands a waiting connection to its own thread, so a browser's idle
232/// speculative connection cannot hold up the real one.
233fn accept_one(
234    listener: &TcpListener,
235    state: &str,
236    sender: &Sender<Callback>,
237) -> Result<(), AuthError> {
238    match listener.accept() {
239        Ok((stream, _)) => {
240            let (state, sender) = (state.to_owned(), sender.clone());
241            std::thread::spawn(move || {
242                if let Some(callback) = answer(stream, &state) {
243                    let _ = sender.send(callback);
244                }
245            });
246            Ok(())
247        }
248        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(()),
249        Err(error) => Err(listener_error(error)),
250    }
251}
252
253/// Reads one request, answers it with a page and gives what it meant.
254fn answer(stream: TcpStream, state: &str) -> Option<Callback> {
255    stream.set_nonblocking(false).ok()?;
256    stream.set_read_timeout(Some(READ_LIMIT)).ok()?;
257    let mut reader = BufReader::new(stream.try_clone().ok()?);
258    let line = read_line(&mut reader)?;
259    skip_headers(&mut reader)?;
260    let callback =
261        request_target(&line).map_or(Callback::Other, |target| parse_callback(target, state));
262    write_page(stream, &callback);
263    Some(callback)
264}
265
266fn read_line(reader: &mut BufReader<TcpStream>) -> Option<String> {
267    let mut line = String::new();
268    let read = std::io::Read::take(reader, LINE_LIMIT as u64)
269        .read_line(&mut line)
270        .ok()?;
271    (read > 0).then_some(line)
272}
273
274fn skip_headers(reader: &mut BufReader<TcpStream>) -> Option<()> {
275    for _ in 0..MAX_HEADER_LINES {
276        if read_line(reader)?.trim().is_empty() {
277            return Some(());
278        }
279    }
280    None
281}
282
283fn write_page(mut stream: TcpStream, callback: &Callback) {
284    let (status, html) = page(callback);
285    let reason = match status {
286        OK => "OK",
287        BAD_REQUEST => "Bad Request",
288        _ => "Not Found",
289    };
290    let head = format!(
291        "HTTP/1.1 {status} {reason}\r\nContent-Type: text/html; charset=utf-8\r\n\
292         Content-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
293        html.len()
294    );
295    let _ = stream.write_all(head.as_bytes());
296    let _ = stream.write_all(html.as_bytes());
297    let _ = stream.flush();
298}
299
300#[cfg(test)]
301mod tests {
302    use super::{Authorize, Callback, authorize_url, page, parse_callback, request_target};
303    use crate::AuthError;
304    use subspace_core::Secret;
305
306    #[test]
307    fn the_authorize_url_asks_for_pkce_scopes_and_an_account_choice() {
308        let url = authorize_url(&Authorize {
309            oauth: "https://github.com",
310            client_id: "client",
311            redirect_uri: "http://127.0.0.1:5000/callback",
312            state: "state-value",
313            challenge: "challenge-value",
314        });
315        let parsed = url::Url::parse(&url).unwrap();
316        assert_eq!(parsed.path(), "/login/oauth/authorize");
317        let pairs: Vec<(String, String)> = parsed.query_pairs().into_owned().collect();
318        let expected = [
319            ("client_id", "client"),
320            ("redirect_uri", "http://127.0.0.1:5000/callback"),
321            ("scope", "repo read:org"),
322            ("state", "state-value"),
323            ("code_challenge", "challenge-value"),
324            ("code_challenge_method", "S256"),
325            ("prompt", "select_account"),
326        ];
327        assert_eq!(
328            pairs,
329            expected.map(|(key, value)| (key.to_owned(), value.to_owned()))
330        );
331    }
332
333    #[test]
334    fn the_callback_needs_the_expected_state() {
335        assert_eq!(
336            parse_callback("/callback?code=abc&state=good", "good"),
337            Callback::Code(Secret::new("abc"))
338        );
339        assert_eq!(
340            parse_callback("/callback?code=abc&state=bad", "good"),
341            Callback::Failed(AuthError::StateMismatch)
342        );
343        assert_eq!(
344            parse_callback("/callback?code=abc", "good"),
345            Callback::Failed(AuthError::StateMismatch)
346        );
347        assert_eq!(
348            parse_callback("/callback?error=access_denied&state=good", "good"),
349            Callback::Failed(AuthError::Denied)
350        );
351        assert_eq!(parse_callback("/favicon.ico", "good"), Callback::Other);
352        assert_eq!(
353            request_target("GET /callback?x=1 HTTP/1.1\r\n"),
354            Some("/callback?x=1")
355        );
356        assert_eq!(request_target("POST /callback HTTP/1.1"), None);
357    }
358
359    #[test]
360    fn pages_say_what_happened_without_echoing_the_request() {
361        let (status, html) = page(&Callback::Code(Secret::new("code-value")));
362        assert_eq!(status, 200);
363        assert!(html.contains("Signed in to Subspace") && html.contains("close this tab"));
364        assert!(!html.contains("code-value"));
365        let (status, html) = page(&Callback::Failed(AuthError::StateMismatch));
366        assert_eq!(status, 400);
367        assert!(html.contains("Sign-in did not finish"));
368        assert_eq!(page(&Callback::Other).0, 404);
369    }
370}