aria2-protocol 0.3.10

Multi-protocol networking stack for aria2-rust: HTTP/HTTPS client, FTP/SFTP, full BitTorrent (DHT/PEX/MSE), and Metalink V3/V4 parser
Documentation
use base64::{Engine as _, engine::general_purpose::STANDARD};

/// Authentication scheme token parsed from a `WWW-Authenticate` or
/// `Proxy-Authenticate` challenge.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChallengeScheme {
    Basic,
    Digest,
    Negotiate,
    Ntlm,
}

impl ChallengeScheme {
    /// Parse a challenge's leading authentication scheme token.
    pub fn from_header(value: &str) -> Option<Self> {
        let scheme = value.split_ascii_whitespace().next()?;
        if scheme.eq_ignore_ascii_case("basic") {
            Some(Self::Basic)
        } else if scheme.eq_ignore_ascii_case("digest") {
            Some(Self::Digest)
        } else if scheme.eq_ignore_ascii_case("negotiate") {
            Some(Self::Negotiate)
        } else if scheme.eq_ignore_ascii_case("ntlm") {
            Some(Self::Ntlm)
        } else {
            None
        }
    }
}

/// Build the HTTP Basic authentication field value for a credential pair.
pub fn basic_authorization(username: &str, password: &str) -> String {
    let credentials = format!("{username}:{password}");
    format!("Basic {}", STANDARD.encode(credentials))
}

/// Build the HTTP Bearer authentication field value.
pub fn bearer_authorization(token: &str) -> String {
    format!("Bearer {token}")
}

/// Select and build a proxy authorization value from one or more challenge
/// fields. Digest is preferred, Basic is accepted next, and unknown schemes
/// fall back to Basic when a challenge field is present.
pub fn proxy_authorization(
    challenge_values: &[&str],
    username: &str,
    password: &str,
    method: &str,
    uri: &str,
    nonce_count: u32,
) -> Option<String> {
    for value in challenge_values {
        if value
            .split_ascii_whitespace()
            .next()
            .is_some_and(|scheme| scheme.eq_ignore_ascii_case("Digest"))
            && let Ok(challenge) = crate::http::digest::DigestChallenge::parse(value)
        {
            return Some(
                crate::http::digest::DigestResponse::compute(
                    username,
                    password,
                    method,
                    uri,
                    &challenge,
                    nonce_count,
                )
                .to_header_value(),
            );
        }
    }

    for value in challenge_values {
        if value
            .split_ascii_whitespace()
            .next()
            .is_some_and(|scheme| scheme.eq_ignore_ascii_case("Basic"))
        {
            return Some(basic_authorization(username, password));
        }
    }

    (!challenge_values.is_empty()).then(|| basic_authorization(username, password))
}

#[derive(Debug, Clone)]
pub enum AuthScheme {
    Basic,
    Digest,
}

#[derive(Clone)]
pub struct AuthCredentials {
    pub username: String,
    pub password: String,
    pub scheme: AuthScheme,
}

impl std::fmt::Debug for AuthCredentials {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("AuthCredentials")
            .field("username", &"<redacted>")
            .field("password", &"<redacted>")
            .field("scheme", &self.scheme)
            .finish()
    }
}

impl AuthCredentials {
    pub fn new_basic(username: &str, password: &str) -> Self {
        Self {
            username: username.to_string(),
            password: password.to_string(),
            scheme: AuthScheme::Basic,
        }
    }

    pub fn new_digest(username: &str, password: &str) -> Self {
        Self {
            username: username.to_string(),
            password: password.to_string(),
            scheme: AuthScheme::Digest,
        }
    }

    pub fn basic_auth_header(&self) -> String {
        basic_authorization(&self.username, &self.password)
    }
}

pub struct HttpAuth;

impl HttpAuth {
    pub fn apply_auth(
        request: crate::http::request::HttpRequest,
        credentials: &AuthCredentials,
    ) -> crate::http::request::HttpRequest {
        match credentials.scheme {
            AuthScheme::Basic => {
                request.with_header("Authorization", &credentials.basic_auth_header())
            }
            AuthScheme::Digest => request,
        }
    }

