alloy_transport/
common.rsuse base64::{engine::general_purpose, Engine};
use std::{fmt, net::SocketAddr};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Authorization {
Basic(String),
Bearer(String),
Raw(String),
}
impl Authorization {
pub fn extract_from_url(url: &url::Url) -> Option<Self> {
let username = url.username();
let password = url.password().unwrap_or_default();
if username.contains("localhost") || username.parse::<SocketAddr>().is_ok() {
return None;
}
(!username.is_empty() || !password.is_empty()).then(|| Self::basic(username, password))
}
pub fn authority(auth: impl AsRef<str>) -> Self {
let auth_secret = general_purpose::STANDARD.encode(auth.as_ref());
Self::Basic(auth_secret)
}
pub fn basic(username: impl AsRef<str>, password: impl AsRef<str>) -> Self {
let username = username.as_ref();
let password = password.as_ref();
Self::authority(format!("{username}:{password}"))
}
pub fn bearer(token: impl Into<String>) -> Self {
Self::Bearer(token.into())
}
pub fn raw(token: impl Into<String>) -> Self {
Self::Raw(token.into())
}
}
impl fmt::Display for Authorization {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Basic(auth) => write!(f, "Basic {auth}"),
Self::Bearer(auth) => write!(f, "Bearer {auth}"),
Self::Raw(auth) => write!(f, "{auth}"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use url::Url;
#[test]
fn test_extract_from_url_with_basic_auth() {
let url = Url::parse("http://username:password@domain.com").unwrap();
let auth = Authorization::extract_from_url(&url).unwrap();
assert_eq!(
auth,
Authorization::Basic(general_purpose::STANDARD.encode("username:password"))
);
}
#[test]
fn test_extract_from_url_no_auth() {
let url = Url::parse("http://domain.com").unwrap();
assert!(Authorization::extract_from_url(&url).is_none());
}
#[test]
fn test_extract_from_url_with_localhost() {
let url = Url::parse("http://localhost:password@domain.com").unwrap();
assert!(Authorization::extract_from_url(&url).is_none());
}
#[test]
fn test_extract_from_url_with_socket_address() {
let url = Url::parse("http://127.0.0.1:8080").unwrap();
assert!(Authorization::extract_from_url(&url).is_none());
}
#[test]
fn test_authority() {
let auth = Authorization::authority("user:pass");
assert_eq!(auth, Authorization::Basic(general_purpose::STANDARD.encode("user:pass")));
}
#[test]
fn test_basic() {
let auth = Authorization::basic("user", "pass");
assert_eq!(auth, Authorization::Basic(general_purpose::STANDARD.encode("user:pass")));
}
#[test]
fn test_raw() {
let auth = Authorization::raw("raw_token");
assert_eq!(auth, Authorization::Raw("raw_token".to_string()));
}
}