this repo has no description
1use reqwest::{Client, ClientBuilder, Url}; 2use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; 3use std::sync::OnceLock; 4use std::time::Duration; 5use tracing::warn; 6 7pub const DEFAULT_HEADERS_TIMEOUT: Duration = Duration::from_secs(10); 8pub const DEFAULT_BODY_TIMEOUT: Duration = Duration::from_secs(30); 9pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); 10pub const MAX_RESPONSE_SIZE: u64 = 10 * 1024 * 1024; 11 12static PROXY_CLIENT: OnceLock<Client> = OnceLock::new(); 13 14pub fn proxy_client() -> &'static Client { 15 PROXY_CLIENT.get_or_init(|| { 16 ClientBuilder::new() 17 .timeout(DEFAULT_BODY_TIMEOUT) 18 .connect_timeout(DEFAULT_CONNECT_TIMEOUT) 19 .pool_max_idle_per_host(10) 20 .pool_idle_timeout(Duration::from_secs(90)) 21 .redirect(reqwest::redirect::Policy::none()) 22 .build() 23 .expect("Failed to build HTTP client - this indicates a TLS or system configuration issue") 24 }) 25} 26 27pub fn is_ssrf_safe(url: &str) -> Result<(), SsrfError> { 28 let parsed = Url::parse(url).map_err(|_| SsrfError::InvalidUrl)?; 29 let scheme = parsed.scheme(); 30 if scheme != "https" { 31 let allow_http = std::env::var("ALLOW_HTTP_PROXY").is_ok() 32 || url.starts_with("http://127.0.0.1") 33 || url.starts_with("http://localhost"); 34 if !allow_http { 35 return Err(SsrfError::InsecureProtocol(scheme.to_string())); 36 } 37 } 38 let host = parsed.host_str().ok_or(SsrfError::NoHost)?; 39 if host == "localhost" { 40 return Ok(()); 41 } 42 if let Ok(ip) = host.parse::<IpAddr>() { 43 if ip.is_loopback() { 44 return Ok(()); 45 } 46 if !is_unicast_ip(&ip) { 47 return Err(SsrfError::NonUnicastIp(ip.to_string())); 48 } 49 return Ok(()); 50 } 51 let port = parsed.port().unwrap_or(if scheme == "https" { 443 } else { 80 }); 52 let socket_addrs: Vec<SocketAddr> = match (host, port).to_socket_addrs() { 53 Ok(addrs) => addrs.collect(), 54 Err(_) => return Err(SsrfError::DnsResolutionFailed(host.to_string())), 55 }; 56 for addr in &socket_addrs { 57 if !is_unicast_ip(&addr.ip()) { 58 warn!( 59 "DNS resolution for {} returned non-unicast IP: {}", 60 host, 61 addr.ip() 62 ); 63 return Err(SsrfError::NonUnicastIp(addr.ip().to_string())); 64 } 65 } 66 Ok(()) 67} 68 69fn is_unicast_ip(ip: &IpAddr) -> bool { 70 match ip { 71 IpAddr::V4(v4) => { 72 !v4.is_loopback() 73 && !v4.is_broadcast() 74 && !v4.is_multicast() 75 && !v4.is_unspecified() 76 && !v4.is_link_local() 77 && !is_private_v4(v4) 78 } 79 IpAddr::V6(v6) => !v6.is_loopback() && !v6.is_multicast() && !v6.is_unspecified(), 80 } 81} 82 83fn is_private_v4(ip: &std::net::Ipv4Addr) -> bool { 84 let octets = ip.octets(); 85 octets[0] == 10 86 || (octets[0] == 172 && (16..=31).contains(&octets[1])) 87 || (octets[0] == 192 && octets[1] == 168) 88 || (octets[0] == 169 && octets[1] == 254) 89} 90 91#[derive(Debug, Clone)] 92pub enum SsrfError { 93 InvalidUrl, 94 InsecureProtocol(String), 95 NoHost, 96 NonUnicastIp(String), 97 DnsResolutionFailed(String), 98} 99 100impl std::fmt::Display for SsrfError { 101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 102 match self { 103 SsrfError::InvalidUrl => write!(f, "Invalid URL"), 104 SsrfError::InsecureProtocol(p) => write!(f, "Insecure protocol: {}", p), 105 SsrfError::NoHost => write!(f, "No host in URL"), 106 SsrfError::NonUnicastIp(ip) => write!(f, "Non-unicast IP address: {}", ip), 107 SsrfError::DnsResolutionFailed(host) => write!(f, "DNS resolution failed for: {}", host), 108 } 109 } 110} 111 112impl std::error::Error for SsrfError {} 113 114pub const HEADERS_TO_FORWARD: &[&str] = &[ 115 "accept-language", 116 "atproto-accept-labelers", 117 "x-bsky-topics", 118]; 119pub const RESPONSE_HEADERS_TO_FORWARD: &[&str] = &[ 120 "atproto-repo-rev", 121 "atproto-content-labelers", 122 "retry-after", 123 "content-type", 124]; 125 126pub fn validate_at_uri(uri: &str) -> Result<AtUriParts, &'static str> { 127 if !uri.starts_with("at://") { 128 return Err("URI must start with at://"); 129 } 130 let path = uri.trim_start_matches("at://"); 131 let parts: Vec<&str> = path.split('/').collect(); 132 if parts.is_empty() { 133 return Err("URI missing DID"); 134 } 135 let did = parts[0]; 136 if !did.starts_with("did:") { 137 return Err("Invalid DID in URI"); 138 } 139 if parts.len() > 1 { 140 let collection = parts[1]; 141 if collection.is_empty() || !collection.contains('.') { 142 return Err("Invalid collection NSID"); 143 } 144 } 145 Ok(AtUriParts { 146 did: did.to_string(), 147 collection: parts.get(1).map(|s| s.to_string()), 148 rkey: parts.get(2).map(|s| s.to_string()), 149 }) 150} 151 152#[derive(Debug, Clone)] 153pub struct AtUriParts { 154 pub did: String, 155 pub collection: Option<String>, 156 pub rkey: Option<String>, 157} 158 159pub fn validate_limit(limit: Option<u32>, default: u32, max: u32) -> u32 { 160 match limit { 161 Some(l) if l == 0 => default, 162 Some(l) if l > max => max, 163 Some(l) => l, 164 None => default, 165 } 166} 167 168pub fn validate_did(did: &str) -> Result<(), &'static str> { 169 if !did.starts_with("did:") { 170 return Err("Invalid DID format"); 171 } 172 let parts: Vec<&str> = did.split(':').collect(); 173 if parts.len() < 3 { 174 return Err("DID must have at least method and identifier"); 175 } 176 let method = parts[1]; 177 if method != "plc" && method != "web" { 178 return Err("Unsupported DID method"); 179 } 180 Ok(()) 181} 182 183#[cfg(test)] 184mod tests { 185 use super::*; 186 #[test] 187 fn test_ssrf_safe_https() { 188 assert!(is_ssrf_safe("https://api.bsky.app/xrpc/test").is_ok()); 189 } 190 #[test] 191 fn test_ssrf_blocks_http_by_default() { 192 let result = is_ssrf_safe("http://external.example.com/xrpc/test"); 193 assert!(matches!(result, Err(SsrfError::InsecureProtocol(_)) | Err(SsrfError::DnsResolutionFailed(_)))); 194 } 195 #[test] 196 fn test_ssrf_allows_localhost_http() { 197 assert!(is_ssrf_safe("http://127.0.0.1:8080/test").is_ok()); 198 assert!(is_ssrf_safe("http://localhost:8080/test").is_ok()); 199 } 200 #[test] 201 fn test_validate_at_uri() { 202 let result = validate_at_uri("at://did:plc:test/app.bsky.feed.post/abc123"); 203 assert!(result.is_ok()); 204 let parts = result.unwrap(); 205 assert_eq!(parts.did, "did:plc:test"); 206 assert_eq!(parts.collection, Some("app.bsky.feed.post".to_string())); 207 assert_eq!(parts.rkey, Some("abc123".to_string())); 208 } 209 #[test] 210 fn test_validate_at_uri_invalid() { 211 assert!(validate_at_uri("https://example.com").is_err()); 212 assert!(validate_at_uri("at://notadid/collection/rkey").is_err()); 213 } 214 #[test] 215 fn test_validate_limit() { 216 assert_eq!(validate_limit(None, 50, 100), 50); 217 assert_eq!(validate_limit(Some(0), 50, 100), 50); 218 assert_eq!(validate_limit(Some(200), 50, 100), 100); 219 assert_eq!(validate_limit(Some(75), 50, 100), 75); 220 } 221 #[test] 222 fn test_validate_did() { 223 assert!(validate_did("did:plc:abc123").is_ok()); 224 assert!(validate_did("did:web:example.com").is_ok()); 225 assert!(validate_did("notadid").is_err()); 226 assert!(validate_did("did:unknown:test").is_err()); 227 } 228}