Skip to content
This repository was archived by the owner on Mar 13, 2022. It is now read-only.

Commit 31b787c

Browse files
committed
Refresh GCP tokens on retrieval by overriding client config method.
[Fix #59]
1 parent 7d1e449 commit 31b787c

File tree

2 files changed

+88
-15
lines changed

2 files changed

+88
-15
lines changed

config/kube_config.py

+14
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,21 @@ def _load_cluster_info(self):
392392
if 'insecure-skip-tls-verify' in self._cluster:
393393
self.verify_ssl = not self._cluster['insecure-skip-tls-verify']
394394

395+
def _using_gcp_auth_provider(self):
396+
return self._user and \
397+
'auth-provider' in self._user and \
398+
'name' in self._user['auth-provider'] and \
399+
self._user['auth-provider']['name'] == 'gcp'
400+
395401
def _set_config(self, client_configuration):
402+
if self._using_gcp_auth_provider():
403+
# GCP auth tokens must be refreshed regularly, but swagger expects
404+
# a constant token. Replace the swagger-generated client config's
405+
# get_api_key_with_prefix method with our own to allow automatic
406+
# token refresh.
407+
def _gcp_get_api_key(*args):
408+
return self._load_gcp_token(self._user['auth-provider'])
409+
client_configuration.get_api_key_with_prefix = _gcp_get_api_key
396410
if 'token' in self.__dict__:
397411
client_configuration.api_key['authorization'] = self.token
398412
# copy these keys directly from self to configuration object

config/kube_config_test.py

+74-15
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@
3434

3535
EXPIRY_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
3636
# should be less than kube_config.EXPIRY_SKEW_PREVENTION_DELAY
37-
EXPIRY_TIMEDELTA = 2
37+
PAST_EXPIRY_TIMEDELTA = 2
38+
# should be more than kube_config.EXPIRY_SKEW_PREVENTION_DELAY
39+
FUTURE_EXPIRY_TIMEDELTA = 60
3840

3941
NON_EXISTING_FILE = "zz_non_existing_file_472398324"
4042

@@ -47,9 +49,9 @@ def _format_expiry_datetime(dt):
4749
return dt.strftime(EXPIRY_DATETIME_FORMAT)
4850

4951

50-
def _get_expiry(loader):
52+
def _get_expiry(loader, active_context):
5153
expired_gcp_conf = (item for item in loader._config.value.get("users")
52-
if item.get("name") == "expired_gcp")
54+
if item.get("name") == active_context)
5355
return next(expired_gcp_conf).get("user").get("auth-provider") \
5456
.get("config").get("expiry")
5557

@@ -73,8 +75,11 @@ def _raise_exception(st):
7375
TEST_PASSWORD = "pass"
7476
# token for me:pass
7577
TEST_BASIC_TOKEN = "Basic bWU6cGFzcw=="
76-
TEST_TOKEN_EXPIRY = _format_expiry_datetime(
77-
datetime.datetime.utcnow() - datetime.timedelta(minutes=EXPIRY_TIMEDELTA))
78+
DATETIME_EXPIRY_PAST = datetime.datetime.utcnow(
79+
) - datetime.timedelta(minutes=PAST_EXPIRY_TIMEDELTA)
80+
DATETIME_EXPIRY_FUTURE = datetime.datetime.utcnow(
81+
) + datetime.timedelta(minutes=FUTURE_EXPIRY_TIMEDELTA)
82+
TEST_TOKEN_EXPIRY_PAST = _format_expiry_datetime(DATETIME_EXPIRY_PAST)
7883

