kube_client/config/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Kubernetes configuration objects.
//!
//! Reads locally from `$KUBECONFIG` or `~/.kube/config`,
//! 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).
//!
//! # Usage
//! The [`Config`] has several constructors plus logic to infer environment.
//!
//! Unless you have issues, prefer using [`Config::infer`], and pass it to a [`Client`][crate::Client].
use std::{path::PathBuf, time::Duration};

use http::{HeaderName, HeaderValue};
use thiserror::Error;

mod file_config;
mod file_loader;
mod incluster_config;

use file_loader::ConfigLoader;
pub use file_loader::KubeConfigOptions;
pub use incluster_config::Error as InClusterError;

/// Failed to infer config
#[derive(Error, Debug)]
#[error("failed to infer config: in-cluster: ({in_cluster}), kubeconfig: ({kubeconfig})")]
pub struct InferConfigError {
    in_cluster: InClusterError,
    // We can only pick one source, but the kubeconfig failure is more likely to be a user error
    #[source]
    kubeconfig: KubeconfigError,
}

/// Possible errors when loading kubeconfig
#[derive(Error, Debug)]
pub enum KubeconfigError {
    /// Failed to determine current context
    #[error("failed to determine current context")]
    CurrentContextNotSet,

    /// Kubeconfigs with mismatching kind cannot be merged
    #[error("kubeconfigs with mismatching kind cannot be merged")]
    KindMismatch,

    /// Kubeconfigs with mismatching api version cannot be merged
    #[error("kubeconfigs with mismatching api version cannot be merged")]
    ApiVersionMismatch,

    /// Failed to load current context
    #[error("failed to load current context: {0}")]
    LoadContext(String),

    /// Failed to load the cluster of context
    #[error("failed to load the cluster of context: {0}")]
    LoadClusterOfContext(String),

    /// Failed to find the path of kubeconfig
    #[error("failed to find the path of kubeconfig")]
    FindPath,

