Skip to main content

adk_core/egress/
client.rs

1//! [`GuardedClient`]: an HTTP client that enforces an [`EgressPolicy`].
2
3use std::fmt;
4use std::net::SocketAddr;
5use std::sync::Arc;
6use std::time::Duration;
7
8use super::{EgressDenial, EgressPolicy, EgressTarget, HostResolver, SystemResolver};
9
10/// A `reqwest` resolver that refuses any answer containing an address the policy refuses
11/// ([`EgressTarget::Address`]).
12///
13/// One refused address refuses the whole answer, so a name whose records mix public and
14/// internal addresses never connects. Set it with `ClientBuilder::dns_resolver` together with
15/// `ClientBuilder::no_proxy`, since a proxy resolves the host itself; [`GuardedClient`] does
16/// both, and checks IP literals and redirects, which a resolver never sees.
17///
18/// # Example
19///
20/// ```rust
21/// use std::sync::Arc;
22///
23/// use adk_core::egress::{EgressPolicy, EgressResolver};
24///
25/// let client = reqwest::Client::builder()
26///     .no_proxy()
27///     .dns_resolver(Arc::new(EgressResolver::new(EgressPolicy::public_only())))
28///     .build()
29///     .expect("the client builds");
30/// # drop(client);
31/// ```
32#[derive(Debug, Clone)]
33pub struct EgressResolver {
34    policy: Arc<EgressPolicy>,
35    lookup: Arc<dyn HostResolver>,
36}
37
38impl EgressResolver {
39    /// A resolver checking the operating system's answers against `policy`.
40    pub fn new(policy: EgressPolicy) -> Self {
41        Self { policy: Arc::new(policy), lookup: Arc::new(SystemResolver) }
42    }
43
44    /// A resolver checking `lookup`'s answers against `policy`.
45    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/// The guarded client could not be built.
80///
81/// No unguarded client is ever used in its place.
82#[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    /// The underlying build error.
90    pub reason: String,
91}
92
93/// An HTTP client that enforces an [`EgressPolicy`] on every request.
94///
95/// | Check | Where |
96/// |-------|-------|
97/// | Scheme, host name and port, IP literals | Before the request is built ([`EgressPolicy::check_url`]) |
98/// | Every address a name resolves to | At connect time, through [`EgressResolver`]: the address checked is the address connected to |
99/// | Every redirect hop | Scheme, host, port and literal again, then resolution again |
100/// | Proxies | None: environment and system proxy settings are ignored, since a proxy resolves names itself |
101///
102/// A refusal from the resolver or a redirect surfaces as the request's `reqwest::Error`;
103/// [`find_denial`](super::find_denial) recovers the [`EgressDenial`].
104///
105/// # Example
106///
107/// ```rust,no_run
108/// use adk_core::egress::{EgressPolicy, GuardedClient, find_denial};
109///
110/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
111/// let client = GuardedClient::new(EgressPolicy::allowlist(["api.github.com:443"])?)?;
112/// assert!(client.get("https://example.com/").is_err());
113/// match client.get("https://api.github.com/zen")?.send().await {
114///     Ok(response) => println!("{}", response.status()),
115///     Err(error) => match find_denial(&error) {
116///         Some(denial) => println!("refused: {denial}"),
117///         None => println!("failed: {error}"),
118///     },
119/// }
120/// # Ok(())
121/// # }
122/// ```
123#[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    /// A client with the default options of [`GuardedClientBuilder`].
137    ///
138    /// # Errors
139    ///
140    /// Returns [`EgressClientError`] when the TLS stack cannot be set up.
141    pub fn new(policy: EgressPolicy) -> Result<Self, EgressClientError> {
142        Self::builder(policy).build()
143    }
144
145    /// Starts a builder enforcing `policy`.
146    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    /// The policy the client enforces.
159    pub fn policy(&self) -> &EgressPolicy {
160        &self.policy
161    }
162
163    /// Starts a `method` request to `url` once the URL passes the policy.
164    ///
165    /// # Errors
166    ///
167    /// Returns why the URL is refused.
168    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    /// Starts a `GET` request; see [`request`](Self::request).
178    ///
179    /// # Errors
180    ///
181    /// Returns why the URL is refused.
182    pub fn get(&self, url: &str) -> Result<reqwest::RequestBuilder, EgressDenial> {
183        self.request(reqwest::Method::GET, url)
184    }
185
186    /// Starts a `POST` request; see [`request`](Self::request).
187    ///
188    /// # Errors
189    ///
190    /// Returns why the URL is refused.
191    pub fn post(&self, url: &str) -> Result<reqwest::RequestBuilder, EgressDenial> {
192        self.request(reqwest::Method::POST, url)
193    }
194}
195
196/// Builds a [`GuardedClient`].
197///
198/// # Example
199///
200/// ```rust
201/// use std::time::Duration;
202///
203/// use adk_core::egress::{EgressPolicy, GuardedClient};
204///
205/// let client = GuardedClient::builder(EgressPolicy::public_only())
206///     .timeout(Duration::from_secs(10))
207///     .redirects(0)
208///     .user_agent("my-agent/1.0")
209///     .build()
210///     .expect("the client builds");
211/// assert!(client.get("https://10.0.0.1/").is_err());
212/// ```
213pub 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    /// Resolves names through `lookup` instead of the operating system.
237    #[must_use]
238    pub fn resolver(mut self, lookup: Arc<dyn HostResolver>) -> Self {
239        self.lookup = lookup;
240        self
241    }
242
243    /// Bounds one request, from connect to the end of the body.
244    #[must_use]
245    pub fn timeout(mut self, timeout: Duration) -> Self {
246        self.timeout = Some(timeout);
247        self
248    }
249
250    /// Bounds connection setup.
251    #[must_use]
252    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
253        self.connect_timeout = Some(timeout);
254        self
255    }
256
257    /// Sets the `User-Agent` header.
258    #[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    /// Follows at most `redirects` redirects, each checked (default 10); `0` returns redirect
265    /// responses to the caller unfollowed.
266    #[must_use]
267    pub fn redirects(mut self, redirects: usize) -> Self {
268        self.redirects = redirects;
269        self
270    }
271
272    /// Sends `headers` with every request.
273    #[must_use]
274    pub fn default_headers(mut self, headers: reqwest::header::HeaderMap) -> Self {
275        self.default_headers = headers;
276        self
277    }
278
279    /// Builds the client.
280    ///
281    /// # Errors
282    ///
283    /// Returns [`EgressClientError`] when the TLS stack cannot be set up.
284    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    /// Answers each request with the response `route` gives its path; returns the port.
350    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        // Names may resolve to loopback; the literal is admitted on port 1 only.
390        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}