Skip to main content

kube_client/client/
builder.rs

1use bytes::Bytes;
2use http::{Request, Response, header::HeaderMap};
3use hyper::{
4    body::Incoming,
5    rt::{Read, Write},
6};
7use hyper_timeout::TimeoutConnector;
8
9use hyper_util::{
10    client::legacy::connect::{Connection, HttpConnector},
11    rt::TokioExecutor,
12};
13
14use jiff::Timestamp;
15use std::{pin::Pin, time::Duration};
16use tower::{BoxError, Layer, Service, ServiceBuilder, ServiceExt as _, retry::RetryLayer, util::BoxService};
17use tower_http::{ServiceExt as _, classify::ServerErrorsFailureClass, trace::TraceLayer};
18use tracing::Span;
19
20use super::body::Body;
21use crate::{
22    Client, Config, Error, Result,
23    client::{ConfigExt, retry::RetryPolicy},
24};
25
26/// HTTP body of a dynamic backing type.
27///
28/// The suggested implementation type is [`crate::client::Body`].
29pub type DynBody = dyn http_body::Body<Data = Bytes, Error = BoxError> + Send + Unpin;
30
31/// Builder for [`Client`] instances with customized [tower](`Service`) middleware.
32pub struct ClientBuilder<Svc> {
33    service: Svc,
34    default_ns: String,
35    valid_until: Option<Timestamp>,
36}
37
38impl<Svc> ClientBuilder<Svc> {
39    /// Construct a [`ClientBuilder`] from scratch with a fully custom [`Service`] stack.
40    ///
41    /// This method is only intended for advanced use cases, most users will want to use [`ClientBuilder::try_from`] instead,
42    /// which provides a default stack as a starting point.
43    pub fn new(service: Svc, default_namespace: impl Into<String>) -> Self
44    where
45        Svc: Service<Request<Body>>,
46    {
47        Self {
48            service,
49            default_ns: default_namespace.into(),
50            valid_until: None,
51        }
52    }
53
54    /// Add a [`Layer`] to the current [`Service`] stack.
55    pub fn with_layer<L: Layer<Svc>>(self, layer: &L) -> ClientBuilder<L::Service> {
56        let Self {
57            service: stack,
58            default_ns,
59            valid_until,
60        } = self;
61        ClientBuilder {
62            service: layer.layer(stack),
63            default_ns,
64            valid_until,
65        }
66    }
67
68    /// Sets an expiration timestamp for the client.
69    pub fn with_valid_until(self, valid_until: Option<Timestamp>) -> Self {
70        ClientBuilder {
71            service: self.service,
72            default_ns: self.default_ns,
73            valid_until,
74        }
75    }
76
77    /// Build a [`Client`] instance with the current [`Service`] stack.
78    pub fn build<B>(self) -> Client
79    where
80        Svc: Service<Request<Body>, Response = Response<B>> + Send + 'static,
81        Svc::Future: Send + 'static,
82        Svc::Error: Into<BoxError>,
83        B: http_body::Body<Data = bytes::Bytes> + Send + 'static,
84        B::Error: Into<BoxError>,
85    {
86        Client::new(self.service, self.default_ns).with_valid_until(self.valid_until)
87    }
88}
89
90pub type GenericService = BoxService<Request<Body>, Response<Box<DynBody>>, BoxError>;
91
92/// Builds a `Basic` auth header value from a URI userinfo component.
93///
94/// `http::Uri` never decodes percent-escapes, so credentials containing
95/// characters that had to be percent-encoded in the proxy URL (e.g. `@`,
96/// `:`, `%`) are decoded here first — otherwise they'd reach the proxy
97/// still escaped, which any proxy that isn't also skipping decoding will
98/// reject as wrong credentials.
99#[cfg(feature = "http-proxy")]
100fn proxy_basic_auth_value(userinfo: &str) -> String {
101    use base64::Engine;
102
103    format!(
104        "Basic {}",
105        base64::engine::general_purpose::STANDARD
106            .encode(percent_encoding::percent_decode_str(userinfo).collect::<Vec<u8>>())
107    )
108}
109
110#[cfg(feature = "http-proxy")]
111fn with_proxy_basic_auth<C>(
112    proxy_url: &http::Uri,
113    mut connector: hyper_util::client::legacy::connect::proxy::Tunnel<C>,
114) -> hyper_util::client::legacy::connect::proxy::Tunnel<C> {
115    if let Some(authority) = proxy_url.authority()
116        && let Some((userinfo, _)) = authority.as_str().split_once('@')
117    {
118        use http::HeaderValue;
119
120        if let Ok(header) = HeaderValue::from_str(&proxy_basic_auth_value(userinfo)) {
121            connector = connector.with_auth(header);
122        }
123    }
124
125    connector
126}
127
128#[cfg(all(test, feature = "http-proxy"))]
129mod proxy_auth_tests {
130    use super::proxy_basic_auth_value;
131    use base64::Engine;
132
133    fn basic_auth(plain: &str) -> String {
134        format!(
135            "Basic {}",
136            base64::engine::general_purpose::STANDARD.encode(plain)
137        )
138    }
139
140    #[test]
141    fn decodes_percent_escapes_before_basic_auth_encoding() {
142        // password containing '@' and ':' had to be percent-encoded in the proxy URL
143        assert_eq!(
144            proxy_basic_auth_value("user:pa%40ss%3Aword"),
145            basic_auth("user:pa@ss:word")
146        );
147    }
148
149    #[test]
150    fn leaves_plain_userinfo_unchanged() {
151        assert_eq!(proxy_basic_auth_value("user:pass"), basic_auth("user:pass"));
152    }
153
154    #[test]
155    fn passes_through_invalid_escape_with_sign_prefix() {
156        // a leading '+' after '%' is not a valid percent-escape and must not be
157        // treated as one (a naive hex parser like `u8::from_str_radix` would
158        // otherwise accept "+A" as 0x0A instead of passing "%+A" through)
159        assert_eq!(proxy_basic_auth_value("user:pass%+A"), basic_auth("user:pass%+A"));
160    }
161}
162
163impl TryFrom<Config> for ClientBuilder<GenericService> {
164    type Error = Error;
165
166    /// Builds a default [`ClientBuilder`] stack from a given configuration.
167    ///
168    /// By default, the client builder builds an HTTP client that relies on a
169    /// [`TokioExecutor`] to spawn background tasks. To install an executor
170    /// that propagates [`tracing`] spans, use
171    /// `<ClientBuilder<Svc> as TryFrom<(Config, E)>>::try_from()`.
172    ///
173    /// # Examples
174    ///
175    /// ```no_run
176    /// use kube_client::{client::ClientBuilder, config::Config};
177    ///
178    /// #[tokio::main]
179    /// async fn main() {
180    ///     let config = Config::infer().await.unwrap();
181    ///     let builder = ClientBuilder::try_from(config).unwrap();
182    ///     let client = builder.build();
183    /// }
184    /// ```
185    fn try_from(config: Config) -> Result<Self> {
186        let executor = TokioExecutor::new();
187        Self::try_from((config, executor))
188    }
189}
190
191impl<E> TryFrom<(Config, E)> for ClientBuilder<GenericService>
192where
193    E: hyper::rt::Executor<Pin<Box<dyn Future<Output = ()> + Send>>> + Send + Sync + Clone + 'static,
194{
195    type Error = Error;
196
197    /// Builds a default [`ClientBuilder`] stack from a given configuration.
198    ///
199    /// # Examples
200    ///
201    /// Install a tracing executor that propagates [`tracing`] spans to
202    /// spawned tasks.
203    ///
204    /// ```no_run
205    /// # #[cfg(feature = "hyper-util-tracing")]
206    /// # {
207    /// use hyper_util::rt::{CurrentSpanExecutor, TokioExecutor};
208    /// use kube_client::{client::ClientBuilder, config::Config};
209    ///
210    /// #[tokio::main]
211    /// async fn main() {
212    ///     let config = Config::infer().await.unwrap();
213    ///     let executor = CurrentSpanExecutor::new(TokioExecutor::new());
214    ///     let builder = ClientBuilder::try_from((config, executor)).unwrap();
215    ///     let client = builder.build();
216    /// }
217    /// # }
218    /// ```
219    fn try_from((config, executor): (Config, E)) -> Result<Self> {
220        let mut connector = HttpConnector::new();
221        connector.enforce_http(false);
222
223        #[cfg(all(feature = "aws-lc-rs", feature = "rustls-tls"))]
224        {
225            if rustls::crypto::CryptoProvider::get_default().is_none() {
226                // the only error here is if it's been initialized in between: we can ignore it
227                // since our semantic is only to set the default value if it does not exist.
228                let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
229            }
230        }
231
232        match config.proxy_url.as_ref() {
233            // SocksV5 sends hostnames to the proxy by default, so socks5 already resolves DNS
234            // remotely like socks5h. Go's net/http treats the two schemes the same way.
235            Some(proxy_url) if matches!(proxy_url.scheme_str(), Some("socks5" | "socks5h")) => {
236                #[cfg(feature = "socks5")]
237                {
238                    let connector = hyper_util::client::legacy::connect::proxy::SocksV5::new(
239                        proxy_url.clone(),
240                        connector,
241                    );
242                    make_generic_builder(executor, connector, config)
243                }
244
245                #[cfg(not(feature = "socks5"))]
246                Err(Error::ProxyProtocolDisabled {
247                    proxy_url: Box::new(proxy_url.clone()),
248                    protocol_feature: "kube/socks5",
249                })
250            }
251
252            Some(proxy_url) if proxy_url.scheme_str() == Some("http") => {
253                #[cfg(feature = "http-proxy")]
254                {
255                    let connector =
256                        hyper_util::client::legacy::connect::proxy::Tunnel::new(proxy_url.clone(), connector);
257                    let connector = with_proxy_basic_auth(proxy_url, connector);
258
259                    make_generic_builder(executor, connector, config)
260                }
261
262                #[cfg(not(feature = "http-proxy"))]
263                Err(Error::ProxyProtocolDisabled {
264                    proxy_url: Box::new(proxy_url.clone()),
265                    protocol_feature: "kube/http-proxy",
266                })
267            }
268
269            Some(proxy_url) if proxy_url.scheme_str() == Some("https") => {
270                #[cfg(all(feature = "http-proxy", any(feature = "rustls-tls", feature = "openssl-tls")))]
271                {
272                    #[cfg(feature = "rustls-tls")]
273                    let proxy_connector = config.rustls_https_connector_with_connector(connector)?;
274                    #[cfg(all(not(feature = "rustls-tls"), feature = "openssl-tls"))]
275                    let proxy_connector = config.openssl_https_connector_with_connector(connector)?;
276
277                    let connector = hyper_util::client::legacy::connect::proxy::Tunnel::new(
278                        proxy_url.clone(),
279                        proxy_connector,
280                    );
281                    let connector = with_proxy_basic_auth(proxy_url, connector);
282
283                    make_generic_builder(executor, connector, config)
284                }
285
286                #[cfg(all(
287                    feature = "http-proxy",
288                    not(any(feature = "rustls-tls", feature = "openssl-tls"))
289                ))]
290                return Err(Error::TlsRequired);
291
292                #[cfg(not(feature = "http-proxy"))]
293                Err(Error::ProxyProtocolDisabled {
294                    proxy_url: Box::new(proxy_url.clone()),
295                    protocol_feature: "kube/http-proxy",
296                })
297            }
298
299            Some(proxy_url) => Err(Error::ProxyProtocolUnsupported {
300                proxy_url: Box::new(proxy_url.clone()),
301            }),
302
303            None => make_generic_builder(executor, connector, config),
304        }
305    }
306}
307
308/// Helper function for implementation of [`TryFrom<Config>`] for [`ClientBuilder`].
309/// Ignores [`Config::proxy_url`], which at this point is already handled.
310fn make_generic_builder<E, H>(
311    executor: E,
312    connector: H,
313    config: Config,
314) -> Result<ClientBuilder<GenericService>, Error>
315where
316    H: 'static + Clone + Send + Sync + Service<http::Uri>,
317    H::Response: 'static + Connection + Read + Write + Send + Unpin,
318    H::Future: 'static + Send,
319    H::Error: 'static + Send + Sync + std::error::Error,
320    E: hyper::rt::Executor<Pin<Box<dyn Future<Output = ()> + Send>>> + Send + Sync + Clone + 'static,
321{
322    let default_ns = config.default_namespace.clone();
323    let auth_layer = config.auth_layer()?;
324
325    let client: hyper_util::client::legacy::Client<_, Body> = {
326        // Current TLS feature precedence when more than one are set:
327        // 1. rustls-tls
328        // 2. openssl-tls
329        // Create a custom client to use something else.
330        // If TLS features are not enabled, http connector will be used.
331        #[cfg(feature = "rustls-tls")]
332        let connector = config.rustls_https_connector_with_connector(connector)?;
333        #[cfg(all(not(feature = "rustls-tls"), feature = "openssl-tls"))]
334        let connector = config.openssl_https_connector_with_connector(connector)?;
335        #[cfg(all(not(feature = "rustls-tls"), not(feature = "openssl-tls")))]
336        if config.cluster_url.scheme() == Some(&http::uri::Scheme::HTTPS) {
337            // no tls stack situation only works with http scheme
338            return Err(Error::TlsRequired);
339        }
340
341        let mut connector = TimeoutConnector::new(connector);
342
343        // Set the timeouts for the client
344        connector.set_connect_timeout(config.connect_timeout);
345        connector.set_read_timeout(config.read_timeout);
346        connector.set_write_timeout(config.write_timeout);
347        connector.set_reset_reader_on_write(config.reset_reader_on_write);
348
349        hyper_util::client::legacy::Builder::new(executor).build(connector)
350    };
351
352    let stack = ServiceBuilder::new().layer(config.base_uri_layer()).into_inner();
353    #[cfg(feature = "gzip")]
354    let stack = ServiceBuilder::new()
355        .layer(stack)
356        .layer(
357            tower_http::decompression::DecompressionLayer::new()
358                .no_br()
359                .no_deflate()
360                .no_zstd()
361                .gzip(!config.disable_compression),
362        )
363        .into_inner();
364
365    let service = ServiceBuilder::new()
366        .layer(stack)
367        .option_layer(
368            config
369                .default_retry
370                .then_some(RetryLayer::new(RetryPolicy::server_retry())),
371        )
372        .option_layer(auth_layer)
373        .layer(config.extra_headers_layer()?)
374        .layer(
375            // Attribute names follow [Semantic Conventions].
376            // [Semantic Conventions]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md
377            TraceLayer::new_for_http()
378                .make_span_with(|req: &Request<Body>| {
379                    tracing::debug_span!(
380                        "HTTP",
381                         http.method = %req.method(),
382                         http.url = %req.uri(),
383                         http.status_code = tracing::field::Empty,
384                         otel.name = req.extensions().get::<&'static str>().unwrap_or(&"HTTP"),
385                         otel.kind = "client",
386                         otel.status_code = tracing::field::Empty,
387                    )
388                })
389                .on_request(|_req: &Request<Body>, _span: &Span| {
390                    tracing::debug!("requesting");
391                })
392                .on_response(|res: &Response<Incoming>, _latency: Duration, span: &Span| {
393                    let status = res.status();
394                    span.record("http.status_code", status.as_u16());
395                    if status.is_client_error() || status.is_server_error() {
396                        span.record("otel.status_code", "ERROR");
397                    }
398                })
399                // Explicitly disable `on_body_chunk`. The default does nothing.
400                .on_body_chunk(())
401                .on_eos(|_: Option<&HeaderMap>, _duration: Duration, _span: &Span| {
402                    tracing::debug!("stream closed");
403                })
404                .on_failure(|ec: ServerErrorsFailureClass, _latency: Duration, span: &Span| {
405                    // Called when
406                    // - Calling the inner service errored
407                    // - Polling `Body` errored
408                    // - the response was classified as failure (5xx)
409                    // - End of stream was classified as failure
410                    span.record("otel.status_code", "ERROR");
411                    match ec {
412                        ServerErrorsFailureClass::StatusCode(status) => {
413                            span.record("http.status_code", status.as_u16());
414                            tracing::error!("failed with status {}", status)
415                        }
416                        ServerErrorsFailureClass::Error(err) => {
417                            tracing::error!("failed with error {}", err)
418                        }
419                    }
420                }),
421        )
422        .map_err(BoxError::from)
423        .service(client);
424
425    let (_, expiration) = config.exec_identity_pem();
426
427    let client = ClientBuilder::new(
428        service
429            .map_response_body(|body| {
430                Box::new(http_body_util::BodyExt::map_err(body, BoxError::from)) as Box<DynBody>
431            })
432            .boxed(),
433        default_ns,
434    )
435    .with_valid_until(expiration);
436
437    Ok(client)
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn socks5h_proxy_is_handled_like_socks5() {
446        let mut config = Config::new("http://kube.invalid".parse().unwrap());
447        for scheme in ["socks5", "socks5h"] {
448            config.proxy_url = Some(format!("{scheme}://127.0.0.1:1080").parse().unwrap());
449            let result = ClientBuilder::try_from(config.clone());
450            #[cfg(feature = "socks5")]
451            assert!(result.is_ok(), "{scheme}: {:?}", result.err());
452            #[cfg(not(feature = "socks5"))]
453            assert!(
454                matches!(
455                    result,
456                    Err(Error::ProxyProtocolDisabled {
457                        protocol_feature: "kube/socks5",
458                        ..
459                    })
460                ),
461                "{scheme}"
462            );
463        }
464    }
465
466    #[cfg(all(feature = "gzip", feature = "rustls-tls"))]
467    #[tokio::test]
468    async fn test_no_accept_encoding_header_sent_when_compression_disabled()
469    -> Result<(), Box<dyn std::error::Error>> {
470        use http::Uri;
471        use std::net::SocketAddr;
472        use tokio::net::{TcpListener, TcpStream};
473
474        // make_generic_builder skips the provider install in TryFrom<Config>
475        #[cfg(feature = "aws-lc-rs")]
476        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
477
478        // setup a server that echoes back any encoding header value
479        let addr: SocketAddr = ([127, 0, 0, 1], 0).into();
480        let listener = TcpListener::bind(addr).await?;
481        let local_addr = listener.local_addr()?;
482        let uri: Uri = format!("http://{}", local_addr).parse()?;
483
484        tokio::spawn(async move {
485            use http_body_util::Full;
486            use hyper::{server::conn::http1, service::service_fn};
487            use hyper_util::rt::{TokioIo, TokioTimer};
488            use std::convert::Infallible;
489
490            loop {
491                let (tcp, _) = listener.accept().await.unwrap();
492                let io: TokioIo<TcpStream> = TokioIo::new(tcp);
493
494                tokio::spawn(async move {
495                    http1::Builder::new()
496                        .timer(TokioTimer::new())
497                        .serve_connection(
498                            io,
499                            service_fn(|req| async move {
500                                let response = req
501                                    .headers()
502                                    .get(http::header::ACCEPT_ENCODING)
503                                    .map(|b| Bytes::copy_from_slice(b.as_bytes()))
504                                    .unwrap_or_default();
505                                Ok::<_, Infallible>(Response::new(Full::new(response)))
506                            }),
507                        )
508                        .await
509                        .unwrap();
510                });
511            }
512        });
513
514        // confirm gzip echoed back with default config
515        let config = Config { ..Config::new(uri) };
516        let client =
517            make_generic_builder(TokioExecutor::new(), HttpConnector::new(), config.clone())?.build();
518        let response = client.request_text(http::Request::default()).await?;
519        assert_eq!(&response, "gzip");
520
521        // now disable and check empty string echoed back
522        let config = Config {
523            disable_compression: true,
524            ..config
525        };
526        let client = make_generic_builder(TokioExecutor::new(), HttpConnector::new(), config)?.build();
527        let response = client.request_text(http::Request::default()).await?;
528        assert_eq!(&response, "");
529
530        Ok(())
531    }
532}