1use std::fmt;
4use std::net::SocketAddr;
5use std::sync::Arc;
6use std::time::Duration;
7
8use super::{EgressDenial, EgressPolicy, EgressTarget, HostResolver, SystemResolver};
9
10#[derive(Debug, Clone)]
33pub struct EgressResolver {
34 policy: Arc<EgressPolicy>,
35 lookup: Arc<dyn HostResolver>,
36}
37
38impl EgressResolver {
39 pub fn new(policy: EgressPolicy) -> Self {
41 Self { policy: Arc::new(policy), lookup: Arc::new(SystemResolver) }
42 }
43
44 pub fn with_lookup(policy: EgressPolicy, lookup: Arc<dyn HostResolver>) -> Self {
46 Self { policy: Arc::new(policy), lookup }
47 }
48}
49
50impl reqwest::dns::Resolve for EgressResolver {
51 fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
52 let host = name.as_str().to_string();
53 let policy = Arc::clone(&self.policy);
54 let lookup = Arc::clone(&self.lookup);
55 Box::pin(async move {
56 let addresses = lookup.resolve(&host).await?;
57 if addresses.is_empty() {
58 let message = format!("{host} resolves to no address");
59 return Err(std::io::Error::new(std::io::ErrorKind::NotFound, message).into());
60 }
61 for &address in &addresses {
62 if let Err(denial) = policy.decide(&EgressTarget::Address { host: &host, address })
63 {
64 tracing::warn!(
65 egress.host = %host,
66 egress.address = %address,
67 egress.code = denial.code(),
68 "egress refused at resolution"
69 );
70 return Err(denial.into());
71 }
72 }
73 let addresses = addresses.into_iter().map(|address| SocketAddr::new(address, 0));
74 Ok(Box::new(addresses) as reqwest::dns::Addrs)
75 })
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
83#[error(
84 "the egress-guarded HTTP client could not be built ({reason}), so no request is sent \
85 without its egress guard; fix the TLS setup the error names, such as a native root \
86 certificate store with no valid certificate"
87)]
88pub struct EgressClientError {
89 pub reason: String,
91}
92
93#[derive(Clone)]
124pub struct GuardedClient {
125 client: reqwest::Client,
126 policy: Arc<EgressPolicy>,
127}
128
129impl fmt::Debug for GuardedClient {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.debug_struct("GuardedClient").field("policy", &self.policy.to_string()).finish()
132 }
133}
134
135impl GuardedClient {
136 pub fn new(policy: EgressPolicy) -> Result<Self, EgressClientError> {
142 Self::builder(policy).build()
143 }
144
145 pub fn builder(policy: EgressPolicy) -> GuardedClientBuilder {
147 GuardedClientBuilder {
148 policy,
149 lookup: Arc::new(SystemResolver),
150 timeout: None,
151 connect_timeout: None,
152 user_agent: None,
153 redirects: 10,
154 default_headers: reqwest::header::HeaderMap::new(),
155 }
156 }
157
158 pub fn policy(&self) -> &EgressPolicy {
160 &self.policy
161 }
162
163 pub fn request(
169 &self,
170 method: reqwest::Method,
171 url: &str,
172 ) -> Result<reqwest::RequestBuilder, EgressDenial> {
173 let url = self.policy.check_url(url)?;
174 Ok(self.client.request(method, url))
175 }
176
177 pub fn get(&self, url: &str) -> Result<reqwest::RequestBuilder, EgressDenial> {
183 self.request(reqwest::Method::GET, url)
184 }
185
186 pub fn post(&self, url: &str) -> Result<reqwest::RequestBuilder, EgressDenial> {
192 self.request(reqwest::Method::POST, url)
193 }
194}
195
196pub struct GuardedClientBuilder {
214 policy: EgressPolicy,
215 lookup: Arc<dyn HostResolver>,
216 timeout: Option<Duration>,
217 connect_timeout: Option<Duration>,
218 user_agent: Option<String>,
219 redirects: usize,
220 default_headers: reqwest::header::HeaderMap,
221}
222
223impl fmt::Debug for GuardedClientBuilder {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 f.debug_struct("GuardedClientBuilder")
226 .field("policy", &self.policy.to_string())
227 .field("lookup", &self.lookup)
228 .field("timeout", &self.timeout)
229 .field("connect_timeout", &self.connect_timeout)
230 .field("redirects", &self.redirects)
231 .finish()
232 }
233}
234
235impl GuardedClientBuilder {
236 #[must_use]
238 pub fn resolver(mut self, lookup: Arc<dyn HostResolver>) -> Self {
239 self.lookup = lookup;
240 self
241 }
242
243 #[must_use]
245 pub fn timeout(mut self, timeout: Duration) -> Self {
246 self.timeout = Some(timeout);
247 self
248 }
249
250 #[must_use]
252 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
253 self.connect_timeout = Some(timeout);
254 self
255 }
256
257 #[must_use]
259 pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
260 self.user_agent = Some(user_agent.into());
261 self
262 }
263
264 #[must_use]
267 pub fn redirects(mut self, redirects: usize) -> Self {
268 self.redirects = redirects;
269 self
270 }
271
272 #[must_use]
274 pub fn default_headers(mut self, headers: reqwest::header::HeaderMap) -> Self {
275 self.default_headers = headers;
276 self
277 }
278
279 pub fn build(self) -> Result<GuardedClient, EgressClientError> {
285 let policy = Arc::new(self.policy);
286 let redirect = match self.redirects {
287 0 => reqwest::redirect::Policy::none(),
288 max => {
289 let policy = Arc::clone(&policy);
290 reqwest::redirect::Policy::custom(move |attempt| {
291 if attempt.previous().len() > max {
292 let message = format!("more than {max} redirects");
293 return attempt.error(message);
294 }
295 match policy.check_parsed_url(attempt.url()) {
296 Ok(()) => attempt.follow(),
297 Err(denial) => {
298 tracing::warn!(
299 egress.code = denial.code(),
300 error = %denial,
301 "egress refused a redirect"
302 );
303 attempt.error(denial)
304 }
305 }
306 })
307 }
308 };
309 let resolver = EgressResolver { policy: Arc::clone(&policy), lookup: self.lookup };
310 let mut builder = reqwest::Client::builder()
311 .no_proxy()
312 .dns_resolver(Arc::new(resolver))
313 .redirect(redirect)
314 .default_headers(self.default_headers);
315 if let Some(timeout) = self.timeout {
316 builder = builder.timeout(timeout);
317 }
318 if let Some(timeout) = self.connect_timeout {
319 builder = builder.connect_timeout(timeout);
320 }
321 if let Some(user_agent) = self.user_agent {
322 builder = builder.user_agent(user_agent);
323 }
324 let client = builder.build().map_err(|error| {
325 let mut reason = error.to_string();
326 let mut source = std::error::Error::source(&error);
327 while let Some(cause) = source {
328 reason.push_str(": ");
329 reason.push_str(&cause.to_string());
330 source = cause.source();
331 }
332 tracing::error!(error = %reason, "egress-guarded client failed to build");
333 EgressClientError { reason }
334 })?;
335 Ok(GuardedClient { client, policy })
336 }
337}
338
339#[cfg(test)]
340mod tests {
341 use std::net::IpAddr;
342
343 use tokio::io::{AsyncReadExt, AsyncWriteExt};
344 use tokio::net::TcpListener;
345
346 use super::*;
347 use crate::egress::{AddressClass, StaticResolver, find_denial};
348
349 async fn serve(route: fn(&str, u16) -> String) -> u16 {
351 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
352 let port = listener.local_addr().unwrap().port();
353 tokio::spawn(async move {
354 while let Ok((mut stream, _)) = listener.accept().await {
355 tokio::spawn(async move {
356 let mut request = Vec::new();
357 let mut buffer = [0u8; 1024];
358 while !request.windows(4).any(|w| w == b"\r\n\r\n") {
359 match stream.read(&mut buffer).await {
360 Ok(0) | Err(_) => return,
361 Ok(n) => request.extend_from_slice(&buffer[..n]),
362 }
363 }
364 let text = String::from_utf8_lossy(&request);
365 let path = text.split_whitespace().nth(1).unwrap_or("/").to_string();
366 let _ = stream.write_all(route(&path, port).as_bytes()).await;
367 });
368 }
369 });
370 port
371 }
372
373 fn redirect_to(location: &str) -> String {
374 format!("HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\n\r\n")
375 }
376
377 fn route(path: &str, port: u16) -> String {
378 match path {
379 "/to-other" => redirect_to(&format!("http://other.test:{port}/ok")),
380 "/to-metadata" => redirect_to("http://169.254.169.254/latest/meta-data"),
381 "/to-literal" => redirect_to(&format!("http://127.0.0.1:{port}/ok")),
382 "/to-self" => redirect_to(&format!("http://app.test:{port}/ok")),
383 _ => "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok".to_string(),
384 }
385 }
386
387 fn local_client() -> GuardedClient {
388 let loopback: IpAddr = "127.0.0.1".parse().unwrap();
389 let policy =
391 EgressPolicy::allowlist(["app.test", "127.0.0.1:1"]).unwrap().with_plain_http();
392 let resolver = StaticResolver::new()
393 .with_host("app.test", [loopback])
394 .with_host("other.test", [loopback]);
395 GuardedClient::builder(policy).resolver(Arc::new(resolver)).build().unwrap()
396 }
397
398 #[tokio::test]
399 async fn an_admitted_name_reaches_its_checked_address() {
400 let port = serve(route).await;
401 let client = local_client();
402 let response =
403 client.get(&format!("http://app.test:{port}/to-self")).unwrap().send().await.unwrap();
404 assert_eq!(response.status(), 200);
405 assert_eq!(response.text().await.unwrap(), "ok");
406 }
407
408 #[tokio::test]
409 async fn every_redirect_hop_is_checked() {
410 let port = serve(route).await;
411 let client = local_client();
412 let cases = [
413 ("/to-other", "egress.host_not_allowed"),
414 ("/to-metadata", "egress.metadata_address"),
415 ("/to-literal", "egress.literal_not_allowed"),
416 ];
417 for (path, code) in cases {
418 let error = client
419 .get(&format!("http://app.test:{port}{path}"))
420 .unwrap()
421 .send()
422 .await
423 .expect_err(path);
424 let denial = find_denial(&error).unwrap_or_else(|| panic!("{path}: {error:?}"));
425 assert_eq!(denial.code(), code, "{path}");
426 }
427 }
428
429 #[tokio::test]
430 async fn names_resolving_to_refused_addresses_never_connect() {
431 let resolver = StaticResolver::new()
432 .with_host("internal.test", ["10.0.0.1".parse().unwrap()])
433 .with_host(
434 "mixed.test",
435 ["93.184.216.34".parse().unwrap(), "127.0.0.1".parse().unwrap()],
436 )
437 .with_host("metadata.test", ["169.254.169.254".parse().unwrap()]);
438 let client = GuardedClient::builder(EgressPolicy::public_only())
439 .resolver(Arc::new(resolver))
440 .build()
441 .unwrap();
442 for (host, expected) in
443 [("internal.test", AddressClass::Private), ("mixed.test", AddressClass::Loopback)]
444 {
445 let error =
446 client.get(&format!("https://{host}/")).unwrap().send().await.expect_err(host);
447 match find_denial(&error) {
448 Some(EgressDenial::AddressNotAllowed { class, .. }) => assert_eq!(*class, expected),
449 other => panic!("{host}: {other:?} from {error:?}"),
450 }
451 }
452 let error = client.get("https://metadata.test/").unwrap().send().await.unwrap_err();
453 assert!(matches!(find_denial(&error), Some(EgressDenial::MetadataAddress { .. })));
454 }
455
456 #[test]
457 fn refused_urls_build_no_request() {
458 let client = GuardedClient::new(EgressPolicy::allowlist(["api.example.com"]).unwrap())
459 .expect("the client builds");
460 for url in [
461 "https://10.0.0.1/",
462 "https://93.184.216.34/",
463 "http://api.example.com/",
464 "https://other.example.com/",
465 "file:///etc/passwd",
466 ] {
467 assert!(client.get(url).is_err(), "{url}");
468 }
469 assert!(client.get("https://api.example.com/").is_ok());
470 }
471}