1use std::collections::HashMap;
17use std::path::{Path, PathBuf};
18use std::sync::{Arc, Mutex, RwLock};
19use std::time::Instant;
20
21use axum::http::{HeaderMap, HeaderName, Request, StatusCode, header};
22use axum::response::{IntoResponse, Response};
23use base64::Engine as _;
24use schedr_config::{AuthMode, AuthSection};
25
26#[cfg(test)]
27mod tests;
28
29pub const USER_HEADER: &str = "x-schedr-user";
31
32pub const UI_TOKEN_HEADER: &str = "x-schedr-ui-token";
34
35pub const ANONYMOUS: &str = "anonymous";
37
38pub const DEFAULT_PROXY_HEADER: &str = "x-forwarded-user";
40
41pub const MAX_NAME: usize = 256;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct ProvenUi;
48
49#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct User(pub String);
52
53#[derive(Debug)]
58pub struct Followed<T> {
59 file: Option<FollowedFile<T>>,
60 current: RwLock<(Arc<T>, u64)>,
62}
63
64#[derive(Debug)]
65struct FollowedFile<T> {
66 path: PathBuf,
67 what: &'static str,
69 parse: fn(&str) -> Result<T, String>,
70 recheck: std::time::Duration,
72 looked: Mutex<(Instant, Option<Stamp>)>,
74}
75
76pub const RECHECK: std::time::Duration = std::time::Duration::from_secs(5);
78
79type Stamp = (Option<std::time::SystemTime>, u64);
81
82fn stamp(path: &Path) -> Option<Stamp> {
83 std::fs::metadata(path)
84 .ok()
85 .map(|meta| (meta.modified().ok(), meta.len()))
86}
87
88impl<T: Default> Default for Followed<T> {
89 fn default() -> Self {
90 Self::fixed(T::default())
91 }
92}
93
94impl<T> Followed<T> {
95 pub fn fixed(value: T) -> Self {
97 Self {
98 file: None,
99 current: RwLock::new((Arc::new(value), 0)),
100 }
101 }
102
103 pub fn read(
109 path: &Path,
110 what: &'static str,
111 parse: fn(&str) -> Result<T, String>,
112 recheck: std::time::Duration,
113 ) -> Result<Self, String> {
114 let looked = stamp(path);
115 let value = read_file(path)
116 .and_then(|text| parse(&text).map_err(|e| format!("{}: {e}", path.display())))?;
117 Ok(Self {
118 file: Some(FollowedFile {
119 path: path.to_owned(),
120 what,
121 parse,
122 recheck,
123 looked: Mutex::new((Instant::now(), looked)),
124 }),
125 current: RwLock::new((Arc::new(value), 0)),
126 })
127 }
128
129 pub fn current(&self) -> (Arc<T>, u64) {
132 self.follow();
133 let current = read(&self.current);
134 (Arc::clone(¤t.0), current.1)
135 }
136
137 fn follow(&self) {
139 let Some(file) = &self.file else {
140 return;
141 };
142 let now_stamp = {
143 let mut looked = lock(&file.looked);
144 let now = Instant::now();
145 if now.duration_since(looked.0) < file.recheck {
146 return;
147 }
148 looked.0 = now;
150 let now_stamp = stamp(&file.path);
151 if now_stamp == looked.1 {
152 return;
153 }
154 now_stamp
155 };
156 let path = file.path.display();
157 match read_file(&file.path).and_then(|text| (file.parse)(&text)) {
158 Ok(value) => {
159 {
160 let mut current = self
161 .current
162 .write()
163 .unwrap_or_else(std::sync::PoisonError::into_inner);
164 *current = (Arc::new(value), current.1 + 1);
165 }
166 lock(&file.looked).1 = now_stamp;
168 tracing::info!("{path} changed: {} read again", file.what);
169 }
170 Err(error) => tracing::error!(
172 %error,
173 "{path} changed but doesn't read: {} stay as they were",
174 file.what
175 ),
176 }
177 }
178}
179
180fn read_file(path: &Path) -> Result<String, String> {
181 std::fs::read_to_string(path).map_err(|e| format!("can't read {}: {e}", path.display()))
182}
183
184pub type UiToken = Arc<Followed<String>>;
187
188pub const MIN_UI_TOKEN: usize = 16;
190
191pub fn read_ui_token(path: &Path, recheck: std::time::Duration) -> Result<UiToken, String> {
197 let parse = |text: &str| {
198 let token = text.trim();
199 if token.len() < MIN_UI_TOKEN {
200 return Err(format!(
201 "the token is shorter than {MIN_UI_TOKEN} characters"
202 ));
203 }
204 Ok(token.to_owned())
205 };
206 Followed::read(path, "the UI's token", parse, recheck).map(Arc::new)
207}
208
209#[derive(Debug, Clone, Default)]
220pub struct Users {
221 loaded: Arc<Followed<Loaded>>,
222 passed: Arc<Mutex<Passed>>,
223 timings: AuthTimings,
224}
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub struct AuthTimings {
229 pub recheck: std::time::Duration,
232 pub remembered: std::time::Duration,
235 pub remembered_max: usize,
237}
238
239impl Default for AuthTimings {
240 fn default() -> Self {
242 Self {
243 recheck: RECHECK,
244 remembered: REMEMBERED,
245 remembered_max: MAX_REMEMBERED,
246 }
247 }
248}
249
250pub const REMEMBERED: std::time::Duration = std::time::Duration::from_mins(5);
252
253const MAX_REMEMBERED: usize = 1_000;
255
256#[derive(Debug, Default)]
258struct Loaded {
259 hashes: HashMap<String, String>,
260 dummy: String,
263}
264
265#[derive(Debug, Default)]
267struct Passed {
268 key: std::collections::hash_map::RandomState,
269 until: HashMap<u64, Instant>,
270 of: u64,
272}
273
274impl Passed {
275 fn digest(&self, name: &str, password: &str) -> u64 {
276 use std::hash::BuildHasher as _;
277 self.key.hash_one((name, password))
278 }
279
280 fn of(&mut self, read: u64) -> &mut Self {
282 if self.of != read {
283 self.until.clear();
284 self.of = read;
285 }
286 self
287 }
288}
289
290impl PartialEq for Users {
291 fn eq(&self, other: &Self) -> bool {
293 Arc::ptr_eq(&self.loaded, &other.loaded)
294 || self.loaded.current().0.hashes == other.loaded.current().0.hashes
295 }
296}
297
298impl Eq for Users {}
299
300fn read<T>(lock: &RwLock<T>) -> std::sync::RwLockReadGuard<'_, T> {
301 lock.read()
302 .unwrap_or_else(std::sync::PoisonError::into_inner)
303}
304
305fn lock<T>(lock: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
306 lock.lock()
307 .unwrap_or_else(std::sync::PoisonError::into_inner)
308}
309
310fn parse_users(text: &str) -> Result<Loaded, String> {
312 let mut hashes = HashMap::new();
313 for (number, line) in text.lines().enumerate() {
314 let line = line.trim();
315 if line.is_empty() || line.starts_with('#') {
316 continue;
317 }
318 let at = number + 1;
319 let Some((name, hash)) = line.split_once(':') else {
320 return Err(format!("line {at} isn't `name:bcrypt-hash`"));
321 };
322 if name.is_empty() || name.len() > MAX_NAME || !printable(name) {
323 return Err(format!("line {at}: the name isn't usable"));
324 }
325 if !is_bcrypt(hash) {
326 return Err(format!("line {at}: `{name}`'s hash isn't bcrypt's"));
327 }
328 if hashes.insert(name.to_owned(), hash.to_owned()).is_some() {
329 return Err(format!("line {at}: `{name}` is there twice"));
330 }
331 }
332 Ok(Loaded::new(hashes))
333}
334
335fn is_bcrypt(hash: &str) -> bool {
340 cost(hash).is_some()
341 && hash.rsplit_once('$').is_some_and(|(_, body)| {
342 body.len() == 53
343 && body
344 .bytes()
345 .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'/')
346 })
347}
348
349fn cost(hash: &str) -> Option<u32> {
351 let rest = ["$2a$", "$2b$", "$2y$"]
352 .iter()
353 .find_map(|prefix| hash.strip_prefix(prefix))?;
354 let (cost, _) = rest.split_once('$')?;
355 cost.parse().ok().filter(|cost| (4..=31).contains(cost))
356}
357
358impl Loaded {
359 fn new(hashes: HashMap<String, String>) -> Self {
360 let dummy = hashes
362 .values()
363 .filter_map(|hash| cost(hash))
364 .max()
365 .and_then(|cost| bcrypt::hash("schedr: no such user", cost).ok())
366 .unwrap_or_default();
367 Self { hashes, dummy }
368 }
369}
370
371impl Users {
372 pub fn parse(text: &str) -> Result<Self, String> {
379 Ok(Self {
380 loaded: Arc::new(Followed::fixed(parse_users(text)?)),
381 ..Self::default()
382 })
383 }
384
385 pub fn read(path: &Path, timings: AuthTimings) -> Result<Self, String> {
391 Ok(Self {
392 loaded: Arc::new(Followed::read(
393 path,
394 "its users",
395 parse_users,
396 timings.recheck,
397 )?),
398 timings,
399 ..Self::default()
400 })
401 }
402
403 pub async fn verify(&self, name: &str, password: &str) -> bool {
407 let (loaded, read) = self.loaded.current();
408 let now = Instant::now();
409 let digest = {
410 let mut passed = lock(&self.passed);
411 let passed = passed.of(read);
412 let digest = passed.digest(name, password);
413 if passed.until.get(&digest).is_some_and(|until| *until > now) {
414 return true;
415 }
416 digest
417 };
418 let (hash, known) = loaded.hashes.get(name).map_or_else(
421 || (loaded.dummy.clone(), false),
422 |hash| (hash.clone(), true),
423 );
424 let password = password.to_owned();
425 let checked =
426 tokio::task::spawn_blocking(move || bcrypt::verify(&password, &hash).unwrap_or(false))
427 .await
428 .unwrap_or(false);
429 let valid = known && checked;
430 if valid {
431 let mut passed = lock(&self.passed);
432 if passed.of != read {
434 return valid;
435 }
436 passed.until.retain(|_, until| *until > now);
437 if passed.until.len() >= self.timings.remembered_max
438 && let Some(oldest) = passed
439 .until
440 .iter()
441 .min_by_key(|(_, until)| **until)
442 .map(|(digest, _)| *digest)
443 {
444 passed.until.remove(&oldest);
445 }
446 passed.until.insert(digest, now + self.timings.remembered);
447 }
448 valid
449 }
450
451 #[must_use]
453 pub fn len(&self) -> usize {
454 self.loaded.current().0.hashes.len()
455 }
456
457 #[must_use]
459 pub fn is_empty(&self) -> bool {
460 self.len() == 0
461 }
462}
463
464#[derive(Debug, Clone)]
466pub struct Auth {
467 mode: AuthMode,
468 identity_header: Option<HeaderName>,
470 users: Users,
471 ui_token: Option<UiToken>,
473}
474
475impl Default for Auth {
476 fn default() -> Self {
478 Self {
479 mode: AuthMode::None,
480 identity_header: None,
481 users: Users::default(),
482 ui_token: None,
483 }
484 }
485}
486
487#[derive(Debug, Clone, PartialEq, Eq)]
489pub enum Refused {
490 NoProxyHeader(String),
492 Credentials,
494}
495
496impl Auth {
497 pub fn from_config(
505 section: &AuthSection,
506 ui_token: Option<UiToken>,
507 timings: AuthTimings,
508 ) -> Result<Self, String> {
509 let header = |name: &str| {
510 HeaderName::from_bytes(name.as_bytes())
511 .map_err(|_| format!("`{name}` isn't a header name"))
512 };
513 let identity_header = match (section.mode, section.identity_header.as_deref()) {
514 (AuthMode::ProxyHeader, None) => Some(header(DEFAULT_PROXY_HEADER)?),
515 (_, Some(name)) => Some(header(name)?),
516 (_, None) => None,
517 };
518 let users = if section.mode == AuthMode::Basic {
519 let path = section
520 .users_file
521 .as_deref()
522 .ok_or("`basic` needs `users_file` (`name:bcrypt-hash` lines)")?;
523 let users = Users::read(path, timings)?;
524 if users.is_empty() {
525 return Err(format!("{}: no users", path.display()));
526 }
527 users
528 } else {
529 Users::default()
530 };
531 Ok(Self {
532 mode: section.mode,
533 identity_header,
534 users,
535 ui_token,
536 })
537 }
538
539 #[must_use]
546 pub fn identity(identity_header: Option<String>) -> Self {
547 Self {
548 identity_header: identity_header
549 .map(|name| HeaderName::try_from(name).expect("a header name")),
550 ..Self::default()
551 }
552 }
553
554 #[must_use]
557 pub fn without_ui_token(&self) -> Self {
558 Self {
559 ui_token: None,
560 ..self.clone()
561 }
562 }
563
564 #[must_use]
566 pub const fn mode(&self) -> AuthMode {
567 self.mode
568 }
569
570 pub async fn user(&self, headers: &HeaderMap, proven: bool) -> Result<String, Refused> {
577 let value = |name: &str| {
578 single(headers, name)
579 .map(str::trim)
580 .filter(|v| !v.is_empty() && v.len() <= MAX_NAME && printable(v))
581 .map(str::to_owned)
582 };
583 if proven || self.token_matches(headers) {
584 return Ok(value(USER_HEADER).unwrap_or_else(|| ANONYMOUS.to_owned()));
585 }
586 match self.mode {
587 AuthMode::None => Ok(self
588 .identity_header
589 .as_ref()
590 .and_then(|h| value(h.as_str()))
591 .unwrap_or_else(|| ANONYMOUS.to_owned())),
592 AuthMode::ProxyHeader => {
593 let header = self
594 .identity_header
595 .as_ref()
596 .map_or(DEFAULT_PROXY_HEADER, HeaderName::as_str);
597 value(header).ok_or_else(|| Refused::NoProxyHeader(header.to_owned()))
598 }
599 AuthMode::Basic => {
600 let (name, password) = basic_credentials(headers).ok_or(Refused::Credentials)?;
601 if self.users.verify(&name, &password).await {
602 Ok(name)
603 } else {
604 Err(Refused::Credentials)
605 }
606 }
607 }
608 }
609
610 fn token_matches(&self, headers: &HeaderMap) -> bool {
612 let Some(token) = &self.ui_token else {
613 return false;
614 };
615 let (token, _) = token.current();
616 !token.is_empty()
618 && single(headers, UI_TOKEN_HEADER)
619 .is_some_and(|given| constant_time_eq(given.as_bytes(), token.as_bytes()))
620 }
621
622 pub fn refusal(&self, refused: &Refused, body: impl FnOnce(&str) -> Response) -> Response {
625 let message = match refused {
626 Refused::NoProxyHeader(header) => format!(
627 "not signed in: the `{header}` header the sign-in proxy sets is missing (reach \
628 schedr through the proxy)"
629 ),
630 Refused::Credentials => "not signed in: user name and password needed".to_owned(),
631 };
632 let mut response = body(&message);
633 *response.status_mut() = StatusCode::UNAUTHORIZED;
634 if self.mode == AuthMode::Basic {
635 response.headers_mut().insert(
636 header::WWW_AUTHENTICATE,
637 header::HeaderValue::from_static("Basic realm=\"schedr\", charset=\"UTF-8\""),
638 );
639 }
640 response
641 }
642}
643
644#[must_use]
646pub fn basic_credentials(headers: &HeaderMap) -> Option<(String, String)> {
647 let value = single(headers, header::AUTHORIZATION.as_str())?;
648 let (scheme, encoded) = value.trim().split_once(' ')?;
649 if !scheme.eq_ignore_ascii_case("basic") {
650 return None;
651 }
652 let decoded = base64::engine::general_purpose::STANDARD
653 .decode(encoded.trim())
654 .ok()?;
655 let text = String::from_utf8(decoded).ok()?;
656 let (name, password) = text.split_once(':')?;
657 Some((name.to_owned(), password.to_owned()))
658}
659
660fn single<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
663 let mut values = headers.get_all(name).iter();
664 let value = values.next()?;
665 if values.next().is_some() {
666 return None;
667 }
668 value.to_str().ok()
669}
670
671fn constant_time_eq(given: &[u8], expected: &[u8]) -> bool {
674 let differs = expected.iter().enumerate().fold(
675 u8::from(given.len() != expected.len()),
676 |acc, (at, byte)| acc | (byte ^ given.get(at).copied().unwrap_or(0)),
677 );
678 differs == 0
679}
680
681#[must_use]
686pub fn browser_same_origin(headers: &HeaderMap) -> Option<bool> {
687 let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok());
688 if let Some(site) = header("sec-fetch-site") {
689 return Some(site == "same-origin" || site == "none");
690 }
691 let origin = header(header::ORIGIN.as_str())?;
692 let host = header("x-forwarded-host").or_else(|| header(header::HOST.as_str()));
693 let (scheme, origin_host) = origin.split_once("://").unwrap_or(("", origin));
694 let without_default_port = |host: &str| {
695 let default = match scheme {
696 "https" => ":443",
697 "http" => ":80",
698 _ => return host.to_ascii_lowercase(),
699 };
700 host.strip_suffix(default)
701 .unwrap_or(host)
702 .to_ascii_lowercase()
703 };
704 Some(host.is_some_and(|host| {
705 without_default_port(host) == without_default_port(origin_host.trim_end_matches('/'))
706 }))
707}
708
709pub async fn refuse_cross_site(
714 request: Request<axum::body::Body>,
715 next: axum::middleware::Next,
716) -> Response {
717 if !request.method().is_safe() && browser_same_origin(request.headers()) == Some(false) {
718 return crate::error::ApiError::Forbidden(
719 "refused: a write from another site's page (`Sec-Fetch-Site` or `Origin`)".to_owned(),
720 )
721 .into_response();
722 }
723 next.run(request).await
724}
725
726fn printable(text: &str) -> bool {
728 !text.chars().any(char::is_control)
729}
730
731#[must_use]
734pub fn is_open(path: &str) -> bool {
735 path == crate::OPENAPI_PATH || path == crate::DOCS_PATH || path.starts_with("/api/v1/docs/")
736}
737
738pub async fn require(
740 axum::extract::State(state): axum::extract::State<crate::ApiState>,
741 mut request: Request<axum::body::Body>,
742 next: axum::middleware::Next,
743) -> Response {
744 if is_open(request.uri().path()) {
745 return next.run(request).await;
746 }
747 let proven = request.extensions().get::<ProvenUi>().is_some();
748 match state.auth.user(request.headers(), proven).await {
749 Ok(user) => {
750 request.extensions_mut().insert(User(user));
751 next.run(request).await
752 }
753 Err(refused) => state.auth.refusal(&refused, |message| {
754 crate::error::ApiError::Unauthorized(message.to_owned()).into_response()
755 }),
756 }
757}