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