Skip to main content

runnerd_web/
auth.rs

1//! Who may use the dashboard. The port is open to every local user, so every request but the login and the static
2//! assets needs the session cookie, and every write also needs an `Origin` of the dashboard itself: its loopback
3//! address, or one of `[web] origins`, the addresses of a reverse proxy in front of it.
4//!
5//! `Sessions` owns every credential, under one lock: the session secret the cookie holds, which the daemon keeps in
6//! a file only its user can read, so a browser stays signed in across restarts; the one-time login links of the
7//! running dashboard, one per address in `login_file`, each replaced once used; and pairing codes, which sign one
8//! device in on the one origin they were made for, within `PAIRING_LIFETIME`. Signing every browser out replaces
9//! the secret and every code at once, and ends the live pages signed in with the old secret. This module never logs
10//! any of them.
11
12use std::fmt::{self, Write as _};
13use std::io::{self, Read as _, Write as _};
14use std::net::SocketAddr;
15use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
16use std::path::{Path, PathBuf};
17use std::sync::{Arc, Mutex, MutexGuard};
18use std::time::{Duration, Instant};
19
20use axum::extract::{Query, Request, State};
21use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
22use axum::middleware::Next;
23use axum::response::{IntoResponse, Redirect, Response};
24use runnerd_core::config::Origin;
25use rustix::fs::{Mode, OFlags};
26use serde::Deserialize;
27use tokio::sync::watch;
28use tracing::warn;
29
30use crate::views::{self, SignedOut};
31
32/// How long a signed-in browser stays signed in without using the dashboard. Each authenticated response sets the
33/// cookie again, so a phone opened once a month never signs out; one lost in a drawer does after this.
34const SESSION_LIFETIME: Duration = Duration::from_hours(30 * 24);
35
36/// How long a pairing code works: enough to pick up a phone and scan it.
37pub const PAIRING_LIFETIME: Duration = Duration::from_mins(5);
38
39/// The most pairing codes alive at once; making another drops the oldest.
40pub const PAIRING_MAX: usize = 8;
41
42/// Where the daemon serving its API on `socket` keeps the dashboard's login links, one per line: its loopback
43/// address first, then each of `[web] origins`. `runnerd.sock` → `runnerd.web`. `runnerctl web` reads it.
44pub fn login_file(socket: &Path) -> PathBuf {
45    socket.with_extension("web")
46}
47
48/// Where the daemon keeps the session secret: beside its job history, `database`.
49pub fn session_file(database: &Path) -> PathBuf {
50    database.with_file_name("dashboard-session")
51}
52
53/// 32 random bytes as hex.
54fn random_token() -> io::Result<String> {
55    let mut bytes = [0u8; 32];
56    std::fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?;
57    Ok(bytes
58        .iter()
59        .fold(String::with_capacity(64), |mut hex, byte| {
60            let _ = write!(hex, "{byte:02x}");
61            hex
62        }))
63}
64
65/// Compares in time independent of where the strings differ.
66fn same(a: &str, b: &str) -> bool {
67    a.len() == b.len()
68        && a.bytes()
69            .zip(b.bytes())
70            .fold(0u8, |diff, (x, y)| diff | (x ^ y))
71            == 0
72}
73
74/// Writes `text` to `file`, readable by this user only, replacing it atomically.
75fn write_private(file: &Path, text: &str) -> io::Result<()> {
76    let mut temporary = file.as_os_str().to_owned();
77    temporary.push(".new");
78    let temporary = PathBuf::from(temporary);
79    let _ = std::fs::remove_file(&temporary);
80    let mut written = std::fs::OpenOptions::new()
81        .write(true)
82        .create_new(true)
83        .mode(0o600)
84        .open(&temporary)?;
85    written.write_all(text.as_bytes())?;
86    written.sync_all()?;
87    std::fs::rename(&temporary, file)
88}
89
90fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
91    mutex
92        .lock()
93        .unwrap_or_else(std::sync::PoisonError::into_inner)
94}
95
96/// Fails unless `dir` is owned by this user or root and no other user can write to it: another user could
97/// otherwise swap the secret's file for one they know.
98fn check_private_dir(dir: &Path) -> io::Result<()> {
99    let metadata = std::fs::metadata(dir)?;
100    let owner = metadata.uid();
101    let writable_by_others = metadata.mode() & 0o022;
102    if (owner != rustix::process::geteuid().as_raw() && owner != 0) || writable_by_others != 0 {
103        return Err(io::Error::new(
104            io::ErrorKind::PermissionDenied,
105            format!(
106                "{} can be written by other users; keep the job history (history.database) in a directory only \
107                 you can write",
108                dir.display()
109            ),
110        ));
111    }
112    Ok(())
113}
114
115/// The secret in `file`, or none to make a new one: missing, malformed, or readable or owned by another user. A
116/// symbolic link or anything but a regular file is an error. The checks and the read use one descriptor, opened
117/// without following a link, so the file cannot be swapped between them.
118fn read_secret(file: &Path) -> io::Result<Option<String>> {
119    let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
120    let descriptor = match rustix::fs::open(file, flags, Mode::empty()) {
121        Ok(descriptor) => descriptor,
122        Err(rustix::io::Errno::NOENT) => return Ok(None),
123        Err(rustix::io::Errno::LOOP) => {
124            return Err(io::Error::new(
125                io::ErrorKind::InvalidData,
126                format!("{} is a symbolic link; remove it", file.display()),
127            ));
128        }
129        Err(error) => return Err(error.into()),
130    };
131    let opened = std::fs::File::from(descriptor);
132    let metadata = opened.metadata()?;
133    if !metadata.is_file() {
134        return Err(io::Error::new(
135            io::ErrorKind::InvalidData,
136            format!("{} is not a regular file; remove it", file.display()),
137        ));
138    }
139    let shared = metadata.mode() & 0o077;
140    if metadata.uid() != rustix::process::geteuid().as_raw() || shared != 0 {
141        warn!(
142            "{} is readable by or belongs to another user; signing every browser out",
143            file.display()
144        );
145        return Ok(None);
146    }
147    let mut text = String::new();
148    opened.take(256).read_to_string(&mut text)?;
149    let secret = text.trim();
150    Ok(
151        (secret.len() == 64 && secret.bytes().all(|byte| byte.is_ascii_hexdigit()))
152            .then(|| secret.to_owned()),
153    )
154}
155
156/// The origin a request came to: `X-Forwarded-Proto` and `X-Forwarded-Host` from a proxy, or `http` and `Host`,
157/// as a browser would serialize it; none when they do not make an origin.
158fn request_origin(headers: &HeaderMap) -> Option<Origin> {
159    let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
160    let scheme = header("x-forwarded-proto").unwrap_or("http");
161    let host = header("x-forwarded-host").or_else(|| header(header::HOST.as_str()))?;
162    format!("{scheme}://{host}").parse().ok()
163}
164
165/// A pairing code: it works once, on `origin`, until `expires`.
166struct Pairing {
167    code: String,
168    origin: String,
169    expires: Instant,
170}
171
172/// A running dashboard's login links: the file they are written to, and an address and a code per link, the
173/// loopback address first.
174struct Links {
175    file: PathBuf,
176    bases: Vec<String>,
177    codes: Vec<String>,
178}
179
180impl Links {
181    fn write(&self) -> io::Result<()> {
182        let text =
183            self.bases
184                .iter()
185                .zip(&self.codes)
186                .fold(String::new(), |mut text, (base, code)| {
187                    let _ = writeln!(text, "{base}/login?code={code}");
188                    text
189                });
190        write_private(&self.file, &text)
191    }
192
193    /// New codes for every link, written to the file.
194    fn renew(&mut self) {
195        match self.bases.iter().map(|_| random_token()).collect() {
196            Ok(codes) => self.codes = codes,
197            // The old codes go anyway: an empty one matches nothing.
198            Err(error) => {
199                self.codes = vec![String::new(); self.bases.len()];
200                warn!("cannot make new dashboard login codes: {error}");
201            }
202        }
203        if let Err(error) = self.write() {
204            warn!(
205                "cannot write the dashboard's login links to {}: {error}",
206                self.file.display()
207            );
208        }
209    }
210
211    /// `[web] origins`: the addresses after the loopback one.
212    fn proxies(&self) -> &[String] {
213        self.bases.get(1..).unwrap_or_default()
214    }
215}
216
217/// The secret and the codes, changed together.
218struct Credentials {
219    secret: String,
220    /// None while no dashboard runs.
221    links: Option<Links>,
222    pairings: Vec<Pairing>,
223}
224
225/// Why no pairing link was made.
226#[derive(Debug)]
227pub enum PairError {
228    /// The daemon serves no dashboard (`--web off`).
229    DashboardOff,
230    /// `[web] origins` is empty: a phone cannot reach loopback.
231    NoOrigins,
232    /// The origin asked for is not one of `[web] origins`.
233    NotListed(String),
234    /// The session that asked was signed out before the code was made.
235    SignedOut,
236    /// No random code could be read.
237    Io(io::Error),
238}
239
240impl fmt::Display for PairError {
241    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
242        match self {
243            PairError::DashboardOff => formatter.write_str("runnerd serves no dashboard (--web off)"),
244            PairError::NoOrigins => formatter.write_str(
245                "no address another device reaches the dashboard on: list it in `[web] origins` in runnerd.toml \
246                 and restart runnerd",
247            ),
248            PairError::NotListed(origin) => write!(formatter, "{origin} is not one of [web] origins"),
249            PairError::SignedOut => formatter.write_str("this browser was signed out"),
250            PairError::Io(error) => write!(formatter, "cannot make a pairing code: {error}"),
251        }
252    }
253}
254
255impl std::error::Error for PairError {}
256
257/// Every credential of the dashboard: the session secret, kept in a file only the daemon's user can read, which
258/// every signed-in browser holds in its cookie; the login links of a running dashboard; and the pairing codes.
259pub struct Sessions {
260    file: PathBuf,
261    credentials: Mutex<Credentials>,
262    /// Sent each time every device is signed out, so open live pages end.
263    signed_out: watch::Sender<()>,
264}
265
266impl fmt::Debug for Sessions {
267    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
268        formatter
269            .debug_struct("Sessions")
270            .field("file", &self.file)
271            .finish_non_exhaustive()
272    }
273}
274
275impl Sessions {
276    /// The secret in `file`, or a new one written there when it is missing, malformed, or readable by other users.
277    /// Fails when other users can write to its directory, or `file` is a symbolic link or not a regular file.
278    pub fn open(file: PathBuf) -> io::Result<Arc<Sessions>> {
279        let dir = match file.parent() {
280            Some(dir) if !dir.as_os_str().is_empty() => dir,
281            _ => Path::new("."),
282        };
283        check_private_dir(dir)?;
284        let secret = if let Some(secret) = read_secret(&file)? {
285            secret
286        } else {
287            let secret = random_token()?;
288            write_private(&file, &format!("{secret}\n"))?;
289            secret
290        };
291        Ok(Arc::new(Sessions {
292            file,
293            credentials: Mutex::new(Credentials {
294                secret,
295                links: None,
296                pairings: Vec::new(),
297            }),
298            signed_out: watch::Sender::new(()),
299        }))
300    }
301
302    /// Replaces the secret, so every browser signed in is signed out, and every login link and pairing code made
303    /// before, so none signs one in again; the login file gets new links. Live pages open since end.
304    pub fn sign_out_all(&self) -> io::Result<()> {
305        let mut credentials = lock(&self.credentials);
306        let next = random_token()?;
307        write_private(&self.file, &format!("{next}\n"))?;
308        credentials.secret = next;
309        credentials.pairings.clear();
310        if let Some(links) = &mut credentials.links {
311            links.renew();
312        }
313        drop(credentials);
314        self.signed_out.send_replace(());
315        Ok(())
316    }
317
318    /// A link on `origin`, one of `[web] origins`, that signs one device in there within `PAIRING_LIFETIME` of
319    /// `now`, for the daemon's owner.
320    pub fn pair(&self, origin: &str, now: Instant) -> Result<String, PairError> {
321        Self::mint(&mut lock(&self.credentials), origin, now)
322    }
323
324    /// `pair` for a browser signed in with `session`, the secret its request was checked against: none once every
325    /// device was signed out since, checked under the lock that makes the code.
326    fn pair_for(
327        &self,
328        session: &SignedIn,
329        origin: &str,
330        now: Instant,
331    ) -> Result<String, PairError> {
332        let mut credentials = lock(&self.credentials);
333        if !same(&session.secret, &credentials.secret) {
334            return Err(PairError::SignedOut);
335        }
336        Self::mint(&mut credentials, origin, now)
337    }
338
339    fn mint(
340        credentials: &mut Credentials,
341        origin: &str,
342        now: Instant,
343    ) -> Result<String, PairError> {
344        let links = credentials.links.as_ref().ok_or(PairError::DashboardOff)?;
345        if links.proxies().is_empty() {
346            return Err(PairError::NoOrigins);
347        }
348        if !links.proxies().iter().any(|proxy| proxy == origin) {
349            return Err(PairError::NotListed(origin.to_owned()));
350        }
351        let code = random_token().map_err(PairError::Io)?;
352        credentials.pairings.retain(|pairing| pairing.expires > now);
353        if credentials.pairings.len() >= PAIRING_MAX {
354            credentials.pairings.remove(0);
355        }
356        credentials.pairings.push(Pairing {
357            code: code.clone(),
358            origin: origin.to_owned(),
359            expires: now + PAIRING_LIFETIME,
360        });
361        Ok(format!("{origin}/login?code={code}"))
362    }
363
364    /// `[web] origins` of the running dashboard; none when it does not run.
365    pub fn origins(&self) -> Option<Vec<String>> {
366        lock(&self.credentials)
367            .links
368            .as_ref()
369            .map(|links| links.proxies().to_vec())
370    }
371
372    /// Makes a login link for each of `bases`, the loopback address first, and writes them to `file`.
373    fn publish(&self, file: PathBuf, bases: Vec<String>) -> io::Result<()> {
374        let codes = bases
375            .iter()
376            .map(|_| random_token())
377            .collect::<io::Result<_>>()?;
378        let links = Links { file, bases, codes };
379        links.write()?;
380        lock(&self.credentials).links = Some(links);
381        Ok(())
382    }
383
384    /// Drops the login links and their file, when the dashboard stops.
385    fn withdraw(&self) {
386        if let Some(links) = lock(&self.credentials).links.take() {
387            let _ = std::fs::remove_file(&links.file);
388        }
389    }
390
391    /// The secret, if `value` is it: what a renewed cookie carries, so a request that passed with a secret since
392    /// replaced never gets the new one.
393    fn authenticate(&self, value: &str) -> Option<String> {
394        let credentials = lock(&self.credentials);
395        same(value, &credentials.secret).then(|| credentials.secret.clone())
396    }
397
398    /// Takes `code`, a login link's on any address, or a pairing code alive at `now` on `origin`, the one it was
399    /// made for, and returns the secret to sign in with. A used link's code is replaced in the login file.
400    fn redeem(&self, code: &str, origin: Option<&Origin>, now: Instant) -> Option<String> {
401        let mut credentials = lock(&self.credentials);
402        credentials.pairings.retain(|pairing| pairing.expires > now);
403        if let Some(index) = credentials
404            .pairings
405            .iter()
406            .position(|pairing| same(code, &pairing.code))
407        {
408            if origin.is_none_or(|origin| origin.as_str() != credentials.pairings[index].origin) {
409                return None;
410            }
411            credentials.pairings.remove(index);
412            return Some(credentials.secret.clone());
413        }
414        let links = credentials.links.as_mut()?;
415        let index = links.codes.iter().position(|link| same(code, link))?;
416        match random_token() {
417            Ok(next) => {
418                links.codes[index] = next;
419                if let Err(error) = links.write() {
420                    warn!(
421                        "cannot write the dashboard's login links to {}: {error}",
422                        links.file.display()
423                    );
424                }
425            }
426            // The used code goes anyway: a code works once even when no new one can be made.
427            Err(error) => {
428                links.codes[index] = String::new();
429                warn!("cannot make a new dashboard login code: {error}");
430            }
431        }
432        Some(credentials.secret.clone())
433    }
434}
435
436/// The secret a request's session cookie was checked against, which the session check hands its handler.
437#[derive(Clone)]
438pub(crate) struct SignedIn {
439    secret: String,
440    sessions: Arc<Sessions>,
441}
442
443impl SignedIn {
444    /// Completes once every device is signed out after the request was checked, so a live page ends.
445    pub(crate) async fn signed_out(&self) {
446        // Subscribed before checking, so a sign-out in between is seen by one or the other.
447        let mut changes = self.sessions.signed_out.subscribe();
448        while self.sessions.authenticate(&self.secret).is_some() {
449            if changes.changed().await.is_err() {
450                return;
451            }
452        }
453    }
454}
455
456/// The checks of a running dashboard: its cookie's name and the origins its pages may write from.
457#[derive(Debug)]
458pub(crate) struct Auth {
459    sessions: Arc<Sessions>,
460    cookie: String,
461    /// The origins whose pages may write: the loopback address, `localhost` on its port, and the proxies.
462    origins: Vec<String>,
463    proxies: Vec<String>,
464}
465
466impl Auth {
467    /// The checks for a dashboard on `addr`, which also takes writes from `proxies`; writes a login link for each
468    /// to `file`.
469    pub(crate) fn new(
470        addr: SocketAddr,
471        proxies: &[Origin],
472        sessions: Arc<Sessions>,
473        file: PathBuf,
474    ) -> io::Result<Arc<Auth>> {
475        let base = format!("http://{addr}");
476        let proxies: Vec<String> = proxies
477            .iter()
478            .map(|origin| origin.as_str().to_owned())
479            .collect();
480        let mut origins = vec![base.clone()];
481        if addr.ip().is_loopback() {
482            origins.push(format!("http://localhost:{}", addr.port()));
483        }
484        origins.extend(proxies.iter().cloned());
485        sessions.publish(
486            file,
487            std::iter::once(base)
488                .chain(proxies.iter().cloned())
489                .collect(),
490        )?;
491        Ok(Arc::new(Auth {
492            sessions,
493            cookie: format!("runnerd-{}", addr.port()),
494            origins,
495            proxies,
496        }))
497    }
498
499    /// `[web] origins`, the addresses a QR code can sign a phone in on.
500    pub(crate) fn proxies(&self) -> &[String] {
501        &self.proxies
502    }
503
504    /// Removes the login file, when the dashboard stops.
505    pub(crate) fn remove_login_file(&self) {
506        self.sessions.withdraw();
507    }
508
509    /// The secret the request's session cookie holds, if it is the current one.
510    fn authenticate(&self, headers: &HeaderMap) -> Option<String> {
511        headers
512            .get_all(header::COOKIE)
513            .iter()
514            .filter_map(|value| value.to_str().ok())
515            .flat_map(|value| value.split(';'))
516            .filter_map(|pair| pair.trim().split_once('='))
517            .filter(|(name, _)| *name == self.cookie)
518            .find_map(|(_, value)| self.sessions.authenticate(value))
519    }
520
521    fn same_origin(&self, headers: &HeaderMap) -> bool {
522        headers
523            .get(header::ORIGIN)
524            .and_then(|origin| origin.to_str().ok())
525            .is_some_and(|origin| self.origins.iter().any(|allowed| allowed == origin))
526    }
527
528    /// The session cookie holding `secret`. `SameSite=Lax`: a link from another site (GitHub, a notification, the
529    /// browser's history) opens the page signed in, while a write from another site still lacks the dashboard's
530    /// `Origin` and is refused. Through a proxy that says it took the request over https
531    /// (`X-Forwarded-Proto`, as `tailscale serve` sends), it is `Secure`.
532    fn cookie(&self, headers: &HeaderMap, secret: &str) -> Option<HeaderValue> {
533        let https = headers
534            .get("x-forwarded-proto")
535            .is_some_and(|proto| proto.as_bytes().eq_ignore_ascii_case(b"https"));
536        HeaderValue::try_from(format!(
537            "{}={secret}; Path=/; Max-Age={}; HttpOnly; SameSite=Lax{}",
538            self.cookie,
539            SESSION_LIFETIME.as_secs(),
540            if https { "; Secure" } else { "" }
541        ))
542        .ok()
543    }
544}
545
546/// A response carrying a credential, which no cache may keep.
547fn no_store(mut response: Response) -> Response {
548    response
549        .headers_mut()
550        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
551    response
552}
553
554#[derive(Deserialize)]
555pub(crate) struct Login {
556    code: String,
557}
558
559/// `GET /login?code=…`: a live code sets the session cookie and goes to the overview. A pairing code works only on
560/// the origin it was made for, as `X-Forwarded-Proto` and `X-Forwarded-Host` or `Host` name it.
561pub(crate) async fn login(
562    State(auth): State<Arc<Auth>>,
563    Query(login): Query<Login>,
564    headers: HeaderMap,
565) -> Response {
566    let origin = request_origin(&headers);
567    let Some(secret) = auth
568        .sessions
569        .redeem(&login.code, origin.as_ref(), Instant::now())
570    else {
571        // A browser that opens a link twice, as a phone's QR scanner can, is signed in by the first open.
572        if auth.authenticate(&headers).is_some() {
573            return no_store(Redirect::to("/").into_response());
574        }
575        return (
576            StatusCode::UNAUTHORIZED,
577            views::signed_out(SignedOut::CodeUsed),
578        )
579            .into_response();
580    };
581    let mut response = Redirect::to("/").into_response();
582    if let Some(cookie) = auth.cookie(&headers, &secret) {
583        response.headers_mut().insert(header::SET_COOKIE, cookie);
584    }
585    no_store(response)
586}
587
588#[derive(Deserialize)]
589pub(crate) struct PairRequest {
590    /// The proxy to sign in on; the first when the page sends none.
591    #[serde(default)]
592    pairing: String,
593}
594
595/// `POST /pair`: a fresh one-time login link on one of `[web] origins`, as a QR code the page shows.
596pub(crate) async fn pair(
597    State(auth): State<Arc<Auth>>,
598    axum::Extension(session): axum::Extension<SignedIn>,
599    request: Option<axum::Json<PairRequest>>,
600) -> Response {
601    let wanted = request.map(|request| request.0.pairing).unwrap_or_default();
602    let origin = if wanted.is_empty() {
603        auth.proxies().first().cloned().unwrap_or_default()
604    } else {
605        wanted
606    };
607    let markup = match auth.sessions.pair_for(&session, &origin, Instant::now()) {
608        Ok(url) => views::config::pairing_code(&url, &origin),
609        Err(PairError::SignedOut) => {
610            return (
611                StatusCode::UNAUTHORIZED,
612                views::signed_out(SignedOut::NoSession),
613            )
614                .into_response();
615        }
616        Err(error) => views::notice(&error.to_string(), views::Tone::Failed),
617    };
618    no_store(axum::response::Html(markup.into_string()).into_response())
619}
620
621/// Lets through the login, the assets, and requests with the session cookie, which they get again with its
622/// lifetime renewed and hand their handler as `SignedIn`; writes also need the dashboard's own `Origin` or a proxy's. A missing or wrong cookie is 401,
623/// a foreign origin 403.
624pub(crate) async fn require_session(
625    State(auth): State<Arc<Auth>>,
626    request: Request,
627    next: Next,
628) -> Response {
629    let path = request.uri().path();
630    if path == "/login" || path.starts_with("/assets/") {
631        return next.run(request).await;
632    }
633    let Some(secret) = auth.authenticate(request.headers()) else {
634        return (
635            StatusCode::UNAUTHORIZED,
636            views::signed_out(SignedOut::NoSession),
637        )
638            .into_response();
639    };
640    let safe = matches!(*request.method(), Method::GET | Method::HEAD);
641    if !safe && !auth.same_origin(request.headers()) {
642        return (
643            StatusCode::FORBIDDEN,
644            "writes must come from the dashboard's own pages",
645        )
646            .into_response();
647    }
648    let cookie = auth.cookie(request.headers(), &secret);
649    let mut request = request;
650    request.extensions_mut().insert(SignedIn {
651        secret,
652        sessions: auth.sessions.clone(),
653    });
654    let mut response = next.run(request).await;
655    if let Some(cookie) = cookie {
656        response.headers_mut().append(header::SET_COOKIE, cookie);
657    }
658    response
659}
660
661#[cfg(test)]
662mod tests {
663    use std::os::unix::fs::PermissionsExt as _;
664
665    use super::*;
666
667    const PROXY: &str = "https://forge.example.ts.net:8443";
668
669    fn links(file: &Path) -> Vec<String> {
670        std::fs::read_to_string(file)
671            .unwrap()
672            .lines()
673            .map(str::to_owned)
674            .collect()
675    }
676
677    fn code(link: &str) -> &str {
678        link.split_once("code=").unwrap().1
679    }
680
681    fn mode(file: &Path) -> u32 {
682        std::fs::symlink_metadata(file)
683            .unwrap()
684            .permissions()
685            .mode()
686            & 0o777
687    }
688
689    fn origin(text: &str) -> Origin {
690        text.parse().unwrap()
691    }
692
693    /// The secret in the session file.
694    fn stored(dir: &Path) -> String {
695        std::fs::read_to_string(dir.join("dashboard-session"))
696            .unwrap()
697            .trim()
698            .to_owned()
699    }
700
701    fn dashboard(dir: &Path, proxies: &[&str]) -> Arc<Auth> {
702        let proxies: Vec<Origin> = proxies.iter().map(|p| p.parse().unwrap()).collect();
703        let sessions = Sessions::open(dir.join("dashboard-session")).unwrap();
704        Auth::new(
705            "127.0.0.1:7477".parse().unwrap(),
706            &proxies,
707            sessions,
708            dir.join("runnerd.web"),
709        )
710        .unwrap()
711    }
712
713    #[test]
714    fn a_login_code_works_once_and_the_file_then_holds_a_new_one() {
715        let dir = crate::tests::TempDir::new();
716        let auth = dashboard(&dir.0, &[]);
717        let file = dir.0.join("runnerd.web");
718        let url = links(&file).remove(0);
719        assert!(url.starts_with("http://127.0.0.1:7477/login?code="));
720        let now = Instant::now();
721        assert!(
722            auth.sessions.redeem(code(&url), None, now).is_some(),
723            "the code works"
724        );
725        assert!(
726            auth.sessions.redeem(code(&url), None, now).is_none(),
727            "the code works only once"
728        );
729        assert_ne!(links(&file)[0], url);
730        assert_eq!(mode(&file), 0o600);
731    }
732
733    #[test]
734    fn each_address_gets_its_own_link_and_using_one_leaves_the_others_working() {
735        let dir = crate::tests::TempDir::new();
736        let auth = dashboard(&dir.0, &[PROXY, "https://forge.lan"]);
737        let before = links(&dir.0.join("runnerd.web"));
738        let bases: Vec<&str> = before
739            .iter()
740            .map(|link| link.split_once("/login?").unwrap().0)
741            .collect();
742        assert_eq!(bases, ["http://127.0.0.1:7477", PROXY, "https://forge.lan"]);
743        let now = Instant::now();
744        assert!(auth.sessions.redeem(code(&before[0]), None, now).is_some());
745        let after = links(&dir.0.join("runnerd.web"));
746        assert_ne!(after[0], before[0], "the used link is replaced");
747        assert_eq!(after[1..], before[1..], "the others stay as printed");
748        assert!(
749            auth.sessions.redeem(code(&before[1]), None, now).is_some(),
750            "the proxy's link still works"
751        );
752    }
753
754    #[test]
755    fn a_pairing_code_works_once_and_not_after_it_expires() {
756        let dir = crate::tests::TempDir::new();
757        let auth = dashboard(&dir.0, &[PROXY]);
758        let now = Instant::now();
759        let url = auth.sessions.pair(PROXY, now).unwrap();
760        assert!(url.starts_with("https://forge.example.ts.net:8443/login?code="));
761        let on_proxy = Some(origin(PROXY));
762        assert!(
763            auth.sessions
764                .redeem(code(&url), on_proxy.as_ref(), now)
765                .is_some(),
766            "a fresh code works"
767        );
768        assert!(
769            auth.sessions
770                .redeem(code(&url), on_proxy.as_ref(), now)
771                .is_none(),
772            "a used code does not"
773        );
774        let late = auth.sessions.pair(PROXY, now).unwrap();
775        let after = now + PAIRING_LIFETIME + Duration::from_secs(1);
776        assert!(
777            auth.sessions
778                .redeem(code(&late), on_proxy.as_ref(), after)
779                .is_none(),
780            "an expired code does not"
781        );
782    }
783
784    #[test]
785    fn a_pairing_code_works_only_on_the_origin_it_was_made_for() {
786        let dir = crate::tests::TempDir::new();
787        let auth = dashboard(&dir.0, &[PROXY, "https://forge.lan"]);
788        let now = Instant::now();
789        let url = auth.sessions.pair(PROXY, now).unwrap();
790        for elsewhere in [
791            Some(origin("http://127.0.0.1:7477")),
792            Some(origin("https://forge.lan")),
793            Some(origin("https://unlisted.example")),
794            None,
795        ] {
796            assert!(
797                auth.sessions
798                    .redeem(code(&url), elsewhere.as_ref(), now)
799                    .is_none(),
800                "the code does not work on {elsewhere:?}"
801            );
802        }
803        assert!(
804            auth.sessions
805                .redeem(code(&url), Some(&origin(PROXY)), now)
806                .is_some(),
807            "nor is it spent there"
808        );
809    }
810
811    #[test]
812    fn a_pairing_code_is_only_for_a_configured_proxy() {
813        let dir = crate::tests::TempDir::new();
814        let auth = dashboard(&dir.0, &[PROXY]);
815        assert!(
816            matches!(
817                auth.sessions.pair("https://evil.example", Instant::now()),
818                Err(PairError::NotListed(_))
819            ),
820            "no link on an address the owner did not list"
821        );
822        let dir = crate::tests::TempDir::new();
823        let auth = dashboard(&dir.0, &[]);
824        assert!(
825            matches!(
826                auth.sessions.pair(PROXY, Instant::now()),
827                Err(PairError::NoOrigins)
828            ),
829            "none without [web] origins"
830        );
831        let sessions = Sessions::open(dir.0.join("other-session")).unwrap();
832        assert!(
833            matches!(
834                sessions.pair(PROXY, Instant::now()),
835                Err(PairError::DashboardOff)
836            ),
837            "none while no dashboard runs"
838        );
839    }
840
841    #[test]
842    fn at_most_eight_pairing_codes_live_at_once() {
843        let dir = crate::tests::TempDir::new();
844        let auth = dashboard(&dir.0, &[PROXY]);
845        let now = Instant::now();
846        let urls: Vec<String> = (0..9)
847            .map(|_| auth.sessions.pair(PROXY, now).unwrap())
848            .collect();
849        let on_proxy = Some(origin(PROXY));
850        assert!(
851            auth.sessions
852                .redeem(code(&urls[0]), on_proxy.as_ref(), now)
853                .is_none(),
854            "the oldest is dropped"
855        );
856        assert!(
857            auth.sessions
858                .redeem(code(&urls[1]), on_proxy.as_ref(), now)
859                .is_some(),
860            "the next still works"
861        );
862    }
863
864    #[test]
865    fn the_session_survives_a_restart_until_every_device_is_signed_out() {
866        let dir = crate::tests::TempDir::new();
867        let file = dir.0.join("dashboard-session");
868        Sessions::open(file.clone()).unwrap();
869        let cookie = stored(&dir.0);
870        assert_eq!(mode(&file), 0o600);
871        let restarted = Sessions::open(file.clone()).unwrap();
872        assert!(
873            restarted.authenticate(&cookie).is_some(),
874            "the cookie works after a restart"
875        );
876        restarted.sign_out_all().unwrap();
877        assert!(
878            restarted.authenticate(&cookie).is_none(),
879            "signing out ends it"
880        );
881        assert!(
882            Sessions::open(file.clone())
883                .unwrap()
884                .authenticate(&cookie)
885                .is_none(),
886            "and it stays ended after the next restart"
887        );
888        assert_eq!(mode(&file), 0o600);
889    }
890
891    #[test]
892    fn signing_every_device_out_ends_every_code_made_before_and_writes_new_links() {
893        let dir = crate::tests::TempDir::new();
894        let auth = dashboard(&dir.0, &[PROXY]);
895        let now = Instant::now();
896        let pairing = auth.sessions.pair(PROXY, now).unwrap();
897        let printed = links(&dir.0.join("runnerd.web"));
898        auth.sessions.sign_out_all().unwrap();
899        let on_proxy = Some(origin(PROXY));
900        assert!(
901            auth.sessions
902                .redeem(code(&pairing), on_proxy.as_ref(), now)
903                .is_none(),
904            "a QR code shown before no longer signs in"
905        );
906        for link in &printed {
907            assert!(
908                auth.sessions.redeem(code(link), None, now).is_none(),
909                "a link printed before no longer signs in"
910            );
911        }
912        let fresh = links(&dir.0.join("runnerd.web"));
913        assert_ne!(fresh, printed);
914        let secret = auth.sessions.redeem(code(&fresh[0]), None, now).unwrap();
915        assert!(
916            auth.sessions.authenticate(&secret).is_some(),
917            "a new link signs in with the new secret"
918        );
919    }
920
921    #[test]
922    fn a_request_that_passed_before_a_sign_out_is_renewed_with_its_old_secret_only() {
923        let dir = crate::tests::TempDir::new();
924        let auth = dashboard(&dir.0, &[]);
925        let old = stored(&dir.0);
926        let mut headers = HeaderMap::new();
927        headers.insert(
928            header::COOKIE,
929            format!("{}={old}", auth.cookie).parse().unwrap(),
930        );
931        // The middleware's order: authenticate, the handler runs while every device is signed out, renew.
932        let passed = auth.authenticate(&headers).unwrap();
933        auth.sessions.sign_out_all().unwrap();
934        let renewed = auth.cookie(&headers, &passed).unwrap();
935        let renewed = renewed.to_str().unwrap();
936        let new = stored(&dir.0);
937        assert!(
938            renewed.contains(&old) && !renewed.contains(&new),
939            "the renewed cookie carries the secret the request came with, not its replacement"
940        );
941        assert!(
942            auth.authenticate(&headers).is_none(),
943            "and the next request is signed out"
944        );
945    }
946
947    #[test]
948    fn a_session_file_other_users_can_read_is_replaced() {
949        let dir = crate::tests::TempDir::new();
950        let file = dir.0.join("dashboard-session");
951        Sessions::open(file.clone()).unwrap();
952        let cookie = stored(&dir.0);
953        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
954        assert!(
955            Sessions::open(file.clone())
956                .unwrap()
957                .authenticate(&cookie)
958                .is_none(),
959            "a secret others could read no longer signs in"
960        );
961        assert_eq!(mode(&file), 0o600);
962    }
963
964    #[test]
965    fn a_session_file_that_is_a_symbolic_link_or_a_pipe_is_refused() {
966        let dir = crate::tests::TempDir::new();
967        let known = dir.0.join("known");
968        std::fs::write(&known, format!("{}\n", "ab".repeat(32))).unwrap();
969        std::fs::set_permissions(&known, std::fs::Permissions::from_mode(0o600)).unwrap();
970        let file = dir.0.join("dashboard-session");
971        std::os::unix::fs::symlink(&known, &file).unwrap();
972        let error = Sessions::open(file).unwrap_err();
973        assert!(
974            error.to_string().contains("symbolic link"),
975            "a known secret behind a link is not taken"
976        );
977        let fifo = dir.0.join("fifo-session");
978        rustix::fs::mknodat(
979            rustix::fs::CWD,
980            &fifo,
981            rustix::fs::FileType::Fifo,
982            Mode::RUSR | Mode::WUSR,
983            0,
984        )
985        .unwrap();
986        let error = Sessions::open(fifo).unwrap_err();
987        assert!(
988            error.to_string().contains("not a regular file"),
989            "a pipe is refused without blocking"
990        );
991    }
992
993    #[test]
994    fn a_session_file_in_a_directory_others_can_write_is_refused() {
995        let dir = crate::tests::TempDir::new();
996        let shared = dir.0.join("shared");
997        std::fs::create_dir(&shared).unwrap();
998        for unsafe_mode in [0o777, 0o1777, 0o770] {
999            std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(unsafe_mode))
1000                .unwrap();
1001            let error = Sessions::open(shared.join("dashboard-session")).unwrap_err();
1002            assert!(
1003                error.to_string().contains("can be written by other users"),
1004                "mode {unsafe_mode:o} is refused"
1005            );
1006        }
1007        assert!(
1008            !shared.join("dashboard-session").exists(),
1009            "nothing is written there"
1010        );
1011    }
1012
1013    #[test]
1014    fn the_log_shows_no_secret_or_code_even_when_a_new_link_cannot_be_written() {
1015        let dir = crate::tests::TempDir::new();
1016        let log = Arc::new(Mutex::new(Vec::new()));
1017        let writer = log.clone();
1018        let subscriber = tracing_subscriber::fmt()
1019            .with_writer(move || Writer(writer.clone()))
1020            .finish();
1021        let mut secrets = Vec::new();
1022        tracing::subscriber::with_default(subscriber, || {
1023            let auth = dashboard(&dir.0, &[PROXY]);
1024            let first = links(&dir.0.join("runnerd.web")).remove(0);
1025            secrets.push(code(&first).to_owned());
1026            // A directory in place of the login file's temporary: the new link cannot be written, and that is
1027            // logged.
1028            std::fs::create_dir(dir.0.join("runnerd.web.new")).unwrap();
1029            std::fs::create_dir(dir.0.join("runnerd.web.new/x")).unwrap();
1030            let secret = auth
1031                .sessions
1032                .redeem(code(&first), None, Instant::now())
1033                .unwrap();
1034            secrets.push(secret);
1035            let pairing = auth.sessions.pair(PROXY, Instant::now()).unwrap();
1036            secrets.push(code(&pairing).to_owned());
1037            auth.sessions.sign_out_all().unwrap();
1038            let credentials = lock(&auth.sessions.credentials);
1039            secrets.push(credentials.secret.clone());
1040            secrets.extend(credentials.links.as_ref().unwrap().codes.iter().cloned());
1041        });
1042        let log = String::from_utf8(lock(&log).clone()).unwrap();
1043        assert!(log.contains("cannot write"), "the failure is logged: {log}");
1044        for secret in secrets {
1045            assert!(!log.contains(&secret), "the log shows a secret");
1046        }
1047    }
1048
1049    struct Writer(Arc<Mutex<Vec<u8>>>);
1050
1051    impl io::Write for Writer {
1052        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1053            lock(&self.0).extend_from_slice(bytes);
1054            Ok(bytes.len())
1055        }
1056
1057        fn flush(&mut self) -> io::Result<()> {
1058            Ok(())
1059        }
1060    }
1061
1062    #[test]
1063    fn debug_output_shows_no_secret_or_code() {
1064        let dir = crate::tests::TempDir::new();
1065        let auth = dashboard(&dir.0, &[PROXY]);
1066        let pairing = auth.sessions.pair(PROXY, Instant::now()).unwrap();
1067        let debug = format!("{auth:?} {:?}", auth.sessions);
1068        let mut secrets = vec![stored(&dir.0), code(&pairing).to_owned()];
1069        secrets.extend(
1070            links(&dir.0.join("runnerd.web"))
1071                .iter()
1072                .map(|link| code(link).to_owned()),
1073        );
1074        for secret in secrets {
1075            assert!(!debug.contains(&secret), "Debug shows a secret");
1076        }
1077    }
1078}