    pub fn parse_www_authenticate(header_value: &str) -> Option<AuthChallenge> {
        match ChallengeScheme::from_header(header_value)? {
            ChallengeScheme::Basic => Some(AuthChallenge::Basic),
            ChallengeScheme::Digest => {
                let challenge = crate::http::digest::DigestChallenge::parse(header_value).ok()?;
                Some(AuthChallenge::Digest(DigestChallenge {
                    realm: challenge.realm,
                    nonce: challenge.nonce,
                    qop: challenge.qop.unwrap_or_default(),
                    algorithm: challenge.algorithm,
                    opaque: challenge.opaque.unwrap_or_default(),
                    stale: challenge.stale,
                }))
            }
            ChallengeScheme::Negotiate | ChallengeScheme::Ntlm => None,
        }
    }

    pub fn build_digest_response(
        challenge: &DigestChallenge,
        credentials: &AuthCredentials,
        method: &str,
        uri: &str,
        nc: u32,
        cnonce: &str,
    ) -> String {
        let protocol_challenge = crate::http::digest::DigestChallenge {
            realm: challenge.realm.clone(),
            nonce: challenge.nonce.clone(),
            qop: (!challenge.qop.is_empty()).then(|| challenge.qop.clone()),
            algorithm: challenge.algorithm.clone(),
            opaque: (!challenge.opaque.is_empty()).then(|| challenge.opaque.clone()),
            stale: challenge.stale,
        };
        crate::http::digest::DigestResponse::compute_with_cnonce(
            &credentials.username,
            &credentials.password,
            method,
            uri,
            &protocol_challenge,
            nc,
            cnonce,
        )
        .to_header_value()
    }
}

#[derive(Debug, Clone)]
pub enum AuthChallenge {
    Basic,
    Digest(DigestChallenge),
}

#[derive(Clone)]
pub struct DigestChallenge {
    pub realm: String,
    pub nonce: String,
    pub qop: String,
    pub algorithm: String,
    pub opaque: String,
    pub stale: bool,
}