    /// Failed to read kubeconfig
    #[error("failed to read kubeconfig from '{1:?}': {0}")]
    ReadConfig(#[source] std::io::Error, PathBuf),

    /// Failed to parse kubeconfig YAML
    #[error("failed to parse kubeconfig YAML: {0}")]
    Parse(#[source] serde_yaml::Error),

    /// The structure of the parsed kubeconfig is invalid
    #[error("the structure of the parsed kubeconfig is invalid: {0}")]
    InvalidStructure(#[source] serde_yaml::Error),

    /// Cluster url is missing on selected cluster
    #[error("cluster url is missing on selected cluster")]
    MissingClusterUrl,

    /// Failed to parse cluster url
    #[error("failed to parse cluster url: {0}")]
    ParseClusterUrl(#[source] http::uri::InvalidUri),

    /// Failed to parse proxy url
    #[error("failed to parse proxy url: {0}")]
    ParseProxyUrl(#[source] http::uri::InvalidUri),

    /// Failed to load certificate authority
    #[error("failed to load certificate authority")]
    LoadCertificateAuthority(#[source] LoadDataError),

    /// Failed to load client certificate
    #[error("failed to load client certificate")]
    LoadClientCertificate(#[source] LoadDataError),

    /// Failed to load client key
    #[error("failed to load client key")]
    LoadClientKey(#[source] LoadDataError),

    /// Failed to parse PEM-encoded certificates
    #[error("failed to parse PEM-encoded certificates: {0}")]
    ParseCertificates(#[source] pem::PemError),
}

/// Errors from loading data from a base64 string or a file
#[derive(Debug, Error)]
pub enum LoadDataError {
    /// Failed to decode base64 data
    #[error("failed to decode base64 data: {0}")]
    DecodeBase64(#[source] base64::DecodeError),

    /// Failed to read file
    #[error("failed to read file '{1:?}': {0}")]
    ReadFile(#[source] std::io::Error, PathBuf),

    /// No base64 data or file path was provided
    #[error("no base64 data or file")]
    NoBase64DataOrFile,
}

/// Configuration object for accessing a Kuernetes cluster
///
/// The configurable parameters for connecting like cluster URL, default namespace, root certificates, and timeouts.
/// Normally created implicitly through [`Config::infer`] or [`Client::try_default`](crate::Client::try_default).
///
/// # Usage
/// Construct a [`Config`] instance by using one of the many constructors.
///
/// Prefer [`Config::infer`] unless you have particular issues, and avoid manually managing
/// the data in this struct unless you have particular needs. It exists to be consumed by the [`Client`][crate::Client].
///
/// If you are looking to parse the kubeconfig found in a user's home directory see [`Kubeconfig`].
#[cfg_attr(docsrs, doc(cfg(feature = "config")))]
#[derive(Debug, Clone)]
pub struct Config {
    /// The configured cluster url
    pub cluster_url: http::Uri,
    /// The configured default namespace
    pub default_namespace: String,
    /// The configured root certificate
    pub root_cert: Option<Vec<Vec<u8>>>,
    /// Set the timeout for connecting to the Kubernetes API.
    ///
    /// A value of `None` means no timeout
    pub connect_timeout: Option<std::time::Duration>,
    /// Set the timeout for the Kubernetes API response.
    ///
    /// A value of `None` means no timeout
    pub read_timeout: Option<std::time::Duration>,
    /// Set the timeout for the Kubernetes API request.
    ///
    /// A value of `None` means no timeout
    pub write_timeout: Option<std::time::Duration>,
    /// Whether to accept invalid certificates
    pub accept_invalid_certs: bool,
    /// Stores information to tell the cluster who you are.
    pub auth_info: AuthInfo,
    /// Whether to disable compression (would only have an effect when the `gzip` feature is enabled)
    pub disable_compression: bool,
    /// Optional proxy URL. Proxy support requires the `socks5` feature.
    pub proxy_url: Option<http::Uri>,
    /// If set, apiserver certificate will be validated to contain this string
    ///
    /// If not set, the `cluster_url` is used instead
    pub tls_server_name: Option<String>,
    /// Headers to pass with every request.
    pub headers: Vec<(HeaderName, HeaderValue)>,
}

impl Config {
    /// Construct a new config where only the `cluster_url` is set by the user.
    /// and everything else receives a default value.
    ///
    /// Most likely you want to use [`Config::infer`] to infer the config from
    /// the environment.
    pub fn new(cluster_url: http::Uri) -> Self {
        Self {
            cluster_url,
            default_namespace: String::from("default"),
            root_cert: None,
            connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
            read_timeout: Some(DEFAULT_READ_TIMEOUT),
            write_timeout: Some(DEFAULT_WRITE_TIMEOUT),
            accept_invalid_certs: false,
            auth_info: AuthInfo::default(),
            disable_compression: false,
            proxy_url: None,
            tls_server_name: None,
            headers: Vec::new(),
        }
    }

    /// Infer a Kubernetes client configuration.
    ///
    /// First, a user's kubeconfig is loaded from `KUBECONFIG` or
    /// `~/.kube/config`. If that fails, an in-cluster config is loaded via
    /// [`Config::incluster`]. If inference from both sources fails, then an
    /// error is returned.
    ///
    /// [`Config::apply_debug_overrides`] is used to augment the loaded
    /// configuration based on the environment.
    pub async fn infer() -> Result<Self, InferConfigError> {
        let mut config = match Self::from_kubeconfig(&KubeConfigOptions::default()).await {
            Err(kubeconfig_err) => {
                tracing::trace!(
                    error = &kubeconfig_err as &dyn std::error::Error,
                    "no local config found, falling back to local in-cluster config"
                );

                Self::incluster().map_err(|in_cluster| InferConfigError {
                    in_cluster,
                    kubeconfig: kubeconfig_err,
                })?
            }
            Ok(success) => success,
        };
        config.apply_debug_overrides();
        Ok(config)
    }

    /// Load an in-cluster Kubernetes client configuration using
    /// [`Config::incluster_env`].
    pub fn incluster() -> Result<Self, InClusterError> {
        Self::incluster_env()
    }

    /// Load an in-cluster config using the `KUBERNETES_SERVICE_HOST` and
    /// `KUBERNETES_SERVICE_PORT` environment variables.
    ///
    /// A service account's token must be available in
    /// `/var/run/secrets/kubernetes.io/serviceaccount/`.
    ///
    /// This method matches the behavior of the official Kubernetes client
    /// libraries and is the default for both TLS stacks.
    pub fn incluster_env() -> Result<Self, InClusterError> {
        let uri = incluster_config::try_kube_from_env()?;
        Self::incluster_with_uri(uri)
    }

    /// Load an in-cluster config using the API server at
    /// `https://kubernetes.default.svc`.
    ///
    /// A service account's token must be available in
    /// `/var/run/secrets/kubernetes.io/serviceaccount/`.
    ///
    /// This behavior does not match that of the official Kubernetes clients,
    /// but can be used as a consistent entrypoint in many clusters.
    /// See <https://github.com/kube-rs/kube/issues/1003> for more info.
    pub fn incluster_dns() -> Result<Self, InClusterError> {
        Self::incluster_with_uri(incluster_config::kube_dns())
    }

    fn incluster_with_uri(cluster_url: http::uri::Uri) -> Result<Self, InClusterError> {
        let default_namespace = incluster_config::load_default_ns()?;
        let root_cert = incluster_config::load_cert()?;

        Ok(Self {
            cluster_url,
            default_namespace,
            root_cert: Some(root_cert),
            connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
            read_timeout: Some(DEFAULT_READ_TIMEOUT),
            write_timeout: Some(DEFAULT_WRITE_TIMEOUT),
            accept_invalid_certs: false,
            auth_info: AuthInfo {
                token_file: Some(incluster_config::token_file()),
                ..Default::default()
            },
            disable_compression: false,
            proxy_url: None,
            tls_server_name: None,
            headers: Vec::new(),
        })
    }

    /// Create configuration from the default local config file
    ///
    /// This will respect the `$KUBECONFIG` evar, but otherwise default to `~/.kube/config`.
    /// You can also customize what context/cluster/user you want to use here,
    /// but it will default to the current-context.
    pub async fn from_kubeconfig(options: &KubeConfigOptions) -> Result<Self, KubeconfigError> {
        let loader = ConfigLoader::new_from_options(options).await?;
        Self::new_from_loader(loader).await
    }

    /// Create configuration from a [`Kubeconfig`] struct
    ///
    /// This bypasses kube's normal config parsing to obtain custom functionality.
    pub async fn from_custom_kubeconfig(
        kubeconfig: Kubeconfig,
        options: &KubeConfigOptions,
    ) -> Result<Self, KubeconfigError> {
        let loader = ConfigLoader::new_from_kubeconfig(kubeconfig, options).await?;
        Self::new_from_loader(loader).await
    }

    async fn new_from_loader(loader: ConfigLoader) -> Result<Self, KubeconfigError> {
        let cluster_url = loader
            .cluster
            .server
            .clone()
            .ok_or(KubeconfigError::MissingClusterUrl)?
            .parse::<http::Uri>()
            .map_err(KubeconfigError::ParseClusterUrl)?;

        let default_namespace = loader
            .current_context
            .namespace
            .clone()
            .unwrap_or_else(|| String::from("default"));

        let accept_invalid_certs = loader.cluster.insecure_skip_tls_verify.unwrap_or(false);
        let disable_compression = loader.cluster.disable_compression.unwrap_or(false);

        let mut root_cert = None;

        if let Some(ca_bundle) = loader.ca_bundle()? {
            root_cert = Some(ca_bundle);
        }

        Ok(Self {
            cluster_url,
            default_namespace,
            root_cert,
            connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
            read_timeout: Some(DEFAULT_READ_TIMEOUT),
            write_timeout: Some(DEFAULT_WRITE_TIMEOUT),
            accept_invalid_certs,
            disable_compression,
            proxy_url: loader.proxy_url()?,
            auth_info: loader.user,
            tls_server_name: loader.cluster.tls_server_name,
            headers: Vec::new(),
        })
    }

    /// Override configuration based on environment variables
    ///
    /// This is only intended for use as a debugging aid, and the specific variables and their behaviour
    /// should **not** be considered stable across releases.
    ///
    /// Currently, the following overrides are supported:
    ///
    /// - `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`
    /// - `KUBE_RS_DEBUG_IMPERSONATE_GROUP`: A Kubernetes group to impersonate, multiple groups may be specified by separating them with commas
    /// - `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`
    pub fn apply_debug_overrides(&mut self) {
        // Log these overrides loudly, to emphasize that this is only a debugging aid, and should not be relied upon in production
        if let Ok(impersonate_user) = std::env::var("KUBE_RS_DEBUG_IMPERSONATE_USER") {
            tracing::warn!(?impersonate_user, "impersonating user");
            self.auth_info.impersonate = Some(impersonate_user);
        }
        if let Ok(impersonate_groups) = std::env::var("KUBE_RS_DEBUG_IMPERSONATE_GROUP") {
            let impersonate_groups = impersonate_groups.split(',').map(str::to_string).collect();
            tracing::warn!(?impersonate_groups, "impersonating groups");
            self.auth_info.impersonate_groups = Some(impersonate_groups);
        }
        if let Ok(url) = std::env::var("KUBE_RS_DEBUG_OVERRIDE_URL") {
            tracing::warn!(?url, "overriding cluster URL");
            match url.parse() {
                Ok(uri) => {
                    self.cluster_url = uri;
                }
                Err(err) => {
                    tracing::warn!(
                        ?url,
                        error = &err as &dyn std::error::Error,
                        "failed to parse override cluster URL, ignoring"
                    );
                }
            }
        }
    }

    /// Client certificate and private key in PEM.
    pub(crate) fn identity_pem(&self) -> Option<Vec<u8>> {
        self.auth_info.identity_pem().ok()
    }
}

fn certs(data: &[u8]) -> Result<Vec<Vec<u8>>, pem::PemError> {
    Ok(pem::parse_many(data)?
        .into_iter()
        .filter_map(|p| {
            if p.tag() == "CERTIFICATE" {
                Some(p.into_contents())
            } else {
                None
            }
        })
        .collect::<Vec<_>>())
}

// https://github.com/kube-rs/kube/issues/146#issuecomment-590924397
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(295);
const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(295);

// Expose raw config structs
pub use file_config::{
    AuthInfo, AuthProviderConfig, Cluster, Context, ExecAuthCluster, ExecConfig, ExecInteractiveMode,
    Kubeconfig, NamedAuthInfo, NamedCluster, NamedContext, NamedExtension, Preferences,
};

#[cfg(test)]
mod tests {
    #[cfg(not(feature = "client"))] // want to ensure this works without client features
    #[tokio::test]
    async fn config_loading_on_small_feature_set() {
        use super::Config;
        let cfgraw = r#"
        apiVersion: v1
        clusters:
        - cluster:
            certificate-authority-data: aGVsbG8K
            server: https://0.0.0.0:6443
          name: k3d-test
        contexts:
        - context:
            cluster: k3d-test
            user: admin@k3d-test
          name: k3d-test
        current-context: k3d-test
        kind: Config
        preferences: {}
        users:
        - name: admin@k3d-test
          user:
            client-certificate-data: aGVsbG8K
            client-key-data: aGVsbG8K
        "#;
        let file = tempfile::NamedTempFile::new().expect("create config tempfile");
        std::fs::write(file.path(), cfgraw).unwrap();
        std::env::set_var("KUBECONFIG", file.path());
        let kubeconfig = Config::infer().await.unwrap();
        assert_eq!(kubeconfig.cluster_url, "https://0.0.0.0:6443/");
    }
}