glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! HTTP Basic authentication, as Rails' `http_basic_authenticate_with`:
//! one name and password for a staging site, an admin area or a metrics
//! endpoint.
//!
//! ```ignore
//! // `[ops] username = "ops"` in the config, and the password in
//! // `ops.password` or `OPS_PASSWORD`.
//! pipeline ops = Pipeline.new().with(BasicAuth.from_config("ops"))
//! ```
//!
//! In a pipeline (`Pipeline::new().with(BasicAuth::new(…))`) it covers only
//! that pipeline's routes.

use base64::Engine;
use base64::engine::general_purpose::STANDARD;

use crate::context::Context;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::Response;

/// See the [module docs](self).
pub struct BasicAuth {
    name: String,
    password: String,
    realm: String,
}

impl BasicAuth {
    /// Lets through requests with this name and password, and answers
    /// others `401 Unauthorized`, which makes a browser ask for them.
    ///
    /// # Panics
    ///
    /// If the password is empty: that would let anyone in.
    pub fn new(name: impl Into<String>, password: impl Into<String>) -> Self {
        let password = password.into();
        assert!(!password.is_empty(), "BasicAuth needs a password");
        Self {
            name: name.into(),
            password,
            realm: "Application".to_owned(),
        }
    }

    /// The name and password from the config's `[section]`: `username`
    /// (the section's name unless set) and `password`, or the
    /// `<SECTION>_PASSWORD` environment variable (`OPS_PASSWORD`), as
    /// `Config::secret` reads secrets. With no password set, every
    /// request is refused (and an error logged): never open by mistake.
    pub fn from_config(section: &str) -> Self {
        let config = crate::config::Config::current().ok();
        let name = config
            .as_ref()
            .and_then(|c| {
                c.get_opt::<String>(&format!("{section}.username"))
                    .ok()
                    .flatten()
            })
            .unwrap_or_else(|| section.to_owned());
        let env_var = format!("{}_PASSWORD", section.to_ascii_uppercase());
        let password = config
            .as_ref()
            .and_then(|c| {
                c.secret(&format!("{section}.password"), &env_var)
                    .ok()
                    .flatten()
            })
            .unwrap_or_default();
        if password.is_empty() {
            tracing::error!(
                section,
                "BasicAuth has no password ({section}.password or {env_var}); refusing every request"
            );
        }
        Self {
            name,
            password,
            realm: "Application".to_owned(),
        }
    }

    /// The name the browser shows when it asks (`"Application"` unless
    /// set).
    #[must_use]
    pub fn realm(mut self, realm: impl Into<String>) -> Self {
        self.realm = realm.into().replace('"', "");
        self
    }

    /// Whether an `Authorization` header gives this name and password.
    fn allows(&self, header: Option<&str>) -> bool {
        if self.password.is_empty() {
            return false;
        }
        let Some(encoded) = header.and_then(|h| {
            h.strip_prefix("Basic ")
                .or_else(|| h.strip_prefix("basic "))
        }) else {
            return false;
        };
        let Ok(decoded) = STANDARD.decode(encoded.trim()) else {
            return false;
        };
        let Ok(decoded) = String::from_utf8(decoded) else {
            return false;
        };
        let Some((name, password)) = decoded.split_once(':') else {
            return false;
        };
        // Both compared in full, so the time taken says nothing.
        let name_ok = constant_time_eq(name.as_bytes(), self.name.as_bytes());
        let password_ok = constant_time_eq(password.as_bytes(), self.password.as_bytes());
        name_ok & password_ok
    }
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

impl Middleware for BasicAuth {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        if self.allows(ctx.header(http::header::AUTHORIZATION)) {
            return Box::pin(next.run(ctx));
        }
        let challenge = format!("Basic realm=\"{}\", charset=\"UTF-8\"", self.realm);
        Box::pin(async move {
            Response::text("HTTP Basic: Access denied.\n")
                .with_status(http::StatusCode::UNAUTHORIZED)
                .with_header(http::header::WWW_AUTHENTICATE, challenge)
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn header(credentials: &str) -> String {
        format!("Basic {}", STANDARD.encode(credentials))
    }

    #[test]
    fn checks_the_name_and_password() {
        let auth = BasicAuth::new("admin", "s3cret");
        assert!(auth.allows(Some(&header("admin:s3cret"))));
        assert!(!auth.allows(Some(&header("admin:wrong"))));
        assert!(!auth.allows(Some(&header("someone:s3cret"))));
        assert!(!auth.allows(Some("Basic not-base64!")));
        assert!(!auth.allows(Some("Bearer abc")));
        assert!(!auth.allows(None));
        // A password may have a colon in it.
        assert!(BasicAuth::new("a", "b:c").allows(Some(&header("a:b:c"))));
    }
}