mod credentials;
pub mod netrc;
mod netrc_store;
pub use credentials::{AuthConfig, BasicCred};
pub use netrc_store::{NetrcEntry, NetrcStore};
use std::collections::BTreeSet;
use std::fmt;
use std::path::Path;
use tracing::{debug, info, warn};
use url::Url;
use crate::http::request::basic_auth;
pub(crate) fn request_directory(path: &str) -> &str {
match path.rfind('/') {
Some(index) => &path[..=index],
None => "/",
}
}
const FTP_DEFAULT_USER: &str = "anonymous";
const FTP_DEFAULT_PASSWD: &str = "ARIA2USER@";
pub struct AuthConfigFactory {
basic_creds: BTreeSet<BasicCred>,
netrc: Option<NetrcStore>,
}
impl fmt::Debug for AuthConfigFactory {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("AuthConfigFactory")
.field("basic_credential_count", &self.basic_creds.len())
.field("has_netrc", &self.netrc.is_some())
.finish()
}
}
#[derive(Clone, Default)]
pub struct AuthResolveOptions {
pub http_auth_challenge: bool,
pub no_netrc: bool,
pub http_user: Option<String>,
pub http_passwd: Option<String>,
pub ftp_user: Option<String>,
pub ftp_passwd: Option<String>,
pub proxy_user: Option<String>,
pub proxy_passwd: Option<String>,
}
impl fmt::Debug for AuthResolveOptions {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("AuthResolveOptions")
.field("http_auth_challenge", &self.http_auth_challenge)
.field("no_netrc", &self.no_netrc)
.field("http_user_configured", &self.http_user.is_some())
.field("http_passwd_configured", &self.http_passwd.is_some())
.field("ftp_user_configured", &self.ftp_user.is_some())
.field("ftp_passwd_configured", &self.ftp_passwd.is_some())
.field("proxy_user_configured", &self.proxy_user.is_some())
.field("proxy_passwd_configured", &self.proxy_passwd.is_some())
.finish()
}
}
impl AuthConfigFactory {
pub fn new() -> Self {
Self {
basic_creds: BTreeSet::new(),
netrc: None,
}
}
pub fn set_netrc(&mut self, netrc: NetrcStore) {
self.netrc = Some(netrc);
}
pub fn load_netrc_file(&mut self, path: &Path) -> Result<(), netrc::NetrcError> {
let parser = netrc::NetrcParser::parse_file(path)?;
self.netrc = Some(NetrcStore::from(parser));
Ok(())
}
pub fn load_netrc_str(&mut self, content: &str) -> Result<(), netrc::NetrcError> {
let parser = netrc::NetrcParser::parse(content)?;
self.netrc = Some(NetrcStore::from(parser));
Ok(())
}
pub fn resolve_proxy(&self, opts: &AuthResolveOptions) -> Option<AuthConfig> {
let user = opts.proxy_user.clone()?;
AuthConfig::new(user, opts.proxy_passwd.clone().unwrap_or_default())
}
pub fn resolve_basic_authorization(
&mut self,
url: &Url,
opts: &AuthResolveOptions,
) -> Option<String> {
self.resolve(url, url.password().is_some(), opts)
.map(|config| basic_auth(config.user(), config.password()))
}
pub fn resolve(
&mut self,
url: &Url,
has_password: bool,
opts: &AuthResolveOptions,
) -> Option<AuthConfig> {
let scheme = url.scheme();
if scheme == "http" || scheme == "https" {
self.resolve_http(url, has_password, opts)
} else if scheme == "ftp" || scheme == "sftp" {
self.resolve_ftp(url, has_password, opts)
} else {
None
}
}
fn resolve_http(
&mut self,
url: &Url,
_has_password: bool,
opts: &AuthResolveOptions,
) -> Option<AuthConfig> {
let username = url.username();
let password = url.password().unwrap_or("");
let host = url.host_str().unwrap_or("");
let port = url.port_or_known_default().unwrap_or(80);
if opts.http_auth_challenge {
if !username.is_empty() {
let path = request_directory(url.path());
self.update_basic_cred(BasicCred::new(
username.to_string(),
password.to_string(),
host.to_string(),
port,
path.to_string(),
true,
));
return AuthConfig::new(username.to_string(), password.to_string());
}
let cred = self.find_basic_cred(host, port, request_directory(url.path()));
match cred {
Some(bc) => AuthConfig::new(bc.user.clone(), bc.password.clone()),
None => None,
}
} else {
if !username.is_empty() {
return AuthConfig::new(username.to_string(), password.to_string());
}
self.resolve_http_via_chain(host, opts)
}
}
fn resolve_http_via_chain(&self, host: &str, opts: &AuthResolveOptions) -> Option<AuthConfig> {
if let Some(ref user) = opts.http_user
&& !user.is_empty()
{
debug!("Resolved HTTP auth for {} from CLI options", host);
return AuthConfig::new(user.clone(), opts.http_passwd.clone().unwrap_or_default());
}
if !opts.no_netrc
&& let Some(ref netrc) = self.netrc
&& let Some(entry) = netrc.find(host)
{
debug!("Resolved HTTP auth for {} from Netrc", host);
return AuthConfig::new(entry.login.clone(), entry.password.clone());
}
None
}
fn resolve_ftp(
&mut self,
url: &Url,
has_password: bool,
opts: &AuthResolveOptions,
) -> Option<AuthConfig> {
let username = url.username();
let host = url.host_str().unwrap_or("");
if !username.is_empty() {
if has_password {
let password = url.password().unwrap_or("");
return AuthConfig::new(username.to_string(), password.to_string());
}
if !opts.no_netrc
&& let Some(ref netrc) = self.netrc
&& let Some(entry) = netrc.find(host)
&& entry.login == username
{
return AuthConfig::new(entry.login.clone(), entry.password.clone());
}
let ftp_passwd = opts.ftp_passwd.clone().unwrap_or_default();
return AuthConfig::new(username.to_string(), ftp_passwd);
}
self.resolve_ftp_via_chain(host, opts)
}
fn resolve_ftp_via_chain(&self, host: &str, opts: &AuthResolveOptions) -> Option<AuthConfig> {
if !opts.no_netrc
&& let Some(ref netrc) = self.netrc
&& let Some(entry) = netrc.find_with_fallback(host)
{
debug!("Resolved FTP auth for {} from Netrc", host);
return AuthConfig::new(entry.login.clone(), entry.password.clone());
}
if let Some(ref user) = opts.ftp_user
&& !user.is_empty()
{
let passwd = opts.ftp_passwd.clone().unwrap_or_default();
return AuthConfig::new(user.clone(), passwd);
}
debug!("Resolved FTP auth for {} as anonymous (default)", host);
AuthConfig::new(FTP_DEFAULT_USER.to_string(), FTP_DEFAULT_PASSWD.to_string())
}
pub fn update_basic_cred(&mut self, cred: BasicCred) {
if let Some(existing) = self.basic_creds.take(&cred) {
let mut updated = cred;
if !updated.activated && existing.activated {
updated.activated = true;
}
self.basic_creds.insert(updated);
debug!(
"Updated BasicCred for {}:{}{}",
existing.host, existing.port, existing.path
);
} else {
debug!(
"Inserted BasicCred for {}:{}{}",
cred.host, cred.port, cred.path
);
self.basic_creds.insert(cred);
}
}
pub fn activate_basic_cred(
&mut self,
host: &str,
port: u16,
path: &str,
opts: &AuthResolveOptions,
) -> bool {
let found = self.find_basic_cred(host, port, path).is_some();
if found {
self.find_basic_cred_mut(host, port, path, |cred| {
cred.activate();
});
info!("Activated existing BasicCred for {}:{}{}", host, port, path);
true
} else {
let auth = self.resolve_http_via_chain(host, opts);
match auth {
Some(ac) => {
self.basic_creds.insert(BasicCred::new(
ac.user().to_string(),
ac.password().to_string(),
host.to_string(),
port,
"/".to_string(),
true,
));
info!(
"Created and activated BasicCred for {}:{}{}",
host, port, path
);
true
}
None => {
warn!(
"Cannot activate BasicCred for {}:{}{} — no credentials found",
host, port, path
);
false
}
}
}
}
pub fn find_basic_cred(&self, host: &str, port: u16, path: &str) -> Option<&BasicCred> {
let search = BasicCred::new(
String::new(),
String::new(),
host.to_string(),
port,
path.to_string(),
false,
);
let search_path = search.path.clone();
for cred in self.basic_creds.range(search..) {
if cred.host != host || cred.port != port {
break;
}
if search_path.starts_with(&cred.path) || search_path == cred.path {
return Some(cred);
}
}
None
}
fn find_basic_cred_mut<F>(&mut self, host: &str, port: u16, path: &str, mut mutate: F)
where
F: FnMut(&mut BasicCred),
{
if let Some(cred) = self.find_basic_cred(host, port, path).cloned() {
self.basic_creds.remove(&cred);
let mut modified = cred;
mutate(&mut modified);
self.basic_creds.insert(modified);
}
}
pub fn basic_cred_count(&self) -> usize {
self.basic_creds.len()
}
}
impl Default for AuthConfigFactory {
fn default() -> Self {
Self::new()
}
}
pub fn erase_confidential_info(raw: &str) -> String {
let mut result = String::with_capacity(raw.len());
for line in raw.lines() {
let confidential_header = line.split_once(':').and_then(|(name, _)| {
if name.eq_ignore_ascii_case("authorization") {
Some("Authorization: <snip>\n")
} else if name.eq_ignore_ascii_case("proxy-authorization") {
Some("Proxy-Authorization: <snip>\n")
} else if name.eq_ignore_ascii_case("cookie") {
Some("Cookie: <snip>\n")
} else if name.eq_ignore_ascii_case("set-cookie") {
Some("Set-Cookie: <snip>\n")
} else {
None
}
});
if let Some(replacement) = confidential_header {
result.push_str(replacement);
} else {
result.push_str(line);
result.push('\n');
}
}
result
}