7984
TEST_SSL_HOST = "https://test-host"
8085
TEST_CERTIFICATE_AUTH = "cert-auth"
@@ -371,6 +376,13 @@ class TestKubeConfigLoader(BaseTestCase):
371376
"user": "expired_gcp"
372377
}
373378
},
379+
{
380+
"name": "expired_gcp_refresh",
381+
"context": {
382+
"cluster": "default",
383+
"user": "expired_gcp_refresh"
384+
}
385+
},
374386
{
375387
"name": "oidc",
376388
"context": {
@@ -509,7 +521,22 @@ class TestKubeConfigLoader(BaseTestCase):
509521
"name": "gcp",
510522
"config": {
511523
"access-token": TEST_DATA_BASE64,
512-
"expiry": TEST_TOKEN_EXPIRY, # always in past
524+
"expiry": TEST_TOKEN_EXPIRY_PAST, # always in past
525+
}
526+
},
527+
"token": TEST_DATA_BASE64, # should be ignored
528+
"username": TEST_USERNAME, # should be ignored
529+
"password": TEST_PASSWORD, # should be ignored
530+
}
531+
},
532+
{
533+
"name": "expired_gcp_refresh",
534+
"user": {
535+
"auth-provider": {
536+
"name": "gcp",
537+
"config": {
538+
"access-token": TEST_DATA_BASE64,
539+
"expiry": TEST_TOKEN_EXPIRY_PAST, # always in past
513540
}
514541
},
515542
"token": TEST_DATA_BASE64, # should be ignored
@@ -630,16 +657,20 @@ def test_load_user_token(self):
630657
self.assertEqual(BEARER_TOKEN_FORMAT % TEST_DATA_BASE64, loader.token)
631658

632659
def test_gcp_no_refresh(self):
633-
expected = FakeConfig(
634-
host=TEST_HOST,
635-
token=BEARER_TOKEN_FORMAT % TEST_DATA_BASE64)
636-
actual = FakeConfig()
660+
fake_config = FakeConfig()
661+
# swagger-generated config has this, but FakeConfig does not.
662+
self.assertFalse(hasattr(fake_config, 'get_api_key_with_prefix'))
637663
KubeConfigLoader(
638664
config_dict=self.TEST_KUBE_CONFIG,
639665
active_context="gcp",
640666
get_google_credentials=lambda: _raise_exception(
641-
"SHOULD NOT BE CALLED")).load_and_set(actual)
642-
self.assertEqual(expected, actual)
667+
"SHOULD NOT BE CALLED")).load_and_set(fake_config)
668+
# Should now be populated with a gcp token fetcher.
669+
self.assertIsNotNone(fake_config.get_api_key_with_prefix)
670+
self.assertEqual(TEST_HOST, fake_config.host)
671+
# For backwards compatibility, authorization field should still be set.
672+
self.assertEqual(BEARER_TOKEN_FORMAT % TEST_DATA_BASE64,
673+
fake_config.api_key['authorization'])
643674

644675
def test_load_gcp_token_no_refresh(self):
645676
loader = KubeConfigLoader(
@@ -654,20 +685,48 @@ def test_load_gcp_token_no_refresh(self):
654685
def test_load_gcp_token_with_refresh(self):
655686
def cred(): return None
656687
cred.token = TEST_ANOTHER_DATA_BASE64
657-
cred.expiry = datetime.datetime.now()
688+
cred.expiry = datetime.datetime.utcnow()
658689

659690
loader = KubeConfigLoader(
660691
config_dict=self.TEST_KUBE_CONFIG,
661692
active_context="expired_gcp",
662693
get_google_credentials=lambda: cred)
663-
original_expiry = _get_expiry(loader)
694+
original_expiry = _get_expiry(loader, "expired_gcp")
664695
self.assertTrue(loader._load_auth_provider_token())
665-
new_expiry = _get_expiry(loader)
696+
new_expiry = _get_expiry(loader, "expired_gcp")
666697
# assert that the configs expiry actually updates
667698
self.assertTrue(new_expiry > original_expiry)
668699
self.assertEqual(BEARER_TOKEN_FORMAT % TEST_ANOTHER_DATA_BASE64,
669700
loader.token)
670701

702+
def test_gcp_get_api_key_with_prefix(self):
703+
class cred_old:
704+
token = TEST_DATA_BASE64
705+
expiry = DATETIME_EXPIRY_PAST
706+
707+
class cred_new:
708+
token = TEST_ANOTHER_DATA_BASE64
709+
expiry = DATETIME_EXPIRY_FUTURE
710+
fake_config = FakeConfig()
711+
_get_google_credentials = mock.Mock()
712+
_get_google_credentials.side_effect = [cred_old, cred_new]
713+
714+
loader = KubeConfigLoader(
715+
config_dict=self.TEST_KUBE_CONFIG,
716+
active_context="expired_gcp_refresh",
717+
get_google_credentials=_get_google_credentials)
718+
loader.load_and_set(fake_config)
719+
original_expiry = _get_expiry(loader, "expired_gcp_refresh")
720+
# Call GCP token fetcher.
721+
token = fake_config.get_api_key_with_prefix()
722+
new_expiry = _get_expiry(loader, "expired_gcp_refresh")
723+
724+
self.assertTrue(new_expiry > original_expiry)
725+
self.assertEqual(BEARER_TOKEN_FORMAT % TEST_ANOTHER_DATA_BASE64,
726+
loader.token)
727+
self.assertEqual(BEARER_TOKEN_FORMAT % TEST_ANOTHER_DATA_BASE64,
728+
token)
729+
671730
def test_oidc_no_refresh(self):
672731
loader = KubeConfigLoader(
673732
config_dict=self.TEST_KUBE_CONFIG,

0 commit comments

Comments
 (0)