use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use url::{Host, Url};
const ALWAYS_BLOCKED_HOSTS: &[&str] =
&["metadata.google.internal", "metadata.goog", "instance-data"];
const ALWAYS_BLOCKED_IPS: &[Ipv4Addr] = &[
Ipv4Addr::new(169, 254, 169, 254), Ipv4Addr::new(169, 254, 170, 2), Ipv4Addr::new(100, 100, 100, 200), ];
fn allow_local_from_env() -> bool {
matches!(
std::env::var("ALLOW_LOCAL_LLM").as_deref(),
Ok("1") | Ok("true") | Ok("yes")
)
}
fn is_private_v4(ip: Ipv4Addr) -> bool {
ip.is_loopback()
|| ip.is_private()
|| ip.is_link_local()
|| ip.is_unspecified()
|| ip.is_broadcast()
|| ip.is_documentation()
|| (ip.octets()[0] == 100 && (64..128).contains(&ip.octets()[1]))
|| ip.octets()[0] == 0
}
fn is_private_v6(ip: Ipv6Addr) -> bool {
ip.is_loopback()
|| ip.is_unspecified()
|| (ip.segments()[0] & 0xfe00) == 0xfc00
|| (ip.segments()[0] & 0xffc0) == 0xfe80
|| ip.to_ipv4_mapped().map(is_private_v4).unwrap_or(false)
}
pub fn validate_llm_base_url(raw: &str) -> Result<Url, String> {
validate_base_url_with(raw, allow_local_from_env())
}
pub fn validate_base_url_with(raw: &str, allow_local: bool) -> Result<Url, String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err("base_url is empty".into());
}
let u = Url::parse(trimmed).map_err(|e| format!("base_url is not a valid URL: {e}"))?;
match u.scheme() {
"https" => {}
"http" if allow_local => {}
"http" => {
return Err(
"base_url must use https (set ALLOW_LOCAL_LLM=1 to allow http for a local model)"
.into(),
)
}
other => return Err(format!("base_url scheme {other:?} is not allowed")),
}
let host = u.host().ok_or_else(|| "base_url has no host".to_string())?;
match host {
Host::Domain(d) => {
let dl = d.to_lowercase();
if ALWAYS_BLOCKED_HOSTS
.iter()
.any(|b| dl == *b || dl.ends_with(&format!(".{b}")))
{
return Err(format!("base_url host {d:?} is blocked"));
}
if (dl == "localhost" || dl.ends_with(".localhost") || dl.ends_with(".local"))
&& !allow_local
{
return Err(
"base_url points at localhost (set ALLOW_LOCAL_LLM=1 to allow a local model)"
.into(),
);
}
}
Host::Ipv4(ip) => {
if ALWAYS_BLOCKED_IPS.contains(&ip) {
return Err(format!("base_url {ip} is a cloud metadata endpoint"));
}
if is_private_v4(ip) && !allow_local {
return Err(format!(
"base_url {ip} is a private address (set ALLOW_LOCAL_LLM=1 to allow it)"
));
}
}
Host::Ipv6(ip) => {
if is_private_v6(ip) && !allow_local {
return Err(format!(
"base_url {ip} is a private address (set ALLOW_LOCAL_LLM=1 to allow it)"
));
}
}
}
Ok(u)
}
#[allow(dead_code)]
pub fn is_ip_allowed(ip: IpAddr) -> bool {
is_ip_allowed_with(ip, allow_local_from_env())
}
pub fn is_ip_allowed_with(ip: IpAddr, allow_local: bool) -> bool {
match ip {
IpAddr::V4(v4) => !ALWAYS_BLOCKED_IPS.contains(&v4) && (!is_private_v4(v4) || allow_local),
IpAddr::V6(v6) => !is_private_v6(v6) || allow_local,
}
}
pub fn scrape_url_allowed(u: &Url) -> bool {
if !matches!(u.scheme(), "http" | "https") {
return false;
}
match u.host() {
Some(url::Host::Ipv4(ip)) => is_ip_allowed_with(IpAddr::V4(ip), false),
Some(url::Host::Ipv6(ip)) => is_ip_allowed_with(IpAddr::V6(ip), false),
Some(url::Host::Domain(d)) => {
let d = d.trim_end_matches('.').to_ascii_lowercase();
!(d == "localhost"
|| d.ends_with(".localhost")
|| d.ends_with(".internal")
|| d.ends_with(".local"))
}
None => false,
}
}
pub struct PublicOnlyResolver;
impl reqwest::dns::Resolve for PublicOnlyResolver {
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
Box::pin(async move {
let host = name.as_str().to_string();
let addrs: Vec<std::net::SocketAddr> = tokio::net::lookup_host((host.as_str(), 0))
.await?
.filter(|a| is_ip_allowed_with(a.ip(), false))
.collect();
if addrs.is_empty() {
return Err(format!("{host}: no public address").into());
}
Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs)
})
}
}
pub fn scrape_redirect_policy(max: usize) -> reqwest::redirect::Policy {
reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= max {
attempt.error("too many redirects")
} else if !scrape_url_allowed(attempt.url()) {
attempt.stop()
} else {
attempt.follow()
}
})
}
#[cfg(test)]
mod tests {
use super::*;
const DENY: bool = false;
const ALLOW: bool = true;
#[test]
fn blocks_cloud_metadata_endpoints_even_with_opt_in() {
for allow in [DENY, ALLOW] {
for u in [
"http://169.254.169.254/latest/meta-data/",
"https://169.254.169.254/",
"http://169.254.170.2/v2/credentials",
"http://100.100.100.200/latest/meta-data/",
"http://metadata.google.internal/computeMetadata/v1/",
] {
assert!(
validate_base_url_with(u, allow).is_err(),
"metadata endpoint must be blocked unconditionally: {u} (allow_local={allow})"
);
}
}
}
#[test]
fn blocks_loopback_and_private_ranges_by_default() {
for u in [
"http://localhost:11434/v1",
"http://127.0.0.1:8080/v1",
"https://127.0.0.1/v1",
"http://10.0.0.5/v1",
"http://192.168.1.1/v1",
"http://172.16.0.1/v1",
"http://0.0.0.0/v1",
"http://[::1]/v1",
"http://[fc00::1]/v1",
"https://foo.local/v1",
] {
assert!(
validate_base_url_with(u, DENY).is_err(),
"should be blocked by default: {u}"
);
}
}
#[test]
fn permits_local_models_when_opted_in() {
for u in [
"http://localhost:11434/v1",
"http://127.0.0.1:1234/v1",
"http://192.168.1.50:8000/v1",
"http://[::1]:8080/v1",
] {
assert!(
validate_base_url_with(u, ALLOW).is_ok(),
"should be allowed with opt-in: {u}"
);
}
}
#[test]
fn requires_https_for_public_endpoints() {
assert!(validate_base_url_with("http://api.openai.com/v1", DENY).is_err());
assert!(validate_base_url_with("https://api.openai.com/v1", DENY).is_ok());
}
#[test]
fn rejects_non_http_schemes() {
for u in [
"file:///etc/passwd",
"gopher://x/",
"ftp://x/",
"javascript:alert(1)",
] {
for allow in [DENY, ALLOW] {
assert!(validate_base_url_with(u, allow).is_err(), "{u}");
}
}
}
#[test]
fn allows_normal_provider_endpoints() {
for u in [
"https://api.openai.com/v1",
"https://api.anthropic.com/",
"https://generativelanguage.googleapis.com/v1beta/openai/",
"https://api.groq.com/openai/v1",
"https://openrouter.ai/api/v1",
"https://api.deepseek.com/v1",
] {
assert!(
validate_base_url_with(u, DENY).is_ok(),
"{u} should be allowed"
);
}
}
#[test]
fn ip_allowlist_guards_dns_rebinding() {
assert!(!is_ip_allowed_with("127.0.0.1".parse().unwrap(), DENY));
assert!(!is_ip_allowed_with(
"169.254.169.254".parse().unwrap(),
ALLOW
));
assert!(!is_ip_allowed_with("10.1.2.3".parse().unwrap(), DENY));
assert!(!is_ip_allowed_with("::1".parse().unwrap(), DENY));
assert!(is_ip_allowed_with("1.1.1.1".parse().unwrap(), DENY));
assert!(is_ip_allowed_with("2606:4700::1111".parse().unwrap(), DENY));
assert!(is_ip_allowed_with("127.0.0.1".parse().unwrap(), ALLOW));
}
#[test]
fn rejects_garbage_input() {
for u in ["", " ", "not a url", "https://"] {
assert!(validate_base_url_with(u, ALLOW).is_err(), "{u:?}");
}
}
#[test]
fn carrier_grade_nat_and_zero_network_are_private() {
assert!(validate_base_url_with("http://100.64.0.1/v1", DENY).is_err());
assert!(validate_base_url_with("http://0.1.2.3/v1", DENY).is_err());
}
#[test]
fn ipv4_mapped_ipv6_loopback_is_caught() {
assert!(validate_base_url_with("http://[::ffff:127.0.0.1]/v1", DENY).is_err());
}
#[test]
fn scraping_never_reaches_local_or_metadata_hosts() {
for u in [
"http://127.0.0.1:8000/",
"http://169.254.169.254/latest/meta-data/",
"http://10.0.0.5/",
"http://192.168.1.1/admin",
"http://[::1]/",
"http://localhost:3000/",
"http://metadata.google.internal/",
"file:///etc/passwd",
] {
assert!(
!scrape_url_allowed(&Url::parse(u).unwrap()),
"{u} must be blocked"
);
}
for u in [
"https://en.wikipedia.org/wiki/Paris",
"http://93.184.216.34/",
] {
assert!(
scrape_url_allowed(&Url::parse(u).unwrap()),
"{u} must be allowed"
);
}
}
}