Skip to content

Commit

Permalink
Add support for IPv6 in service account lookups (#512)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobtomlinson authored Nov 1, 2024
1 parent 8f9d71a commit dd9b2b1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
16 changes: 13 additions & 3 deletions kr8s/_auth.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# SPDX-FileCopyrightText: Copyright (c) 2023-2024, Kr8s Developers (See LICENSE for list)
# SPDX-License-Identifier: BSD 3-Clause License
import base64
import ipaddress
import json
import os
import pathlib
Expand Down Expand Up @@ -256,9 +257,10 @@ async def _load_service_account(self) -> None:
self._serviceaccount = os.path.expanduser(self._serviceaccount)
if not os.path.isdir(self._serviceaccount):
return
host = os.environ["KUBERNETES_SERVICE_HOST"]
port = os.environ["KUBERNETES_SERVICE_PORT"]
self.server = f"https://{host}:{port}"
self.server = self._format_server_address(
os.environ["KUBERNETES_SERVICE_HOST"],
os.environ["KUBERNETES_SERVICE_PORT"],
)
async with await anyio.open_file(
os.path.join(self._serviceaccount, "token")
) as f:
Expand All @@ -269,3 +271,11 @@ async def _load_service_account(self) -> None:
os.path.join(self._serviceaccount, "namespace")
) as f:
self.namespace = await f.read()

@staticmethod
def _format_server_address(host, port):
try:
ipaddress.IPv6Address(host)
return f"https://[{host}]:{port}"
except ipaddress.AddressValueError:
return f"https://{host}:{port}"
14 changes: 14 additions & 0 deletions kr8s/tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import yaml

import kr8s
from kr8s._auth import KubeAuth
from kr8s._config import KubeConfig
from kr8s._testutils import set_env

Expand Down Expand Up @@ -317,3 +318,16 @@ async def test_certs_not_encoded(kubeconfig_with_decoded_certs):
async def test_certs_with_encoded_line_breaks(kubeconfig_with_line_breaks_in_certs):
api = await kr8s.asyncio.api(kubeconfig=kubeconfig_with_line_breaks_in_certs)
assert await api.get("pods", namespace=kr8s.ALL)


@pytest.mark.parametrize(
"host,port,expected",
[
("localhost", "8080", "https://localhost:8080"),
("9.9.9.9", "1234", "https://9.9.9.9:1234"),
("fd97:3495:4300::1", "443", "https://[fd97:3495:4300::1]:443"),
("kubernetes.default.svc", "8080", "https://kubernetes.default.svc:8080"),
],
)
def test_url_formatting(host, port, expected):
assert KubeAuth._format_server_address(host, port) == expected

0 comments on commit dd9b2b1

Please sign in to comment.