Skip to main content

schedr_api/
auth.rs

1//! Who the user is (M3.5; see archive/PROJECT.md, Authentication: as little as possible in schedr).
2//! The name is recorded on commands, never used to allow or deny anything; there are no roles.
3//!
4//! - **A caller proven to be `schedr ui`** passes the person's name on in [`USER_HEADER`]
5//!   (decision 36): proven by its mTLS certificate on the webserver's UI port (that listener
6//!   marks its requests [`ProvenUi`]), by the token it presents in [`UI_TOKEN_HEADER`] where
7//!   there is no mTLS (a mesh, a standalone), or by calling in-process (standalone's own UI).
8//!   Only so proven is the name taken; anyone else's [`USER_HEADER`] is ignored.
9//! - **Anyone else**, by the mode: `none` takes the identity header's value if there is one
10//!   (else `anonymous`); `proxy_header` requires the SSO proxy's header; `basic` checks HTTP
11//!   Basic credentials against bcrypt hashes. A request refused is 401 (with a Basic challenge
12//!   in `basic` mode).
13//!
14//! The same rules serve the UI's own pages (`[ui.auth]`), with no UI in front of it.
15
16use 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
29/// The header `schedr ui` names the person in (taken only from a proven UI).
30pub const USER_HEADER: &str = "x-schedr-user";
31
32/// The header `schedr ui` presents its token in, where there is no mTLS.
33pub const UI_TOKEN_HEADER: &str = "x-schedr-ui-token";
34
35/// The name recorded when no one is named.
36pub const ANONYMOUS: &str = "anonymous";
37
38/// The header an SSO proxy names the user in, when `identity_header` isn't set.
39pub const DEFAULT_PROXY_HEADER: &str = "x-forwarded-user";
40
41/// The longest name taken (a longer one is refused, not cut).
42pub const MAX_NAME: usize = 256;
43
44/// A request from `schedr ui`, proven by how it arrived (the UI port's mTLS, or in-process):
45/// a request extension, which no client can set.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct ProvenUi;
48
49/// Who a request is from (a request extension, set by [`Auth::user`]'s middleware).
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct User(pub String);
52
53/// A value read from a file, and read again when the file changes: the file is looked at at
54/// most every [`RECHECK`] (its modification time and length), and read again when they
55/// changed. A file that can't be read or doesn't parse leaves the value as it was (logged as an
56/// error: a mistake in the deployment), and is tried again at the next look. Or a fixed value.
57#[derive(Debug)]
58pub struct Followed<T> {
59    file: Option<FollowedFile<T>>,
60    /// The value, and how many times it was read again.
61    current: RwLock<(Arc<T>, u64)>,
62}
63
64#[derive(Debug)]
65struct FollowedFile<T> {
66    path: PathBuf,
67    /// What it holds, for the logs (`users`, `the UI's token`).
68    what: &'static str,
69    parse: fn(&str) -> Result<T, String>,
70    /// How often it is looked at, at most.
71    recheck: std::time::Duration,
72    /// When it was last looked at, and how it was when last read.
73    looked: Mutex<(Instant, Option<Stamp>)>,
74}
75
76/// How often a followed file is looked at for a change, at most.
77pub const RECHECK: std::time::Duration = std::time::Duration::from_secs(5);
78
79/// What tells a file changed: its modification time and length.
80type 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    /// A value that doesn't change.
96    pub fn fixed(value: T) -> Self {
97        Self {
98            file: None,
99            current: RwLock::new((Arc::new(value), 0)),
100        }
101    }
102
103    /// The value `parse` makes of the file at `path` (`what` it holds, for the logs), followed.
104    ///
105    /// # Errors
106    ///
107    /// Why it can't be read or doesn't parse (the path named).
108    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    /// The value as last read, and how many times it was read again (after reading the file
130    /// again if it changed).
131    pub fn current(&self) -> (Arc<T>, u64) {
132        self.follow();
133        let current = read(&self.current);
134        (Arc::clone(&current.0), current.1)
135    }
136
137    /// Reads the file again if it changed since it was last read, at most every [`RECHECK`].
138    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            // Others don't look meanwhile.
149            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                // Only once read: a failed read is tried again at the next look.
167                lock(&file.looked).1 = now_stamp;
168                tracing::info!("{path} changed: {} read again", file.what);
169            }
170            // A deployment's mistake, not a way to change anything (an empty users file is).
171            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
184/// The token a UI presents (`[webserver] ui_token_file`, `[[ui.deployments]] token_file`),
185/// followed: a new token takes effect without a restart.
186pub type UiToken = Arc<Followed<String>>;
187
188/// The shortest token taken.
189pub const MIN_UI_TOKEN: usize = 16;
190
191/// The UI's token in the file at `path`, followed (its text, trimmed).
192///
193/// # Errors
194///
195/// Why it can't be read, or a token shorter than [`MIN_UI_TOKEN`].
196pub 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/// Users of `basic` mode: names and their bcrypt hashes.
210///
211/// bcrypt is slow on purpose (about 0.1-0.3 s a check), and without sessions (24A) every
212/// request carries the credentials: a check that passed is remembered for [`REMEMBERED`]
213/// (live pages make several requests a second), by a keyed hash of the name and password
214/// (its key random for each process: never the password itself). A failed check isn't
215/// remembered, so guessing pays the full price each time.
216///
217/// Read from a file, the users follow it ([`Followed`]): a password changed or a user removed
218/// takes effect, what was remembered forgotten; an empty file signs no one in.
219#[derive(Debug, Clone, Default)]
220pub struct Users {
221    loaded: Arc<Followed<Loaded>>,
222    passed: Arc<Mutex<Passed>>,
223    timings: AuthTimings,
224}
225
226/// How the users and the UI's token are followed.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub struct AuthTimings {
229    /// How often their files are looked at, at most (`auth_recheck`): what a change takes to
230    /// count.
231    pub recheck: std::time::Duration,
232    /// How long a check that passed is remembered (`auth_remembered`). A change of the users
233    /// forgets them all.
234    pub remembered: std::time::Duration,
235    /// How many are remembered at once, the oldest dropped first (`auth_remembered_max`).
236    pub remembered_max: usize,
237}
238
239impl Default for AuthTimings {
240    /// [`RECHECK`], [`REMEMBERED`] and `MAX_REMEMBERED`.
241    fn default() -> Self {
242        Self {
243            recheck: RECHECK,
244            remembered: REMEMBERED,
245            remembered_max: MAX_REMEMBERED,
246        }
247    }
248}
249
250/// How long a check that passed is remembered.
251pub const REMEMBERED: std::time::Duration = std::time::Duration::from_mins(5);
252
253/// At most this many remembered at once (the oldest go first).
254const MAX_REMEMBERED: usize = 1_000;
255
256/// The users as read.
257#[derive(Debug, Default)]
258struct Loaded {
259    hashes: HashMap<String, String>,
260    /// A real hash at the file's highest cost, verified for an unknown name, so the time taken
261    /// doesn't tell which names exist (a malformed one would be refused at once).
262    dummy: String,
263}
264
265/// Checks that passed: the credentials' keyed hash, and until when.
266#[derive(Debug, Default)]
267struct Passed {
268    key: std::collections::hash_map::RandomState,
269    until: HashMap<u64, Instant>,
270    /// The users' read these are of: once read again, forgotten.
271    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    /// Forgets what was remembered of an earlier read of the users.
281    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    /// The same users (what was remembered aside).
292    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
310/// The users of a text of `name:hash` lines.
311fn 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
335/// Whether `hash` is a whole bcrypt hash: its version and cost, then 53 characters of
336/// bcrypt's base64 (the 22 of its salt, the 31 of its hash). One cut short or altered would
337/// be read, and no password would match it (B135: a users file reloaded with one replaced
338/// the working users).
339fn 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
349/// A bcrypt hash's cost (`$2b$12$...`: 12; bcrypt takes 4 to 31), if it is one.
350fn 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        // No users: no name to tell apart, every check refused at once.
361        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    /// The users of a text of `name:hash` lines (blank lines and `#` comments skipped).
373    ///
374    /// # Errors
375    ///
376    /// Why the text doesn't read: a line without a name or a hash, a hash bcrypt doesn't know,
377    /// a name twice.
378    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    /// The users of the file at `path`, following it (see [`Users`]).
386    ///
387    /// # Errors
388    ///
389    /// Why it can't be read or doesn't read.
390    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    /// Whether `password` is `name`'s (a check that passed within [`REMEMBERED`] isn't run
404    /// again). The bcrypt check runs on the blocking pool (B134): about a second of CPU at
405    /// cost 12, it would otherwise hold a runtime worker, and a few at once every worker.
406    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        // An unknown name is checked against the dummy hash all the same: as slow as a known
419        // one, so the time doesn't tell which names exist.
420        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            // Read again while this was checked: not remembered.
433            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    /// How many there are.
452    #[must_use]
453    pub fn len(&self) -> usize {
454        self.loaded.current().0.hashes.len()
455    }
456
457    /// Whether there are none.
458    #[must_use]
459    pub fn is_empty(&self) -> bool {
460        self.len() == 0
461    }
462}
463
464/// How a role tells who the user is.
465#[derive(Debug, Clone)]
466pub struct Auth {
467    mode: AuthMode,
468    /// `none`: the header recorded if present; `proxy_header`: the required one.
469    identity_header: Option<HeaderName>,
470    users: Users,
471    /// The token a UI may present (`[webserver] ui_token_file`'s).
472    ui_token: Option<UiToken>,
473}
474
475impl Default for Auth {
476    /// `none`, no identity header, no UI token.
477    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/// Why a request is refused.
488#[derive(Debug, Clone, PartialEq, Eq)]
489pub enum Refused {
490    /// `proxy_header`: the proxy's header is missing (the request didn't come through it).
491    NoProxyHeader(String),
492    /// `basic`: no credentials, or wrong ones.
493    Credentials,
494}
495
496impl Auth {
497    /// The rules of `section`, a UI trusted by `ui_token` (empty: none), the users read from
498    /// `section.users_file` in `basic` mode.
499    ///
500    /// # Errors
501    ///
502    /// Why they can't be used: `basic` without a readable users file, or with no users; a
503    /// header name that isn't one.
504    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    /// `none` mode naming the user by `identity_header` if given (what a webserver did before
540    /// M3.5).
541    ///
542    /// # Panics
543    ///
544    /// If `identity_header` isn't a header name.
545    #[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    /// The same rules without the UI's token: for standalone's own pages, which a token
555    /// mustn't open without the person's sign-in.
556    #[must_use]
557    pub fn without_ui_token(&self) -> Self {
558        Self {
559            ui_token: None,
560            ..self.clone()
561        }
562    }
563
564    /// The mode.
565    #[must_use]
566    pub const fn mode(&self) -> AuthMode {
567        self.mode
568    }
569
570    /// Who a request with `headers` (and `proven`: arrived as `schedr ui`'s) is from, or why
571    /// it is refused.
572    ///
573    /// # Errors
574    ///
575    /// [`Refused`] in `proxy_header` and `basic` modes.
576    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    /// Whether the request presents the UI's token (compared in constant time).
611    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        // An empty token proves nothing.
617        !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    /// The answer to a refused request: 401, a Basic challenge in `basic` mode; its body
623    /// `body(message)`.
624    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/// The user name and password of an `Authorization: Basic` header.
645#[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
660/// A header's value when it is there once (sent twice, say a client's and a proxy's after it,
661/// neither is taken).
662fn 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
671/// Whether `given` is `expected`, in time depending only on `expected`'s length (every byte of
672/// it compared, whatever `given`'s length).
673fn 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/// Whether a browser says a request comes from the page's own origin: `Sec-Fetch-Site`
682/// (`same-origin`, or `none`: typed by the user), else an `Origin` whose host is the request's
683/// (`X-Forwarded-Host` behind a proxy; default ports aside). `None` when neither header is
684/// there: not a browser's request (a CLI, `schedr ui`), or an old browser's GET.
685#[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
709/// The webserver's middleware refusing (403) a write a browser sends from another site: a
710/// browser attaches Basic credentials it remembers, or a proxy's cookie, to any site's form,
711/// so a page elsewhere could act as the person signed in. Requests no browser header marks
712/// (the CLI, `schedr ui`) pass.
713pub 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
726/// Only printable characters (no control characters to forge a log line or a cell).
727fn printable(text: &str) -> bool {
728    !text.chars().any(char::is_control)
729}
730
731/// Whether a request for `path` is open to anyone: the API's description and Swagger UI
732/// (they show what the API is, nothing of its data; decision 2.11a).
733#[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
738/// The webserver's middleware: the request's [`User`] set, or a 401.
739pub 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}