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

Commit d6725e2

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

File tree

2 files changed

+92
-15
lines changed

2 files changed

+92
-15
lines changed

Diff for: config/kube_config.py

+16
Original file line numberDiff line numberDiff line change
@@ -392,8 +392,24 @@ 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__:
411+
# Note: this line runs for GCP auth tokens as well, but this entry
412+
# will not be updated upon GCP token refresh.
397413
client_configuration.api_key['authorization'] = self.token
398414
# copy these keys directly from self to configuration object
399415
keys = ['host', 'ssl_ca_cert', 'cert_file', 'key_file', 'verify_ssl']

Diff for: config/kube_config_test.py

+76-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,24 @@ 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+
# Duplicated from "expired_gcp" so test_load_gcp_token_with_refresh
533+
# is isolated from test_gcp_get_api_key_with_prefix.
534+
{
535+
"name": "expired_gcp_refresh",
536+
"user": {
537+
"auth-provider": {
538+
"name": "gcp",
539+
"config": {
540+
"access-token": TEST_DATA_BASE64,
541+
"expiry": TEST_TOKEN_EXPIRY_PAST, # always in past
513542
}
514543
},
515544
"token": TEST_DATA_BASE64, # should be ignored
@@ -630,16 +659,20 @@ def test_load_user_token(self):
630659
self.assertEqual(BEARER_TOKEN_FORMAT % TEST_DATA_BASE64, loader.token)
631660

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

644677
def test_load_gcp_token_no_refresh(self):
645678
loader = KubeConfigLoader(
@@ -654,20 +687,48 @@ def test_load_gcp_token_no_refresh(self):
654687
def test_load_gcp_token_with_refresh(self):
655688
def cred(): return None
656689
cred.token = TEST_ANOTHER_DATA_BASE64
657-
cred.expiry = datetime.datetime.now()
690+
cred.expiry = datetime.datetime.utcnow()
658691

659692
loader = KubeConfigLoader(
660693
config_dict=self.TEST_KUBE_CONFIG,
661694
active_context="expired_gcp",
662695
get_google_credentials=lambda: cred)
663-
original_expiry = _get_expiry(loader)
696+
original_expiry = _get_expiry(loader, "expired_gcp")
664697
self.assertTrue(loader._load_auth_provider_token())
665-
new_expiry = _get_expiry(loader)
698+
new_expiry = _get_expiry(loader, "expired_gcp")
666699
# assert that the configs expiry actually updates
667700
self.assertTrue(new_expiry > original_expiry)
668701
self.assertEqual(BEARER_TOKEN_FORMAT % TEST_ANOTHER_DATA_BASE64,
669702
loader.token)
670703

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

0 commit comments

Comments
 (0)