Skip to main content

mildly_basic_auth/
config.rs

1//! Startup configuration, validated once from the environment.
2//!
3//! `Config` is only constructible when every value is valid, so the rest
4//! of the program never has to defend against a half-configured state.
5
6use std::collections::HashSet;
7use std::error::Error;
8use std::ffi::OsString;
9use std::fmt;
10use std::net::SocketAddr;
11use std::path::PathBuf;
12
13use axum::body::Bytes;
14use axum::http::Uri;
15use blake3::Hash;
16
17/// Embedded password-page template. Compiled into the binary so rendering
18/// has no runtime asset dependency.
19const WALL_TEMPLATE: &str = include_str!("template.html");
20/// Default IP socket address the service listens on.
21const DEFAULT_BIND_ADDRESS: &str = "0.0.0.0:8000";
22/// Environment variable holding the IP socket address to listen on.
23const ENV_ADDRESS: &str = "MBA_ADDRESS";
24/// Environment variable holding a plain password. At least one of the
25/// `MBA_PASSWORD*` family (this or a `MBA_PASSWORD_<label>`) must be
26/// non-empty.
27const ENV_PASSWORD: &str = "MBA_PASSWORD";
28/// Prefix for additional password variables, e.g. `MBA_PASSWORD_BOB`. The
29/// suffix is a free-form label (typically who the password belongs to);
30/// it carries no meaning at request time. Reserved: future config must
31/// not land under `MBA_PASSWORD_*` or it would be read as a password.
32const ENV_PASSWORD_PREFIX: &str = "MBA_PASSWORD_";
33/// Environment variable holding an optional custom password-page template
34/// path. The file is read once and both login states render at startup.
35const ENV_TEMPLATE_FILE: &str = "MBA_TEMPLATE_FILE";
36/// Environment variable overriding the password page's document language.
37const ENV_TEMPLATE_PAGE_LANGUAGE: &str = "MBA_TEMPLATE_PAGE_LANGUAGE";
38/// Environment variable overriding the password page's title.
39const ENV_TEMPLATE_PAGE_TITLE: &str = "MBA_TEMPLATE_PAGE_TITLE";
40/// Environment variable overriding the password field's accessible label.
41const ENV_TEMPLATE_PASSWORD_LABEL: &str = "MBA_TEMPLATE_PASSWORD_LABEL";
42/// Environment variable overriding the password field's placeholder.
43const ENV_TEMPLATE_PASSWORD_PLACEHOLDER: &str = "MBA_TEMPLATE_PASSWORD_PLACEHOLDER";
44/// Environment variable overriding the failed-login message. In the
45/// built-in page it is announced to assistive technologies only and not
46/// shown visually (sighted users see the invalid-field icon and red
47/// border); a custom template may render `{{WRONG_PASSWORD_MESSAGE}}`
48/// wherever it likes.
49const ENV_TEMPLATE_WRONG_PASSWORD_MESSAGE: &str = "MBA_TEMPLATE_WRONG_PASSWORD_MESSAGE";
50/// Environment variable overriding the submit button's text.
51const ENV_TEMPLATE_SUBMIT_BUTTON_TEXT: &str = "MBA_TEMPLATE_SUBMIT_BUTTON_TEXT";
52/// Environment variable holding the upstream URL (required, absolute
53/// `http(s)://host[:port]`).
54const ENV_UPSTREAM: &str = "MBA_UPSTREAM";
55
56/// Immutable runtime configuration, built once at startup.
57///
58/// Cloned per request by the gate middleware (`from_fn_with_state`
59/// requires the state to be `Clone`), which is why fields stay cheap to
60/// clone (`SocketAddr` is `Copy`; `Bytes` is reference-counted; `Vec<Hash>`
61/// and `String` each clone one small heap allocation per request).
62#[derive(Clone)]
63pub struct Config {
64    /// Validated IP socket address the service listens on.
65    bind_address: SocketAddr,
66    /// BLAKE3 digests of the configured passwords. The session cookie
67    /// carries one of these as hex; a request authenticates by presenting
68    /// a cookie that matches **any** of them. `Config` stores only the
69    /// digests, not the plaintext. The cookie is not harmless: it never
70    /// contains the plaintext password, but it holds a password-equivalent
71    /// bearer token and remains sensitive (see the `Debug` redaction
72    /// below). This is not memory scrubbing — the plaintext still lives in
73    /// the process environment.
74    sessions: Vec<Hash>,
75    /// Validated absolute `http(s)://host[:port]` upstream. Stored as a
76    /// `String` (not `Uri`) because `ReverseProxy::new` takes one generic
77    /// `S: Into<String>` for both arguments; a `&Uri` would not satisfy
78    /// that bound.
79    upstream: String,
80    /// Password page rendered once at startup without a login error.
81    /// `Bytes` keeps per-response and per-state clones cheap despite the
82    /// page's size.
83    wall: Bytes,
84    /// The same password-page template rendered with a failed-login error.
85    wrong_password_wall: Bytes,
86}
87
88impl Config {
89    /// Build from the process environment. Delegates to the same pure
90    /// validation as [`Config::from_values`] so tests do not have to
91    /// mutate process-wide env (which is `unsafe` in Rust 2024).
92    ///
93    /// # Errors
94    ///
95    /// Returns [`ConfigError`] if `MBA_ADDRESS` is not a valid non-zero
96    /// IP socket address, no `MBA_PASSWORD*` variable has a non-empty
97    /// UTF-8 value, two of them share the same value, a custom template
98    /// file is unusable, a template-text override is not valid Unicode,
99    /// or `MBA_UPSTREAM` is not a valid absolute HTTP(S) URL.
100    pub fn from_env() -> Result<Self, ConfigError> {
101        let address = match std::env::var(ENV_ADDRESS) {
102            Ok(address) => address,
103            Err(std::env::VarError::NotPresent) => DEFAULT_BIND_ADDRESS.to_string(),
104            Err(std::env::VarError::NotUnicode(address)) => {
105                return Err(ConfigError::InvalidAddress {
106                    value: address.to_string_lossy().into_owned(),
107                    reason: "not valid Unicode",
108                });
109            }
110        };
111        let passwords = passwords_from_env(std::env::vars_os());
112        let passwords: Vec<&str> = passwords.iter().map(String::as_str).collect();
113        let custom_template = load_custom_template(std::env::var_os(ENV_TEMPLATE_FILE))?;
114        let template = custom_template.as_deref().unwrap_or(WALL_TEMPLATE);
115        let template_text = TemplateText::from_env(std::env::vars_os())?;
116        let upstream = std::env::var(ENV_UPSTREAM).unwrap_or_default();
117        Self::from_passwords_address_template_and_text(
118            &passwords,
119            &upstream,
120            &address,
121            template,
122            &template_text,
123        )
124    }
125
126    /// Build and validate from explicit values (pure, env-free).
127    ///
128    /// # Examples
129    ///
130    /// ```
131    /// # use mildly_basic_auth::Config;
132    /// assert!(Config::from_values("hunter2", "http://app:2001").is_ok());
133    /// assert!(Config::from_values("", "http://app:2001").is_err()); // No password.
134    /// assert!(Config::from_values("hunter2", "/relative").is_err()); // No host.
135    /// ```
136    ///
137    /// # Errors
138    ///
139    /// Returns [`ConfigError::MissingPassword`] for an empty password, or
140    /// [`ConfigError::MissingUpstream`] / [`ConfigError::InvalidUpstream`]
141    /// if the upstream is not a valid absolute HTTP(S) URL. The bind
142    /// address uses the default `0.0.0.0:8000`.
143    pub fn from_values(password: &str, upstream: &str) -> Result<Self, ConfigError> {
144        Self::from_values_and_address(password, upstream, DEFAULT_BIND_ADDRESS)
145    }
146
147    /// Build and validate from several explicit passwords (pure, env-free).
148    /// Empty entries are ignored; at least one must remain, and all must be
149    /// distinct. Any of them authenticates.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// # use mildly_basic_auth::Config;
155    /// assert!(Config::from_passwords(&["alice", "bob"], "http://app:2001").is_ok());
156    /// assert!(Config::from_passwords(&[], "http://app:2001").is_err()); // No password.
157    /// assert!(Config::from_passwords(&["x", "x"], "http://app:2001").is_err()); // Duplicate.
158    /// ```
159    ///
160    /// # Errors
161    ///
162    /// Returns [`ConfigError::MissingPassword`] if no password is non-empty,
163    /// [`ConfigError::DuplicatePassword`] if two passwords share a value, or
164    /// [`ConfigError::MissingUpstream`] / [`ConfigError::InvalidUpstream`]
165    /// if the upstream is not a valid absolute HTTP(S) URL. The bind
166    /// address uses the default `0.0.0.0:8000`.
167    pub fn from_passwords(passwords: &[&str], upstream: &str) -> Result<Self, ConfigError> {
168        Self::from_passwords_and_address(passwords, upstream, DEFAULT_BIND_ADDRESS)
169    }
170
171    /// Validated IP socket address the service listens on.
172    #[must_use]
173    pub fn bind_address(&self) -> SocketAddr {
174        self.bind_address
175    }
176
177    /// Build and validate the complete runtime configuration from a single
178    /// password.
179    fn from_values_and_address(
180        password: &str,
181        upstream: &str,
182        address: &str,
183    ) -> Result<Self, ConfigError> {
184        Self::from_passwords_and_address(&[password], upstream, address)
185    }
186
187    /// Build and validate the complete runtime configuration.
188    fn from_passwords_and_address(
189        passwords: &[&str],
190        upstream: &str,
191        address: &str,
192    ) -> Result<Self, ConfigError> {
193        Self::from_passwords_address_template_and_text(
194            passwords,
195            upstream,
196            address,
197            WALL_TEMPLATE,
198            &TemplateText::default(),
199        )
200    }
201
202    /// Build and validate the complete runtime configuration with an
203    /// explicit password-page template and text.
204    fn from_passwords_address_template_and_text(
205        passwords: &[&str],
206        upstream: &str,
207        address: &str,
208        template: &str,
209        template_text: &TemplateText,
210    ) -> Result<Self, ConfigError> {
211        // Keep non-empty values (drop unset/blank vars).
212        let passwords: Vec<&str> = passwords
213            .iter()
214            .copied()
215            .filter(|p| !p.is_empty())
216            .collect();
217        if passwords.is_empty() {
218            return Err(ConfigError::MissingPassword);
219        }
220        // Reject duplicates: two variables sharing a value hash to the same
221        // digest, so removing one would not revoke the other — breaking
222        // independent revocation. Startup-time over operator input, so a
223        // `HashSet` compare (not constant-time) is fine; this is not the
224        // request path.
225        let unique: HashSet<&str> = passwords.iter().copied().collect();
226        if unique.len() != passwords.len() {
227            return Err(ConfigError::DuplicatePassword);
228        }
229        // Only the digests are retained in `Config`; the plaintext stays
230        // with the caller and the process environment (not scrubbed here).
231        let sessions: Vec<Hash> = passwords
232            .iter()
233            .map(|p| blake3::hash(p.as_bytes()))
234            .collect();
235        let upstream = validate_upstream(upstream)?;
236        let address = validate_address(address)?;
237        let wall = render_template(template, template_text, false);
238        let wrong_password_wall = render_template(template, template_text, true);
239        Ok(Self {
240            bind_address: address,
241            sessions,
242            upstream,
243            wall,
244            wrong_password_wall,
245        })
246    }
247
248    /// Expected session-cookie digests. A request authenticates by matching
249    /// any of them.
250    pub(crate) fn sessions(&self) -> &[Hash] {
251        &self.sessions
252    }
253
254    /// Validated upstream URL, ready for `ReverseProxy::new`.
255    pub(crate) fn upstream(&self) -> &str {
256        &self.upstream
257    }
258
259    /// Rendered password page, ready to use as an HTML response body.
260    pub(crate) fn wall(&self) -> &Bytes {
261        &self.wall
262    }
263
264    /// Rendered password page with the failed-login state visible.
265    pub(crate) fn wrong_password_wall(&self) -> &Bytes {
266        &self.wrong_password_wall
267    }
268}
269
270impl fmt::Debug for Config {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        // Never print the session digests: each is a password-equivalent
273        // bearer token, so an accidental log must not leak it.
274        f.debug_struct("Config")
275            .field("bind_address", &self.bind_address)
276            .field("sessions", &"<redacted>")
277            .field("upstream", &self.upstream)
278            .field("wall", &"<rendered HTML>")
279            .field("wrong_password_wall", &"<rendered HTML>")
280            .finish()
281    }
282}
283
284/// Text substituted into the password-page template.
285struct TemplateText {
286    page_language: String,
287    page_title: String,
288    password_label: String,
289    password_placeholder: String,
290    wrong_password_message: String,
291    submit_button_text: String,
292}
293
294impl TemplateText {
295    /// Read fixed template-text overrides from the environment. Unknown
296    /// `MBA_TEMPLATE_*` variables are deliberately ignored: the prefix is
297    /// reserved for explicit settings, including the future template file.
298    fn from_env(vars: impl Iterator<Item = (OsString, OsString)>) -> Result<Self, ConfigError> {
299        let mut text = Self::default();
300        for (name, value) in vars {
301            let Some(name) = name.to_str() else { continue };
302            let target = match name {
303                ENV_TEMPLATE_PAGE_LANGUAGE => &mut text.page_language,
304                ENV_TEMPLATE_PAGE_TITLE => &mut text.page_title,
305                ENV_TEMPLATE_PASSWORD_LABEL => &mut text.password_label,
306                ENV_TEMPLATE_PASSWORD_PLACEHOLDER => &mut text.password_placeholder,
307                ENV_TEMPLATE_WRONG_PASSWORD_MESSAGE => &mut text.wrong_password_message,
308                ENV_TEMPLATE_SUBMIT_BUTTON_TEXT => &mut text.submit_button_text,
309                _ => continue,
310            };
311            *target = value
312                .into_string()
313                .map_err(|_| ConfigError::InvalidTemplateText {
314                    variable: name.to_owned(),
315                })?;
316        }
317        Ok(text)
318    }
319}
320
321impl Default for TemplateText {
322    fn default() -> Self {
323        Self {
324            page_language: "en".to_owned(),
325            page_title: "Welcome!".to_owned(),
326            password_label: "Password".to_owned(),
327            password_placeholder: "password".to_owned(),
328            wrong_password_message: "Wrong password.".to_owned(),
329            submit_button_text: "Enter".to_owned(),
330        }
331    }
332}
333
334/// Load an explicitly configured template, returning `None` when unset.
335/// Custom files must contain non-whitespace UTF-8 so a definite
336/// misconfiguration cannot turn the login page into an empty response.
337fn load_custom_template(path: Option<OsString>) -> Result<Option<String>, ConfigError> {
338    let Some(path) = path else { return Ok(None) };
339    let path = PathBuf::from(path);
340    let invalid = |reason: String| ConfigError::InvalidTemplateFile {
341        path: path.clone(),
342        reason,
343    };
344
345    if path.as_os_str().is_empty() {
346        return Err(invalid("path must not be empty".to_owned()));
347    }
348
349    let template = std::fs::read_to_string(&path).map_err(|error| invalid(error.to_string()))?;
350    if template.trim().is_empty() {
351        return Err(invalid(
352            "template must contain non-whitespace HTML".to_owned(),
353        ));
354    }
355    Ok(Some(template))
356}
357
358/// Render known markers from one template for the requested login state,
359/// preserving unknown or absent markers. Scanning only the original
360/// template ensures marker-like text in an override is not interpreted
361/// recursively.
362fn render_template(template: &str, text: &TemplateText, wrong_password: bool) -> Bytes {
363    let mut rendered = String::with_capacity(template.len());
364    let mut remaining = template;
365    // String form of the invalid flag, for `aria-invalid`.
366    let is_password_invalid = if wrong_password { "true" } else { "false" };
367    // Focus the field only on the error wall, so the failed-login state
368    // is announced immediately after submission (see `template.html`).
369    let autofocus_attribute = if wrong_password { "autofocus" } else { "" };
370    let wrong_password_message = if wrong_password {
371        text.wrong_password_message.as_str()
372    } else {
373        ""
374    };
375
376    while let Some(marker_start) = remaining.find("{{") {
377        rendered.push_str(&remaining[..marker_start]);
378        remaining = &remaining[marker_start..];
379
380        let replacement = [
381            ("{{PAGE_LANGUAGE}}", text.page_language.as_str()),
382            ("{{PAGE_TITLE}}", text.page_title.as_str()),
383            ("{{PASSWORD_LABEL}}", text.password_label.as_str()),
384            (
385                "{{PASSWORD_PLACEHOLDER}}",
386                text.password_placeholder.as_str(),
387            ),
388            ("{{WRONG_PASSWORD_MESSAGE}}", wrong_password_message),
389            ("{{SUBMIT_BUTTON_TEXT}}", text.submit_button_text.as_str()),
390            ("{{_IS_PASSWORD_INVALID}}", is_password_invalid),
391            ("{{_PASSWORD_AUTOFOCUS_ATTRIBUTE}}", autofocus_attribute),
392        ]
393        .into_iter()
394        .find(|(marker, _)| remaining.starts_with(marker));
395
396        if let Some((marker, value)) = replacement {
397            push_html_escaped(&mut rendered, value);
398            remaining = &remaining[marker.len()..];
399        } else {
400            rendered.push_str("{{");
401            remaining = &remaining[2..];
402        }
403    }
404    rendered.push_str(remaining);
405    Bytes::from(rendered)
406}
407
408/// Append plain text escaped for HTML text and double-quoted attributes.
409fn push_html_escaped(rendered: &mut String, value: &str) {
410    for character in value.chars() {
411        match character {
412            '&' => rendered.push_str("&amp;"),
413            '<' => rendered.push_str("&lt;"),
414            '>' => rendered.push_str("&gt;"),
415            '"' => rendered.push_str("&quot;"),
416            '\'' => rendered.push_str("&#39;"),
417            _ => rendered.push(character),
418        }
419    }
420}
421
422/// Every configured password from the environment: `MBA_PASSWORD` and any
423/// name starting with `MBA_PASSWORD_`. Order is irrelevant (any match
424/// authenticates); empty values are dropped downstream. Non-Unicode names
425/// never match; non-Unicode values are skipped (a form-entered password is
426/// always UTF-8, so such a value is unusable anyway).
427///
428/// Pure over the iterator so it is testable without mutating process-wide
429/// env (which is `unsafe` in Rust 2024). `from_env` calls it with
430/// `std::env::vars_os()` — `vars_os` (not `vars`) because `vars` panics on
431/// any non-Unicode variable anywhere in the environment.
432fn passwords_from_env(vars: impl Iterator<Item = (OsString, OsString)>) -> Vec<String> {
433    vars.filter_map(|(name, value)| {
434        // Filter by name *before* touching the value, so an unrelated
435        // non-Unicode variable can never reach `into_string`.
436        let name = name.to_str()?;
437        (name == ENV_PASSWORD || name.starts_with(ENV_PASSWORD_PREFIX))
438            .then(|| value.into_string().ok())
439            .flatten()
440    })
441    .collect()
442}
443
444/// Validate `address` as a non-zero IP socket address.
445///
446/// # Examples
447///
448/// ```ignore
449/// assert!(validate_address("0.0.0.0:4630").is_ok());
450/// assert!(validate_address("[::]:4630").is_ok());
451/// assert!(validate_address("localhost:4630").is_err()); // Not an IP.
452/// assert!(validate_address("0.0.0.0:0").is_err()); // Zero port.
453/// ```
454fn validate_address(address: &str) -> Result<SocketAddr, ConfigError> {
455    let address = address.trim();
456    let invalid = |reason: &'static str| ConfigError::InvalidAddress {
457        value: address.to_string(),
458        reason,
459    };
460    let address: SocketAddr = address
461        .parse()
462        .map_err(|_| invalid("expected an IP address and port"))?;
463    if address.port() == 0 {
464        return Err(invalid("port must not be zero"));
465    }
466    Ok(address)
467}
468
469/// Validate `upstream` as an absolute `http(s)://host[:port]` URL.
470///
471/// Strictness matters: `http::Uri` parses relative refs like `/foo` or
472/// `example:8080` that carry no authority, and `axum-reverse-proxy` then
473/// `.expect()`s an authority and **panics** at request time. We reject
474/// anything that isn't an absolute HTTP(S) URL up front.
475///
476/// # Examples
477///
478/// ```ignore
479/// assert!(validate_upstream("http://app:2001").is_ok());
480/// assert!(validate_upstream("").is_err()); // Empty.
481/// assert!(validate_upstream("/foo").is_err()); // No scheme/host.
482/// assert!(validate_upstream("example:8080").is_err()); // No host.
483/// assert!(validate_upstream("ftp://host").is_err()); // Not HTTP(S).
484/// ```
485fn validate_upstream(upstream: &str) -> Result<String, ConfigError> {
486    let upstream = upstream.trim();
487    if upstream.is_empty() {
488        return Err(ConfigError::MissingUpstream);
489    }
490
491    let invalid = |reason: &'static str| ConfigError::InvalidUpstream {
492        value: upstream.to_string(),
493        reason,
494    };
495
496    let uri: Uri = upstream.parse().map_err(|_| invalid("not a valid URL"))?;
497
498    if !matches!(uri.scheme_str(), Some("http" | "https")) {
499        return Err(invalid("scheme must be http or https"));
500    }
501    let host = uri.host().unwrap_or_default();
502    // An authority can parse with an empty host (`http://:8080`), which the
503    // connector cannot use.
504    if host.is_empty() {
505        return Err(invalid("missing host"));
506    }
507    // Port 0 is never a real destination.
508    if uri.port_u16() == Some(0) {
509        return Err(invalid("invalid port"));
510    }
511    // `http::Uri` silently *drops* malformed detail: a bad port (`:abc`,
512    // `:`, `:99999`) or junk after an IPv6 literal (`[::1]junk`) all parse
513    // with that text discarded, so the connector would target the wrong
514    // place (e.g. the scheme default port). Catch it by reconstructing the
515    // canonical `host[:port]` from the parsed parts and requiring it to
516    // equal the input authority (ignoring any `userinfo@`); a mismatch is
517    // exactly the garbage that was dropped. The port is taken from
518    // `port().as_str()` (its original text), not `port_u16()`, so a valid
519    // leading-zero port like `:080` round-trips instead of collapsing to
520    // `:80` and failing the comparison.
521    let authority = uri.authority().map_or("", |a| a.as_str());
522    let host_port = authority.rsplit_once('@').map_or(authority, |(_, hp)| hp);
523    let canonical = match uri.port() {
524        Some(port) => format!("{host}:{}", port.as_str()),
525        None => host.to_string(),
526    };
527    if host_port != canonical {
528        return Err(invalid("invalid host or port"));
529    }
530
531    // Normalized form. The proxy trims any trailing slash when joining
532    // paths, so the canonical `http://host:port/` cannot produce `//`.
533    Ok(uri.to_string())
534}
535
536/// Why a `Config` could not be built. Surfaced to stderr at startup so a
537/// misconfiguration fails fast with an actionable message.
538#[derive(Debug, PartialEq, Eq)]
539pub enum ConfigError {
540    /// `MBA_ADDRESS` was not a valid non-zero IP socket address.
541    InvalidAddress { value: String, reason: &'static str },
542    /// No `MBA_PASSWORD*` variable had a non-empty UTF-8 value.
543    MissingPassword,
544    /// Two `MBA_PASSWORD*` variables shared the same value, which would
545    /// break independent revocation.
546    DuplicatePassword,
547    /// A configured template-text override was not valid Unicode.
548    InvalidTemplateText { variable: String },
549    /// `MBA_TEMPLATE_FILE` did not name a usable UTF-8 template.
550    InvalidTemplateFile { path: PathBuf, reason: String },
551    /// `MBA_UPSTREAM` was unset or empty.
552    MissingUpstream,
553    /// `MBA_UPSTREAM` was set but is not an absolute HTTP(S) URL.
554    InvalidUpstream { value: String, reason: &'static str },
555}
556
557impl fmt::Display for ConfigError {
558    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559        match self {
560            Self::InvalidAddress { value, reason } => write!(
561                f,
562                "`{ENV_ADDRESS}` is not a valid IP socket address ({reason}): {value:?}"
563            ),
564            Self::MissingPassword => write!(
565                f,
566                "at least one password variable (`{ENV_PASSWORD}` or \
567                 `{ENV_PASSWORD_PREFIX}<label>`) must have a non-empty UTF-8 value"
568            ),
569            Self::DuplicatePassword => write!(
570                f,
571                "two password variables share the same value; each password \
572                 must be distinct to be revoked independently"
573            ),
574            Self::InvalidTemplateText { variable } => {
575                write!(f, "`{variable}` must contain valid Unicode")
576            }
577            Self::InvalidTemplateFile { path, reason } => write!(
578                f,
579                "`{ENV_TEMPLATE_FILE}` is not a usable UTF-8 template ({reason}): \"{}\"",
580                path.display(),
581            ),
582            Self::MissingUpstream => write!(f, "`{ENV_UPSTREAM}` must be set"),
583            Self::InvalidUpstream { value, reason } => write!(
584                f,
585                "`{ENV_UPSTREAM}` is not a valid absolute http(s) URL \
586                 ({reason}): {value:?}"
587            ),
588        }
589    }
590}
591
592impl Error for ConfigError {}
593
594#[cfg(test)]
595mod tests {
596    use std::assert_matches;
597    use std::sync::atomic::{AtomicUsize, Ordering};
598
599    use super::*;
600
601    /// A uniquely named file removed when its test ends.
602    struct TemporaryTemplate {
603        path: PathBuf,
604    }
605
606    impl TemporaryTemplate {
607        /// Write `contents` to a new temporary template.
608        fn new(contents: &[u8]) -> Self {
609            static NEXT_FILE: AtomicUsize = AtomicUsize::new(0);
610
611            let sequence = NEXT_FILE.fetch_add(1, Ordering::Relaxed);
612            let path = std::env::temp_dir().join(format!(
613                "mildly-basic-auth-config-test-{}-{sequence}",
614                std::process::id(),
615            ));
616            std::fs::write(&path, contents).unwrap();
617            Self { path }
618        }
619    }
620
621    impl Drop for TemporaryTemplate {
622        fn drop(&mut self) {
623            _ = std::fs::remove_file(&self.path);
624        }
625    }
626
627    /// Build template text from explicit variables without mutating the
628    /// process-wide environment.
629    fn template_text_from_vars(vars: &[(&str, &str)]) -> TemplateText {
630        TemplateText::from_env(
631            vars.iter()
632                .map(|(name, value)| (OsString::from(name), OsString::from(value))),
633        )
634        .unwrap()
635    }
636
637    #[test]
638    fn valid_values_build_a_config() {
639        assert!(Config::from_values("hunter2", "http://app:2001").is_ok());
640    }
641
642    #[test]
643    fn default_template_text_renders_the_existing_page_text() {
644        let config = Config::from_values("hunter2", "http://app:2001").unwrap();
645        let wall = std::str::from_utf8(config.wall()).unwrap();
646
647        assert!(wall.contains("<html lang=\"en\">"));
648        assert!(wall.contains("<title>Welcome!</title>"));
649        assert!(wall.contains(">Password</label>"));
650        assert!(wall.contains("placeholder=\"password\""));
651        assert!(wall.contains(">Enter</button>"));
652    }
653
654    #[test]
655    fn default_wall_hides_the_wrong_password_error() {
656        let config = Config::from_values("hunter2", "http://app:2001").unwrap();
657        let wall = std::str::from_utf8(config.wall()).unwrap();
658
659        assert!(wall.contains("aria-invalid=\"false\""));
660        assert!(!wall.contains("Wrong password."));
661    }
662
663    #[test]
664    fn wrong_password_wall_shows_the_error() {
665        let config = Config::from_values("hunter2", "http://app:2001").unwrap();
666        let wall = std::str::from_utf8(config.wrong_password_wall()).unwrap();
667
668        assert!(wall.contains("aria-invalid=\"true\""));
669        assert!(wall.contains("Wrong password."));
670    }
671
672    #[test]
673    fn wrong_password_wall_autofocuses_the_field() {
674        let config = Config::from_values("hunter2", "http://app:2001").unwrap();
675        let wall = std::str::from_utf8(config.wrong_password_wall()).unwrap();
676
677        // Scope the check to the `<input>` start tag: the page also carries
678        // a marker comment that mentions `autofocus`.
679        let tag = &wall[wall.find("<input").unwrap()..];
680        let tag = &tag[..tag.find('>').unwrap()];
681        assert!(tag.contains("autofocus"));
682    }
683
684    #[test]
685    fn default_wall_does_not_autofocus() {
686        let config = Config::from_values("hunter2", "http://app:2001").unwrap();
687        let wall = std::str::from_utf8(config.wall()).unwrap();
688
689        let tag = &wall[wall.find("<input").unwrap()..];
690        let tag = &tag[..tag.find('>').unwrap()];
691        assert!(!tag.contains("autofocus"));
692    }
693
694    #[test]
695    fn built_in_wall_includes_the_alert_icon_glyph() {
696        let config = Config::from_values("hunter2", "http://app:2001").unwrap();
697        let wall = std::str::from_utf8(config.wall()).unwrap();
698
699        // The lucide `circle-alert` outline; guards against the icon being
700        // dropped. Actual visibility is verified in the browser.
701        assert!(wall.contains(r#"<circle cx="12" cy="12" r="10">"#));
702    }
703
704    #[test]
705    fn unset_template_file_has_no_override() {
706        assert_eq!(load_custom_template(None).unwrap(), None);
707    }
708
709    #[test]
710    fn custom_template_file_is_loaded() {
711        let file = TemporaryTemplate::new(b"<p>{{PAGE_TITLE}}</p>");
712
713        let template = load_custom_template(Some(file.path.clone().into_os_string())).unwrap();
714
715        assert_eq!(template.as_deref(), Some("<p>{{PAGE_TITLE}}</p>"));
716    }
717
718    #[test]
719    fn explicit_template_uses_configured_text() {
720        let text = TemplateText {
721            page_title: "Custom title".to_owned(),
722            ..TemplateText::default()
723        };
724
725        let config = Config::from_passwords_address_template_and_text(
726            &["hunter2"],
727            "http://app:2001",
728            DEFAULT_BIND_ADDRESS,
729            "<title>{{PAGE_TITLE}}</title>",
730            &text,
731        )
732        .unwrap();
733
734        assert_eq!(config.wall(), "<title>Custom title</title>");
735    }
736
737    #[test]
738    fn empty_template_file_path_is_rejected() {
739        let result = load_custom_template(Some(OsString::new()));
740
741        assert_matches!(
742            result,
743            Err(ConfigError::InvalidTemplateFile { path, reason })
744                if path == PathBuf::new() && reason == "path must not be empty"
745        );
746    }
747
748    #[test]
749    fn missing_template_file_is_rejected() {
750        let file = TemporaryTemplate::new(b"temporary");
751        let path = file.path.clone();
752        std::fs::remove_file(&path).unwrap();
753
754        let result = load_custom_template(Some(path.clone().into_os_string()));
755
756        assert_matches!(
757            result,
758            Err(ConfigError::InvalidTemplateFile { path: error_path, .. })
759                if error_path == path
760        );
761    }
762
763    #[test]
764    fn non_utf8_template_file_is_rejected() {
765        let file = TemporaryTemplate::new(&[0xff]);
766
767        let result = load_custom_template(Some(file.path.clone().into_os_string()));
768
769        assert_matches!(result, Err(ConfigError::InvalidTemplateFile { .. }));
770    }
771
772    #[test]
773    fn empty_template_file_is_rejected() {
774        let file = TemporaryTemplate::new(b"");
775
776        let result = load_custom_template(Some(file.path.clone().into_os_string()));
777
778        assert_matches!(
779            result,
780            Err(ConfigError::InvalidTemplateFile { reason, .. })
781                if reason == "template must contain non-whitespace HTML"
782        );
783    }
784
785    #[test]
786    fn whitespace_only_template_file_is_rejected() {
787        let file = TemporaryTemplate::new(b" \n\t");
788
789        let result = load_custom_template(Some(file.path.clone().into_os_string()));
790
791        assert_matches!(result, Err(ConfigError::InvalidTemplateFile { .. }));
792    }
793
794    #[test]
795    fn page_language_variable_overrides_the_default() {
796        let text = template_text_from_vars(&[(ENV_TEMPLATE_PAGE_LANGUAGE, "fr")]);
797        assert_eq!(text.page_language, "fr");
798    }
799
800    #[test]
801    fn page_title_variable_overrides_the_default() {
802        let text = template_text_from_vars(&[(ENV_TEMPLATE_PAGE_TITLE, "Mon site")]);
803        assert_eq!(text.page_title, "Mon site");
804    }
805
806    #[test]
807    fn password_label_variable_overrides_the_default() {
808        let text = template_text_from_vars(&[(ENV_TEMPLATE_PASSWORD_LABEL, "Mot de passe")]);
809        assert_eq!(text.password_label, "Mot de passe");
810    }
811
812    #[test]
813    fn password_placeholder_variable_overrides_the_default() {
814        let text = template_text_from_vars(&[(ENV_TEMPLATE_PASSWORD_PLACEHOLDER, "Secret")]);
815        assert_eq!(text.password_placeholder, "Secret");
816    }
817
818    #[test]
819    fn wrong_password_message_variable_overrides_the_default() {
820        let text = template_text_from_vars(&[(
821            ENV_TEMPLATE_WRONG_PASSWORD_MESSAGE,
822            "Mot de passe incorrect.",
823        )]);
824        assert_eq!(text.wrong_password_message, "Mot de passe incorrect.");
825    }
826
827    #[test]
828    fn submit_button_text_variable_overrides_the_default() {
829        let text = template_text_from_vars(&[(ENV_TEMPLATE_SUBMIT_BUTTON_TEXT, "Entrer")]);
830        assert_eq!(text.submit_button_text, "Entrer");
831    }
832
833    #[test]
834    fn empty_template_text_variable_overrides_the_default() {
835        let text = template_text_from_vars(&[(ENV_TEMPLATE_PAGE_TITLE, "")]);
836        assert!(text.page_title.is_empty());
837    }
838
839    #[test]
840    fn unknown_template_variable_is_ignored() {
841        let text = template_text_from_vars(&[(ENV_TEMPLATE_FILE, "/tmp/wall.html")]);
842        assert_eq!(text.page_title, "Welcome!");
843    }
844
845    #[cfg(unix)]
846    #[test]
847    fn non_unicode_template_text_is_rejected() {
848        use std::os::unix::ffi::OsStringExt;
849
850        let result = TemplateText::from_env(
851            [(
852                OsString::from(ENV_TEMPLATE_PAGE_TITLE),
853                OsString::from_vec(vec![0xff]),
854            )]
855            .into_iter(),
856        );
857
858        let Err(error) = result else {
859            panic!("non-Unicode template text was accepted");
860        };
861        assert_matches!(
862            error,
863            ConfigError::InvalidTemplateText { variable }
864                if variable == ENV_TEMPLATE_PAGE_TITLE
865        );
866    }
867
868    #[test]
869    fn template_values_are_html_escaped() {
870        let text = TemplateText {
871            page_title: "&<>\"'".to_owned(),
872            ..TemplateText::default()
873        };
874
875        let rendered = render_template("{{PAGE_TITLE}}", &text, false);
876
877        assert_eq!(rendered, "&amp;&lt;&gt;&quot;&#39;");
878    }
879
880    #[test]
881    fn wrong_password_message_is_html_escaped() {
882        let text = TemplateText {
883            wrong_password_message: "&<>\"'".to_owned(),
884            ..TemplateText::default()
885        };
886
887        let rendered = render_template("{{WRONG_PASSWORD_MESSAGE}}", &text, true);
888
889        assert_eq!(rendered, "&amp;&lt;&gt;&quot;&#39;");
890    }
891
892    #[test]
893    fn template_values_are_not_rendered_recursively() {
894        let text = TemplateText {
895            page_title: "{{SUBMIT_BUTTON_TEXT}}".to_owned(),
896            submit_button_text: "Submit".to_owned(),
897            ..TemplateText::default()
898        };
899
900        let rendered = render_template("{{PAGE_TITLE}}", &text, false);
901
902        assert_eq!(rendered, "{{SUBMIT_BUTTON_TEXT}}");
903    }
904
905    #[test]
906    fn template_without_known_markers_is_unchanged() {
907        let rendered = render_template("<p>{{UNKNOWN}}</p>", &TemplateText::default(), false);
908        assert_eq!(rendered, "<p>{{UNKNOWN}}</p>");
909    }
910
911    #[test]
912    fn renderer_leaves_an_empty_template_empty() {
913        let rendered = render_template("", &TemplateText::default(), false);
914        assert!(rendered.is_empty());
915    }
916
917    #[test]
918    fn values_use_the_default_address() {
919        let config = Config::from_values("hunter2", "http://app:2001").unwrap();
920        assert_eq!(config.bind_address(), "0.0.0.0:8000".parse().unwrap());
921    }
922
923    #[test]
924    fn custom_ipv4_address_is_accepted() {
925        let config =
926            Config::from_values_and_address("hunter2", "http://app:2001", "127.0.0.1:4630")
927                .unwrap();
928        assert_eq!(config.bind_address(), "127.0.0.1:4630".parse().unwrap());
929    }
930
931    #[test]
932    fn custom_ipv6_address_is_accepted() {
933        let config =
934            Config::from_values_and_address("hunter2", "http://app:2001", "[::1]:4630").unwrap();
935        assert_eq!(config.bind_address(), "[::1]:4630".parse().unwrap());
936    }
937
938    #[test]
939    fn surrounding_whitespace_in_address_is_trimmed() {
940        let config =
941            Config::from_values_and_address("hunter2", "http://app:2001", "  127.0.0.1:4630  ")
942                .unwrap();
943        assert_eq!(config.bind_address(), "127.0.0.1:4630".parse().unwrap());
944    }
945
946    #[test]
947    fn empty_address_is_rejected() {
948        assert_matches!(
949            Config::from_values_and_address("hunter2", "http://app:2001", ""),
950            Err(ConfigError::InvalidAddress { .. })
951        );
952    }
953
954    #[test]
955    fn hostname_address_is_rejected() {
956        assert_matches!(
957            Config::from_values_and_address("hunter2", "http://app:2001", "localhost:4630"),
958            Err(ConfigError::InvalidAddress { .. })
959        );
960    }
961
962    #[test]
963    fn address_without_port_is_rejected() {
964        assert_matches!(
965            Config::from_values_and_address("hunter2", "http://app:2001", "127.0.0.1"),
966            Err(ConfigError::InvalidAddress { .. })
967        );
968    }
969
970    #[test]
971    fn address_with_non_numeric_port_is_rejected() {
972        assert_matches!(
973            Config::from_values_and_address("hunter2", "http://app:2001", "127.0.0.1:abc"),
974            Err(ConfigError::InvalidAddress { .. })
975        );
976    }
977
978    #[test]
979    fn address_with_out_of_range_port_is_rejected() {
980        assert_matches!(
981            Config::from_values_and_address("hunter2", "http://app:2001", "127.0.0.1:99999"),
982            Err(ConfigError::InvalidAddress { .. })
983        );
984    }
985
986    #[test]
987    fn address_with_zero_port_is_rejected() {
988        assert_matches!(
989            Config::from_values_and_address("hunter2", "http://app:2001", "127.0.0.1:0"),
990            Err(ConfigError::InvalidAddress { .. })
991        );
992    }
993
994    #[test]
995    fn https_upstream_is_accepted() {
996        assert!(Config::from_values("hunter2", "https://app.example.com").is_ok());
997    }
998
999    #[test]
1000    fn empty_password_is_rejected() {
1001        assert_matches!(
1002            Config::from_values("", "http://app:2001"),
1003            Err(ConfigError::MissingPassword)
1004        );
1005    }
1006
1007    #[test]
1008    fn empty_upstream_is_rejected() {
1009        assert_matches!(
1010            Config::from_values("hunter2", ""),
1011            Err(ConfigError::MissingUpstream)
1012        );
1013    }
1014
1015    #[test]
1016    fn relative_upstream_is_rejected() {
1017        assert_matches!(
1018            Config::from_values("hunter2", "/foo"),
1019            Err(ConfigError::InvalidUpstream { .. })
1020        );
1021    }
1022
1023    #[test]
1024    fn scheme_only_upstream_without_authority_is_rejected() {
1025        assert_matches!(
1026            Config::from_values("hunter2", "example:8080"),
1027            Err(ConfigError::InvalidUpstream { .. })
1028        );
1029    }
1030
1031    #[test]
1032    fn non_http_scheme_is_rejected() {
1033        assert_matches!(
1034            Config::from_values("hunter2", "ftp://host"),
1035            Err(ConfigError::InvalidUpstream { .. })
1036        );
1037    }
1038
1039    #[test]
1040    fn empty_host_upstream_is_rejected() {
1041        assert_matches!(
1042            Config::from_values("hunter2", "http://:8080"),
1043            Err(ConfigError::InvalidUpstream { .. })
1044        );
1045    }
1046
1047    #[test]
1048    fn out_of_range_port_is_rejected() {
1049        assert_matches!(
1050            Config::from_values("hunter2", "http://host:99999"),
1051            Err(ConfigError::InvalidUpstream { .. })
1052        );
1053    }
1054
1055    #[test]
1056    fn non_numeric_port_is_rejected() {
1057        assert_matches!(
1058            Config::from_values("hunter2", "http://host:abc"),
1059            Err(ConfigError::InvalidUpstream { .. })
1060        );
1061    }
1062
1063    #[test]
1064    fn empty_port_is_rejected() {
1065        assert_matches!(
1066            Config::from_values("hunter2", "http://host:"),
1067            Err(ConfigError::InvalidUpstream { .. })
1068        );
1069    }
1070
1071    #[test]
1072    fn zero_port_is_rejected() {
1073        assert_matches!(
1074            Config::from_values("hunter2", "http://host:0"),
1075            Err(ConfigError::InvalidUpstream { .. })
1076        );
1077    }
1078
1079    #[test]
1080    fn leading_zero_port_is_accepted() {
1081        // `:080` is a valid port (80); the connector resolves it fine.
1082        assert!(Config::from_values("hunter2", "http://host:080").is_ok());
1083    }
1084
1085    #[test]
1086    fn all_zero_port_is_rejected() {
1087        // `:00` is still port 0.
1088        assert_matches!(
1089            Config::from_values("hunter2", "http://host:00"),
1090            Err(ConfigError::InvalidUpstream { .. })
1091        );
1092    }
1093
1094    #[test]
1095    fn ipv6_upstream_is_accepted() {
1096        assert!(Config::from_values("hunter2", "http://[::1]:8080").is_ok());
1097    }
1098
1099    #[test]
1100    fn ipv6_with_trailing_junk_is_rejected() {
1101        assert_matches!(
1102            Config::from_values("hunter2", "http://[::1]junk"),
1103            Err(ConfigError::InvalidUpstream { .. })
1104        );
1105    }
1106
1107    #[test]
1108    fn ipv6_junk_before_port_is_rejected() {
1109        assert_matches!(
1110            Config::from_values("hunter2", "http://[::1]junk:8080"),
1111            Err(ConfigError::InvalidUpstream { .. })
1112        );
1113    }
1114
1115    #[test]
1116    fn session_digest_matches_blake3_of_password() {
1117        let config = Config::from_values("hunter2", "http://app:2001").unwrap();
1118        assert_eq!(config.sessions(), &[blake3::hash(b"hunter2")]);
1119    }
1120
1121    #[test]
1122    fn multiple_passwords_build_one_digest_each() {
1123        let config = Config::from_passwords(&["hunter2", "swordfish"], "http://app:2001").unwrap();
1124        assert_eq!(
1125            config.sessions(),
1126            &[blake3::hash(b"hunter2"), blake3::hash(b"swordfish")]
1127        );
1128    }
1129
1130    #[test]
1131    fn empty_passwords_are_filtered_out() {
1132        let config = Config::from_passwords(&["", "hunter2", ""], "http://app:2001").unwrap();
1133        assert_eq!(config.sessions(), &[blake3::hash(b"hunter2")]);
1134    }
1135
1136    #[test]
1137    fn all_empty_passwords_are_rejected() {
1138        assert_matches!(
1139            Config::from_passwords(&["", ""], "http://app:2001"),
1140            Err(ConfigError::MissingPassword)
1141        );
1142    }
1143
1144    #[test]
1145    fn no_passwords_are_rejected() {
1146        assert_matches!(
1147            Config::from_passwords(&[], "http://app:2001"),
1148            Err(ConfigError::MissingPassword)
1149        );
1150    }
1151
1152    #[test]
1153    fn duplicate_passwords_are_rejected() {
1154        assert_matches!(
1155            Config::from_passwords(&["hunter2", "hunter2"], "http://app:2001"),
1156            Err(ConfigError::DuplicatePassword)
1157        );
1158    }
1159
1160    #[test]
1161    fn duplicate_check_ignores_filtered_empties() {
1162        // The two empties are dropped before the duplicate check, so they
1163        // are not treated as duplicates of each other.
1164        assert!(Config::from_passwords(&["a", "", ""], "http://app:2001").is_ok());
1165    }
1166
1167    #[test]
1168    fn passwords_from_env_collects_base_and_suffixed() {
1169        let vars = [
1170            ("MBA_PASSWORD", "alpha"),
1171            ("MBA_PASSWORD_BOB", "bravo"),
1172            ("MBA_ADDRESS", "0.0.0.0:8000"),
1173            ("MBA_UPSTREAM", "http://app:2001"),
1174            ("PATH", "/usr/bin"),
1175        ]
1176        .into_iter()
1177        .map(|(k, v)| (OsString::from(k), OsString::from(v)));
1178        let mut got = passwords_from_env(vars);
1179        got.sort();
1180        assert_eq!(got, ["alpha".to_string(), "bravo".to_string()]);
1181    }
1182
1183    #[test]
1184    fn passwords_from_env_keeps_empty_values_for_later_filtering() {
1185        // The scanner is not where empties are dropped; the constructor is.
1186        let vars = [("MBA_PASSWORD_BOB", "")]
1187            .into_iter()
1188            .map(|(k, v)| (OsString::from(k), OsString::from(v)));
1189        assert_eq!(passwords_from_env(vars), [String::new()]);
1190    }
1191
1192    #[cfg(unix)]
1193    #[test]
1194    fn passwords_from_env_skips_non_unicode_without_panicking() {
1195        use std::os::unix::ffi::OsStringExt;
1196
1197        // An unrelated variable with a non-Unicode *name*, and a
1198        // `MBA_PASSWORD_*` with a non-Unicode *value*: both must be skipped
1199        // (not panic), while a valid entry alongside them still collects.
1200        let vars = vec![
1201            (OsString::from_vec(vec![0xff]), OsString::from("ignored")),
1202            (
1203                OsString::from("MBA_PASSWORD_BAD"),
1204                OsString::from_vec(vec![0xff]),
1205            ),
1206            (OsString::from("MBA_PASSWORD"), OsString::from("alpha")),
1207        ]
1208        .into_iter();
1209        assert_eq!(passwords_from_env(vars), ["alpha".to_string()]);
1210    }
1211
1212    #[test]
1213    fn surrounding_whitespace_in_upstream_is_trimmed() {
1214        let config = Config::from_values("hunter2", "  http://app:2001  ").unwrap();
1215        assert_eq!(config.upstream(), "http://app:2001/");
1216    }
1217}