mod challenge;
mod qop;
#[cfg(test)]
mod tests;
use std::fmt;
use std::sync::atomic::{AtomicU32, Ordering};
use crate::error::{Aria2Error, Result};
pub use challenge::parse_www_authenticate;
pub struct Secret<T: zeroize::Zeroize>(pub(crate) T);
impl<T: zeroize::Zeroize> Secret<T> {
pub fn new(value: T) -> Self {
Secret(value)
}
pub fn expose_secret(&self) -> &T {
&self.0
}
}
impl<T: zeroize::Zeroize + Clone> Clone for Secret<T> {
fn clone(&self) -> Self {
Secret(self.0.clone())
}
}
impl<T: zeroize::Zeroize + fmt::Debug> fmt::Debug for Secret<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Secret(***)")
}
}
impl<T: zeroize::Zeroize> Drop for Secret<T> {
fn drop(&mut self) {
self.0.zeroize();
}
}
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum DigestAlgorithm {
#[default]
Md5,
Sha256,
Sha512_256,
}
impl fmt::Display for DigestAlgorithm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DigestAlgorithm::Md5 => write!(f, "MD5"),
DigestAlgorithm::Sha256 => write!(f, "SHA-256"),
DigestAlgorithm::Sha512_256 => write!(f, "SHA-512-256"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum AuthScheme {
Basic,
Digest { algorithm: DigestAlgorithm },
}
impl fmt::Display for AuthScheme {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AuthScheme::Basic => write!(f, "Basic"),
AuthScheme::Digest { .. } => write!(f, "Digest"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct AuthChallenge {
pub scheme: AuthScheme,
pub realm: String,
pub nonce: Option<String>,
pub opaque: Option<String>,
pub qop: Option<String>,
pub stale: bool,
}
#[async_trait::async_trait]
pub trait AuthProvider: Send + Sync {
fn scheme(&self) -> AuthScheme;
fn build_authorization_header(&self, challenge: &AuthChallenge) -> Result<String>;
}
pub struct DigestAuthProvider {
pub(crate) username: Secret<String>,
pub(crate) password: Secret<String>,
pub(crate) nc_count: AtomicU32,
pub(crate) algorithm: DigestAlgorithm,
}
impl DigestAuthProvider {
pub fn new(username: String, password: String, algorithm: Option<DigestAlgorithm>) -> Self {
DigestAuthProvider {
username: Secret::new(username),
password: Secret::new(password),
nc_count: AtomicU32::new(1),
algorithm: algorithm.unwrap_or_default(),
}
}
pub fn algorithm(&self) -> DigestAlgorithm {
self.algorithm
}
pub fn reset_nonce_counter(&self) {
self.nc_count.store(1, Ordering::SeqCst);
}
}
#[async_trait::async_trait]
impl AuthProvider for DigestAuthProvider {
fn scheme(&self) -> AuthScheme {
AuthScheme::Digest {
algorithm: self.algorithm,
}
}
fn build_authorization_header(&self, _challenge: &AuthChallenge) -> Result<String> {
Err(Aria2Error::Parse(
"Digest auth requires method and URI. Use build_authorization_header_with_method()"
.to_string(),
))
}
}