Skip to main content

kube_client/config/
file_config.rs

1use std::{
2    collections::{BTreeMap, HashMap},
3    fs, io,
4    path::{Path, PathBuf},
5};
6
7use secrecy::{ExposeSecret, SecretString};
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use super::{KubeconfigError, LoadDataError};
11
12/// [`CLUSTER_EXTENSION_KEY`] is reserved in the cluster extensions list for exec plugin config.
13const CLUSTER_EXTENSION_KEY: &str = "client.authentication.k8s.io/exec";
14
15/// [`Kubeconfig`] represents information on how to connect to a remote Kubernetes cluster
16///
17/// Stored in `~/.kube/config` by default, but can be distributed across multiple paths in passed through `KUBECONFIG`.
18/// An analogue of the [config type from client-go](https://github.com/kubernetes/client-go/blob/7697067af71046b18e03dbda04e01a5bb17f9809/tools/clientcmd/api/types.go).
19///
20/// This type (and its children) are exposed primarily for convenience.
21///
22/// [`Config`][crate::Config] is the __intended__ developer interface to help create a [`Client`][crate::Client],
23/// and this will handle the difference between in-cluster deployment and local development.
24#[derive(Clone, Debug, Serialize, Deserialize, Default)]
25#[cfg_attr(test, derive(PartialEq))]
26pub struct Kubeconfig {
27    /// General information to be use for cli interactions
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub preferences: Option<Preferences>,
30    /// Referenceable names to cluster configs
31    #[serde(default, deserialize_with = "deserialize_null_as_default")]
32    pub clusters: Vec<NamedCluster>,
33    /// Referenceable names to user configs
34    #[serde(rename = "users")]
35    #[serde(default, deserialize_with = "deserialize_null_as_default")]
36    pub auth_infos: Vec<NamedAuthInfo>,
37    /// Referenceable names to context configs
38    #[serde(default, deserialize_with = "deserialize_null_as_default")]
39    pub contexts: Vec<NamedContext>,
40    /// The name of the context that you would like to use by default
41    #[serde(rename = "current-context")]
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub current_context: Option<String>,
44    /// Additional information for extenders so that reads and writes don't clobber unknown fields.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub extensions: Option<Vec<NamedExtension>>,
47
48    // legacy fields TODO: remove
49    /// Legacy field from TypeMeta
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub kind: Option<String>,
52    /// Legacy field from TypeMeta
53    #[serde(rename = "apiVersion")]
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub api_version: Option<String>,
56
57    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
58    ///
59    /// If you are relying on this for standard fields present in upstream client-go,
60    /// please consider submitting a PR to add them as typed fields.
61    #[serde(flatten)]
62    pub other: BTreeMap<String, serde_json::Value>,
63}
64
65/// Preferences stores extensions for cli.
66#[derive(Clone, Debug, Serialize, Deserialize, Default)]
67#[cfg_attr(test, derive(PartialEq, Eq))]
68pub struct Preferences {
69    /// Enable colors
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub colors: Option<bool>,
72    /// Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub extensions: Option<Vec<NamedExtension>>,
75
76    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
77    ///
78    /// If you are relying on this for standard fields present in upstream client-go,
79    /// please consider submitting a PR to add them as typed fields.
80    #[serde(flatten)]
81    pub other: BTreeMap<String, serde_json::Value>,
82}
83
84/// NamedExtension associates name with extension.
85#[derive(Clone, Debug, Serialize, Deserialize)]
86#[cfg_attr(test, derive(PartialEq, Eq))]
87pub struct NamedExtension {
88    /// Name of extension
89    pub name: String,
90    /// Additional information for extenders so that reads and writes don't clobber unknown fields
91    pub extension: serde_json::Value,
92}
93
94/// NamedCluster associates name with cluster.
95#[derive(Clone, Debug, Serialize, Deserialize, Default)]
96#[cfg_attr(test, derive(PartialEq, Eq))]
97pub struct NamedCluster {
98    /// Name of cluster
99    pub name: String,
100    /// Information about how to communicate with a kubernetes cluster
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub cluster: Option<Cluster>,
103
104    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
105    ///
106    /// If you are relying on this for standard fields present in upstream client-go,
107    /// please consider submitting a PR to add them as typed fields.
108    #[serde(flatten)]
109    pub other: BTreeMap<String, serde_json::Value>,
110}
111
112/// Cluster stores information to connect Kubernetes cluster.
113#[derive(Clone, Debug, Serialize, Deserialize, Default)]
114#[cfg_attr(test, derive(PartialEq, Eq))]
115pub struct Cluster {
116    /// The address of the kubernetes cluster (https://hostname:port).
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub server: Option<String>,
119    /// Skips the validity check for the server's certificate. This will make your HTTPS connections insecure.
120    #[serde(rename = "insecure-skip-tls-verify")]
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub insecure_skip_tls_verify: Option<bool>,
123    /// The path to a cert file for the certificate authority.
124    #[serde(rename = "certificate-authority")]
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub certificate_authority: Option<String>,
127    /// PEM-encoded certificate authority certificates. Overrides `certificate_authority`
128    #[serde(rename = "certificate-authority-data")]
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub certificate_authority_data: Option<String>,
131    /// URL to the proxy to be used for all requests.
132    #[serde(rename = "proxy-url")]
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub proxy_url: Option<String>,
135    /// Compression is enabled by default with the `gzip` feature.
136    /// `disable_compression` allows client to opt-out of response compression for all requests to the server.
137    /// This is useful to speed up requests (specifically lists) when client-server network bandwidth is ample,
138    /// by saving time on compression (server-side) and decompression (client-side):
139    /// https://github.com/kubernetes/kubernetes/issues/112296
140    #[serde(rename = "disable-compression")]
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub disable_compression: Option<bool>,
143    /// Name used to check server certificate.
144    ///
145    /// If `tls_server_name` is `None`, the hostname used to contact the server is used.
146    #[serde(rename = "tls-server-name")]
147    #[serde(skip_serializing_if = "Option::is_none")]
148    pub tls_server_name: Option<String>,
149    /// Additional information for extenders so that reads and writes don't clobber unknown fields
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub extensions: Option<Vec<NamedExtension>>,
152
153    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
154    ///
155    /// If you are relying on this for standard fields present in upstream client-go,
156    /// please consider submitting a PR to add them as typed fields.
157    #[serde(flatten)]
158    pub other: BTreeMap<String, serde_json::Value>,
159}
160
161/// NamedAuthInfo associates name with authentication.
162#[derive(Clone, Debug, Serialize, Deserialize, Default)]
163#[cfg_attr(test, derive(PartialEq))]
164pub struct NamedAuthInfo {
165    /// Name of the user
166    pub name: String,
167    /// Information that describes identity of the user
168    #[serde(rename = "user")]
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub auth_info: Option<AuthInfo>,
171
172    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
173    ///
174    /// If you are relying on this for standard fields present in upstream client-go,
175    /// please consider submitting a PR to add them as typed fields.
176    #[serde(flatten)]
177    pub other: BTreeMap<String, serde_json::Value>,
178}
179
180fn serialize_secretstring<S>(pw: &Option<SecretString>, serializer: S) -> Result<S::Ok, S::Error>
181where
182    S: Serializer,
183{
184    match pw {
185        Some(secret) => serializer.serialize_str(secret.expose_secret()),
186        None => serializer.serialize_none(),
187    }
188}
189
190fn deserialize_secretstring<'de, D>(deserializer: D) -> Result<Option<SecretString>, D::Error>
191where
192    D: Deserializer<'de>,
193{
194    match Option::<String>::deserialize(deserializer) {
195        Ok(Some(secret)) => Ok(Some(SecretString::new(secret.into()))),
196        Ok(None) => Ok(None),
197        Err(e) => Err(e),
198    }
199}
200
201fn deserialize_null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
202where
203    T: Default + Deserialize<'de>,
204    D: Deserializer<'de>,
205{
206    let opt = Option::deserialize(deserializer)?;
207    Ok(opt.unwrap_or_default())
208}
209
210/// AuthInfo stores information to tell cluster who you are.
211#[derive(Clone, Debug, Serialize, Deserialize, Default)]
212pub struct AuthInfo {
213    /// The username for basic authentication to the kubernetes cluster.
214    #[serde(skip_serializing_if = "Option::is_none")]
215    pub username: Option<String>,
216    /// The password for basic authentication to the kubernetes cluster.
217    #[serde(skip_serializing_if = "Option::is_none", default)]
218    #[serde(
219        serialize_with = "serialize_secretstring",
220        deserialize_with = "deserialize_secretstring"
221    )]
222    pub password: Option<SecretString>,
223
224    /// The bearer token for authentication to the kubernetes cluster.
225    #[serde(skip_serializing_if = "Option::is_none", default)]
226    #[serde(
227        serialize_with = "serialize_secretstring",
228        deserialize_with = "deserialize_secretstring"
229    )]
230    pub token: Option<SecretString>,
231    /// Pointer to a file that contains a bearer token (as described above). If both `token` and token_file` are present, `token` takes precedence.
232    #[serde(rename = "tokenFile")]
233    #[serde(skip_serializing_if = "Option::is_none")]
234    pub token_file: Option<String>,
235
236    /// Path to a client cert file for TLS.
237    #[serde(rename = "client-certificate")]
238    #[serde(skip_serializing_if = "Option::is_none")]
239    pub client_certificate: Option<String>,
240    /// PEM-encoded data from a client cert file for TLS. Overrides `client_certificate`
241    /// this key should be base64 encoded instead of the decode string data
242    #[serde(rename = "client-certificate-data")]
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub client_certificate_data: Option<String>,
245
246    /// Path to a client key file for TLS.
247    #[serde(rename = "client-key")]
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub client_key: Option<String>,
250    /// PEM-encoded data from a client key file for TLS. Overrides `client_key`
251    /// this key should be base64 encoded instead of the decode string data
252    #[serde(rename = "client-key-data")]
253    #[serde(skip_serializing_if = "Option::is_none", default)]
254    #[serde(
255        serialize_with = "serialize_secretstring",
256        deserialize_with = "deserialize_secretstring"
257    )]
258    pub client_key_data: Option<SecretString>,
259
260    /// The username to act-as.
261    #[serde(rename = "as")]
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub impersonate: Option<String>,
264    /// The uid to impersonate.
265    #[serde(rename = "as-uid")]
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub impersonate_uid: Option<String>,
268    /// The groups to imperonate.
269    #[serde(rename = "as-groups")]
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub impersonate_groups: Option<Vec<String>>,
272    /// Additional information for impersonated user.
273    #[serde(rename = "as-user-extra")]
274    #[serde(skip_serializing_if = "Option::is_none")]
275    pub impersonate_user_extra: Option<HashMap<String, Vec<String>>>,
276
277    /// Additional information for extenders so that reads and writes don't clobber unknown fields.
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub extensions: Option<Vec<NamedExtension>>,
280
281    /// Specifies a custom authentication plugin for the kubernetes cluster.
282    #[serde(rename = "auth-provider")]
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub auth_provider: Option<AuthProviderConfig>,
285
286    /// Specifies a custom exec-based authentication plugin for the kubernetes cluster.
287    #[serde(skip_serializing_if = "Option::is_none")]
288    pub exec: Option<ExecConfig>,
289
290    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
291    ///
292    /// If you are relying on this for standard fields present in upstream client-go,
293    /// please consider submitting a PR to add them as typed fields.
294    #[serde(flatten)]
295    pub other: BTreeMap<String, serde_json::Value>,
296}
297
298#[cfg(test)]
299impl PartialEq for AuthInfo {
300    fn eq(&self, other: &Self) -> bool {
301        serde_json::to_value(self).unwrap() == serde_json::to_value(other).unwrap()
302    }
303}
304
305/// AuthProviderConfig stores auth for specified cloud provider.
306#[derive(Clone, Debug, Serialize, Deserialize, Default)]
307#[cfg_attr(test, derive(PartialEq, Eq))]
308pub struct AuthProviderConfig {
309    /// Name of the auth provider
310    pub name: String,
311    /// Auth provider configuration
312    #[serde(default)]
313    pub config: HashMap<String, String>,
314
315    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
316    ///
317    /// If you are relying on this for standard fields present in upstream client-go,
318    /// please consider submitting a PR to add them as typed fields.
319    #[serde(flatten)]
320    pub other: BTreeMap<String, serde_json::Value>,
321}
322
323/// ExecConfig stores credential-plugin configuration.
324#[derive(Clone, Debug, Serialize, Deserialize, Default)]
325#[cfg_attr(test, derive(PartialEq, Eq))]
326pub struct ExecConfig {
327    /// Preferred input version of the ExecInfo.
328    ///
329    /// The returned ExecCredentials MUST use the same encoding version as the input.
330    #[serde(rename = "apiVersion")]
331    #[serde(skip_serializing_if = "Option::is_none")]
332    pub api_version: Option<String>,
333    /// Command to execute.
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub command: Option<String>,
336    /// Arguments to pass to the command when executing it.
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub args: Option<Vec<String>>,
339    /// Env defines additional environment variables to expose to the process.
340    ///
341    /// TODO: These are unioned with the host's environment, as well as variables client-go uses to pass argument to the plugin.
342    #[serde(skip_serializing_if = "Option::is_none")]
343    pub env: Option<Vec<HashMap<String, String>>>,
344    /// Specifies which environment variables the host should avoid passing to the auth plugin.
345    ///
346    /// This does currently not exist upstream and cannot be specified on disk.
347    /// It has been suggested in client-go via <https://github.com/kubernetes/client-go/issues/1177>
348    #[serde(skip)]
349    pub drop_env: Option<Vec<String>>,
350
351    /// This text is shown to the user when the executable doesn't seem to be present.
352    /// For example, `brew install foo-cli` might be a good InstallHint for foo-cli on Mac OS systems.
353    #[serde(rename = "installHint")]
354    #[serde(skip_serializing_if = "Option::is_none")]
355    pub install_hint: Option<String>,
356
357    /// Interactive mode of the auth plugins
358    #[serde(rename = "interactiveMode")]
359    #[serde(skip_serializing_if = "Option::is_none")]
360    pub interactive_mode: Option<ExecInteractiveMode>,
361
362    /// ProvideClusterInfo determines whether or not to provide cluster information,
363    /// which could potentially contain very large CA data, to this exec plugin as a
364    /// part of the KUBERNETES_EXEC_INFO environment variable. By default, it is set
365    /// to false. Package k8s.io/client-go/tools/auth/exec provides helper methods for
366    /// reading this environment variable.
367    #[serde(default, rename = "provideClusterInfo")]
368    pub provide_cluster_info: bool,
369
370    /// Cluster information to pass to the plugin.
371    /// Should be used only when `provide_cluster_info` is True.
372    #[serde(skip)]
373    pub cluster: Option<ExecAuthCluster>,
374
375    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
376    ///
377    /// If you are relying on this for standard fields present in upstream client-go,
378    /// please consider submitting a PR to add them as typed fields.
379    #[serde(flatten)]
380    pub other: BTreeMap<String, serde_json::Value>,
381}
382
383/// ExecInteractiveMode define the interactity of the child process
384#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
385#[cfg_attr(test, derive(Eq))]
386pub enum ExecInteractiveMode {
387    /// Never get interactive
388    Never,
389    /// If available et interactive
390    IfAvailable,
391    /// Alwayes get interactive
392    Always,
393}
394
395/// NamedContext associates name with context.
396#[derive(Clone, Debug, Serialize, Deserialize, Default)]
397#[cfg_attr(test, derive(PartialEq, Eq))]
398pub struct NamedContext {
399    /// Name of the context
400    pub name: String,
401    /// Associations for the context
402    #[serde(skip_serializing_if = "Option::is_none")]
403    pub context: Option<Context>,
404
405    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
406    ///
407    /// If you are relying on this for standard fields present in upstream client-go,
408    /// please consider submitting a PR to add them as typed fields.
409    #[serde(flatten)]
410    pub other: BTreeMap<String, serde_json::Value>,
411}
412
413/// Context stores tuple of cluster and user information.
414#[derive(Clone, Debug, Serialize, Deserialize, Default)]
415#[cfg_attr(test, derive(PartialEq, Eq))]
416pub struct Context {
417    /// Name of the cluster for this context
418    pub cluster: String,
419    /// Name of the `AuthInfo` for this context
420    pub user: Option<String>,
421    /// The default namespace to use on unspecified requests
422    #[serde(skip_serializing_if = "Option::is_none")]
423    pub namespace: Option<String>,
424    /// Additional information for extenders so that reads and writes don't clobber unknown fields
425    #[serde(skip_serializing_if = "Option::is_none")]
426    pub extensions: Option<Vec<NamedExtension>>,
427
428    /// Additional fields not explicitly modeled, preserved for round-trip serialization.
429    ///
430    /// If you are relying on this for standard fields present in upstream client-go,
431    /// please consider submitting a PR to add them as typed fields.
432    #[serde(flatten)]
433    pub other: BTreeMap<String, serde_json::Value>,
434}
435
436const KUBECONFIG: &str = "KUBECONFIG";
437
438/// Some helpers on the raw Config object are exposed for people needing to parse it
439impl Kubeconfig {
440    /// Read a Config from an arbitrary location
441    pub fn read_from<P: AsRef<Path>>(path: P) -> Result<Kubeconfig, KubeconfigError> {
442        let data =
443            read_path(&path).map_err(|source| KubeconfigError::ReadConfig(source, path.as_ref().into()))?;
444
445        // Remap all files we read to absolute paths.
446        let mut merged_docs = None;
447        for mut config in kubeconfig_from_yaml(&data)? {
448            if let Some(dir) = path.as_ref().parent() {
449                for named in config.clusters.iter_mut() {
450                    if let Some(cluster) = &mut named.cluster
451                        && let Some(path) = &cluster.certificate_authority
452                        && let Some(abs_path) = to_absolute(dir, path)
453                    {
454                        cluster.certificate_authority = Some(abs_path);
455                    }
456                }
457                for named in config.auth_infos.iter_mut() {
458                    if let Some(auth_info) = &mut named.auth_info {
459                        if let Some(path) = &auth_info.client_certificate
460                            && let Some(abs_path) = to_absolute(dir, path)
461                        {
462                            auth_info.client_certificate = Some(abs_path);
463                        }
464                        if let Some(path) = &auth_info.client_key
465                            && let Some(abs_path) = to_absolute(dir, path)
466                        {
467                            auth_info.client_key = Some(abs_path);
468                        }
469                        if let Some(path) = &auth_info.token_file
470                            && let Some(abs_path) = to_absolute(dir, path)
471                        {
472                            auth_info.token_file = Some(abs_path);
473                        }
474                        // Exec plugin commands can also be relative paths. Match
475                        // client-go (`GetAuthInfoFileReferences`) and only resolve
476                        // them when they contain a path separator, so bare `PATH`
477                        // lookups like `aws` are left untouched.
478                        if let Some(exec) = &mut auth_info.exec
479                            && let Some(command) = &exec.command
480                            && command.contains(std::path::MAIN_SEPARATOR)
481                            && let Some(abs_path) = to_absolute(dir, command)
482                        {
483                            exec.command = Some(abs_path);
484                        }
485                    }
486                }
487            }
488            if let Some(c) = merged_docs {
489                merged_docs = Some(Kubeconfig::merge(c, config)?);
490            } else {
491                merged_docs = Some(config);
492            }
493        }
494        // Empty file defaults to an empty Kubeconfig
495        Ok(merged_docs.unwrap_or_default())
496    }
497
498    /// Read a Config from an arbitrary YAML string
499    ///
500    /// This is preferable to using serde_saphyr::from_str() because it will correctly
501    /// parse multi-document YAML text and merge them into a single `Kubeconfig`
502    pub fn from_yaml(text: &str) -> Result<Kubeconfig, KubeconfigError> {
503        kubeconfig_from_yaml(text)?
504            .into_iter()
505            .try_fold(Kubeconfig::default(), Kubeconfig::merge)
506    }
507
508    /// Read a Config from `KUBECONFIG` or the the default location.
509    pub fn read() -> Result<Kubeconfig, KubeconfigError> {
510        match Self::from_env()? {
511            Some(config) => Ok(config),
512            None => Self::read_from(default_kube_path().ok_or(KubeconfigError::FindPath)?),
513        }
514    }
515
516    /// Create `Kubeconfig` from `KUBECONFIG` environment variable.
517    /// Supports list of files to be merged.
518    ///
519    /// # Panics
520    ///
521    /// Panics if `KUBECONFIG` value contains the NUL character.
522    pub fn from_env() -> Result<Option<Self>, KubeconfigError> {
523        match std::env::var_os(KUBECONFIG) {
524            Some(value) => {
525                let paths = std::env::split_paths(&value)
526                    .filter(|p| !p.as_os_str().is_empty())
527                    .collect::<Vec<_>>();
528                if paths.is_empty() {
529                    return Ok(None);
530                }
531
532                let merged = paths.iter().try_fold(Kubeconfig::default(), |m, p| {
533                    Kubeconfig::read_from(p).and_then(|c| m.merge(c))
534                })?;
535                Ok(Some(merged))
536            }
537
538            None => Ok(None),
539        }
540    }
541
542    /// Merge kubeconfig file according to the rules described in
543    /// <https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#merging-kubeconfig-files>
544    ///
545    /// > Merge the files listed in the `KUBECONFIG` environment variable according to these rules:
546    /// >
547    /// > - Ignore empty filenames.
548    /// > - Produce errors for files with content that cannot be deserialized.
549    /// > - The first file to set a particular value or map key wins.
550    /// > - Never change the value or map key.
551    /// >   Example: Preserve the context of the first file to set `current-context`.
552    /// >   Example: If two files specify a `red-user`, use only values from the first file's `red-user`.
553    /// >            Even if the second file has non-conflicting entries under `red-user`, discard them.
554    pub fn merge(mut self, next: Kubeconfig) -> Result<Self, KubeconfigError> {
555        if self.kind.is_some() && next.kind.is_some() && self.kind != next.kind {
556            return Err(KubeconfigError::KindMismatch);
557        }
558        if self.api_version.is_some() && next.api_version.is_some() && self.api_version != next.api_version {
559            return Err(KubeconfigError::ApiVersionMismatch);
560        }
561
562        self.kind = self.kind.or(next.kind);
563        self.api_version = self.api_version.or(next.api_version);
564        self.preferences = self.preferences.or(next.preferences);
565        append_new_named(&mut self.clusters, next.clusters, |x| &x.name);
566        append_new_named(&mut self.auth_infos, next.auth_infos, |x| &x.name);
567        append_new_named(&mut self.contexts, next.contexts, |x| &x.name);
568        self.current_context = self.current_context.or(next.current_context);
569        self.extensions = self.extensions.or(next.extensions);
570        // Merge extra fields: first-wins per key
571        for (key, value) in next.other {
572            self.other.entry(key).or_insert(value);
573        }
574        Ok(self)
575    }
576}
577
578fn kubeconfig_from_yaml(text: &str) -> Result<Vec<Kubeconfig>, KubeconfigError> {
579    serde_saphyr::from_multiple(text).map_err(|e| KubeconfigError::Parse(Box::new(e)))
580}
581
582fn append_new_named<T, F>(base: &mut Vec<T>, next: Vec<T>, f: F)
583where
584    F: Fn(&T) -> &String,
585{
586    use std::collections::HashSet;
587    base.extend({
588        let existing = base.iter().map(&f).collect::<HashSet<_>>();
589        next.into_iter()
590            .filter(|x| !existing.contains(f(x)))
591            .collect::<Vec<_>>()
592    });
593}
594
595fn read_path<P: AsRef<Path>>(path: P) -> io::Result<String> {
596    let bytes = fs::read(&path)?;
597    match bytes.as_slice() {
598        [0xFF, 0xFE, ..] => {
599            let utf16_data: Vec<u16> = bytes[2..]
600                .chunks(2)
601                .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
602                .collect();
603            String::from_utf16(&utf16_data)
604                .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-16 LE"))
605        }
606        [0xFE, 0xFF, ..] => {
607            let utf16_data: Vec<u16> = bytes[2..]
608                .chunks(2)
609                .map(|chunk| u16::from_be_bytes([chunk[0], chunk[1]]))
610                .collect();
611            String::from_utf16(&utf16_data)
612                .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-16 BE"))
613        }
614        [0xEF, 0xBB, 0xBF, ..] => String::from_utf8(bytes[3..].to_vec())
615            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8 BOM")),
616        _ => {
617            String::from_utf8(bytes).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"))
618        }
619    }
620}
621
622fn to_absolute(dir: &Path, file: &str) -> Option<String> {
623    let path = Path::new(&file);
624    if path.is_relative() {
625        dir.join(path).to_str().map(str::to_owned)
626    } else {
627        None
628    }
629}
630
631impl Cluster {
632    pub(crate) fn load_certificate_authority(&self) -> Result<Option<Vec<u8>>, KubeconfigError> {
633        if self.certificate_authority.is_none() && self.certificate_authority_data.is_none() {
634            return Ok(None);
635        }
636
637        let ca = load_from_base64_or_file(
638            &self.certificate_authority_data.as_deref(),
639            &self.certificate_authority,
640        )
641        .map_err(KubeconfigError::LoadCertificateAuthority)?;
642        Ok(ca)
643    }
644}
645
646impl AuthInfo {
647    pub(crate) fn identity_pem(&self) -> Result<Option<Vec<u8>>, KubeconfigError> {
648        let client_cert = self.load_client_certificate()?;
649        let client_key = self.load_client_key()?;
650
651        match (client_cert, client_key) {
652            (None, None) => Ok(None),
653
654            (Some(_), None) => Err(KubeconfigError::LoadClientKey(LoadDataError::NoBase64DataOrFile)),
655
656            (None, Some(_)) => Err(KubeconfigError::LoadClientCertificate(
657                LoadDataError::NoBase64DataOrFile,
658            )),
659
660            (Some(cert), Some(mut key)) => {
661                key.extend_from_slice(&cert);
662                Ok(Some(key))
663            }
664        }
665    }
666
667    pub(crate) fn load_client_certificate(&self) -> Result<Option<Vec<u8>>, KubeconfigError> {
668        // TODO Shouldn't error when `self.client_certificate_data.is_none() && self.client_certificate.is_none()`
669
670        load_from_base64_or_file(&self.client_certificate_data.as_deref(), &self.client_certificate)
671            .map_err(KubeconfigError::LoadClientCertificate)
672    }
673
674    pub(crate) fn load_client_key(&self) -> Result<Option<Vec<u8>>, KubeconfigError> {
675        // TODO Shouldn't error when `self.client_key_data.is_none() && self.client_key.is_none()`
676
677        load_from_base64_or_file(
678            &self.client_key_data.as_ref().map(|secret| secret.expose_secret()),
679            &self.client_key,
680        )
681        .map_err(KubeconfigError::LoadClientKey)
682    }
683}
684
685/// Connection information for auth plugins that have `provideClusterInfo` enabled.
686///
687/// This is a copy of [`Cluster`] with certificate_authority passed as bytes without the path.
688/// Taken from [clientauthentication/types.go#Cluster](https://github.com/kubernetes/client-go/blob/477cb782cf024bc70b7239f0dca91e5774811950/pkg/apis/clientauthentication/types.go#L73-L129)
689#[derive(Clone, Debug, Serialize, Deserialize, Default)]
690#[serde(rename_all = "kebab-case")]
691#[cfg_attr(test, derive(PartialEq, Eq))]
692pub struct ExecAuthCluster {
693    /// The address of the kubernetes cluster (https://hostname:port).
694    #[serde(skip_serializing_if = "Option::is_none")]
695    pub server: Option<String>,
696    /// Skips the validity check for the server's certificate. This will make your HTTPS connections insecure.
697    #[serde(skip_serializing_if = "Option::is_none")]
698    pub insecure_skip_tls_verify: Option<bool>,
699    /// PEM-encoded certificate authority certificates. Overrides `certificate_authority`
700    #[serde(default, skip_serializing_if = "Option::is_none")]
701    #[serde(with = "base64serde")]
702    pub certificate_authority_data: Option<Vec<u8>>,
703    /// URL to the proxy to be used for all requests.
704    #[serde(skip_serializing_if = "Option::is_none")]
705    pub proxy_url: Option<String>,
706    /// Name used to check server certificate.
707    ///
708    /// If `tls_server_name` is `None`, the hostname used to contact the server is used.
709    #[serde(skip_serializing_if = "Option::is_none")]
710    pub tls_server_name: Option<String>,
711    /// This can be anything
712    #[serde(skip_serializing_if = "Option::is_none")]
713    pub config: Option<serde_json::Value>,
714}
715
716impl TryFrom<&Cluster> for ExecAuthCluster {
717    type Error = KubeconfigError;
718
719    fn try_from(cluster: &crate::config::Cluster) -> Result<Self, KubeconfigError> {
720        let certificate_authority_data = cluster.load_certificate_authority()?;
721        Ok(Self {
722            server: cluster.server.clone(),
723            insecure_skip_tls_verify: cluster.insecure_skip_tls_verify,
724            certificate_authority_data,
725            proxy_url: cluster.proxy_url.clone(),
726            tls_server_name: cluster.tls_server_name.clone(),
727            config: cluster.extensions.as_ref().and_then(|extensions| {
728                extensions
729                    .iter()
730                    .find(|extension| extension.name == CLUSTER_EXTENSION_KEY)
731                    .map(|extension| extension.extension.clone())
732            }),
733        })
734    }
735}
736
737fn load_from_base64_or_file<P: AsRef<Path>>(
738    value: &Option<&str>,
739    file: &Option<P>,
740) -> Result<Option<Vec<u8>>, LoadDataError> {
741    let data = value
742        .map(load_from_base64)
743        .or_else(|| file.as_ref().map(load_from_file));
744    match data {
745        Some(data) => Ok(Some(ensure_trailing_newline(data?))),
746        None => Ok(None),
747    }
748}
749
750fn load_from_base64(value: &str) -> Result<Vec<u8>, LoadDataError> {
751    use base64::Engine;
752    base64::engine::general_purpose::STANDARD
753        .decode(value)
754        .map_err(LoadDataError::DecodeBase64)
755}
756
757fn load_from_file<P: AsRef<Path>>(file: &P) -> Result<Vec<u8>, LoadDataError> {
758    fs::read(file).map_err(|source| LoadDataError::ReadFile(source, file.as_ref().into()))
759}
760
761// Ensure there is a trailing newline in the blob
762// Don't bother if the blob is empty
763fn ensure_trailing_newline(mut data: Vec<u8>) -> Vec<u8> {
764    if data.last().map(|end| *end != b'\n').unwrap_or(false) {
765        data.push(b'\n');
766    }
767    data
768}
769
770/// Returns kubeconfig path from `$HOME/.kube/config`.
771fn default_kube_path() -> Option<PathBuf> {
772    // Before Rust 1.85.0, `home_dir` would return wrong results on Windows, usage of the crate
773    // `home` was encouraged (and is what kube-rs did).
774    // Rust 1.85.0 fixed the problem (https://doc.rust-lang.org/1.85.0/std/env/fn.home_dir.html),
775    // Rust 1.87.0 removed the function deprecation.
776    // As the MSRV was bumped to 1.85.0 we are safe to use the fixed std function.
777    std::env::home_dir().map(|h| h.join(".kube").join("config"))
778}
779
780mod base64serde {
781    use base64::Engine;
782    use serde::{Deserialize, Deserializer, Serialize, Serializer};
783
784    pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
785        match v {
786            Some(v) => {
787                let encoded = base64::engine::general_purpose::STANDARD.encode(v);
788                String::serialize(&encoded, s)
789            }
790            None => <Option<String>>::serialize(&None, s),
791        }
792    }
793
794    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
795        let data = <Option<String>>::deserialize(d)?;
796        match data {
797            Some(data) => Ok(Some(
798                base64::engine::general_purpose::STANDARD
799                    .decode(data.as_bytes())
800                    .map_err(serde::de::Error::custom)?,
801            )),
802            None => Ok(None),
803        }
804    }
805}
806
807#[cfg(test)]
808mod tests {
809    use crate::config::file_loader::ConfigLoader;
810
811    use super::*;
812    use serde_json::{Value, json};
813
814    #[test]
815    fn kubeconfig_merge() {
816        let kubeconfig1 = Kubeconfig {
817            current_context: Some("default".into()),
818            auth_infos: vec![NamedAuthInfo {
819                name: "red-user".into(),
820                auth_info: Some(AuthInfo {
821                    token: Some(SecretString::new("first-token".into())),
822                    ..Default::default()
823                }),
824                ..Default::default()
825            }],
826            ..Default::default()
827        };
828        let kubeconfig2 = Kubeconfig {
829            current_context: Some("dev".into()),
830            auth_infos: vec![
831                NamedAuthInfo {
832                    name: "red-user".into(),
833                    auth_info: Some(AuthInfo {
834                        token: Some(SecretString::new("second-token".into())),
835                        username: Some("red-user".into()),
836                        ..Default::default()
837                    }),
838                    ..Default::default()
839                },
840                NamedAuthInfo {
841                    name: "green-user".into(),
842                    auth_info: Some(AuthInfo {
843                        token: Some(SecretString::new("new-token".into())),
844                        ..Default::default()
845                    }),
846                    ..Default::default()
847                },
848            ],
849            ..Default::default()
850        };
851
852        let merged = kubeconfig1.merge(kubeconfig2).unwrap();
853        // Preserves first `current_context`
854        assert_eq!(merged.current_context, Some("default".into()));
855        // Auth info with the same name does not overwrite
856        assert_eq!(merged.auth_infos[0].name, "red-user");
857        assert_eq!(
858            merged.auth_infos[0]
859                .auth_info
860                .as_ref()
861                .unwrap()
862                .token
863                .as_ref()
864                .map(|t| t.expose_secret()),
865            Some("first-token")
866        );
867        // Even if it's not conflicting
868        assert_eq!(merged.auth_infos[0].auth_info.as_ref().unwrap().username, None);
869        // New named auth info is appended
870        assert_eq!(merged.auth_infos[1].name, "green-user");
871    }
872
873    #[test]
874    fn kubeconfig_deserialize() {
875        let config_yaml = "apiVersion: v1
876clusters:
877- cluster:
878    certificate-authority-data: LS0t<SNIP>LS0tLQo=
879    server: https://ABCDEF0123456789.gr7.us-west-2.eks.amazonaws.com
880  name: eks
881- cluster:
882    certificate-authority: /home/kevin/.minikube/ca.crt
883    extensions:
884    - extension:
885        last-update: Thu, 18 Feb 2021 16:59:26 PST
886        provider: minikube.sigs.k8s.io
887        version: v1.17.1
888      name: cluster_info
889    server: https://192.168.49.2:8443
890  name: minikube
891contexts:
892- context:
893    cluster: minikube
894    extensions:
895    - extension:
896        last-update: Thu, 18 Feb 2021 16:59:26 PST
897        provider: minikube.sigs.k8s.io
898        version: v1.17.1
899      name: context_info
900    namespace: default
901    user: minikube
902  name: minikube
903- context:
904    cluster: arn:aws:eks:us-west-2:012345678912:cluster/eks
905    user: arn:aws:eks:us-west-2:012345678912:cluster/eks
906  name: eks
907current-context: minikube
908kind: Config
909preferences: {}
910users:
911- name: arn:aws:eks:us-west-2:012345678912:cluster/eks
912  user:
913    exec:
914      apiVersion: client.authentication.k8s.io/v1alpha1
915      args:
916      - --region
917      - us-west-2
918      - eks
919      - get-token
920      - --cluster-name
921      - eks
922      command: aws
923      env: null
924      installHint: Please install aws cli
925      provideClusterInfo: false
926    as: admin
927    as-uid: '12345'
928    as-groups:
929    - group1
930    - group2
931    as-user-extra:
932      scopes:
933      - read
934      - write
935    extensions:
936    - name: authinfo_ext
937      extension:
938        key: value
939- name: minikube
940  user:
941    client-certificate: /home/kevin/.minikube/profiles/minikube/client.crt
942    client-key: /home/kevin/.minikube/profiles/minikube/client.key";
943
944        let config = Kubeconfig::from_yaml(config_yaml).unwrap();
945
946        assert_eq!(config.clusters[0].name, "eks");
947        assert_eq!(config.clusters[1].name, "minikube");
948
949        let cluster1 = config.clusters[1].cluster.as_ref().unwrap();
950        assert_eq!(
951            cluster1.extensions.as_ref().unwrap()[0].extension.get("provider"),
952            Some(&Value::String("minikube.sigs.k8s.io".to_owned()))
953        );
954
955        // Verify new AuthInfo fields (impersonate_uid, impersonate_user_extra, extensions)
956        let auth_info = config.auth_infos[0].auth_info.as_ref().unwrap();
957        assert_eq!(auth_info.impersonate.as_deref(), Some("admin"));
958        assert_eq!(auth_info.impersonate_uid.as_deref(), Some("12345"));
959        assert_eq!(
960            auth_info.impersonate_groups.as_deref(),
961            Some(["group1".to_string(), "group2".to_string()].as_slice())
962        );
963        let extra = auth_info.impersonate_user_extra.as_ref().unwrap();
964        assert_eq!(extra.get("scopes").unwrap(), &vec![
965            "read".to_string(),
966            "write".to_string()
967        ]);
968        let auth_ext = auth_info.extensions.as_ref().unwrap();
969        assert_eq!(auth_ext[0].name, "authinfo_ext");
970
971        // Verify ExecConfig.install_hint
972        let exec = auth_info.exec.as_ref().unwrap();
973        assert_eq!(exec.install_hint.as_deref(), Some("Please install aws cli"));
974    }
975
976    #[test]
977    fn kubeconfig_multi_document_merge() -> Result<(), KubeconfigError> {
978        let config_yaml = r#"---
979apiVersion: v1
980clusters:
981- cluster:
982    certificate-authority-data: aGVsbG8K
983    server: https://0.0.0.0:6443
984  name: k3d-promstack
985contexts:
986- context:
987    cluster: k3d-promstack
988    user: admin@k3d-promstack
989  name: k3d-promstack
990current-context: k3d-promstack
991kind: Config
992preferences: {}
993users:
994- name: admin@k3d-promstack
995  user:
996    client-certificate-data: aGVsbG8K
997    client-key-data: aGVsbG8K
998---
999apiVersion: v1
1000clusters:
1001- cluster:
1002    certificate-authority-data: aGVsbG8K
1003    server: https://0.0.0.0:6443
1004  name: k3d-k3s-default
1005contexts:
1006- context:
1007    cluster: k3d-k3s-default
1008    user: admin@k3d-k3s-default
1009  name: k3d-k3s-default
1010current-context: k3d-k3s-default
1011kind: Config
1012preferences: {}
1013users:
1014- name: admin@k3d-k3s-default
1015  user:
1016    client-certificate-data: aGVsbG8K
1017    client-key-data: aGVsbG8K
1018"#;
1019        let cfg = Kubeconfig::from_yaml(config_yaml)?;
1020
1021        // Ensure we have data from both documents:
1022        assert_eq!(cfg.clusters[0].name, "k3d-promstack");
1023        assert_eq!(cfg.clusters[1].name, "k3d-k3s-default");
1024
1025        Ok(())
1026    }
1027
1028    #[test]
1029    fn kubeconfig_split_sections_merge() -> Result<(), KubeconfigError> {
1030        let config1 = r#"
1031apiVersion: v1
1032clusters:
1033- cluster:
1034    certificate-authority-data: aGVsbG8K
1035    server: https://0.0.0.0:6443
1036  name: k3d-promstack
1037contexts:
1038- context:
1039    cluster: k3d-promstack
1040    user: admin@k3d-promstack
1041  name: k3d-promstack
1042current-context: k3d-promstack
1043kind: Config
1044preferences: {}
1045"#;
1046
1047        let config2 = r#"
1048users:
1049- name: admin@k3d-k3s-default
1050  user:
1051    client-certificate-data: aGVsbG8K
1052    client-key-data: aGVsbG8K
1053"#;
1054
1055        let kubeconfig1 = Kubeconfig::from_yaml(config1)?;
1056        let kubeconfig2 = Kubeconfig::from_yaml(config2)?;
1057        let merged = kubeconfig1.merge(kubeconfig2).unwrap();
1058
1059        // Ensure we have data from both files:
1060        assert_eq!(merged.clusters[0].name, "k3d-promstack");
1061        assert_eq!(merged.contexts[0].name, "k3d-promstack");
1062        assert_eq!(merged.auth_infos[0].name, "admin@k3d-k3s-default");
1063
1064        Ok(())
1065    }
1066
1067    #[test]
1068    fn kubeconfig_from_empty_string() {
1069        let cfg = Kubeconfig::from_yaml("").unwrap();
1070
1071        assert_eq!(cfg, Kubeconfig::default());
1072    }
1073
1074    #[test]
1075    fn authinfo_deserialize_null_secret() {
1076        let authinfo_yaml = r#"
1077username: user
1078password: 
1079"#;
1080        let authinfo: AuthInfo = serde_saphyr::from_str(authinfo_yaml).unwrap();
1081        assert_eq!(authinfo.username, Some("user".to_string()));
1082        assert!(authinfo.password.is_none());
1083    }
1084
1085    #[test]
1086    fn authinfo_debug_does_not_output_password() {
1087        let authinfo_yaml = r#"
1088username: user
1089password: kube_rs
1090"#;
1091        let authinfo: AuthInfo = serde_saphyr::from_str(authinfo_yaml).unwrap();
1092        let authinfo_debug_output = format!("{authinfo:?}");
1093        let expected_output = "AuthInfo { \
1094        username: Some(\"user\"), \
1095        password: Some(SecretBox<str>([REDACTED])), \
1096        token: None, token_file: None, client_certificate: None, \
1097        client_certificate_data: None, client_key: None, \
1098        client_key_data: None, impersonate: None, \
1099        impersonate_uid: None, \
1100        impersonate_groups: None, \
1101        impersonate_user_extra: None, \
1102        extensions: None, \
1103        auth_provider: None, \
1104        exec: None, \
1105        other: {} \
1106        }";
1107
1108        assert_eq!(authinfo_debug_output, expected_output)
1109    }
1110
1111    #[tokio::test]
1112    async fn authinfo_exec_provide_cluster_info() {
1113        let config = r#"
1114apiVersion: v1
1115clusters:
1116- cluster:
1117    server: https://localhost:8080
1118    extensions:
1119    - name: client.authentication.k8s.io/exec
1120      extension:
1121        audience: foo
1122        other: bar
1123  name: foo-cluster
1124contexts:
1125- context:
1126    cluster: foo-cluster
1127    user: foo-user
1128    namespace: bar
1129  name: foo-context
1130current-context: foo-context
1131kind: Config
1132users:
1133- name: foo-user
1134  user:
1135    exec:
1136      apiVersion: client.authentication.k8s.io/v1alpha1
1137      args:
1138      - arg-1
1139      - arg-2
1140      command: foo-command
1141      provideClusterInfo: true
1142"#;
1143        let kube_config = Kubeconfig::from_yaml(config).unwrap();
1144        let config_loader = ConfigLoader::load(kube_config, None, None, None).await.unwrap();
1145        let auth_info = config_loader.user;
1146        let exec = auth_info.exec.unwrap();
1147        assert!(exec.provide_cluster_info);
1148        let cluster = exec.cluster.unwrap();
1149        assert_eq!(
1150            cluster.config.unwrap(),
1151            json!({"audience": "foo", "other": "bar"})
1152        );
1153    }
1154
1155    #[tokio::test]
1156    async fn parse_kubeconfig_encodings() {
1157        let files = vec![
1158            "kubeconfig_utf8.yaml",
1159            "kubeconfig_utf16le.yaml",
1160            "kubeconfig_utf16be.yaml",
1161        ];
1162
1163        for file_name in files {
1164            let path = PathBuf::from(format!(
1165                "{}/src/config/test_data/{}",
1166                env!("CARGO_MANIFEST_DIR"),
1167                file_name
1168            ));
1169            let cfg = Kubeconfig::read_from(path).unwrap();
1170            assert_eq!(cfg.clusters[0].name, "k3d-promstack");
1171            assert_eq!(cfg.contexts[0].name, "k3d-promstack");
1172            assert_eq!(cfg.auth_infos[0].name, "admin@k3d-k3s-default");
1173        }
1174    }
1175
1176    #[test]
1177    fn read_from_resolves_relative_exec_command() {
1178        // Relative exec plugin commands are resolved against the kubeconfig
1179        // directory (like client-go), while bare PATH commands are left as-is.
1180        // Regression for kdash-rs/kdash#541.
1181        let dir = tempfile::TempDir::new().unwrap();
1182        let path = dir.path().join("config");
1183        // Build the relative command with the platform separator so it contains
1184        // `MAIN_SEPARATOR` on every OS (the guard uses `MAIN_SEPARATOR`, which is
1185        // `\` on Windows), keeping the test separator-agnostic.
1186        let rel_cmd = format!("auth{}token.sh", std::path::MAIN_SEPARATOR);
1187        std::fs::write(
1188            &path,
1189            format!(
1190                r#"
1191apiVersion: v1
1192kind: Config
1193current-context: ctx
1194clusters:
1195- name: cluster
1196  cluster:
1197    server: https://localhost:6443
1198contexts:
1199- name: ctx
1200  context:
1201    cluster: cluster
1202    user: relative-user
1203users:
1204- name: relative-user
1205  user:
1206    exec:
1207      apiVersion: client.authentication.k8s.io/v1beta1
1208      command: {rel_cmd}
1209- name: path-user
1210  user:
1211    exec:
1212      apiVersion: client.authentication.k8s.io/v1beta1
1213      command: aws
1214"#
1215            ),
1216        )
1217        .unwrap();
1218
1219        let cfg = Kubeconfig::read_from(&path).unwrap();
1220
1221        // Relative command containing a separator is made absolute.
1222        let expected = to_absolute(dir.path(), &rel_cmd);
1223        assert_eq!(
1224            cfg.auth_infos[0]
1225                .auth_info
1226                .as_ref()
1227                .and_then(|a| a.exec.as_ref())
1228                .and_then(|e| e.command.clone()),
1229            expected
1230        );
1231
1232        // Bare PATH command is untouched.
1233        assert_eq!(
1234            cfg.auth_infos[1]
1235                .auth_info
1236                .as_ref()
1237                .and_then(|a| a.exec.as_ref())
1238                .and_then(|e| e.command.as_deref()),
1239            Some("aws")
1240        );
1241    }
1242
1243    #[test]
1244    fn kubeconfig_round_trip_preserves_unknown_fields() {
1245        let yaml = r#"
1246apiVersion: v1
1247kind: Config
1248current-context: test
1249custom-top-level-field: should-be-preserved
1250clusters:
1251- name: test-cluster
1252  cluster:
1253    server: https://localhost:6443
1254    certificate-authority-data: dGVzdA==
1255    custom-cluster-field: cluster-extra
1256contexts:
1257- name: test
1258  context:
1259    cluster: test-cluster
1260    user: test-user
1261    custom-context-field: context-extra
1262users:
1263- name: test-user
1264  user:
1265    exec:
1266      apiVersion: client.authentication.k8s.io/v1beta1
1267      command: gke-gcloud-auth-plugin
1268      provideClusterInfo: true
1269      interactiveMode: IfAvailable
1270      custom-exec-field: exec-extra
1271"#;
1272
1273        let config: Kubeconfig = Kubeconfig::from_yaml(yaml).unwrap();
1274
1275        // Verify custom field is captured in the catch-all `other` map
1276        let exec = config.auth_infos[0]
1277            .auth_info
1278            .as_ref()
1279            .unwrap()
1280            .exec
1281            .as_ref()
1282            .unwrap();
1283        assert_eq!(
1284            exec.other.get("custom-exec-field").and_then(|v| v.as_str()),
1285            Some("exec-extra")
1286        );
1287
1288        // Round-trip: serialize back to YAML
1289        let serialized = serde_saphyr::to_string(&config).unwrap();
1290
1291        // Verify unknown fields are preserved
1292        assert!(
1293            serialized.contains("custom-top-level-field"),
1294            "top-level unknown field was lost:\n{serialized}"
1295        );
1296        assert!(
1297            serialized.contains("custom-cluster-field"),
1298            "cluster unknown field was lost:\n{serialized}"
1299        );
1300        assert!(
1301            serialized.contains("custom-context-field"),
1302            "context unknown field was lost:\n{serialized}"
1303        );
1304        assert!(
1305            serialized.contains("custom-exec-field"),
1306            "exec unknown field was lost:\n{serialized}"
1307        );
1308
1309        // Verify re-deserialization produces the same result
1310        let reparsed = Kubeconfig::from_yaml(&serialized).unwrap();
1311        assert_eq!(config, reparsed);
1312    }
1313}