Skip to main content

day_part_auth/
session.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The web auth session: the system's own sign-in browser, which returns the URL the provider
5//! redirected to. Layer one of the crate; everything above it takes the callback URL from here.
6//!
7//! | Platform | Browser | Callback |
8//! |---|---|---|
9//! | iOS, macOS | `ASWebAuthenticationSession` (Swift arm) | returned by the session itself |
10//! | Android | a Custom Tab (Java arm) | the app's custom scheme, through the deep-link rail |
11//! | Web | a popup of the same origin (JavaScript arm) | the popup posts its URL to the opener |
12//! | Windows, Linux | the default browser | a loopback listener, or the deep-link rail |
13//! | HarmonyOS | the default browser | the deep-link rail |
14//!
15//! Embedded web views are not offered on any platform: providers refuse them (RFC 8252 §8.12),
16//! and the person has no address bar to check who is asking.
17//!
18//! # Callbacks on the deep-link rail
19//!
20//! A custom-scheme redirect arrives like any other URL the OS hands the app: through
21//! `day::on_open_url`. The session registers a handler in a scope of its own for the one URL it
22//! expects and declines everything else, so the app's handler keeps seeing the rest; the
23//! registration goes when the session ends. Registering needs the UI thread, which is where a
24//! sign-in starts (a button's action).
25//!
26//! # The loopback listener
27//!
28//! [`Loopback`] binds `127.0.0.1` (port 0 lets the OS pick, RFC 8252 §7.3), answers the one
29//! request the browser makes with a short "you can return to the app" page, and hands the
30//! request URL back. It accepts one connection, on a thread of its own, within the timeout.
31
32use std::io::{Read, Write};
33use std::net::{TcpListener, TcpStream};
34#[cfg(any(
35    target_os = "android",
36    target_os = "windows",
37    target_os = "linux",
38    target_env = "ohos"
39))]
40use std::sync::{Arc, Mutex};
41use std::time::{Duration, Instant};
42
43use crate::AuthError;
44
45/// How the browser session is shown.
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct SessionOptions {
48    /// Ask for a browsing session that shares no cookies with the person's browser, so the
49    /// provider does not know them from an earlier sign-in. Honored by Apple
50    /// (`prefersEphemeralWebBrowserSession`); the other platforms cannot and ignore it.
51    pub ephemeral: bool,
52    /// How long a loopback listener waits for the browser's request before giving up with
53    /// [`AuthError::Timeout`]. The interactive sessions have no timeout of their own: the
54    /// person closes them.
55    pub timeout: Duration,
56    /// The page the loopback listener answers the browser with. HTML; the default says the
57    /// sign-in is done and the window can be closed.
58    pub completion_page: Option<String>,
59}
60
61impl Default for SessionOptions {
62    fn default() -> Self {
63        SessionOptions {
64            ephemeral: false,
65            timeout: Duration::from_secs(300),
66            completion_page: None,
67        }
68    }
69}
70
71/// What this platform's session can do.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct SessionCapabilities {
74    /// Whether a session can be opened at all.
75    pub support: day_bridge::Support,
76    /// Whether an `https://` callback is received without leaving the browser (Apple from
77    /// iOS 17.4 and macOS 14.4 with an associated domain; the web).
78    pub https_callback: bool,
79    /// Whether [`SessionOptions::ephemeral`] is honored.
80    pub ephemeral: bool,
81    /// Whether a custom-scheme callback is received (every platform with a deep-link rail).
82    pub scheme_callback: bool,
83    /// Whether a loopback listener can serve as the callback (the desktops).
84    pub loopback: bool,
85}
86
87/// What this platform's session can do.
88pub fn capabilities() -> SessionCapabilities {
89    let apple = cfg!(any(target_os = "ios", target_os = "macos"));
90    let desktop = cfg!(any(
91        target_os = "windows",
92        all(target_os = "linux", not(target_env = "ohos"))
93    ));
94    let web = cfg!(target_arch = "wasm32");
95    let support = if cfg!(any(
96        target_os = "ios",
97        target_os = "macos",
98        target_os = "android",
99        target_os = "windows",
100        target_os = "linux",
101        target_env = "ohos",
102        target_arch = "wasm32"
103    )) {
104        day_bridge::Support::Native
105    } else {
106        day_bridge::Support::Unsupported
107    };
108    SessionCapabilities {
109        support,
110        https_callback: apple || web,
111        ephemeral: apple,
112        scheme_callback: !web,
113        loopback: desktop || apple,
114    }
115}
116
117/// Open `url` in the system's sign-in browser and resolve with the callback URL once the
118/// provider returns to the exact callback endpoint, preserving its registered query fields. The person
119/// dismissing the browser resolves with [`AuthError::Cancelled`].
120///
121/// Call it on the UI thread: the custom-scheme platforms register for the callback on the
122/// deep-link rail, which lives there. The future is `Send`; awaited under `day::task` the
123/// continuation runs on the UI thread again.
124///
125/// # Errors
126///
127/// The future resolves to [`AuthError::Cancelled`] when the person dismisses the browser,
128/// [`AuthError::InvalidRequest`] when `url` or the callback is unusable here, and the
129/// platform's error otherwise.
130pub fn open(
131    url: &str,
132    callback_prefix: &str,
133    options: &SessionOptions,
134) -> impl std::future::Future<Output = Result<String, AuthError>> + Send {
135    let (tx, rx) = day_async::oneshot();
136    start(
137        url,
138        callback_prefix,
139        options,
140        Box::new(move |answer| tx.send(answer)),
141    );
142    let expected = callback_prefix.to_string();
143    async move {
144        let received = rx.await.unwrap_or(Err(AuthError::Cancelled))?;
145        if !crate::urls::callback_matches(&expected, &received) {
146            return Err(AuthError::InvalidRequest(
147                "authentication callback endpoint mismatch".into(),
148            ));
149        }
150        Ok(received)
151    }
152}
153
154/// The page's own URL without its fragment, on the web: the redirect the popup flow returns to,
155/// and what [`crate::Redirect::Auto`] resolves to there. `None` everywhere else.
156pub fn page_url() -> Option<String> {
157    if cfg!(target_arch = "wasm32") {
158        crate::native::page_url()
159            .ok()
160            .filter(|u| u.starts_with("https://") || u.starts_with("http://"))
161    } else {
162        None
163    }
164}
165
166/// Dismiss the session on screen, if any. Its caller resolves with [`AuthError::Cancelled`].
167pub fn cancel() {
168    imp::cancel();
169}
170
171type OnDone = Box<dyn FnOnce(Result<String, AuthError>) + Send>;
172
173fn start(url: &str, callback_prefix: &str, options: &SessionOptions, on_done: OnDone) {
174    if crate::urls::parse(callback_prefix).is_err() {
175        on_done(Err(AuthError::InvalidRequest(
176            "the callback must be an absolute URL".into(),
177        )));
178        return;
179    }
180    if !crate::provider::is_trusted_url(url) {
181        on_done(Err(AuthError::InvalidRequest(
182            "the sign-in URL must be https (or loopback for a local provider)".into(),
183        )));
184        return;
185    }
186    imp::start(url, callback_prefix, options, on_done);
187}
188
189/// Wrap a one-shot completion so it can be called from two places and fire once.
190#[cfg(any(
191    target_os = "android",
192    target_os = "windows",
193    target_os = "linux",
194    target_env = "ohos"
195))]
196fn once(cb: OnDone) -> Arc<dyn Fn(Result<String, AuthError>) + Send + Sync> {
197    let cell = Mutex::new(Some(cb));
198    Arc::new(move |answer| {
199        let taken = match cell.lock() {
200            Ok(mut g) => g.take(),
201            Err(poisoned) => poisoned.into_inner().take(),
202        };
203        if let Some(cb) = taken {
204            cb(answer);
205        }
206    })
207}
208
209// ---------------------------------------------------------------------------
210// The deep-link rail: a custom-scheme callback through `day::on_open_url`
211// ---------------------------------------------------------------------------
212
213// The scope of the rail watch in flight on this (the UI) thread. One at a time: a new session
214// replaces the last, and a delivered callback removes its own.
215#[cfg(any(
216    target_os = "android",
217    target_os = "windows",
218    target_os = "linux",
219    target_env = "ohos"
220))]
221thread_local! {
222    static WATCH: std::cell::RefCell<Option<day_reactive::Scope>> = const { std::cell::RefCell::new(None) };
223}
224
225/// Watch the deep-link rail for one URL starting with `prefix`, in a scope of its own, from the
226/// UI thread. The handler delivers the URL and removes itself; a session that ends another way
227/// leaves the watch until the next session replaces it, which is harmless, since the completion
228/// it would deliver to fires once.
229#[cfg(any(
230    target_os = "android",
231    target_os = "windows",
232    target_os = "linux",
233    target_env = "ohos"
234))]
235fn watch_rail(prefix: String, deliver: Arc<dyn Fn(Result<String, AuthError>) + Send + Sync>) {
236    unwatch_rail();
237    let scope = day_reactive::Scope::child();
238    scope.enter(|| {
239        day_core::on_open_url(move |url| {
240            if crate::urls::callback_matches(&prefix, url) {
241                deliver(Ok(url.to_string()));
242                unwatch_rail();
243                true
244            } else {
245                false
246            }
247        });
248    });
249    WATCH.with(|w| *w.borrow_mut() = Some(scope));
250}
251
252/// Dispose the rail watch in flight, if any.
253#[cfg(any(
254    target_os = "android",
255    target_os = "windows",
256    target_os = "linux",
257    target_env = "ohos"
258))]
259fn unwatch_rail() {
260    let taken = WATCH.with(|w| w.borrow_mut().take());
261    if let Some(scope) = taken {
262        scope.dispose();
263    }
264}
265
266// ---------------------------------------------------------------------------
267// The loopback listener (desktops, and any platform with a browser to open)
268// ---------------------------------------------------------------------------
269
270/// A listener on `127.0.0.1` for the provider's redirect.
271pub struct Loopback {
272    listener: TcpListener,
273    redirect_uri: String,
274}
275
276impl Loopback {
277    /// Bind `127.0.0.1:port` (0 for any free port) and build the redirect URI with the port
278    /// the OS gave and `path` (`/callback` by default).
279    ///
280    /// # Errors
281    ///
282    /// Returns [`AuthError::Platform`] when the port cannot be bound.
283    pub fn bind(port: u16, path: &str) -> Result<Loopback, AuthError> {
284        let listener = TcpListener::bind(("127.0.0.1", port))
285            .map_err(|e| AuthError::Platform(format!("loopback listener: {e}")))?;
286        let bound = listener
287            .local_addr()
288            .map_err(|e| AuthError::Platform(format!("loopback listener: {e}")))?;
289        let path = if path.is_empty() { "/callback" } else { path };
290        let path = if path.starts_with('/') {
291            path.to_string()
292        } else {
293            format!("/{path}")
294        };
295        Ok(Loopback {
296            listener,
297            redirect_uri: format!("http://127.0.0.1:{}{}", bound.port(), path),
298        })
299    }
300
301    /// The redirect URI to send the provider: `http://127.0.0.1:<port><path>`.
302    pub fn redirect_uri(&self) -> &str {
303        &self.redirect_uri
304    }
305
306    /// Wait on a thread of its own for the browser's request and resolve with its full URL.
307    /// Any request to another path is answered 404 and ignored.
308    ///
309    /// # Errors
310    ///
311    /// The future resolves to [`AuthError::Timeout`] when no callback arrives within the
312    /// session's limit, and [`AuthError::Platform`] when the listener fails.
313    pub fn wait(
314        self,
315        options: &SessionOptions,
316    ) -> impl std::future::Future<Output = Result<String, AuthError>> + Send {
317        let (tx, rx) = day_async::oneshot();
318        let timeout = options.timeout;
319        let page = options
320            .completion_page
321            .clone()
322            .unwrap_or_else(|| DEFAULT_COMPLETION_PAGE.to_string());
323        let spawned = std::thread::Builder::new()
324            .name("day-auth-loopback".into())
325            .spawn(move || tx.send(self.serve(timeout, &page)));
326        let started = spawned.is_ok();
327        async move {
328            if !started {
329                return Err(AuthError::Platform(
330                    "could not start the loopback thread".into(),
331                ));
332            }
333            rx.await.unwrap_or(Err(AuthError::Cancelled))
334        }
335    }
336
337    fn serve(self, timeout: Duration, page: &str) -> Result<String, AuthError> {
338        let deadline = Instant::now() + timeout;
339        self.listener
340            .set_nonblocking(true)
341            .map_err(|e| AuthError::Platform(format!("loopback listener: {e}")))?;
342        let path = self
343            .redirect_uri
344            .splitn(4, '/')
345            .nth(3)
346            .map_or_else(|| "/".to_string(), |p| format!("/{p}"));
347        loop {
348            match self.listener.accept() {
349                Ok((stream, _)) => {
350                    let _ = stream.set_nonblocking(false);
351                    let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
352                    if let Some(url) = self.answer(stream, &path, page) {
353                        return Ok(url);
354                    }
355                }
356                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
357                    if Instant::now() >= deadline {
358                        return Err(AuthError::Timeout);
359                    }
360                    std::thread::sleep(Duration::from_millis(50));
361                }
362                Err(e) => return Err(AuthError::Platform(format!("loopback listener: {e}"))),
363            }
364        }
365    }
366
367    /// Read one request line, answer it, and return the full URL when it is the callback.
368    fn answer(&self, mut stream: TcpStream, path: &str, page: &str) -> Option<String> {
369        let mut buf = Vec::with_capacity(4096);
370        let mut chunk = [0u8; 1024];
371        loop {
372            match stream.read(&mut chunk) {
373                Ok(0) | Err(_) => break,
374                Ok(n) => {
375                    buf.extend_from_slice(&chunk[..n]);
376                    if buf.windows(4).any(|w| w == b"\r\n\r\n") || buf.len() > 64 * 1024 {
377                        break;
378                    }
379                }
380            }
381        }
382        let head = String::from_utf8_lossy(&buf);
383        let request_line = head.lines().next().unwrap_or("");
384        let mut parts = request_line.split(' ');
385        let (Some(method), Some(target)) = (parts.next(), parts.next()) else {
386            let _ = respond(&mut stream, 400, "text/plain", "bad request");
387            return None;
388        };
389        let target_path = target.split('?').next().unwrap_or("");
390        if method != "GET" || target_path != path {
391            let _ = respond(&mut stream, 404, "text/plain", "not found");
392            return None;
393        }
394        let _ = respond(&mut stream, 200, "text/html; charset=utf-8", page);
395        let base = self.redirect_uri.trim_end_matches(path);
396        Some(format!("{base}{target}"))
397    }
398}
399
400fn respond(
401    stream: &mut TcpStream,
402    status: u16,
403    content_type: &str,
404    body: &str,
405) -> std::io::Result<()> {
406    let reason = match status {
407        200 => "OK",
408        400 => "Bad Request",
409        404 => "Not Found",
410        _ => "",
411    };
412    write!(
413        stream,
414        "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n",
415        body.len()
416    )?;
417    stream.write_all(body.as_bytes())?;
418    stream.flush()
419}
420
421/// The page the browser shows once the provider has redirected back.
422const DEFAULT_COMPLETION_PAGE: &str = "<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>Signed in</title><style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f4f5f7;color:#1f2933}main{text-align:center;padding:2rem}h1{font-size:1.4rem;margin:0 0 .5rem}p{margin:0;color:#52606d}</style></head><body><main><h1>Signed in</h1><p>You can close this window and return to the app.</p></main></body></html>";
423
424// ---------------------------------------------------------------------------
425// Per-platform sessions
426// ---------------------------------------------------------------------------
427
428/// Apple: `ASWebAuthenticationSession`, through the Swift arm. It returns the callback URL
429/// itself, custom scheme or (iOS 17.4, macOS 14.4) https.
430#[cfg(any(target_os = "ios", target_os = "macos"))]
431mod imp {
432    use super::*;
433    use crate::native::{close_session, open_session_native_async};
434
435    pub fn start(url: &str, callback_prefix: &str, options: &SessionOptions, on_done: OnDone) {
436        let scheme = callback_prefix.split(':').next().unwrap_or("").to_string();
437        let _ = open_session_native_async(
438            url,
439            &scheme,
440            callback_prefix,
441            options.ephemeral,
442            move |answer| on_done(super::read_answer(answer)),
443        );
444    }
445
446    pub fn cancel() {
447        let _ = close_session();
448    }
449}
450
451/// Android: a Custom Tab through the Java arm; the callback arrives on the deep-link rail. The
452/// arm reports when the app's activity resumes, which is the tab closing: a callback that has
453/// not arrived shortly after that is a dismissal.
454#[cfg(target_os = "android")]
455mod imp {
456    use super::*;
457    use crate::native::{close_session, open_session_native_async};
458
459    pub fn start(url: &str, callback_prefix: &str, options: &SessionOptions, on_done: OnDone) {
460        let deliver = once(on_done);
461        watch_rail(callback_prefix.to_string(), deliver.clone());
462        let scheme = callback_prefix.split(':').next().unwrap_or("").to_string();
463        let resumed = deliver.clone();
464        let _ = open_session_native_async(
465            url,
466            &scheme,
467            callback_prefix,
468            options.ephemeral,
469            move |answer| match answer {
470                // The tab closed. The deep link, when there is one, is delivered on the UI thread
471                // as the activity resumes; give it a moment before calling this a dismissal.
472                Ok(_) => {
473                    let resumed = resumed.clone();
474                    let _ = std::thread::Builder::new()
475                        .name("day-auth-resume".into())
476                        .spawn(move || {
477                            std::thread::sleep(Duration::from_millis(700));
478                            resumed(Err(AuthError::Cancelled));
479                        });
480                }
481                Err(e) => resumed(Err(AuthError::from(e))),
482            },
483        );
484    }
485
486    pub fn cancel() {
487        let _ = close_session();
488    }
489}
490
491/// The web: a popup of the same origin through the JavaScript arm, which posts the callback
492/// URL to its opener and closes.
493#[cfg(target_arch = "wasm32")]
494mod imp {
495    use super::*;
496    use crate::native::{close_session, open_session_native_async};
497
498    pub fn start(url: &str, callback_prefix: &str, options: &SessionOptions, on_done: OnDone) {
499        let _ =
500            open_session_native_async(url, "", callback_prefix, options.ephemeral, move |answer| {
501                on_done(super::read_answer(answer));
502            });
503    }
504
505    pub fn cancel() {
506        let _ = close_session();
507    }
508}
509
510/// Windows, Linux and HarmonyOS: the default browser, and the callback on the deep-link rail
511/// (desktop single-instance forwarding or the HarmonyOS want). A loopback redirect does not come
512/// through here: [`Loopback`] serves it.
513#[cfg(not(any(
514    target_os = "ios",
515    target_os = "macos",
516    target_os = "android",
517    target_arch = "wasm32"
518)))]
519mod imp {
520    use super::*;
521
522    type Deliver = Arc<dyn Fn(Result<String, AuthError>) + Send + Sync>;
523    static ACTIVE: Mutex<Option<Deliver>> = Mutex::new(None);
524
525    pub fn start(url: &str, callback_prefix: &str, _options: &SessionOptions, on_done: OnDone) {
526        let deliver = once(on_done);
527        watch_rail(callback_prefix.to_string(), deliver.clone());
528        if let Ok(mut slot) = ACTIVE.lock() {
529            *slot = Some(deliver);
530        }
531        day_core::open_url(url);
532    }
533
534    pub fn cancel() {
535        let taken = ACTIVE.lock().ok().and_then(|mut s| s.take());
536        if let Some(deliver) = taken {
537            deliver(Err(AuthError::Cancelled));
538        }
539    }
540}
541
542/// The arm's completion: a URL, `cancelled`, or `error:<message>`.
543#[cfg(any(target_os = "ios", target_os = "macos", target_arch = "wasm32"))]
544fn read_answer(answer: Result<String, day_bridge::Error>) -> Result<String, AuthError> {
545    match answer {
546        Ok(text) if text == "cancelled" => Err(AuthError::Cancelled),
547        Ok(text) if text == "unsupported" => Err(AuthError::Unsupported),
548        Ok(text) if text.starts_with("error:") => Err(AuthError::Platform(text[6..].to_string())),
549        Ok(url) if url.contains(':') => Ok(url),
550        Ok(other) => Err(AuthError::Platform(format!(
551            "unexpected session answer {other:?}"
552        ))),
553        Err(e) => Err(AuthError::from(e)),
554    }
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560
561    #[test]
562    fn capabilities_answer_for_this_host() {
563        let caps = capabilities();
564        if cfg!(any(
565            target_os = "macos",
566            target_os = "linux",
567            target_os = "windows"
568        )) {
569            assert_eq!(caps.support, day_bridge::Support::Native);
570            assert!(caps.loopback);
571        }
572    }
573
574    #[test]
575    fn loopback_binds_builds_the_redirect_and_returns_the_request_url() {
576        let loopback = Loopback::bind(0, "/callback").expect("bind");
577        let redirect = loopback.redirect_uri().to_string();
578        assert!(redirect.starts_with("http://127.0.0.1:"));
579        assert!(redirect.ends_with("/callback"));
580        let options = SessionOptions {
581            timeout: Duration::from_secs(5),
582            ..SessionOptions::default()
583        };
584        let (tx, rx) = std::sync::mpsc::channel();
585        let server = std::thread::spawn(move || {
586            let answer = loopback.serve(options.timeout, "done");
587            let _ = tx.send(answer);
588        });
589        // A request to another path is ignored; the callback is answered and returned.
590        let port: u16 = redirect
591            .trim_start_matches("http://127.0.0.1:")
592            .split('/')
593            .next()
594            .and_then(|p| p.parse().ok())
595            .expect("port");
596        let mut other = TcpStream::connect(("127.0.0.1", port)).expect("connect");
597        other
598            .write_all(b"GET /favicon.ico HTTP/1.1\r\nHost: x\r\n\r\n")
599            .expect("write");
600        let mut reply = String::new();
601        let _ = other.read_to_string(&mut reply);
602        assert!(reply.starts_with("HTTP/1.1 404"));
603        let mut browser = TcpStream::connect(("127.0.0.1", port)).expect("connect");
604        browser
605            .write_all(b"GET /callback?code=abc&state=xyz HTTP/1.1\r\nHost: x\r\n\r\n")
606            .expect("write");
607        let mut reply = String::new();
608        let _ = browser.read_to_string(&mut reply);
609        assert!(reply.starts_with("HTTP/1.1 200"));
610        assert!(reply.ends_with("done"));
611        let answer = rx.recv().expect("answer");
612        assert_eq!(answer, Ok(format!("{redirect}?code=abc&state=xyz")));
613        server.join().expect("join");
614    }
615
616    #[test]
617    fn loopback_times_out_without_a_request() {
618        let loopback = Loopback::bind(0, "cb").expect("bind");
619        assert!(loopback.redirect_uri().ends_with("/cb"));
620        assert_eq!(
621            loopback.serve(Duration::from_millis(120), "done"),
622            Err(AuthError::Timeout)
623        );
624    }
625
626    #[test]
627    fn open_rejects_unusable_arguments_through_the_callback() {
628        let (tx, rx) = std::sync::mpsc::channel();
629        start(
630            "https://x",
631            "",
632            &SessionOptions::default(),
633            Box::new(move |a| {
634                let _ = tx.send(a);
635            }),
636        );
637        std::assert_matches!(rx.recv(), Ok(Err(AuthError::InvalidRequest(_))));
638        let (tx, rx) = std::sync::mpsc::channel();
639        start(
640            "ftp://x",
641            "myapp://cb",
642            &SessionOptions::default(),
643            Box::new(move |a| {
644                let _ = tx.send(a);
645            }),
646        );
647        std::assert_matches!(rx.recv(), Ok(Err(AuthError::InvalidRequest(_))));
648    }
649}