use super::{Credential, HttpBasicAuth};
use crate::error::{GarrisonError, GarrisonResult};
use base64::{engine::general_purpose::STANDARD, Engine};
const MAX_CREDENTIAL_LEN: usize = 4 * 1024;
impl HttpBasicAuth {
pub fn encode(user: &str, pass: &str) -> String {
let credentials = format!("{}:{}", user, pass);
STANDARD.encode(credentials.as_bytes())
}
pub fn decode(header_value: &str) -> GarrisonResult<Credential> {
if header_value.len() > MAX_CREDENTIAL_LEN {
return Err(GarrisonError::InvalidParam(
"secure-cred-too-long::".to_string(),
));
}
let decoded = STANDARD
.decode(header_value)
.map_err(|e| GarrisonError::InvalidParam(format!("secure-base64-decode::{}", e)))?;
let decoded_str = String::from_utf8(decoded)
.map_err(|e| GarrisonError::InvalidParam(format!("secure-utf8-decode::{}", e)))?;
let (user, pass) = decoded_str.split_once(':').ok_or_else(|| {
GarrisonError::InvalidParam("secure-cred-missing-colon::".to_string())
})?;
Ok(Credential {
user: user.to_string(),
pass: pass.to_string(),
})
}
pub fn parse_authorization_header(header: &str) -> GarrisonResult<Credential> {
if header.len() > MAX_CREDENTIAL_LEN {
return Err(GarrisonError::InvalidParam(
"secure-cred-too-long::".to_string(),
));
}
let header = header.trim();
let (scheme, credentials) = header.split_once(char::is_whitespace).ok_or_else(|| {
GarrisonError::InvalidParam("secure-auth-header-no-cred::".to_string())
})?;
if !scheme.eq_ignore_ascii_case("basic") {
return Err(GarrisonError::InvalidParam(format!(
"secure-httpbasic-unsupported-scheme::{}",
scheme
)));
}
let credentials = credentials.trim();
if credentials.is_empty() {
return Err(GarrisonError::InvalidParam(
"secure-auth-header-no-cred::".to_string(),
));
}
Self::decode(credentials)
}
}