Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions kubernetes/config/kube_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,35 @@ def _is_expired(expiry):
datetime.datetime.now(tz=UTC))


def _get_jwt_expiry(token):
"""Return the expiry of a JWT from its ``exp`` claim.

Returns None for malformed tokens and tokens without an ``exp``
claim.
"""
parts = token.split('.')
if len(parts) != 3: # Not a valid JWT
return None

padding = (4 - len(parts[1]) % 4) * '='
if len(padding) == 3:
# According to spec, 3 padding characters cannot occur
# in a valid jwt
# https://tools.ietf.org/html/rfc7515#appendix-C
return None

try:
jwt_attributes = json.loads(
base64.urlsafe_b64decode(parts[1] + padding).decode('utf-8')
)
expire = jwt_attributes.get('exp')
if expire is None:
return None
return datetime.datetime.fromtimestamp(expire, tz=UTC)
except (ValueError, TypeError, AttributeError, OverflowError):
return None


class FileOrData:
"""Utility class to read content of obj[%data_key_name] or file's
content of obj[%file_key_name] and represent it as file or data.
Expand Down Expand Up @@ -377,6 +406,14 @@ def _load_oid_token(self, provider):

self.token = "Bearer %s" % provider['config']['id-token']

# Record when the token in use expires so the refresh hook
# installed by _set_config() refreshes it instead of sending an
# expired token on later requests. The expiry is read from the
# final id-token because a refresh above replaces it.
expiry = _get_jwt_expiry(provider['config']['id-token'])
if expiry is not None:
self.expiry = expiry

return self.token

def _refresh_oidc(self, provider):
Expand Down
87 changes: 87 additions & 0 deletions kubernetes/config/kube_config_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import base64
import copy
import datetime
import io
import json
Expand Down Expand Up @@ -136,6 +137,15 @@ def _raise_exception(st):
TEST_OIDC_CA = _base64(TEST_CERTIFICATE_AUTH)


def _oidc_token_with_exp(exp):
payload = json.dumps({"name": "test", "exp": exp})
return ".".join([
_urlsafe_unpadded_b64encode(TEST_OIDC_TOKEN),
_urlsafe_unpadded_b64encode(payload),
_urlsafe_unpadded_b64encode(TEST_CLIENT_CERT)
])


class BaseTestCase(unittest.TestCase):

def setUp(self):
Expand Down Expand Up @@ -1070,6 +1080,83 @@ def test_oidc_fails_if_contains_reserved_chars(self):
None,
)

def test_oidc_sets_expiry_from_id_token(self):
exp = int((datetime.datetime.now(tz=UTC) +
datetime.timedelta(hours=1)).timestamp())
config_dict = copy.deepcopy(self.TEST_KUBE_CONFIG)
for user in config_dict["users"]:
if user["name"] == "oidc":
user["user"]["auth-provider"]["config"]["id-token"] = (
_oidc_token_with_exp(exp))
loader = KubeConfigLoader(
config_dict=config_dict,
active_context="oidc",
)
self.assertTrue(loader._load_auth_provider_token())
self.assertEqual(
datetime.datetime.fromtimestamp(exp, tz=UTC), loader.expiry)

@mock.patch('kubernetes.config.kube_config.OAuth2Session.refresh_token')
@mock.patch('kubernetes.config.kube_config.ApiClient.call_api')
def test_oidc_refresh_api_key_hook(self, mock_ApiClient,
mock_OAuth2Session):
now = datetime.datetime.now(tz=UTC)
first_exp = int((now + datetime.timedelta(hours=1)).timestamp())
new_exp = int((now + datetime.timedelta(hours=2)).timestamp())
config_dict = copy.deepcopy(self.TEST_KUBE_CONFIG)
for user in config_dict["users"]:
if user["name"] == "oidc":
config = user["user"]["auth-provider"]["config"]
config["id-token"] = _oidc_token_with_exp(first_exp)
config["client-id"] = "tectonic-kubectl"
config["client-secret"] = "FAKE_SECRET"
config["idp-issuer-url"] = "https://example.org/identity"
config["refresh-token"] = (
"lucWJjEhlxZW01cXI3YmVlcYnpxNGhzk")

mock_response = mock.MagicMock()
type(mock_response).status = mock.PropertyMock(
return_value=200
)
type(mock_response).data = mock.PropertyMock(
return_value=json.dumps({
"token_endpoint": "https://example.org/identity/token"
})
)

mock_ApiClient.return_value = mock_response

new_token = _oidc_token_with_exp(new_exp)
mock_OAuth2Session.return_value = {"id_token": new_token,
"refresh_token": "newtoken123"}

fake_config = FakeConfig()
loader = KubeConfigLoader(
config_dict=config_dict,
active_context="oidc",
)
loader.load_and_set(fake_config)
self.assertIsNotNone(fake_config.refresh_api_key_hook)
self.assertEqual(
datetime.datetime.fromtimestamp(first_exp, tz=UTC),
loader.expiry)

# Simulate the token expiring: the id-token recorded in the
# config is now past its expiry, as it would be once the clock
# moves past the expiry the loader recorded at load time.
expired_exp = int((now - datetime.timedelta(hours=1)).timestamp())
loader.expiry = datetime.datetime.fromtimestamp(expired_exp, tz=UTC)
provider = loader._user['auth-provider']
provider['config'].value['id-token'] = (
_oidc_token_with_exp(expired_exp))

fake_config.refresh_api_key_hook(fake_config)

self.assertEqual(BEARER_TOKEN_FORMAT % new_token,
fake_config.api_key['BearerToken'])
self.assertEqual(
datetime.datetime.fromtimestamp(new_exp, tz=UTC), loader.expiry)

def test_oidc_fails_if_invalid_padding_length(self):
loader = KubeConfigLoader(
config_dict=self.TEST_KUBE_CONFIG,
Expand Down