impl std::fmt::Debug for DigestChallenge {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("DigestChallenge")
            .field("realm", &self.realm)
            .field("nonce", &"<redacted>")
            .field("qop", &self.qop)
            .field("algorithm", &self.algorithm)
            .field("opaque", &(!self.opaque.is_empty()).then_some("<redacted>"))
            .field("stale", &self.stale)
            .finish()
    }
}

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

    #[test]
    fn test_basic_auth_header() {
        let creds = AuthCredentials::new_basic("admin", "secret123");
        let header = creds.basic_auth_header();
        assert!(header.starts_with("Basic "));
        assert!(!header.contains("admin"));
        assert!(!header.contains("secret123"));
        assert_eq!(bearer_authorization("token"), "Bearer token");
    }

    #[test]
    fn credential_debug_output_redacts_username_and_password() {
        let credentials = AuthCredentials::new_basic("debug-user", "debug-secret");
        let formatted = format!("{credentials:?}");

        assert!(formatted.contains("<redacted>"));
        assert!(!formatted.contains("debug-user"));
        assert!(!formatted.contains("debug-secret"));
    }

    #[test]
    fn parsed_digest_challenge_debug_redacts_nonce_and_opaque_values() {
        let challenge = HttpAuth::parse_www_authenticate(
            "Digest realm=example, nonce=private-nonce, qop=auth, opaque=private-opaque",
        )
        .unwrap();
        let formatted = format!("{challenge:?}");

        assert!(!formatted.contains("private-nonce"));
        assert!(!formatted.contains("private-opaque"));
        assert!(formatted.contains("<redacted>"));
    }

    #[test]
    fn proxy_authorization_prefers_digest_then_basic_and_preserves_fallback() {
        let challenges = [
            "Basic realm=\"proxy\"",
            "Digest realm=\"proxy\", nonce=\"n1\", qop=\"auth\"",
        ];
        let digest = proxy_authorization(&challenges, "u", "p", "GET", "/file", 2).unwrap();
        assert!(digest.starts_with("Digest "));
        assert!(digest.contains("nc=00000002"));

        let basic = proxy_authorization(&challenges[..1], "u", "p", "GET", "/file", 1).unwrap();
        assert_eq!(basic, "Basic dTpw");
        let fallback = proxy_authorization(&["NTLM"], "u", "p", "GET", "/file", 1).unwrap();
        assert_eq!(fallback, "Basic dTpw");
        assert!(proxy_authorization(&[], "u", "p", "GET", "/file", 1).is_none());
    }

    #[test]
    fn test_parse_basic_challenge() {
        let result = HttpAuth::parse_www_authenticate("Basic");
        assert!(matches!(result, Some(AuthChallenge::Basic)));
        assert!(matches!(
            HttpAuth::parse_www_authenticate("bAsIc realm=\"proxy\""),
            Some(AuthChallenge::Basic)
        ));
    }

    #[test]
    fn parses_supported_authentication_scheme_tokens() {
        assert_eq!(
            ChallengeScheme::from_header("Basic realm=\"test\""),
            Some(ChallengeScheme::Basic)
        );
        assert_eq!(
            ChallengeScheme::from_header("dIgEsT nonce=abc"),
            Some(ChallengeScheme::Digest)
        );
        assert_eq!(
            ChallengeScheme::from_header("Negotiate token"),
            Some(ChallengeScheme::Negotiate)
        );
        assert_eq!(
            ChallengeScheme::from_header("NTLM token"),
            Some(ChallengeScheme::Ntlm)
        );
        assert_eq!(ChallengeScheme::from_header("Unknown token"), None);
        assert_eq!(ChallengeScheme::from_header(""), None);
    }

    #[test]
    fn test_parse_digest_challenge() {
        let header = r#"Digest realm="testrealm@host.com", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", qop="auth", algorithm=MD5"#;
        let result = HttpAuth::parse_www_authenticate(header);
        assert!(matches!(result, Some(AuthChallenge::Digest(_))));
        if let Some(AuthChallenge::Digest(d)) = result {
            assert_eq!(d.realm, "testrealm@host.com");
            assert_eq!(d.nonce, "dcd98b7102dd2f0e8b11d0f600bfb0c093");
            assert_eq!(d.qop, "auth");
        }
    }

    #[test]
    fn parses_digest_challenges_with_quoted_commas_and_supported_algorithms() {
        let result = HttpAuth::parse_www_authenticate(
            r#"dIgEsT realm="private, proxy", nonce="n1", qop="auth-int", algorithm=SHA-256-sess"#,
        );
        let Some(AuthChallenge::Digest(challenge)) = result else {
            panic!("expected parsed Digest challenge");
        };
        assert_eq!(challenge.realm, "private, proxy");
        assert_eq!(challenge.qop, "auth-int");
        assert_eq!(challenge.algorithm, "SHA-256-sess");
    }

    #[test]
    fn test_build_digest_response() {
        let challenge = DigestChallenge {
            realm: "testrealm".to_string(),
            nonce: "abcdef123456".to_string(),
            qop: "auth".to_string(),
            algorithm: "MD5".to_string(),
            opaque: "".to_string(),
            stale: false,
        };
        let creds = AuthCredentials::new_digest("user", "pass");
        let response =
            HttpAuth::build_digest_response(&challenge, &creds, "GET", "/path", 1, "abc");
        assert!(response.starts_with("Digest "));
        assert!(response.contains("username=\"user\""));
        assert!(response.contains("realm=\"testrealm\""));
    }

    #[test]
    fn computes_digest_with_explicit_cnonce_through_shared_protocol_engine() {
        let challenge = DigestChallenge {
            realm: "private, proxy".to_owned(),
            nonce: "n1".to_owned(),
            qop: "auth-int".to_owned(),
            algorithm: "SHA-256-sess".to_owned(),
            opaque: "opaque".to_owned(),
            stale: false,
        };
        let credentials = AuthCredentials::new_digest("user", "pass");
        let response = HttpAuth::build_digest_response(
            &challenge,
            &credentials,
            "CONNECT",
            "ftp.example.test:21",
            1,
            "fixed-cnonce",
        );
        assert!(response.contains("realm=\"private, proxy\""));
        assert!(response.contains("qop=auth-int"));
        assert!(response.contains("algorithm=SHA-256-sess"));
        assert!(response.contains("cnonce=\"fixed-cnonce\""));
        assert!(response.contains("opaque=\"opaque\""));
        let digest = response
            .split("response=\"")
            .nth(1)
            .and_then(|tail| tail.split('"').next())
            .expect("response hash is emitted");
        assert_eq!(digest.len(), 64);
    }
}