Skip to main content

kube_client/config/
file_loader.rs

1#[cfg(any(feature = "http-proxy", feature = "socks5"))]
2use crate::config::{NoProxyError, no_proxy::NoProxy};
3
4use crate::{
5    config::{
6        KubeconfigError,
7        file_config::{AuthInfo, Cluster, Context, Kubeconfig},
8    },
9    util::nonempty,
10};
11
12/// KubeConfigOptions stores options used when loading kubeconfig file.
13#[derive(Default, Clone)]
14pub struct KubeConfigOptions {
15    /// The named context to load
16    pub context: Option<String>,
17    /// The cluster to load
18    pub cluster: Option<String>,
19    /// The user to load
20    pub user: Option<String>,
21}
22
23/// ConfigLoader loads current context, cluster, and authentication information
24/// from a kubeconfig file.
25#[derive(Clone, Debug)]
26pub struct ConfigLoader {
27    pub current_context: Context,
28    pub cluster: Cluster,
29    pub user: AuthInfo,
30}
31
32impl ConfigLoader {
33    /// Returns a config loader based on the cluster information from the kubeconfig file.
34    pub async fn new_from_options(options: &KubeConfigOptions) -> Result<Self, KubeconfigError> {
35        let config = Kubeconfig::read()?;
36        let loader = Self::load(
37            config,
38            options.context.as_ref(),
39            options.cluster.as_ref(),
40            options.user.as_ref(),
41        )
42        .await?;
43
44        Ok(loader)
45    }
46
47    pub async fn new_from_kubeconfig(
48        config: Kubeconfig,
49        options: &KubeConfigOptions,
50    ) -> Result<Self, KubeconfigError> {
51        let loader = Self::load(
52            config,
53            options.context.as_ref(),
54            options.cluster.as_ref(),
55            options.user.as_ref(),
56        )
57        .await?;
58
59        Ok(loader)
60    }
61
62    fn load_from_kubeconfig(
63        config: Kubeconfig,
64        context: Option<&String>,
65        cluster: Option<&String>,
66        user: Option<&String>,
67    ) -> Result<Self, KubeconfigError> {
68        let context_name = if let Some(name) = context {
69            name
70        } else if let Some(name) = &config.current_context {
71            name
72        } else {
73            return Err(KubeconfigError::CurrentContextNotSet);
74        };
75
76        let current_context = config
77            .contexts
78            .iter()
79            .find(|named_context| &named_context.name == context_name)
80            .and_then(|named_context| named_context.context.clone())
81            .ok_or_else(|| KubeconfigError::LoadContext(context_name.clone()))?;
82
83        let cluster_name = cluster.unwrap_or(&current_context.cluster);
84        let cluster = config
85            .clusters
86            .iter()
87            .find(|named_cluster| &named_cluster.name == cluster_name)
88            .and_then(|named_cluster| named_cluster.cluster.clone())
89            .ok_or_else(|| KubeconfigError::LoadClusterOfContext(cluster_name.clone()))?;
90
91        let user_name = user.or_else(|| current_context.user.as_ref());
92
93        // client-go doesn't fail on empty/missing user, so we don't either
94        // see https://github.com/kube-rs/kube/issues/1594
95        let mut auth_info = if let Some(user) = user_name {
96            config
97                .auth_infos
98                .iter()
99                .find(|named_user| &named_user.name == user)
100                .and_then(|named_user| named_user.auth_info.clone())
101                .unwrap_or_else(AuthInfo::default)
102        } else {
103            AuthInfo::default()
104        };
105
106        if let Some(exec_config) = &mut auth_info.exec
107            && exec_config.provide_cluster_info
108        {
109            exec_config.cluster = Some((&cluster).try_into()?);
110        }
111
112        Ok(ConfigLoader {
113            current_context,
114            cluster,
115            user: auth_info,
116        })
117    }
118
119    pub async fn load(
120        config: Kubeconfig,
121        context: Option<&String>,
122        cluster: Option<&String>,
123        user: Option<&String>,
124    ) -> Result<Self, KubeconfigError> {
125        Self::load_from_kubeconfig(config, context, cluster, user)
126    }
127
128    pub fn ca_bundle(&self) -> Result<Option<Vec<Vec<u8>>>, KubeconfigError> {
129        if let Some(bundle) = self.cluster.load_certificate_authority()? {
130            Ok(Some(
131                super::certs(&bundle).map_err(KubeconfigError::ParseCertificates)?,
132            ))
133        } else {
134            Ok(None)
135        }
136    }
137
138    /// The proxy to reach the apiserver at `cluster_url` through, if any.
139    pub fn proxy_url(&self, cluster_url: &http::Uri) -> Result<Option<http::Uri>, KubeconfigError> {
140        let proxy = nonempty(self.cluster.proxy_url.clone())
141            .or_else(|| nonempty(std::env::var("HTTPS_PROXY").ok()))
142            .or_else(|| nonempty(std::env::var("https_proxy").ok()))
143            .map(|proxy| proxy.parse::<http::Uri>().map_err(KubeconfigError::ParseProxyUrl))
144            .transpose()?;
145
146        #[cfg(any(feature = "http-proxy", feature = "socks5"))]
147        {
148            Self::apply_no_proxy(proxy, cluster_url, NoProxy::from_env)
149        }
150
151        #[cfg(not(any(feature = "http-proxy", feature = "socks5")))]
152        {
153            let _ = cluster_url; // NO_PROXY is only honored with a proxy feature
154            Ok(proxy)
155        }
156    }
157
158    /// Drops `proxy` if `NO_PROXY` exempts `cluster_url`. Only reads `NO_PROXY` when a proxy is configured.
159    #[cfg(any(feature = "http-proxy", feature = "socks5"))]
160    fn apply_no_proxy(
161        proxy: Option<http::Uri>,
162        cluster_url: &http::Uri,
163        load_no_proxy: impl FnOnce() -> Result<Option<NoProxy>, NoProxyError>,
164    ) -> Result<Option<http::Uri>, KubeconfigError> {
165        let Some(proxy) = proxy else {
166            return Ok(None);
167        };
168        if let Some(no_proxy) = load_no_proxy().map_err(KubeconfigError::ParseNoProxy)?
169            && no_proxy
170                .matches(cluster_url)
171                .map_err(KubeconfigError::ParseNoProxy)?
172        {
173            return Ok(None);
174        }
175        Ok(Some(proxy))
176    }
177}
178
179impl TryFrom<Kubeconfig> for ConfigLoader {
180    type Error = KubeconfigError;
181
182    fn try_from(kubeconfig: Kubeconfig) -> Result<Self, KubeconfigError> {
183        Self::load_from_kubeconfig(kubeconfig, None, None, None)
184    }
185}
186
187#[cfg(all(test, any(feature = "http-proxy", feature = "socks5")))]
188mod tests {
189    use rstest::rstest;
190
191    use super::*;
192
193    // NO_PROXY is matched against the apiserver, never against the proxy itself
194    #[rstest]
195    #[case("10.2.2.5", false)]
196    #[case("10.0.0.0/8", false)]
197    #[case("localhost, 10.2.2.5", false)]
198    #[case("proxy.corporate.com", true)]
199    #[case("proxy.corporate.com:80", true)]
200    #[case("1.2.3.4", true)]
201    fn no_proxy_matches_cluster_url(#[case] no_proxy: &str, #[case] proxied: bool) {
202        let proxy_url = http::Uri::from_static("http://proxy.corporate.com:80");
203        let cluster_url = http::Uri::from_static("https://10.2.2.5:6443");
204
205        let proxy = ConfigLoader::apply_no_proxy(Some(proxy_url.clone()), &cluster_url, || {
206            no_proxy.parse::<NoProxy>().map(Some)
207        })
208        .expect("valid proxy and NO_PROXY configuration");
209        assert_eq!(proxy, proxied.then_some(proxy_url), "NO_PROXY={no_proxy}");
210    }
211
212    #[test]
213    fn no_proxy_is_not_read_without_proxy() {
214        let cluster_url = http::Uri::from_static("https://kube.rs");
215        let proxy = ConfigLoader::apply_no_proxy(None, &cluster_url, || {
216            panic!("NO_PROXY must not be read without a proxy")
217        })
218        .expect("no proxy requires no NO_PROXY configuration");
219        assert_eq!(proxy, None);
220    }
221
222    #[test]
223    fn absent_no_proxy_preserves_proxy() {
224        let proxy_url = http::Uri::from_static("http://proxy.corporate.com:80");
225        let cluster_url = http::Uri::from_static("https://kube.rs");
226        let proxy = ConfigLoader::apply_no_proxy(Some(proxy_url.clone()), &cluster_url, || Ok(None))
227            .expect("absent NO_PROXY is valid");
228        assert_eq!(proxy, Some(proxy_url));
229    }
230
231    #[test]
232    fn malformed_no_proxy_is_reported_with_proxy() {
233        let proxy_url = http::Uri::from_static("http://proxy.corporate.com:80");
234        let cluster_url = http::Uri::from_static("https://kube.rs");
235        let result =
236            ConfigLoader::apply_no_proxy(Some(proxy_url), &cluster_url, || ",".parse::<NoProxy>().map(Some));
237        assert!(matches!(result, Err(KubeconfigError::ParseNoProxy(_))));
238    }
239
240    const PROXY: &str = "http://proxy.corporate.com:80";
241    const CHILD_KUBECONFIG_PROXY: &str = "KUBE_TEST_PROXY_URL_KUBECONFIG";
242    const CHILD_EXPECT: &str = "KUBE_TEST_PROXY_URL_EXPECT";
243
244    // The env can only be set safely for a child process, so this reruns `config_proxy_url_child` in one
245    #[rstest]
246    #[case(Some(PROXY), None, None, true)]
247    #[case(Some(PROXY), None, Some("10.2.2.5"), false)]
248    #[case(Some(PROXY), None, Some("proxy.corporate.com:80"), true)]
249    #[case(Some(PROXY), None, Some("*"), false)]
250    #[case(None, Some(PROXY), None, true)]
251    #[case(None, Some(PROXY), Some("10.2.2.5"), false)]
252    fn config_proxy_url(
253        #[case] kubeconfig_proxy: Option<&str>,
254        #[case] https_proxy: Option<&str>,
255        #[case] no_proxy: Option<&str>,
256        #[case] proxied: bool,
257    ) {
258        let mut child = std::process::Command::new(std::env::current_exe().unwrap());
259        child.args(["--exact", "config::file_loader::tests::config_proxy_url_child"]);
260        for var in [
261            "HTTPS_PROXY",
262            "https_proxy",
263            "NO_PROXY",
264            "no_proxy",
265            CHILD_KUBECONFIG_PROXY,
266        ] {
267            child.env_remove(var);
268        }
269        if let Some(proxy) = kubeconfig_proxy {
270            child.env(CHILD_KUBECONFIG_PROXY, proxy);
271        }
272        if let Some(proxy) = https_proxy {
273            child.env("HTTPS_PROXY", proxy);
274        }
275        if let Some(no_proxy) = no_proxy {
276            child.env("NO_PROXY", no_proxy);
277        }
278        child.env(CHILD_EXPECT, if proxied { PROXY } else { "" });
279        let output = child.output().unwrap();
280        let stdout = String::from_utf8_lossy(&output.stdout);
281        assert!(output.status.success() && stdout.contains("1 passed"), "{stdout}");
282    }
283
284    // Does nothing unless started by `config_proxy_url`
285    #[tokio::test]
286    async fn config_proxy_url_child() {
287        let Ok(expect) = std::env::var(CHILD_EXPECT) else {
288            return;
289        };
290        let proxy_line = std::env::var(CHILD_KUBECONFIG_PROXY)
291            .map(|proxy| format!("    proxy-url: {proxy}\n"))
292            .unwrap_or_default();
293        let kubeconfig = Kubeconfig::from_yaml(&format!(
294            "clusters:\n- name: c\n  cluster:\n    server: https://10.2.2.5:6443\n{proxy_line}\
295             contexts:\n- name: c\n  context: {{ cluster: c, user: u }}\n\
296             users:\n- name: u\n  user: {{}}\ncurrent-context: c\n"
297        ))
298        .unwrap();
299        let config = crate::Config::from_custom_kubeconfig(kubeconfig, &Default::default())
300            .await
301            .unwrap();
302        assert_eq!(
303            config.proxy_url,
304            nonempty(Some(expect)).map(|p| p.parse().unwrap())
305        );
306    }
307}