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