use axum::http::HeaderMap;
pub const DEFAULT_CREDENTIAL_LOCATION: &str = "header:Authorization:Bearer";
pub(crate) fn extract_bearer_token(headers: &HeaderMap) -> Option<String> {
let auth_header = headers.get(axum::http::header::AUTHORIZATION)?.to_str().ok()?;
let token = auth_header.strip_prefix("Bearer ")?;
if token.is_empty() {
return None;
}
Some(token.to_string())
}
pub(crate) fn effective_location(location: Option<&str>) -> &str {
location.unwrap_or(DEFAULT_CREDENTIAL_LOCATION)
}
pub struct CredentialLocation<'a> {
pub header_name: &'a str,
pub prefix: &'a str,
}
pub fn parse_credential_location(location: &str) -> Result<CredentialLocation<'_>, String> {
let parts: Vec<&str> = location.splitn(3, ':').collect();
match parts.as_slice() {
["header", header_name, prefix] => Ok(CredentialLocation {
header_name,
prefix,
}),
_ => Err(format!(
"unsupported credential_location format: '{location}'. Expected 'header:<name>:<prefix>'"
)),
}
}
pub fn format_credential_value(loc: &CredentialLocation<'_>, secret_value: &str) -> String {
if loc.prefix.is_empty() {
secret_value.to_string()
} else {
format!("{} {secret_value}", loc.prefix)
}
}
const BLOCKED_HOSTS: &[&str] = &[
"localhost",
"0.0.0.0",
"::1",
"169.254.169.254",
"fd00:ec2::254",
"metadata.google.internal",
"metadata.goog",
"metadata",
"100.100.100.200",
];
const BLOCKED_SUFFIXES: &[&str] = &[".internal", ".local"];
pub(crate) fn is_blocked_host(host: &str) -> bool {
let host = host.split(':').next().unwrap_or(host);
if BLOCKED_HOSTS.contains(&host) {
return true;
}
if BLOCKED_SUFFIXES.iter().any(|suffix| host.ends_with(suffix)) {
return true;
}
if let Ok(ip) = host.trim_matches(|c| c == '[' || c == ']').parse::<std::net::IpAddr>() {
return match ip {
std::net::IpAddr::V4(v4) => {
v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified()
}
std::net::IpAddr::V6(v6) => {
if v6.is_loopback() || v6.is_unspecified() {
return true;
}
if let Some(v4) = v6.to_ipv4_mapped() {
v4.is_loopback() || v4.is_private() || v4.is_link_local()
} else {
false
}
}
};
}
false
}