Skip to main content

kube_client/client/
mod.rs

1//! API client for interacting with the Kubernetes API
2//!
3//! The [`Client`] uses standard kube error handling.
4//!
5//! This client can be used on its own or in conjunction with the [`Api`][crate::api::Api]
6//! type for more structured interaction with the kubernetes API.
7//!
8//! The [`Client`] can also be used with [`Discovery`](crate::Discovery) to dynamically
9//! retrieve the resources served by the kubernetes API.
10use either::{Either, Left, Right};
11use futures::{AsyncBufRead, StreamExt, TryStream, TryStreamExt, future::BoxFuture};
12use http::{self, Request, Response};
13use http_body_util::BodyExt;
14#[cfg(feature = "ws")] use hyper_util::rt::TokioIo;
15use jiff::Timestamp;
16use k8s_openapi::apimachinery::pkg::apis::meta::v1 as k8s_meta_v1;
17use kube_core::{discovery::v2::ACCEPT_AGGREGATED_DISCOVERY_V2, response::Status};
18use serde::de::DeserializeOwned;
19use serde_json::{self, Value};
20#[cfg(feature = "ws")]
21use tokio_tungstenite::{WebSocketStream, tungstenite as ws};
22use tokio_util::{
23    codec::{FramedRead, LinesCodec, LinesCodecError},
24    io::StreamReader,
25};
26use tower::{BoxError, Service, ServiceExt as _, buffer::Buffer};
27use tower_http::ServiceExt as _;
28
29pub use self::body::Body;
30use crate::{Config, Error, Result, api::WatchEvent, config::Kubeconfig};
31
32mod auth;
33mod body;
34mod builder;
35pub use kube_core::discovery::v2::{
36    APIGroupDiscovery, APIGroupDiscoveryList, APIResourceDiscovery, APISubresourceDiscovery,
37    APIVersionDiscovery, GroupVersionKind as DiscoveryGroupVersionKind,
38};
39#[cfg_attr(docsrs, doc(cfg(feature = "unstable-client")))]
40#[cfg(feature = "unstable-client")]
41mod client_ext;
42#[cfg_attr(docsrs, doc(cfg(feature = "unstable-client")))]
43#[cfg(feature = "unstable-client")]
44pub use client_ext::scope;
45mod config_ext;
46pub use auth::Error as AuthError;
47pub use config_ext::ConfigExt;
48pub mod middleware;
49pub mod retry;
50
51#[cfg(any(feature = "rustls-tls", feature = "openssl-tls"))] mod tls;
52
53#[cfg(feature = "openssl-tls")]
54pub use tls::openssl_tls::Error as OpensslTlsError;
55#[cfg(feature = "rustls-tls")] pub use tls::rustls_tls::Error as RustlsTlsError;
56#[cfg(feature = "ws")] mod upgrade;
57
58#[cfg(feature = "oauth")]
59#[cfg_attr(docsrs, doc(cfg(feature = "oauth")))]
60pub use auth::OAuthError;
61
62#[cfg(feature = "oidc")]
63#[cfg_attr(docsrs, doc(cfg(feature = "oidc")))]
64pub use auth::oidc_errors;
65
66#[cfg(feature = "ws")]
67#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
68pub use upgrade::UpgradeConnectionError;
69
70#[cfg(feature = "kubelet-debug")]
71#[cfg_attr(docsrs, doc(cfg(feature = "kubelet-debug")))]
72mod kubelet_debug;
73
74pub use builder::{ClientBuilder, DynBody};
75
76/// Client for connecting with a Kubernetes cluster.
77///
78/// The easiest way to instantiate the client is either by
79/// inferring the configuration from the environment using
80/// [`Client::try_default`] or with an existing [`Config`]
81/// using [`Client::try_from`].
82#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
83#[derive(Clone)]
84pub struct Client {
85    // - `Buffer` for cheap clone
86    // - `BoxFuture` for dynamic response future type
87    inner: Buffer<Request<Body>, BoxFuture<'static, Result<Response<Body>, BoxError>>>,
88    default_ns: String,
89    valid_until: Option<Timestamp>,
90}
91
92/// Represents a WebSocket connection.
93/// Value returned by [`Client::connect`].
94#[cfg(feature = "ws")]
95#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
96pub struct Connection {
97    stream: WebSocketStream<TokioIo<hyper::upgrade::Upgraded>>,
98    protocol: upgrade::StreamProtocol,
99}
100
101#[cfg(feature = "ws")]
102#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
103impl Connection {
104    /// Return true if the stream supports graceful close signaling.
105    pub fn supports_stream_close(&self) -> bool {
106        self.protocol.supports_stream_close()
107    }
108
109    /// Transform into the raw WebSocketStream.
110    pub fn into_stream(self) -> WebSocketStream<TokioIo<hyper::upgrade::Upgraded>> {
111        self.stream
112    }
113}
114
115/// Constructors and low-level api interfaces.
116///
117/// Most users only need [`Client::try_default`] or [`Client::new`] from this block.
118///
119/// The many various lower level interfaces here are for more advanced use-cases with specific requirements.
120impl Client {
121    /// Create a [`Client`] using a custom `Service` stack.
122    ///
123    /// [`ConfigExt`](crate::client::ConfigExt) provides extensions for
124    /// building a custom stack.
125    ///
126    /// To create with the default stack with a [`Config`], use
127    /// [`Client::try_from`].
128    ///
129    /// To create with the default stack with an inferred [`Config`], use
130    /// [`Client::try_default`].
131    ///
132    /// # Example
133    ///
134    /// ```rust
135    /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> {
136    /// use kube::{client::ConfigExt, Client, Config};
137    /// use tower::{BoxError, ServiceBuilder};
138    /// use hyper_util::rt::TokioExecutor;
139    ///
140    /// let config = Config::infer().await?;
141    /// let service = ServiceBuilder::new()
142    ///     .layer(config.base_uri_layer())
143    ///     .option_layer(config.auth_layer()?)
144    ///     .map_err(BoxError::from)
145    ///     .service(hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build_http());
146    /// let client = Client::new(service, config.default_namespace);
147    /// # Ok(())
148    /// # }
149    /// ```
150    pub fn new<S, B, T>(service: S, default_namespace: T) -> Self
151    where
152        S: Service<Request<Body>, Response = Response<B>> + Send + 'static,
153        S::Future: Send + 'static,
154        S::Error: Into<BoxError>,
155        B: http_body::Body<Data = bytes::Bytes> + Send + 'static,
156        B::Error: Into<BoxError>,
157        T: Into<String>,
158    {
159        // Transform response body to `crate::client::Body` and use type erased error to avoid type parameters.
160        let service = service
161            .map_response_body(Body::wrap_body)
162            .map_err(Into::into)
163            .boxed();
164        Self {
165            inner: Buffer::new(service, 1024),
166            default_ns: default_namespace.into(),
167            valid_until: None,
168        }
169    }
170
171    /// Sets an expiration timestamp to the client, which has to be checked by the user using [`Client::valid_until`] function.
172    pub fn with_valid_until(self, valid_until: Option<Timestamp>) -> Self {
173        Client { valid_until, ..self }
174    }
175
176    /// Get the expiration timestamp of the client, if it has been set.
177    pub fn valid_until(&self) -> &Option<Timestamp> {
178        &self.valid_until
179    }
180
181    /// Create and initialize a [`Client`] using the inferred configuration.
182    ///
183    /// Will use [`Config::infer`] which attempts to load the local kubeconfig first,
184    /// and then if that fails, trying the in-cluster environment variables.
185    ///
186    /// Will fail if neither configuration could be loaded.
187    ///
188    /// ```rust
189    /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> {
190    /// # use kube::Client;
191    /// let client = Client::try_default().await?;
192    /// # Ok(())
193    /// # }
194    /// ```
195    ///
196    /// If you already have a [`Config`] then use [`Client::try_from`](Self::try_from)
197    /// instead.
198    pub async fn try_default() -> Result<Self> {
199        Self::try_from(Config::infer().await.map_err(Error::InferConfig)?)
200    }
201
202    /// Get the default namespace for the client
203    ///
204    /// The namespace is either configured on `context` in the kubeconfig,
205    /// falls back to `default` when running locally,
206    /// or uses the service account's namespace when deployed in-cluster.
207    pub fn default_namespace(&self) -> &str {
208        &self.default_ns
209    }
210
211    /// Perform a raw HTTP request against the API and return the raw response back.
212    /// This method can be used to get raw access to the API which may be used to, for example,
213    /// create a proxy server or application-level gateway between localhost and the API server.
214    pub async fn send(&self, request: Request<Body>) -> Result<Response<Body>> {
215        let mut svc = self.inner.clone();
216        let res = svc
217            .ready()
218            .await
219            .map_err(Error::Service)?
220            .call(request)
221            .await
222            .map_err(|err| {
223                // Error decorating request
224                err.downcast::<Error>()
225                    .map(|e| *e)
226                    // Error requesting
227                    .or_else(|err| err.downcast::<hyper::Error>().map(|err| Error::HyperError(*err)))
228                    // Error from another middleware
229                    .unwrap_or_else(Error::Service)
230            })?;
231        Ok(res)
232    }
233
234    /// Make WebSocket connection.
235    #[cfg(feature = "ws")]
236    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
237    pub async fn connect(&self, request: Request<Vec<u8>>) -> Result<Connection> {
238        use http::header::HeaderValue;
239        let (mut parts, body) = request.into_parts();
240        parts
241            .headers
242            .insert(http::header::CONNECTION, HeaderValue::from_static("Upgrade"));
243        parts
244            .headers
245            .insert(http::header::UPGRADE, HeaderValue::from_static("websocket"));
246        parts.headers.insert(
247            http::header::SEC_WEBSOCKET_VERSION,
248            HeaderValue::from_static("13"),
249        );
250        let key = tokio_tungstenite::tungstenite::handshake::client::generate_key();
251        parts.headers.insert(
252            http::header::SEC_WEBSOCKET_KEY,
253            key.parse().expect("valid header value"),
254        );
255        upgrade::StreamProtocol::add_to_headers(&mut parts.headers)?;
256
257        let res = self.send(Request::from_parts(parts, Body::from(body))).await?;
258        // 4xx/5xx bodies are `metav1.Status`. Surface them as `Error::Api`
259        // before the upgrade check, which only understands 101.
260        let res = handle_api_errors(res).await?;
261        let protocol = upgrade::verify_response(&res, &key).map_err(Error::UpgradeConnection)?;
262        match hyper::upgrade::on(res).await {
263            Ok(upgraded) => Ok(Connection {
264                stream: WebSocketStream::from_raw_socket(
265                    TokioIo::new(upgraded),
266                    ws::protocol::Role::Client,
267                    None,
268                )
269                .await,
270                protocol,
271            }),
272
273            Err(e) => Err(Error::UpgradeConnection(
274                UpgradeConnectionError::GetPendingUpgrade(e),
275            )),
276        }
277    }
278
279    /// Perform a raw HTTP request against the API and deserialize the response
280    /// as JSON to some known type.
281    pub async fn request<T>(&self, request: Request<Vec<u8>>) -> Result<T>
282    where
283        T: DeserializeOwned,
284    {
285        let text = self.request_text(request).await?;
286
287        serde_json::from_str(&text).map_err(|e| {
288            tracing::warn!("{}, {:?}", text, e);
289            Error::SerdeError(e)
290        })
291    }
292
293    /// Perform a raw HTTP request against the API and get back the response
294    /// as a string
295    pub async fn request_text(&self, request: Request<Vec<u8>>) -> Result<String> {
296        let res = self.send(request.map(Body::from)).await?;
297        let res = handle_api_errors(res).await?;
298        let body_bytes = res.into_body().collect().await?.to_bytes();
299        let text = String::from_utf8(body_bytes.to_vec()).map_err(Error::FromUtf8)?;
300        Ok(text)
301    }
302
303    /// Perform a raw HTTP request against the API and stream the response body.
304    ///
305    /// The response can be processed using [`AsyncReadExt`](futures::AsyncReadExt)
306    /// and [`AsyncBufReadExt`](futures::AsyncBufReadExt).
307    ///
308    /// Reads fail with an [`std::io::Error`] of kind
309    /// [`UnexpectedEof`](std::io::ErrorKind::UnexpectedEof) if the connection
310    /// is dropped before the response is complete.
311    /// Long-lived streams, such as followed logs, can check for it and resume the request.
312    pub async fn request_stream(&self, request: Request<Vec<u8>>) -> Result<impl AsyncBufRead + use<>> {
313        let res = self.send(request.map(Body::from)).await?;
314        let res = handle_api_errors(res).await?;
315        // `into_async_read` requires `std::io::Error` as the stream's error type.
316        let body = res.into_body().into_data_stream().map_err(body_error_to_io);
317        Ok(body.into_async_read())
318    }
319
320    /// Perform a raw HTTP request against the API and get back either an object
321    /// deserialized as JSON or a [`Status`] Object.
322    pub async fn request_status<T>(&self, request: Request<Vec<u8>>) -> Result<Either<T, Status>>
323    where
324        T: DeserializeOwned,
325    {
326        let text = self.request_text(request).await?;
327        // It needs to be JSON:
328        let v: Value = serde_json::from_str(&text).map_err(Error::SerdeError)?;
329        if v["kind"] == "Status" {
330            tracing::trace!("Status from {}", text);
331            Ok(Right(serde_json::from_str::<Status>(&text).map_err(|e| {
332                tracing::warn!("{}, {:?}", text, e);
333                Error::SerdeError(e)
334            })?))
335        } else {
336            Ok(Left(serde_json::from_str::<T>(&text).map_err(|e| {
337                tracing::warn!("{}, {:?}", text, e);
338                Error::SerdeError(e)
339            })?))
340        }
341    }
342
343    /// Perform a raw request and get back a stream of [`WatchEvent`] objects
344    pub async fn request_events<T>(
345        &self,
346        mut request: Request<Vec<u8>>,
347    ) -> Result<impl TryStream<Item = Result<WatchEvent<T>>> + use<T>>
348    where
349        T: Clone + DeserializeOwned,
350    {
351        // Kubernetes >=1.37 gzips watch streams one member per event, but our decompression
352        // middleware only decodes the first member, so opt watch streams out of compression.
353        // Drop this once tower-http decodes multi-member gzip again: tower-rs/tower-http#737,
354        // fixed upstream by Nullus157/async-compression#489.
355        request
356            .headers_mut()
357            .entry(http::header::ACCEPT_ENCODING)
358            .or_insert(http::HeaderValue::from_static("identity"));
359        let res = self.send(request.map(Body::from)).await?;
360        let res = handle_api_errors(res).await?;
361        // trace!("Streaming from {} -> {}", res.url(), res.status().as_str());
362        tracing::trace!("headers: {:?}", res.headers());
363
364        let frames = FramedRead::new(
365            StreamReader::new(res.into_body().into_data_stream().map_err(body_error_to_io)),
366            LinesCodec::new(),
367        );
368
369        Ok(frames.filter_map(|res| async {
370            match res {
371                Ok(line) => match serde_json::from_str::<WatchEvent<T>>(&line) {
372                    Ok(event) => Some(Ok(event)),
373                    Err(e) => {
374                        // Ignore EOF error that can happen for incomplete line from `decode_eof`.
375                        if e.is_eof() {
376                            return None;
377                        }
378
379                        // Got general error response
380                        if let Ok(status) = serde_json::from_str::<Status>(&line) {
381                            return Some(Err(Error::Api(status.boxed())));
382                        }
383                        // Parsing error
384                        Some(Err(Error::SerdeError(e)))
385                    }
386                },
387
388                Err(LinesCodecError::Io(e)) => match e.kind() {
389                    // Client timeout
390                    std::io::ErrorKind::TimedOut => {
391                        tracing::warn!("timeout in poll: {}", e); // our client timeout
392                        None
393                    }
394                    // Unexpected EOF from the chunked decoder, or a nested
395                    // `io::ErrorKind::UnexpectedEof`. Tends to happen after 300+s
396                    // of watching. End the stream so it can be resumed.
397                    std::io::ErrorKind::UnexpectedEof => {
398                        tracing::warn!("eof in poll: {:?}", e);
399                        None
400                    }
401                    _ => Some(Err(Error::ReadEvents(e))),
402                },
403
404                // Reached the maximum line length without finding a newline.
405                // This should never happen because we're using the default `usize::MAX`.
406                Err(LinesCodecError::MaxLineLengthExceeded) => {
407                    Some(Err(Error::LinesCodecMaxLineLengthExceeded))
408                }
409            }
410        }))
411    }
412}
413
414/// Low level discovery methods using `k8s_openapi` types.
415///
416/// Consider using the [`discovery`](crate::discovery) module for
417/// easier-to-use variants of this functionality.
418/// The following methods might be deprecated to avoid confusion between similarly named types within `discovery`.
419impl Client {
420    /// Returns apiserver version.
421    pub async fn apiserver_version(&self) -> Result<k8s_openapi::apimachinery::pkg::version::Info> {
422        self.request(Request::get("/version").body(vec![]).map_err(Error::HttpError)?)
423            .await
424    }
425
426    /// Lists api groups that apiserver serves.
427    pub async fn list_api_groups(&self) -> Result<k8s_meta_v1::APIGroupList> {
428        self.request(Request::get("/apis").body(vec![]).map_err(Error::HttpError)?)
429            .await
430    }
431
432    /// Lists resources served in given API group.
433    ///
434    /// ### Example usage:
435    /// ```rust
436    /// # async fn scope(client: kube::Client) -> Result<(), Box<dyn std::error::Error>> {
437    /// let apigroups = client.list_api_groups().await?;
438    /// for g in apigroups.groups {
439    ///     let ver = g
440    ///         .preferred_version
441    ///         .as_ref()
442    ///         .or_else(|| g.versions.first())
443    ///         .expect("preferred or versions exists");
444    ///     let apis = client.list_api_group_resources(&ver.group_version).await?;
445    ///     dbg!(apis);
446    /// }
447    /// # Ok(())
448    /// # }
449    /// ```
450    pub async fn list_api_group_resources(&self, apiversion: &str) -> Result<k8s_meta_v1::APIResourceList> {
451        let url = format!("/apis/{apiversion}");
452        self.request(Request::get(url).body(vec![]).map_err(Error::HttpError)?)
453            .await
454    }
455
456    /// Lists versions of `core` a.k.a. `""` legacy API group.
457    pub async fn list_core_api_versions(&self) -> Result<k8s_meta_v1::APIVersions> {
458        self.request(Request::get("/api").body(vec![]).map_err(Error::HttpError)?)
459            .await
460    }
461
462    /// Lists resources served in particular `core` group version.
463    pub async fn list_core_api_resources(&self, version: &str) -> Result<k8s_meta_v1::APIResourceList> {
464        let url = format!("/api/{version}");
465        self.request(Request::get(url).body(vec![]).map_err(Error::HttpError)?)
466            .await
467    }
468}
469
470/// Aggregated Discovery API methods
471///
472/// These methods use the Aggregated Discovery API (available since Kubernetes 1.26, stable in 1.30)
473/// to fetch all API resources in a single request, reducing the number of API calls compared to
474/// the traditional discovery methods.
475impl Client {
476    /// Returns aggregated discovery for all API groups served at /apis.
477    ///
478    /// This uses the Aggregated Discovery API to fetch all non-core API groups
479    /// and their resources in a single request.
480    ///
481    /// Requires Kubernetes 1.26+ (beta) or 1.30+ (stable).
482    ///
483    /// ### Example usage:
484    /// ```rust,no_run
485    /// # async fn scope(client: kube::Client) -> Result<(), Box<dyn std::error::Error>> {
486    /// let discovery = client.list_api_groups_aggregated().await?;
487    /// for group in discovery.items {
488    ///     let name = group.metadata.as_ref().and_then(|m| m.name.as_ref());
489    ///     println!("Group: {:?}", name);
490    ///     for version in group.versions {
491    ///         println!("  Version: {:?}", version.version);
492    ///         for resource in version.resources {
493    ///             println!("    Resource: {:?}", resource.resource);
494    ///         }
495    ///     }
496    /// }
497    /// # Ok(())
498    /// # }
499    /// ```
500    pub async fn list_api_groups_aggregated(&self) -> Result<APIGroupDiscoveryList> {
501        self.request(
502            Request::get("/apis")
503                .header(http::header::ACCEPT, ACCEPT_AGGREGATED_DISCOVERY_V2)
504                .body(vec![])
505                .map_err(Error::HttpError)?,
506        )
507        .await
508    }
509
510    /// Returns aggregated discovery for core API group served at /api.
511    ///
512    /// This uses the Aggregated Discovery API to fetch the core API group
513    /// and all its resources in a single request.
514    ///
515    /// Requires Kubernetes 1.26+ (beta) or 1.30+ (stable).
516    ///
517    /// ### Example usage:
518    /// ```rust,no_run
519    /// # async fn scope(client: kube::Client) -> Result<(), Box<dyn std::error::Error>> {
520    /// let discovery = client.list_core_api_versions_aggregated().await?;
521    /// for group in discovery.items {
522    ///     for version in group.versions {
523    ///         println!("Core version: {:?}", version.version);
524    ///         for resource in version.resources {
525    ///             println!("  Resource: {:?} (scope: {:?})", resource.resource, resource.scope);
526    ///         }
527    ///     }
528    /// }
529    /// # Ok(())
530    /// # }
531    /// ```
532    pub async fn list_core_api_versions_aggregated(&self) -> Result<APIGroupDiscoveryList> {
533        self.request(
534            Request::get("/api")
535                .header(http::header::ACCEPT, ACCEPT_AGGREGATED_DISCOVERY_V2)
536                .body(vec![])
537                .map_err(Error::HttpError)?,
538        )
539        .await
540    }
541}
542
543// Converts a response body error into the `std::io::Error` that streaming
544// readers expect, keeping the original error as the source.
545//
546// A connection dropped mid-response becomes `UnexpectedEof`, so long-lived
547// streams (watches, followed logs) can tell it apart and resume. TLS stacks
548// nest an `io::Error` of kind `UnexpectedEof`, while chunk decoders only
549// report "unexpected EOF during chunk" in the error text, so check both.
550fn body_error_to_io(err: Error) -> std::io::Error {
551    let chunk_eof = err.to_string().contains("unexpected EOF during chunk");
552    if error_chain_contains_unexpected_eof(&err) || chunk_eof {
553        return std::io::Error::new(std::io::ErrorKind::UnexpectedEof, err);
554    }
555    std::io::Error::other(err)
556}
557
558// `err` or an error reached through `std::error::Error::source` is an
559// `std::io::Error` of kind `UnexpectedEof`.
560fn error_chain_contains_unexpected_eof(err: &(dyn std::error::Error + 'static)) -> bool {
561    // HTTP and TLS stacks nest a handful of errors. Stop if a custom `source`
562    // implementation cycles so a watch poll cannot stall.
563    const MAX_SOURCE_DEPTH: usize = 16;
564    let mut current = Some(err);
565    for _ in 0..MAX_SOURCE_DEPTH {
566        let Some(err) = current else {
567            return false;
568        };
569        if let Some(io_err) = err.downcast_ref::<std::io::Error>()
570            && io_err.kind() == std::io::ErrorKind::UnexpectedEof
571        {
572            return true;
573        }
574        current = err.source();
575    }
576    false
577}
578
579/// Kubernetes returned error handling
580///
581/// Either kube returned an explicit ApiError struct,
582/// or it somehow returned something we couldn't parse as one.
583///
584/// In either case, present an ApiError upstream.
585async fn handle_api_errors(res: Response<Body>) -> Result<Response<Body>> {
586    let status = res.status();
587    if status.is_client_error() || status.is_server_error() {
588        // trace!("Status = {:?} for {}", status, res.url());
589        let body_bytes = res.into_body().collect().await?.to_bytes();
590        let text = String::from_utf8(body_bytes.to_vec()).map_err(Error::FromUtf8)?;
591        // Print better debug when things do fail
592        // trace!("Parsing error: {}", text);
593        if let Ok(status) = serde_json::from_str::<Status>(&text) {
594            tracing::debug!("Unsuccessful: {status:?}");
595            Err(Error::Api(status.boxed()))
596        } else {
597            // Not every error response is a JSON `Status`. A proxy, ingress
598            // controller, or a bare API path that doesn't exist (e.g. a CRD
599            // that isn't installed yet) can return a plain-text or HTML body
600            // instead. This is routine rather than exceptional, so it's
601            // logged at `debug` like the parsed case above rather than `warn`.
602            let text = text.trim();
603            tracing::debug!("Unsuccessful data error parse: {text}");
604            let status = Status::failure(text, "Failed to parse error data").with_code(status.as_u16());
605            tracing::debug!("Unsuccessful: {status:?} (reconstruct)");
606            Err(Error::Api(status.boxed()))
607        }
608    } else {
609        Ok(res)
610    }
611}
612
613impl TryFrom<Config> for Client {
614    type Error = Error;
615
616    /// Builds a default [`Client`] from a [`Config`].
617    ///
618    /// See [`ClientBuilder`] or [`Client::new`] if more customization is required
619    fn try_from(config: Config) -> Result<Self> {
620        Ok(ClientBuilder::try_from(config)?.build())
621    }
622}
623
624impl TryFrom<Kubeconfig> for Client {
625    type Error = Error;
626
627    fn try_from(kubeconfig: Kubeconfig) -> Result<Self> {
628        let config = Config::try_from(kubeconfig)?;
629        Ok(ClientBuilder::try_from(config)?.build())
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use std::{fmt, io::ErrorKind, pin::pin, time::Duration};
636
637    use crate::{
638        Api, Client, Error, Result,
639        api::{LogParams, WatchEvent},
640        client::Body,
641        config::{AuthInfo, Cluster, Context, Kubeconfig, NamedAuthInfo, NamedCluster, NamedContext},
642    };
643
644    use bytes::Bytes;
645    use futures::{AsyncBufReadExt, Stream, StreamExt};
646    use http::{Request, Response};
647    use http_body::Frame;
648    use http_body_util::StreamBody;
649    use k8s_openapi::api::core::v1::Pod;
650    use kube_core::metadata::PartialObjectMeta;
651    use tower_test::mock;
652
653    const WATCH_POLL_TIMEOUT: Duration = Duration::from_secs(2);
654
655    #[tokio::test]
656    async fn test_default_ns() {
657        let (mock_service, _) = mock::pair::<Request<Body>, Response<Body>>();
658        let client = Client::new(mock_service, "test-namespace");
659        assert_eq!(client.default_namespace(), "test-namespace");
660    }
661
662    #[tokio::test]
663    async fn test_try_from_kubeconfig() {
664        let config = Kubeconfig {
665            current_context: Some("test-context".to_string()),
666            auth_infos: vec![NamedAuthInfo {
667                name: "test-user".to_string(),
668                auth_info: Some(AuthInfo::default()), // <-- empty but valid
669                ..Default::default()
670            }],
671            contexts: vec![NamedContext {
672                name: "test-context".to_string(),
673                context: Some(Context {
674                    cluster: "test-cluster".to_string(),
675                    user: Some("test-user".to_string()),
676                    namespace: Some("test-namespace".to_string()),
677                    ..Default::default()
678                }),
679                ..Default::default()
680            }],
681            clusters: vec![NamedCluster {
682                name: "test-cluster".to_string(),
683                cluster: Some(Cluster {
684                    server: Some("http://localhost:8080".to_string()),
685                    ..Default::default()
686                }),
687                ..Default::default()
688            }],
689            ..Default::default()
690        };
691        let client = Client::try_from(config).expect("Failed to create client from kubeconfig");
692        assert_eq!(client.default_namespace(), "test-namespace");
693    }
694
695    #[tokio::test]
696    async fn test_mock() {
697        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
698        let spawned = tokio::spawn(async move {
699            // Receive a request for pod and respond with some data
700            let mut handle = pin!(handle);
701            let (request, send) = handle.next_request().await.expect("service not called");
702            assert_eq!(request.method(), http::Method::GET);
703            assert_eq!(request.uri().to_string(), "/api/v1/namespaces/default/pods/test");
704            let pod: Pod = serde_json::from_value(serde_json::json!({
705                "apiVersion": "v1",
706                "kind": "Pod",
707                "metadata": {
708                    "name": "test",
709                    "annotations": { "kube-rs": "test" },
710                },
711                "spec": {
712                    "containers": [{ "name": "test", "image": "test-image" }],
713                }
714            }))
715            .unwrap();
716            send.send_response(Response::new(Body::from(serde_json::to_vec(&pod).unwrap())));
717        });
718
719        let pods: Api<Pod> = Api::default_namespaced(Client::new(mock_service, "default"));
720        let pod = pods.get("test").await.unwrap();
721        assert_eq!(pod.metadata.annotations.unwrap().get("kube-rs").unwrap(), "test");
722        spawned.await.unwrap();
723    }
724
725    #[tokio::test]
726    async fn test_partial_object_meta_get_uses_metadata_header() {
727        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
728        let spawned = tokio::spawn(async move {
729            let mut handle = pin!(handle);
730            let (request, send) = handle.next_request().await.expect("service not called");
731            // Verify the metadata-only Accept header is set
732            assert_eq!(
733                request.headers().get(http::header::ACCEPT).unwrap(),
734                "application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1"
735            );
736            let pod_meta: PartialObjectMeta<Pod> = serde_json::from_value(serde_json::json!({
737                "apiVersion": "meta.k8s.io/v1",
738                "kind": "PartialObjectMetadata",
739                "metadata": {
740                    "name": "test",
741                },
742            }))
743            .unwrap();
744            send.send_response(Response::new(Body::from(serde_json::to_vec(&pod_meta).unwrap())));
745        });
746
747        let pods: Api<PartialObjectMeta<Pod>> = Api::default_namespaced(Client::new(mock_service, "default"));
748        let pod = pods.get("test").await.unwrap();
749        assert_eq!(pod.metadata.name, Some("test".to_string()));
750        spawned.await.unwrap();
751    }
752
753    #[tokio::test]
754    async fn test_partial_object_meta_list_uses_metadata_header() {
755        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
756        let spawned = tokio::spawn(async move {
757            let mut handle = pin!(handle);
758            let (request, send) = handle.next_request().await.expect("service not called");
759            assert_eq!(
760                request.headers().get(http::header::ACCEPT).unwrap(),
761                "application/json;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1"
762            );
763            send.send_response(Response::new(Body::from(
764                serde_json::to_vec(&serde_json::json!({
765                    "apiVersion": "meta.k8s.io/v1",
766                    "kind": "PartialObjectMetadataList",
767                    "metadata": { "resourceVersion": "1" },
768                    "items": [],
769                }))
770                .unwrap(),
771            )));
772        });
773
774        let pods: Api<PartialObjectMeta<Pod>> = Api::default_namespaced(Client::new(mock_service, "default"));
775        let list = pods.list(&Default::default()).await.unwrap();
776        assert_eq!(list.items.len(), 0);
777        spawned.await.unwrap();
778    }
779
780    #[tokio::test]
781    async fn test_partial_object_meta_patch_uses_metadata_header() {
782        use kube_core::params::{Patch, PatchParams};
783
784        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
785        let spawned = tokio::spawn(async move {
786            let mut handle = pin!(handle);
787            let (request, send) = handle.next_request().await.expect("service not called");
788            assert_eq!(request.method(), http::Method::PATCH);
789            assert_eq!(
790                request.headers().get(http::header::ACCEPT).unwrap(),
791                "application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1"
792            );
793            send.send_response(Response::new(Body::from(
794                serde_json::to_vec(&serde_json::json!({
795                    "apiVersion": "meta.k8s.io/v1",
796                    "kind": "PartialObjectMetadata",
797                    "metadata": { "name": "test" },
798                }))
799                .unwrap(),
800            )));
801        });
802
803        let pods: Api<PartialObjectMeta<Pod>> = Api::default_namespaced(Client::new(mock_service, "default"));
804        let patch = Patch::Merge(serde_json::json!({ "metadata": { "labels": { "a": "b" } } }));
805        let pod = pods.patch("test", &PatchParams::default(), &patch).await.unwrap();
806        assert_eq!(pod.metadata.name, Some("test".to_string()));
807        spawned.await.unwrap();
808    }
809
810    #[tokio::test]
811    async fn test_partial_object_meta_watch_uses_metadata_header() {
812        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
813        let spawned = tokio::spawn(async move {
814            let mut handle = pin!(handle);
815            let (request, send) = handle.next_request().await.expect("service not called");
816            assert_eq!(
817                request.headers().get(http::header::ACCEPT).unwrap(),
818                "application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1"
819            );
820            // Send an empty response to close the stream
821            send.send_response(Response::new(Body::from(vec![])));
822        });
823
824        let pods: Api<PartialObjectMeta<Pod>> = Api::default_namespaced(Client::new(mock_service, "default"));
825        let _ = pods.watch(&Default::default(), "0").await;
826        spawned.await.unwrap();
827    }
828
829    #[tokio::test]
830    async fn test_watch_error_response_is_surfaced() {
831        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
832        let spawned = tokio::spawn(async move {
833            let mut handle = pin!(handle);
834            let (_request, send) = handle.next_request().await.expect("service not called");
835            // apiservers pretty-print error bodies for some clients, so this can span several lines
836            let body = serde_json::to_vec_pretty(&serde_json::json!({
837                "kind": "Status",
838                "apiVersion": "v1",
839                "metadata": {},
840                "status": "Failure",
841                "message": "pods is forbidden",
842                "reason": "Forbidden",
843                "code": 403,
844            }))
845            .unwrap();
846            send.send_response(
847                Response::builder()
848                    .status(http::StatusCode::FORBIDDEN)
849                    .body(Body::from(body))
850                    .unwrap(),
851            );
852        });
853
854        let pods: Api<Pod> = Api::default_namespaced(Client::new(mock_service, "default"));
855        let Err(err) = pods.watch(&Default::default(), "0").await else {
856            panic!("watch with an error response should fail");
857        };
858        assert!(matches!(&err, Error::Api(s) if s.code == 403), "got {err:?}");
859        spawned.await.unwrap();
860    }
861
862    #[tokio::test]
863    async fn test_non_json_error_response_is_reconstructed() {
864        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
865        let spawned = tokio::spawn(async move {
866            let mut handle = pin!(handle);
867            let (_request, send) = handle.next_request().await.expect("service not called");
868            // Some routers in front of the apiserver (or a probe for a CRD
869            // that isn't installed yet) return a plain-text 404 instead of a
870            // JSON `Status`.
871            send.send_response(
872                Response::builder()
873                    .status(http::StatusCode::NOT_FOUND)
874                    .body(Body::from(b"404 page not found\n".to_vec()))
875                    .unwrap(),
876            );
877        });
878
879        let pods: Api<Pod> = Api::default_namespaced(Client::new(mock_service, "default"));
880        let Err(err) = pods.get("test").await else {
881            panic!("get with a non-JSON error response should fail");
882        };
883        let Error::Api(status) = &err else {
884            panic!("expected Error::Api, got {err:?}");
885        };
886        assert_eq!(status.code, 404);
887        assert_eq!(status.reason, "Failed to parse error data");
888        assert_eq!(status.message, "404 page not found");
889        spawned.await.unwrap();
890    }
891
892    #[tokio::test]
893    async fn watch_direct_unexpected_eof_delivers_added_then_ends() {
894        // Neutral wording: classification must use `ErrorKind`, not the
895        // rustls missing-close-notify message.
896        let body = body_from_chunks(vec![
897            Ok(pod_event_frame("ADDED", "11")),
898            Err(std::io::Error::new(ErrorKind::UnexpectedEof, "connection closed")),
899        ]);
900        let (spawned, stream) = open_watch(body).await;
901        let mut stream = pin!(stream);
902
903        expect_pod(next_event(&mut stream).await, "ADDED", "11");
904        expect_end(next_event(&mut stream).await);
905        spawned.await.unwrap();
906    }
907
908    #[tokio::test]
909    async fn watch_wrapped_unexpected_eof_delivers_modified_then_ends() {
910        let body = body_from_chunks(vec![
911            Ok(pod_event_frame("MODIFIED", "22")),
912            Err(nested_io(
913                &["outer transport interruption", "inner transport interruption"],
914                std::io::Error::new(ErrorKind::UnexpectedEof, "connection closed"),
915            )),
916        ]);
917        let (spawned, stream) = open_watch(body).await;
918        let mut stream = pin!(stream);
919
920        expect_pod(next_event(&mut stream).await, "MODIFIED", "22");
921        expect_end(next_event(&mut stream).await);
922        spawned.await.unwrap();
923    }
924
925    #[tokio::test]
926    async fn watch_unexpected_eof_before_events_ends() {
927        let body = body_from_chunks(vec![Err(nested_io(
928            &["outer transport interruption", "inner transport interruption"],
929            std::io::Error::new(ErrorKind::UnexpectedEof, "connection closed"),
930        ))]);
931        let (spawned, stream) = open_watch(body).await;
932        let mut stream = pin!(stream);
933
934        expect_end(next_event(&mut stream).await);
935        spawned.await.unwrap();
936    }
937
938    #[tokio::test]
939    async fn watch_unexpected_eof_after_truncated_line_keeps_resource_version() {
940        let mut payload = pod_event_json("ADDED", "33");
941        payload.push('\n');
942        payload.push_str(r#"{"type":"MODIFIED","object":{"apiVersion":"v1""#);
943        let body = body_from_chunks(vec![
944            Ok(Bytes::from(payload)),
945            Err(std::io::Error::new(ErrorKind::UnexpectedEof, "connection closed")),
946        ]);
947        let (spawned, stream) = open_watch(body).await;
948        let mut stream = pin!(stream);
949
950        expect_pod(next_event(&mut stream).await, "ADDED", "33");
951        expect_end(next_event(&mut stream).await);
952        spawned.await.unwrap();
953    }
954
955    #[tokio::test]
956    async fn watch_clean_end_after_truncated_line_keeps_resource_version() {
957        let mut payload = pod_event_json("MODIFIED", "34");
958        payload.push('\n');
959        payload.push_str(r#"{"type":"ADDED","object":{"apiVersion":"v1""#);
960        let body = body_from_chunks::<std::io::Error>(vec![Ok(Bytes::from(payload))]);
961        let (spawned, stream) = open_watch(body).await;
962        let mut stream = pin!(stream);
963
964        expect_pod(next_event(&mut stream).await, "MODIFIED", "34");
965        expect_end(next_event(&mut stream).await);
966        spawned.await.unwrap();
967    }
968
969    #[tokio::test]
970    async fn watch_clean_termination_delivers_every_event() {
971        let payload = format!(
972            "{}{}",
973            pod_event_frame_str("ADDED", "1"),
974            pod_event_frame_str("MODIFIED", "2")
975        );
976        let body = body_from_chunks::<std::io::Error>(vec![Ok(Bytes::from(payload))]);
977        let (spawned, stream) = open_watch(body).await;
978        let mut stream = pin!(stream);
979
980        expect_pod(next_event(&mut stream).await, "ADDED", "1");
981        expect_pod(next_event(&mut stream).await, "MODIFIED", "2");
982        expect_end(next_event(&mut stream).await);
983        spawned.await.unwrap();
984    }
985
986    #[tokio::test]
987    async fn watch_chunk_decoder_eof_text_ends_stream() {
988        let body = body_from_chunks(vec![Ok(pod_event_frame("ADDED", "44")), Err(ChunkDecoderEof)]);
989        let (spawned, stream) = open_watch(body).await;
990        let mut stream = pin!(stream);
991
992        expect_pod(next_event(&mut stream).await, "ADDED", "44");
993        expect_end(next_event(&mut stream).await);
994        spawned.await.unwrap();
995    }
996
997    #[tokio::test]
998    async fn watch_malformed_json_is_serde_error() {
999        let body =
1000            body_from_chunks::<std::io::Error>(vec![Ok(Bytes::from("{\"type\":\"ADDED\",\"object\":}\n"))]);
1001        let (spawned, stream) = open_watch(body).await;
1002        let mut stream = pin!(stream);
1003
1004        match next_event(&mut stream).await {
1005            Some(Err(Error::SerdeError(err))) => assert!(!err.is_eof(), "{err}"),
1006            other => panic!("expected a non-eof serde error, got {other:?}"),
1007        }
1008        spawned.await.unwrap();
1009    }
1010
1011    #[tokio::test]
1012    async fn watch_nested_non_eof_io_error_is_read_events() {
1013        let body = body_from_chunks(vec![
1014            Ok(pod_event_frame("ADDED", "55")),
1015            Err(nested_io(
1016                &["outer transport interruption", "inner transport interruption"],
1017                std::io::Error::new(ErrorKind::ConnectionReset, "socket reset"),
1018            )),
1019        ]);
1020        let (spawned, stream) = open_watch(body).await;
1021        let mut stream = pin!(stream);
1022
1023        expect_pod(next_event(&mut stream).await, "ADDED", "55");
1024        let io_err = expect_read_events(next_event(&mut stream).await);
1025        assert_eq!(io_err.kind(), ErrorKind::Other);
1026        let retained = io_err.get_ref().expect("original body error is the source");
1027        let body_err = retained
1028            .downcast_ref::<Error>()
1029            .expect("source is the body error");
1030        assert!(
1031            chain_has_io_kind(body_err, ErrorKind::ConnectionReset),
1032            "original source chain dropped ConnectionReset: {body_err:?}"
1033        );
1034        assert!(
1035            chain_has_message(body_err, "outer transport interruption"),
1036            "{body_err:?}"
1037        );
1038        assert!(
1039            chain_has_message(body_err, "inner transport interruption"),
1040            "{body_err:?}"
1041        );
1042        spawned.await.unwrap();
1043    }
1044
1045    #[tokio::test]
1046    async fn watch_close_notify_message_with_other_io_kind_is_read_events() {
1047        let body = body_from_chunks(vec![
1048            Ok(pod_event_frame("MODIFIED", "66")),
1049            Err(std::io::Error::new(
1050                ErrorKind::InvalidData,
1051                "peer closed connection without sending TLS close_notify",
1052            )),
1053        ]);
1054        let (spawned, stream) = open_watch(body).await;
1055        let mut stream = pin!(stream);
1056
1057        expect_pod(next_event(&mut stream).await, "MODIFIED", "66");
1058        let io_err = expect_read_events(next_event(&mut stream).await);
1059        assert_eq!(io_err.kind(), ErrorKind::Other);
1060        let retained = io_err.get_ref().expect("original body error is the source");
1061        let body_err = retained
1062            .downcast_ref::<Error>()
1063            .expect("source is the body error");
1064        assert!(
1065            chain_has_message(body_err, "close_notify"),
1066            "fixture must mention close_notify, got {body_err}"
1067        );
1068        assert!(
1069            chain_has_io_kind(body_err, ErrorKind::InvalidData),
1070            "original InvalidData kind dropped: {body_err:?}"
1071        );
1072        assert!(
1073            !chain_has_io_kind(body_err, ErrorKind::UnexpectedEof),
1074            "a close_notify message with a different kind was treated as eof: {body_err:?}"
1075        );
1076        spawned.await.unwrap();
1077    }
1078
1079    fn pod_event_json(action: &str, resource_version: &str) -> String {
1080        serde_json::json!({
1081            "type": action,
1082            "object": {
1083                "apiVersion": "v1",
1084                "kind": "Pod",
1085                "metadata": {
1086                    "name": "test",
1087                    "namespace": "default",
1088                    "resourceVersion": resource_version,
1089                },
1090                "spec": {
1091                    "containers": [{ "name": "test", "image": "test-image" }],
1092                }
1093            }
1094        })
1095        .to_string()
1096    }
1097
1098    #[tokio::test]
1099    async fn log_stream_direct_unexpected_eof_is_eof_error() {
1100        let body = body_from_chunks(vec![
1101            Ok(Bytes::from("line one\n")),
1102            Err(std::io::Error::new(ErrorKind::UnexpectedEof, "connection closed")),
1103        ]);
1104        let (spawned, logs) = open_log_stream(body).await;
1105        let mut lines = pin!(logs.lines());
1106
1107        expect_log_line(next_log_line(&mut lines).await, "line one");
1108        let io_err = expect_log_error(next_log_line(&mut lines).await);
1109        assert_eq!(io_err.kind(), ErrorKind::UnexpectedEof, "{io_err:?}");
1110        let body_err = retained_body_error(&io_err);
1111        assert!(
1112            chain_has_io_kind(body_err, ErrorKind::UnexpectedEof),
1113            "{body_err:?}"
1114        );
1115        spawned.await.unwrap();
1116    }
1117
1118    #[tokio::test]
1119    async fn log_stream_wrapped_unexpected_eof_is_eof_error() {
1120        let body = body_from_chunks(vec![
1121            Ok(Bytes::from("line one\n")),
1122            Err(nested_io(
1123                &["outer transport interruption", "inner transport interruption"],
1124                std::io::Error::new(ErrorKind::UnexpectedEof, "connection closed"),
1125            )),
1126        ]);
1127        let (spawned, logs) = open_log_stream(body).await;
1128        let mut lines = pin!(logs.lines());
1129
1130        expect_log_line(next_log_line(&mut lines).await, "line one");
1131        let io_err = expect_log_error(next_log_line(&mut lines).await);
1132        assert_eq!(io_err.kind(), ErrorKind::UnexpectedEof, "{io_err:?}");
1133        let body_err = retained_body_error(&io_err);
1134        assert!(
1135            chain_has_message(body_err, "inner transport interruption"),
1136            "{body_err:?}"
1137        );
1138        spawned.await.unwrap();
1139    }
1140
1141    #[tokio::test]
1142    async fn log_stream_chunk_decoder_eof_text_is_eof_error() {
1143        let body = body_from_chunks(vec![Ok(Bytes::from("line one\n")), Err(ChunkDecoderEof)]);
1144        let (spawned, logs) = open_log_stream(body).await;
1145        let mut lines = pin!(logs.lines());
1146
1147        expect_log_line(next_log_line(&mut lines).await, "line one");
1148        let io_err = expect_log_error(next_log_line(&mut lines).await);
1149        assert_eq!(io_err.kind(), ErrorKind::UnexpectedEof, "{io_err:?}");
1150        let body_err = retained_body_error(&io_err);
1151        assert!(
1152            chain_has_message(body_err, "unexpected EOF during chunk size line"),
1153            "{body_err:?}"
1154        );
1155        spawned.await.unwrap();
1156    }
1157
1158    #[tokio::test]
1159    async fn log_stream_nested_non_eof_io_error_is_other() {
1160        let body = body_from_chunks(vec![
1161            Ok(Bytes::from("line one\n")),
1162            Err(nested_io(
1163                &["outer transport interruption", "inner transport interruption"],
1164                std::io::Error::new(ErrorKind::ConnectionReset, "socket reset"),
1165            )),
1166        ]);
1167        let (spawned, logs) = open_log_stream(body).await;
1168        let mut lines = pin!(logs.lines());
1169
1170        expect_log_line(next_log_line(&mut lines).await, "line one");
1171        let io_err = expect_log_error(next_log_line(&mut lines).await);
1172        assert_eq!(io_err.kind(), ErrorKind::Other, "{io_err:?}");
1173        let body_err = retained_body_error(&io_err);
1174        assert!(
1175            chain_has_io_kind(body_err, ErrorKind::ConnectionReset),
1176            "original source chain dropped ConnectionReset: {body_err:?}"
1177        );
1178        spawned.await.unwrap();
1179    }
1180
1181    #[tokio::test]
1182    async fn log_stream_clean_end_delivers_every_line() {
1183        let body = body_from_chunks::<std::io::Error>(vec![
1184            Ok(Bytes::from("line one\nline ")),
1185            Ok(Bytes::from("two\n")),
1186        ]);
1187        let (spawned, logs) = open_log_stream(body).await;
1188        let mut lines = pin!(logs.lines());
1189
1190        expect_log_line(next_log_line(&mut lines).await, "line one");
1191        expect_log_line(next_log_line(&mut lines).await, "line two");
1192        let end = next_log_line(&mut lines).await;
1193        assert!(end.is_none(), "expected the log stream to end, got {end:?}");
1194        spawned.await.unwrap();
1195    }
1196
1197    /// `Api::log_stream` calls `Client::request_stream`.
1198    async fn open_log_stream(body: Body) -> (tokio::task::JoinHandle<()>, impl futures::AsyncBufRead) {
1199        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
1200        let spawned = tokio::spawn(async move {
1201            let mut handle = pin!(handle);
1202            let (request, send) = handle.next_request().await.expect("service not called");
1203            assert!(
1204                request.uri().path().ends_with("/pods/test/log"),
1205                "expected the pod log path, got {}",
1206                request.uri()
1207            );
1208            send.send_response(Response::new(body));
1209        });
1210        let pods: Api<Pod> = Api::default_namespaced(Client::new(mock_service, "default"));
1211        let lp = LogParams {
1212            follow: true,
1213            ..LogParams::default()
1214        };
1215        let logs = pods.log_stream("test", &lp).await.expect("log stream response");
1216        (spawned, logs)
1217    }
1218
1219    async fn next_log_line<S>(lines: &mut S) -> Option<std::io::Result<String>>
1220    where
1221        S: Stream<Item = std::io::Result<String>> + Unpin,
1222    {
1223        tokio::time::timeout(WATCH_POLL_TIMEOUT, lines.next())
1224            .await
1225            .expect("log stream stalled")
1226    }
1227
1228    fn expect_log_line(item: Option<std::io::Result<String>>, expected: &str) {
1229        match item {
1230            Some(Ok(line)) => assert_eq!(line, expected),
1231            other => panic!("expected log line {expected:?}, got {other:?}"),
1232        }
1233    }
1234
1235    fn expect_log_error(item: Option<std::io::Result<String>>) -> std::io::Error {
1236        match item {
1237            Some(Err(err)) => err,
1238            other => panic!("expected a log stream error, got {other:?}"),
1239        }
1240    }
1241
1242    fn retained_body_error(io_err: &std::io::Error) -> &Error {
1243        io_err
1244            .get_ref()
1245            .expect("original body error is the source")
1246            .downcast_ref::<Error>()
1247            .expect("source is the body error")
1248    }
1249
1250    fn pod_event_frame_str(action: &str, resource_version: &str) -> String {
1251        format!("{}\n", pod_event_json(action, resource_version))
1252    }
1253
1254    fn pod_event_frame(action: &str, resource_version: &str) -> Bytes {
1255        Bytes::from(pod_event_frame_str(action, resource_version))
1256    }
1257
1258    fn body_from_chunks<E>(chunks: Vec<Result<Bytes, E>>) -> Body
1259    where
1260        E: std::error::Error + Send + Sync + 'static,
1261    {
1262        let frames = chunks.into_iter().map(|chunk| chunk.map(Frame::data));
1263        Body::wrap_body(StreamBody::new(futures::stream::iter(frames)))
1264    }
1265
1266    /// `Api::watch` calls `Client::request_events`.
1267    async fn open_watch(
1268        body: Body,
1269    ) -> (
1270        tokio::task::JoinHandle<()>,
1271        impl Stream<Item = Result<WatchEvent<Pod>>>,
1272    ) {
1273        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
1274        let spawned = tokio::spawn(async move {
1275            let mut handle = pin!(handle);
1276            let (request, send) = handle.next_request().await.expect("service not called");
1277            assert!(
1278                request.uri().query().unwrap_or_default().contains("watch=true"),
1279                "expected the client watch path, got {}",
1280                request.uri()
1281            );
1282            send.send_response(Response::new(body));
1283        });
1284        let pods: Api<Pod> = Api::default_namespaced(Client::new(mock_service, "default"));
1285        let stream = pods
1286            .watch(&Default::default(), "0")
1287            .await
1288            .expect("watch response");
1289        (spawned, stream)
1290    }
1291
1292    async fn next_event<S>(stream: &mut S) -> Option<Result<WatchEvent<Pod>>>
1293    where
1294        S: Stream<Item = Result<WatchEvent<Pod>>> + Unpin,
1295    {
1296        tokio::time::timeout(WATCH_POLL_TIMEOUT, stream.next())
1297            .await
1298            .expect("watch stream stalled")
1299    }
1300
1301    fn expect_pod(item: Option<Result<WatchEvent<Pod>>>, action: &str, resource_version: &str) {
1302        let pod = match (action, item) {
1303            ("ADDED", Some(Ok(WatchEvent::Added(pod)))) => pod,
1304            ("MODIFIED", Some(Ok(WatchEvent::Modified(pod)))) => pod,
1305            (_, other) => panic!("expected {action} pod, got {other:?}"),
1306        };
1307        assert_eq!(pod.metadata.name.as_deref(), Some("test"));
1308        assert_eq!(
1309            pod.metadata.resource_version.as_deref(),
1310            Some(resource_version),
1311            "completed event must keep its resource version"
1312        );
1313    }
1314
1315    fn expect_end(item: Option<Result<WatchEvent<Pod>>>) {
1316        assert!(item.is_none(), "expected the watch stream to end, got {item:?}");
1317    }
1318
1319    fn expect_read_events(item: Option<Result<WatchEvent<Pod>>>) -> std::io::Error {
1320        match item {
1321            Some(Err(Error::ReadEvents(err))) => err,
1322            other => panic!("expected ReadEvents, got {other:?}"),
1323        }
1324    }
1325
1326    fn nested_io(messages: &[&'static str], io_err: std::io::Error) -> SourceChain {
1327        let (outer, rest) = messages.split_first().expect("at least one wrapper");
1328        let mut source: Box<dyn std::error::Error + Send + Sync> = Box::new(io_err);
1329        for message in rest.iter().rev() {
1330            source = Box::new(SourceChain {
1331                message,
1332                source: Some(source),
1333            });
1334        }
1335        SourceChain {
1336            message: outer,
1337            source: Some(source),
1338        }
1339    }
1340
1341    fn chain_has_io_kind(err: &(dyn std::error::Error + 'static), kind: ErrorKind) -> bool {
1342        let mut current = Some(err);
1343        for _ in 0..16 {
1344            let Some(err) = current else {
1345                return false;
1346            };
1347            if let Some(io_err) = err.downcast_ref::<std::io::Error>()
1348                && io_err.kind() == kind
1349            {
1350                return true;
1351            }
1352            current = err.source();
1353        }
1354        false
1355    }
1356
1357    fn chain_has_message(err: &(dyn std::error::Error + 'static), message: &str) -> bool {
1358        let mut current = Some(err);
1359        for _ in 0..16 {
1360            let Some(err) = current else {
1361                return false;
1362            };
1363            if err.to_string().contains(message) {
1364                return true;
1365            }
1366            current = err.source();
1367        }
1368        false
1369    }
1370
1371    /// Models a `source()` chain without matching on error text.
1372    struct SourceChain {
1373        message: &'static str,
1374        source: Option<Box<dyn std::error::Error + Send + Sync>>,
1375    }
1376
1377    impl fmt::Debug for SourceChain {
1378        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1379            f.debug_struct("SourceChain")
1380                .field("message", &self.message)
1381                .field("source", &self.source.as_ref().map(ToString::to_string))
1382                .finish()
1383        }
1384    }
1385
1386    impl fmt::Display for SourceChain {
1387        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1388            f.write_str(self.message)
1389        }
1390    }
1391
1392    impl std::error::Error for SourceChain {
1393        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1394            self.source.as_ref().map(|err| err.as_ref() as _)
1395        }
1396    }
1397
1398    /// Legacy chunk-decoder failure. Its display matches the existing text
1399    /// check and it is not an `UnexpectedEof` I/O error.
1400    #[derive(Debug)]
1401    struct ChunkDecoderEof;
1402
1403    impl fmt::Display for ChunkDecoderEof {
1404        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1405            f.write_str("unexpected EOF during chunk size line")
1406        }
1407    }
1408
1409    impl std::error::Error for ChunkDecoderEof {}
1410
1411    #[cfg(feature = "ws")]
1412    #[tokio::test]
1413    async fn connect_returns_api_error_for_forbidden_status() {
1414        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
1415        let spawned = tokio::spawn(async move {
1416            let mut handle = pin!(handle);
1417            let (_request, send) = handle.next_request().await.expect("service not called");
1418            let body = serde_json::json!({
1419                "status": "Failure",
1420                "message": "pods \"my-pod\" is forbidden: User \"system:serviceaccount:default:my-sa\" cannot create resource \"pods/exec\"",
1421                "reason": "Forbidden",
1422                "code": 403
1423            });
1424            send.send_response(
1425                Response::builder()
1426                    .status(403)
1427                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
1428                    .unwrap(),
1429            );
1430        });
1431
1432        let client = Client::new(mock_service, "default");
1433        let request = Request::builder()
1434            .uri("/api/v1/namespaces/default/pods/my-pod/exec")
1435            .body(Vec::new())
1436            .unwrap();
1437        let err = match client.connect(request).await {
1438            Err(err) => err,
1439            Ok(_) => panic!("403 is an API error"),
1440        };
1441        match err {
1442            Error::Api(status) => {
1443                assert_eq!(status.code, 403);
1444                assert!(status.message.contains("forbidden"), "{}", status.message);
1445            }
1446            other => panic!("expected Api error, got {other}"),
1447        }
1448        spawned.await.unwrap();
1449    }
1450}