kube_client/config/mod.rs
1//! Kubernetes configuration objects.
2//!
3//! Reads locally from `$KUBECONFIG` or `~/.kube/config`,
4//! and in-cluster from the [pod environment](https://kubernetes.io/docs/tasks/run-application/access-api-from-pod/#accessing-the-api-from-within-a-pod).
5//!
6//! # Usage
7//! The [`Config`] has several constructors plus logic to infer environment.
8//!
9//! Unless you have issues, prefer using [`Config::infer`], and pass it to a [`Client`][crate::Client].
10use std::{path::PathBuf, time::Duration};
11
12use http::{HeaderName, HeaderValue};
13use thiserror::Error;
14
15mod file_config;
16mod file_loader;
17mod incluster_config;
18#[cfg(any(feature = "http-proxy", feature = "socks5"))] mod no_proxy;
19
20use file_loader::ConfigLoader;
21pub use file_loader::KubeConfigOptions;
22pub use incluster_config::Error as InClusterError;
23#[cfg(any(feature = "http-proxy", feature = "socks5"))]
24pub use no_proxy::Error as NoProxyError;
25
26/// Failed to infer config
27#[derive(Error, Debug)]
28#[error("failed to infer config: in-cluster: ({in_cluster}), kubeconfig: ({kubeconfig})")]
29pub struct InferConfigError {
30 in_cluster: Box<InClusterError>,
31 // We can only pick one source, but the kubeconfig failure is more likely to be a user error
32 #[source]
33 kubeconfig: KubeconfigError,
34}
35
36/// Possible errors when loading kubeconfig
37#[derive(Error, Debug)]
38pub enum KubeconfigError {
39 /// Failed to determine current context
40 #[error("failed to determine current context")]
41 CurrentContextNotSet,
42
43 /// Kubeconfigs with mismatching kind cannot be merged
44 #[error("kubeconfigs with mismatching kind cannot be merged")]
45 KindMismatch,
46
47 /// Kubeconfigs with mismatching api version cannot be merged
48 #[error("kubeconfigs with mismatching api version cannot be merged")]
49 ApiVersionMismatch,
50
51 /// Failed to load current context
52 #[error("failed to load current context: {0}")]
53 LoadContext(String),
54
55 /// Failed to load the cluster of context
56 #[error("failed to load the cluster of context: {0}")]
57 LoadClusterOfContext(String),
58
59 /// Failed to find the path of kubeconfig
60 #[error("failed to find the path of kubeconfig")]
61 FindPath,
62
63 /// Failed to read kubeconfig
64 #[error("failed to read kubeconfig from '{1:?}': {0}")]
65 ReadConfig(#[source] std::io::Error, PathBuf),
66
67 /// Failed to parse kubeconfig YAML
68 #[error("failed to parse kubeconfig YAML: {0}")]
69 Parse(Box<serde_saphyr::Error>),
70
71 /// Cluster url is missing on selected cluster
72 #[error("cluster url is missing on selected cluster")]
73 MissingClusterUrl,
74
75 /// Failed to parse cluster url
76 #[error("failed to parse cluster url: {0}")]
77 ParseClusterUrl(#[source] http::uri::InvalidUri),
78
79 /// Failed to parse proxy url
80 #[error("failed to parse proxy url: {0}")]
81 ParseProxyUrl(#[source] http::uri::InvalidUri),
82
83 /// Failed to load certificate authority
84 #[error("failed to load certificate authority: {0}")]
85 LoadCertificateAuthority(#[source] LoadDataError),
86
87 /// Failed to load client certificate
88 #[error("failed to load client certificate: {0}")]
89 LoadClientCertificate(#[source] LoadDataError),
90
91 /// Failed to load client key
92 #[error("failed to load client key: {0}")]
93 LoadClientKey(#[source] LoadDataError),
94
95 /// Failed to parse PEM-encoded certificates
96 #[error("failed to parse PEM-encoded certificates: {0}")]
97 ParseCertificates(#[source] pem::PemError),
98
99 /// Failed to parse NO_PROXY/no_proxy env var
100 #[cfg(any(feature = "http-proxy", feature = "socks5"))]
101 #[error("failed to parse NO_PROXY/no_proxy env var")]
102 ParseNoProxy(#[source] NoProxyError),
103}
104
105/// Errors from loading data from a base64 string or a file
106#[derive(Debug, Error)]
107pub enum LoadDataError {
108 /// Failed to decode base64 data
109 #[error("failed to decode base64 data: {0}")]
110 DecodeBase64(#[source] base64::DecodeError),
111
112 /// Failed to read file
113 #[error("failed to read file '{1:?}': {0}")]
114 ReadFile(#[source] std::io::Error, PathBuf),
115
116 /// No base64 data or file path was provided
117 #[error("no base64 data or file")]
118 NoBase64DataOrFile,
119}
120
121/// Configuration object for accessing a Kubernetes cluster
122///
123/// The configurable parameters for connecting like cluster URL, default namespace, root certificates, and timeouts.
124/// Normally created implicitly through [`Config::infer`] or [`Client::try_default`](crate::Client::try_default).
125///
126/// # Usage
127/// Construct a [`Config`] instance by using one of the many constructors.
128///
129/// Prefer [`Config::infer`] unless you have particular issues, and avoid manually managing
130/// the data in this struct unless you have particular needs. It exists to be consumed by the [`Client`][crate::Client].
131///
132/// If you are looking to parse the kubeconfig found in a user's home directory see [`Kubeconfig`].
133#[cfg_attr(docsrs, doc(cfg(feature = "config")))]
134#[derive(Debug, Clone)]
135#[non_exhaustive]
136pub struct Config {
137 /// The configured cluster url
138 pub cluster_url: http::Uri,
139 /// The configured default namespace
140 pub default_namespace: String,
141 /// The configured root certificate
142 pub root_cert: Option<Vec<Vec<u8>>>,
143 /// Path to the root certificate bundle file.
144 ///
145 /// When set and the `rustls-tls` feature is enabled, the file is re-read
146 /// periodically (~60 s) to pick up CA rotation, mirroring how
147 /// `token_file` is reloaded. This takes precedence over `root_cert` for
148 /// server certificate verification.
149 ///
150 /// Set automatically by [`Config::incluster`].
151 pub root_cert_file: Option<PathBuf>,
152 /// Set the timeout for connecting to the Kubernetes API.
153 ///
154 /// A value of `None` means no timeout
155 pub connect_timeout: Option<std::time::Duration>,
156 /// Set the timeout for the Kubernetes API response.
157 ///
158 /// A value of `None` means no timeout.
159 ///
160 /// Defaults to `None` to avoid breaking long-lived connections such as
161 /// exec, attach and port-forward sessions. Watch streams are protected
162 /// by a watcher-level idle timeout instead.
163 ///
164 /// If you set this, consider also turning on [`Self::reset_reader_on_write`].
165 /// Otherwise the time a pooled connection sat idle before being handed out
166 /// (up to 90 s) counts against this timeout for the next response on that
167 /// connection.
168 pub read_timeout: Option<std::time::Duration>,
169 /// Set the timeout for the Kubernetes API request.
170 ///
171 /// A value of `None` means no timeout
172 pub write_timeout: Option<std::time::Duration>,
173 /// Whether to make every completed write reset the read timeout. The timeout then counts from
174 /// when a request is sent, not from when its pooled connection went idle (which is potentially a
175 /// long time before the connection was handed out for a request).
176 ///
177 /// Has an effect only when [`Self::read_timeout`] is set.
178 ///
179 /// The tradeoff is that this makes things like kube's 60 s WebSocket pings also reset it on
180 /// exec/attach, and thus the read timeout no longer catches a peer that stops answering while the
181 /// client keeps writing.
182 pub reset_reader_on_write: bool,
183 /// Whether to accept invalid certificates
184 pub accept_invalid_certs: bool,
185 /// Stores information to tell the cluster who you are.
186 pub auth_info: AuthInfo,
187 /// Whether to disable compression (would only have an effect when the `gzip` feature is enabled)
188 pub disable_compression: bool,
189 /// Optional proxy URL. `http` and `https` proxies require the `http-proxy` feature,
190 /// `socks5` and `socks5h` proxies require the `socks5` feature.
191 pub proxy_url: Option<http::Uri>,
192 /// If set, apiserver certificate will be validated to contain this string
193 ///
194 /// If not set, the `cluster_url` is used instead
195 pub tls_server_name: Option<String>,
196 /// Headers to pass with every request.
197 pub headers: Vec<(HeaderName, HeaderValue)>,
198 /// Whether to enable default retrying requests on transient failures (429, 503, 504).
199 pub default_retry: bool,
200}
201
202impl Config {
203 /// Construct a new config where only the `cluster_url` is set by the user.
204 /// and everything else receives a default value.
205 ///
206 /// Most likely you want to use [`Config::infer`] to infer the config from
207 /// the environment.
208 pub fn new(cluster_url: http::Uri) -> Self {
209 Self {
210 cluster_url,
211 default_namespace: String::from("default"),
212 root_cert: None,
213 root_cert_file: None,
214 connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
215 read_timeout: None,
216 write_timeout: Some(DEFAULT_WRITE_TIMEOUT),
217 reset_reader_on_write: false,
218 accept_invalid_certs: false,
219 auth_info: AuthInfo::default(),
220 disable_compression: false,
221 proxy_url: None,
222 tls_server_name: None,
223 headers: Vec::new(),
224 default_retry: true,
225 }
226 }
227
228 /// Infer a Kubernetes client configuration.
229 ///
230 /// First, a user's kubeconfig is loaded from `KUBECONFIG` or
231 /// `~/.kube/config`. If that fails, an in-cluster config is loaded via
232 /// [`Config::incluster`]. If inference from both sources fails, then an
233 /// error is returned.
234 ///
235 /// [`Config::apply_debug_overrides`] is used to augment the loaded
236 /// configuration based on the environment.
237 pub async fn infer() -> Result<Self, InferConfigError> {
238 let mut config = match Self::from_kubeconfig(&KubeConfigOptions::default()).await {
239 Err(kubeconfig_err) => {
240 tracing::trace!(
241 error = &kubeconfig_err as &dyn std::error::Error,
242 "no local config found, falling back to local in-cluster config"
243 );
244
245 Self::incluster().map_err(|in_cluster| InferConfigError {
246 in_cluster: Box::new(in_cluster),
247 kubeconfig: kubeconfig_err,
248 })?
249 }
250 Ok(success) => success,
251 };
252 config.apply_debug_overrides();
253 Ok(config)
254 }
255
256 /// Load an in-cluster Kubernetes client configuration using
257 /// [`Config::incluster_env`].
258 pub fn incluster() -> Result<Self, InClusterError> {
259 Self::incluster_env()
260 }
261
262 /// Load an in-cluster config using the `KUBERNETES_SERVICE_HOST` and
263 /// `KUBERNETES_SERVICE_PORT` environment variables.
264 ///
265 /// A service account's token must be available in
266 /// `/var/run/secrets/kubernetes.io/serviceaccount/`.
267 ///
268 /// This method matches the behavior of the official Kubernetes client
269 /// libraries and is the default for both TLS stacks.
270 pub fn incluster_env() -> Result<Self, InClusterError> {
271 let uri = incluster_config::try_kube_from_env()?;
272 Self::incluster_with_uri(uri)
273 }
274
275 /// Load an in-cluster config using the API server at
276 /// `https://kubernetes.default.svc`.
277 ///
278 /// A service account's token must be available in
279 /// `/var/run/secrets/kubernetes.io/serviceaccount/`.
280 ///
281 /// This behavior does not match that of the official Kubernetes clients,
282 /// but can be used as a consistent entrypoint in many clusters.
283 /// See <https://github.com/kube-rs/kube/issues/1003> for more info.
284 pub fn incluster_dns() -> Result<Self, InClusterError> {
285 Self::incluster_with_uri(incluster_config::kube_dns())
286 }
287
288 fn incluster_with_uri(cluster_url: http::uri::Uri) -> Result<Self, InClusterError> {
289 let default_namespace = incluster_config::load_default_ns()?;
290 let root_cert = incluster_config::load_cert()?;
291
292 Ok(Self {
293 cluster_url,
294 default_namespace,
295 root_cert: Some(root_cert),
296 root_cert_file: Some(PathBuf::from(incluster_config::cert_file())),
297 connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
298 read_timeout: None,
299 write_timeout: Some(DEFAULT_WRITE_TIMEOUT),
300 reset_reader_on_write: false,
301 accept_invalid_certs: false,
302 auth_info: AuthInfo {
303 token_file: Some(incluster_config::token_file()),
304 ..Default::default()
305 },
306 disable_compression: false,
307 proxy_url: None,
308 tls_server_name: None,
309 headers: Vec::new(),
310 default_retry: true,
311 })
312 }
313
314 /// Create configuration from the default local config file
315 ///
316 /// This will respect the `$KUBECONFIG` evar, but otherwise default to `~/.kube/config`.
317 /// You can also customize what context/cluster/user you want to use here,
318 /// but it will default to the current-context.
319 pub async fn from_kubeconfig(options: &KubeConfigOptions) -> Result<Self, KubeconfigError> {
320 let loader = ConfigLoader::new_from_options(options).await?;
321 Self::new_from_loader(loader)
322 }
323
324 /// Create configuration from a [`Kubeconfig`] struct
325 ///
326 /// This bypasses kube's normal config parsing to obtain custom functionality.
327 pub async fn from_custom_kubeconfig(
328 kubeconfig: Kubeconfig,
329 options: &KubeConfigOptions,
330 ) -> Result<Self, KubeconfigError> {
331 let loader = ConfigLoader::new_from_kubeconfig(kubeconfig, options).await?;
332 Self::new_from_loader(loader)
333 }
334
335 fn new_from_loader(loader: ConfigLoader) -> Result<Self, KubeconfigError> {
336 let cluster_url = loader
337 .cluster
338 .server
339 .clone()
340 .ok_or(KubeconfigError::MissingClusterUrl)?
341 .parse::<http::Uri>()
342 .map_err(KubeconfigError::ParseClusterUrl)?;
343
344 let default_namespace = loader
345 .current_context
346 .namespace
347 .clone()
348 .unwrap_or_else(|| String::from("default"));
349
350 let accept_invalid_certs = loader.cluster.insecure_skip_tls_verify.unwrap_or(false);
351 let disable_compression = loader.cluster.disable_compression.unwrap_or(false);
352
353 let mut root_cert = None;
354
355 if let Some(ca_bundle) = loader.ca_bundle()? {
356 root_cert = Some(ca_bundle);
357 }
358
359 let proxy_url = loader.proxy_url(&cluster_url)?;
360
361 Ok(Self {
362 cluster_url,
363 default_namespace,
364 root_cert,
365 root_cert_file: None,
366 connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
367 read_timeout: None,
368 write_timeout: Some(DEFAULT_WRITE_TIMEOUT),
369 reset_reader_on_write: false,
370 accept_invalid_certs,
371 disable_compression,
372 proxy_url,
373 auth_info: loader.user,
374 tls_server_name: loader.cluster.tls_server_name,
375 headers: Vec::new(),
376 default_retry: true,
377 })
378 }
379
380 /// Override configuration based on environment variables
381 ///
382 /// This is only intended for use as a debugging aid, and the specific variables and their behaviour
383 /// should **not** be considered stable across releases.
384 ///
385 /// Currently, the following overrides are supported:
386 ///
387 /// - `KUBE_RS_DEBUG_IMPERSONATE_USER`: A Kubernetes user to impersonate, for example: `system:serviceaccount:default:foo` will impersonate the `ServiceAccount` `foo` in the `Namespace` `default`
388 /// - `KUBE_RS_DEBUG_IMPERSONATE_GROUP`: A Kubernetes group to impersonate, multiple groups may be specified by separating them with commas
389 /// - `KUBE_RS_DEBUG_OVERRIDE_URL`: A Kubernetes cluster URL to use rather than the one specified in the config, useful for proxying traffic through `kubectl proxy`
390 pub fn apply_debug_overrides(&mut self) {
391 // Log these overrides loudly, to emphasize that this is only a debugging aid, and should not be relied upon in production
392 if let Ok(impersonate_user) = std::env::var("KUBE_RS_DEBUG_IMPERSONATE_USER") {
393 tracing::warn!(?impersonate_user, "impersonating user");
394 self.auth_info.impersonate = Some(impersonate_user);
395 }
396 if let Ok(impersonate_groups) = std::env::var("KUBE_RS_DEBUG_IMPERSONATE_GROUP") {
397 let impersonate_groups = impersonate_groups.split(',').map(str::to_string).collect();
398 tracing::warn!(?impersonate_groups, "impersonating groups");
399 self.auth_info.impersonate_groups = Some(impersonate_groups);
400 }
401 if let Ok(url) = std::env::var("KUBE_RS_DEBUG_OVERRIDE_URL") {
402 tracing::warn!(?url, "overriding cluster URL");
403 match url.parse() {
404 Ok(uri) => {
405 self.cluster_url = uri;
406 }
407 Err(err) => {
408 tracing::warn!(
409 ?url,
410 error = &err as &dyn std::error::Error,
411 "failed to parse override cluster URL, ignoring"
412 );
413 }
414 }
415 }
416 }
417
418 /// Client certificate and private key in PEM.
419 pub(crate) fn identity_pem(&self) -> Result<Option<Vec<u8>>, KubeconfigError> {
420 self.auth_info.identity_pem()
421 }
422}
423
424pub(crate) fn certs(data: &[u8]) -> Result<Vec<Vec<u8>>, pem::PemError> {
425 Ok(pem::parse_many(data)?
426 .into_iter()
427 .filter_map(|p| {
428 if p.tag() == "CERTIFICATE" {
429 Some(p.into_contents())
430 } else {
431 None
432 }
433 })
434 .collect::<Vec<_>>())
435}
436
437impl TryFrom<Kubeconfig> for Config {
438 type Error = KubeconfigError;
439
440 fn try_from(kubeconfig: Kubeconfig) -> Result<Self, KubeconfigError> {
441 let loader = ConfigLoader::try_from(kubeconfig)?;
442 Self::new_from_loader(loader)
443 }
444}
445
446// https://github.com/kube-rs/kube/issues/146#issuecomment-590924397
447const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
448const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(295);
449
450// Expose raw config structs
451pub use file_config::{
452 AuthInfo, AuthProviderConfig, Cluster, Context, ExecAuthCluster, ExecConfig, ExecInteractiveMode,
453 Kubeconfig, NamedAuthInfo, NamedCluster, NamedContext, NamedExtension, Preferences,
454};
455
456#[cfg(test)]
457mod tests {
458 #[cfg(not(feature = "client"))] // want to ensure this works without client features
459 #[tokio::test]
460 async fn config_loading_on_small_feature_set() {
461 use super::Config;
462 let cfgraw = r#"
463 apiVersion: v1
464 clusters:
465 - cluster:
466 certificate-authority-data: aGVsbG8K
467 server: https://0.0.0.0:6443
468 name: k3d-test
469 contexts:
470 - context:
471 cluster: k3d-test
472 user: admin@k3d-test
473 name: k3d-test
474 current-context: k3d-test
475 kind: Config
476 preferences: {}
477 users:
478 - name: admin@k3d-test
479 user:
480 client-certificate-data: aGVsbG8K
481 client-key-data: aGVsbG8K
482 "#;
483 let file = tempfile::NamedTempFile::new().expect("create config tempfile");
484 std::fs::write(file.path(), cfgraw).unwrap();
485 std::env::set_var("KUBECONFIG", file.path());
486 let kubeconfig = Config::infer().await.unwrap();
487 assert_eq!(kubeconfig.cluster_url, "https://0.0.0.0:6443/");
488 }
489}