1use 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
32const SESSION_LIFETIME: Duration = Duration::from_hours(30 * 24);
35
36pub const PAIRING_LIFETIME: Duration = Duration::from_mins(5);
38
39pub const PAIRING_MAX: usize = 8;
41
42pub fn login_file(socket: &Path) -> PathBuf {
45 socket.with_extension("web")
46}
47
48pub fn session_file(database: &Path) -> PathBuf {
50 database.with_file_name("dashboard-session")
51}
52
53fn 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
65fn 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
74fn 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
96fn 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
115fn 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
156fn 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
165struct Pairing {
167 code: String,
168 origin: String,
169 expires: Instant,
170}
171
172struct 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 fn renew(&mut self) {
195 match self.bases.iter().map(|_| random_token()).collect() {
196 Ok(codes) => self.codes = codes,
197 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 fn proxies(&self) -> &[String] {
213 self.bases.get(1..).unwrap_or_default()
214 }
215}
216
217struct Credentials {
219 secret: String,
220 links: Option<Links>,
222 pairings: Vec<Pairing>,
223}
224
225#[derive(Debug)]
227pub enum PairError {
228 DashboardOff,
230 NoOrigins,
232 NotListed(String),
234 SignedOut,
236 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
257pub struct Sessions {
260 file: PathBuf,
261 credentials: Mutex<Credentials>,
262 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 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 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 pub fn pair(&self, origin: &str, now: Instant) -> Result<String, PairError> {
321 Self::mint(&mut lock(&self.credentials), origin, now)
322 }
323
324 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 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 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 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 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 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 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#[derive(Clone)]
438pub(crate) struct SignedIn {
439 secret: String,
440 sessions: Arc<Sessions>,
441}
442
443impl SignedIn {
444 pub(crate) async fn signed_out(&self) {
446 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#[derive(Debug)]
458pub(crate) struct Auth {
459 sessions: Arc<Sessions>,
460 cookie: String,
461 origins: Vec<String>,
463 proxies: Vec<String>,
464}
465
466impl Auth {
467 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 pub(crate) fn proxies(&self) -> &[String] {
501 &self.proxies
502 }
503
504 pub(crate) fn remove_login_file(&self) {
506 self.sessions.withdraw();
507 }
508
509 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 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
546fn 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
559pub(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 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 #[serde(default)]
592 pairing: String,
593}
594
595pub(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
621pub(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 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 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 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}