Skip to content

Commit dd9b2b1

Browse files
Add support for IPv6 in service account lookups (#512)
1 parent 8f9d71a commit dd9b2b1

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

kr8s/_auth.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# SPDX-FileCopyrightText: Copyright (c) 2023-2024, Kr8s Developers (See LICENSE for list)
22
# SPDX-License-Identifier: BSD 3-Clause License
33
import base64
4+
import ipaddress
45
import json
56
import os
67
import pathlib
@@ -256,9 +257,10 @@ async def _load_service_account(self) -> None:
256257
self._serviceaccount = os.path.expanduser(self._serviceaccount)
257258
if not os.path.isdir(self._serviceaccount):
258259
return
259-
host = os.environ["KUBERNETES_SERVICE_HOST"]
260-
port = os.environ["KUBERNETES_SERVICE_PORT"]
261-
self.server = f"https://{host}:{port}"
260+
self.server = self._format_server_address(
261+
os.environ["KUBERNETES_SERVICE_HOST"],
262+
os.environ["KUBERNETES_SERVICE_PORT"],
263+
)
262264
async with await anyio.open_file(
263265
os.path.join(self._serviceaccount, "token")
264266
) as f:
@@ -269,3 +271,11 @@ async def _load_service_account(self) -> None:
269271
os.path.join(self._serviceaccount, "namespace")
270272
) as f:
271273
self.namespace = await f.read()
274+
275+
@staticmethod
276+
def _format_server_address(host, port):
277+
try:
278+
ipaddress.IPv6Address(host)
279+
return f"https://[{host}]:{port}"
280+
except ipaddress.AddressValueError:
281+
return f"https://{host}:{port}"

kr8s/tests/test_auth.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import yaml
1111

1212
import kr8s
13+
from kr8s._auth import KubeAuth
1314
from kr8s._config import KubeConfig
1415
from kr8s._testutils import set_env
1516

@@ -317,3 +318,16 @@ async def test_certs_not_encoded(kubeconfig_with_decoded_certs):
317318
async def test_certs_with_encoded_line_breaks(kubeconfig_with_line_breaks_in_certs):
318319
api = await kr8s.asyncio.api(kubeconfig=kubeconfig_with_line_breaks_in_certs)
319320
assert await api.get("pods", namespace=kr8s.ALL)
321+
322+
323+
@pytest.mark.parametrize(
324+
"host,port,expected",
325+
[
326+
("localhost", "8080", "https://localhost:8080"),
327+
("9.9.9.9", "1234", "https://9.9.9.9:1234"),
328+
("fd97:3495:4300::1", "443", "https://[fd97:3495:4300::1]:443"),
329+
("kubernetes.default.svc", "8080", "https://kubernetes.default.svc:8080"),
330+
],
331+
)
332+
def test_url_formatting(host, port, expected):
333+
assert KubeAuth._format_server_address(host, port) == expected

0 commit comments

Comments
 (0)