use std::sync::atomic::Ordering;
use crate::error::{Aria2Error, Result};
use super::{AuthChallenge, DigestAuthProvider};
impl DigestAuthProvider {
pub fn compute_ha1(&self, realm: &str) -> String {
let input = format!(
"{}:{}:{}",
self.username.expose_secret(),
realm,
self.password.expose_secret()
);
self.hash(input.as_bytes())
}
pub fn compute_ha2(
&self,
method: &str,
uri: &str,
qop: Option<&str>,
entity_body: Option<&[u8]>,
) -> String {
let input = if qop == Some("auth-int") {
let body_hash = self.hash(entity_body.unwrap_or_default());
format!("{}:{}:{}", method, uri, body_hash)
} else {
format!("{}:{}", method, uri)
};
self.hash(input.as_bytes())
}
pub fn compute_response(
&self,
ha1: &str,
nonce: &str,
nonce_count: &str,
cnonce: &str,
qop: Option<&str>,
ha2: &str,
) -> String {
let kd_input = match qop {
Some(q) => format!("{}:{}:{}:{}:{}", nonce, nonce_count, cnonce, q, ha2),
None => format!("{}:{}", nonce, ha2),
};
self.hash(format!("{ha1}:{kd_input}").as_bytes())
}
pub fn build_authorization_header_with_method(
&self,
challenge: &AuthChallenge,
method: &str,
uri: &str,
entity_body: Option<&[u8]>,
) -> Result<String> {
let nonce = challenge
.nonce
.as_deref()
.ok_or_else(|| Aria2Error::Parse("Missing nonce in Digest challenge".to_string()))?;
let cnonce = format!("{:016x}", rand::random::<u64>());
let nc_raw = self.nc_count.fetch_add(1, Ordering::SeqCst);
let protocol_challenge = aria2_protocol::http::digest::DigestChallenge {
realm: challenge.realm.clone(),
nonce: nonce.to_owned(),
qop: challenge.qop.clone(),
algorithm: self.algorithm.to_string(),
opaque: challenge.opaque.clone(),
stale: challenge.stale,
};
let response = aria2_protocol::http::digest::DigestResponse::compute_with_body_and_cnonce(
self.username.expose_secret(),
self.password.expose_secret(),
&protocol_challenge,
nc_raw,
&cnonce,
aria2_protocol::http::digest::DigestRequest {
method,
uri,
entity_body,
},
);
Ok(response.to_header_value())
}
pub(crate) fn hash(&self, input: &[u8]) -> String {
aria2_protocol::http::digest::hash_value(&self.algorithm.to_string(), input)
.expect("configured Digest algorithm is supported")
}
}