pub mod netrc;
use std::collections::BTreeSet;
use std::path::Path;
use tracing::{debug, info, warn};
use url::Url;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthConfig {
user: String,
password: String,
}
impl AuthConfig {
pub fn new(user: String, password: String) -> Option<Self> {
if user.is_empty() {
None
} else {
Some(Self { user, password })
}
}
pub fn user(&self) -> &str {
&self.user
}
pub fn password(&self) -> &str {
&self.password
}
pub fn auth_text(&self) -> String {
format!("{}:{}", self.user, self.password)
}
}
impl std::fmt::Display for AuthConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", self.user, self.password)
}
}
#[derive(Debug, Clone)]
pub struct BasicCred {
pub user: String,
pub password: String,
pub host: String,
pub port: u16,
pub path: String,
pub activated: bool,
}
impl BasicCred {
pub fn new(
user: String,
password: String,
host: String,
port: u16,
path: String,
activated: bool,
) -> Self {
let mut path = path;
if path.is_empty() || !path.ends_with('/') {
path.push('/');
}
Self {
user,
password,
host,
port,
path,
activated,
}
}
pub fn activate(&mut self) {
self.activated = true;
}
pub fn is_activated(&self) -> bool {
self.activated
}
}
impl PartialEq for BasicCred {
fn eq(&self, other: &Self) -> bool {
self.host == other.host && self.port == other.port && self.path == other.path
}
}
impl Eq for BasicCred {}
impl PartialOrd for BasicCred {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for BasicCred {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
match self.host.cmp(&other.host) {
std::cmp::Ordering::Equal => match self.port.cmp(&other.port) {
std::cmp::Ordering::Equal => other.path.cmp(&self.path), ord => ord,
},
ord => ord,
}
}
}
const FTP_DEFAULT_USER: &str = "anonymous";
const FTP_DEFAULT_PASSWD: &str = "ARIA2USER@";
#[derive(Debug)]
pub struct AuthConfigFactory {
basic_creds: BTreeSet<BasicCred>,
netrc: Option<NetrcStore>,
}
#[derive(Debug, Clone)]
pub struct NetrcStore {
entries: Vec<NetrcEntry>,
default_entry: Option<NetrcEntry>,
}
#[derive(Debug, Clone)]
pub struct NetrcEntry {
pub host: String,
pub login: String,
pub password: String,
}
impl NetrcStore {
pub fn new() -> Self {
Self {
entries: Vec::new(),
default_entry: None,
}
}
pub fn from_entries(entries: Vec<NetrcEntry>) -> Self {
Self {
entries,
default_entry: None,
}
}
pub fn with_default(entries: Vec<NetrcEntry>, default: Option<NetrcEntry>) -> Self {
Self {
entries,
default_entry: default,
}
}
pub fn find(&self, host: &str) -> Option<&NetrcEntry> {
self.entries.iter().find(|e| e.host == host)
}
pub fn find_with_fallback(&self, host: &str) -> Option<&NetrcEntry> {
self.find(host).or(self.default_entry.as_ref())
}
pub fn default_entry(&self) -> Option<&NetrcEntry> {
self.default_entry.as_ref()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty() && self.default_entry.is_none()
}
}
impl Default for NetrcStore {
fn default() -> Self {
Self::new()
}
}
impl From<netrc::NetrcParser> for NetrcStore {
fn from(parser: netrc::NetrcParser) -> Self {
let mut entries = Vec::with_capacity(parser.entries().len());
for entry in parser.entries() {
if let (Some(login), Some(password)) = (&entry.login, &entry.password) {
entries.push(NetrcEntry {
host: entry.machine.clone(),
login: login.clone(),
password: password.clone(),
});
}
}
let default_entry = parser.default_entry().and_then(|d| {
if let (Some(login), Some(password)) = (&d.login, &d.password) {
Some(NetrcEntry {
host: String::new(),
login: login.clone(),
password: password.clone(),
})
} else {
None
}
});
NetrcStore {
entries,
default_entry,
}
}
}
#[derive(Debug, 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>,
}
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(
&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() {
self.update_basic_cred(BasicCred::new(
username.to_string(),
password.to_string(),
host.to_string(),
port,
url.path().to_string(),
true,
));
return AuthConfig::new(username.to_string(), password.to_string());
}
let cred = self.find_basic_cred(host, port, 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 !opts.no_netrc
&& let Some(ref netrc) = self.netrc
&& let Some(entry) = netrc.find(host)
{
debug!(
"Resolved HTTP auth for {} from Netrc (user={})",
host, entry.login
);
return AuthConfig::new(entry.login.clone(), entry.password.clone());
}
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());
}
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 (user={})",
host, entry.login
);
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,
path.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() {
if line.len() >= 15 && line[..15].eq_ignore_ascii_case("authorization: ") {
result.push_str("Authorization: <snip>\n");
} else if line.len() >= 21 && line[..21].eq_ignore_ascii_case("proxy-authorization: ") {
result.push_str("Proxy-Authorization: <snip>\n");
} else if line.len() >= 8 && line[..8].eq_ignore_ascii_case("cookie: ") {
result.push_str("Cookie: <snip>\n");
} else if line.len() >= 12 && line[..12].eq_ignore_ascii_case("set-cookie: ") {
result.push_str("Set-Cookie: <snip>\n");
} else {
result.push_str(line);
result.push('\n');
}
}
result
}