From 14a350780ac286c10c4aa44ab27a42bf5c972b05 Mon Sep 17 00:00:00 2001 From: Jacob Tomlinson Date: Thu, 8 Feb 2024 11:15:46 +0000 Subject: [PATCH] Ensure reauthenticate calls exec again (#307) --- kr8s/_auth.py | 15 ++++++++------- kr8s/tests/test_auth.py | 19 +++++++++++++++++-- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/kr8s/_auth.py b/kr8s/_auth.py index 3a557339..c8d6af86 100644 --- a/kr8s/_auth.py +++ b/kr8s/_auth.py @@ -29,6 +29,7 @@ def __init__( self.token = None self.namespace = namespace self.active_context = None + self._url = url self._insecure_skip_tls_verify = False self._use_context = context self._context = None @@ -42,9 +43,6 @@ def __init__( self._kubeconfig = kubeconfig or os.environ.get("KUBECONFIG", "~/.kube/config") self.__auth_lock = anyio.Lock() - if url: - self.server = url - def __await__(self): async def f(): await self.reauthenticate() @@ -55,10 +53,13 @@ async def f(): async def reauthenticate(self) -> None: """Reauthenticate with the server.""" async with self.__auth_lock: - if self._kubeconfig is not False and not self.server: - await self._load_kubeconfig() - if self._serviceaccount and not self.server: - await self._load_service_account() + if self._url: + self.server = self._url + else: + if self._kubeconfig is not False: + await self._load_kubeconfig() + if self._serviceaccount: + await self._load_service_account() if not self.server: raise ValueError("Unable to find valid credentials") diff --git a/kr8s/tests/test_auth.py b/kr8s/tests/test_auth.py index e5dd3c3a..2b41ebd4 100644 --- a/kr8s/tests/test_auth.py +++ b/kr8s/tests/test_auth.py @@ -137,8 +137,14 @@ async def test_bad_auth(serviceaccount): async def test_url(kubectl_proxy): api = await kr8s.asyncio.api(url=kubectl_proxy) - version = await api.version() - assert "major" in version + assert await api.get("pods", namespace="kube-system") + assert api.auth.server == kubectl_proxy + + # Ensure reauthentication works + api.auth.server = None + await api.reauthenticate() + assert await api.get("pods", namespace="kube-system") + assert api.auth.server == kubectl_proxy def test_no_config(): @@ -163,6 +169,15 @@ async def test_service_account(serviceaccount): async def test_exec(kubeconfig_with_exec): api = await kr8s.asyncio.api(kubeconfig=kubeconfig_with_exec) assert await api.get("pods", namespace=kr8s.ALL) + assert api.auth.server + assert api.auth.server_ca_file + + # Test reauthentication + api.auth.server = None + api.auth.server_ca_file = None + await api.reauthenticate() + assert api.auth.server + assert api.auth.server_ca_file async def test_token(kubeconfig_with_token):