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

Commit 999c199

Browse files
committed
Add support for getting credentials from exec plugins
1 parent 07ef626 commit 999c199

File tree

4 files changed

+266
-5
lines changed

4 files changed

+266
-5
lines changed

Diff for: config/exec_provider.py

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Copyright 2016 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
import json
15+
import os
16+
import subprocess
17+
import sys
18+
19+
from .config_exception import ConfigException
20+
21+
22+
class ExecProvider(object):
23+
def __init__(self, exec_config):
24+
for key in ['command', 'apiVersion']:
25+
if key not in exec_config:
26+
raise ConfigException(
27+
'exec: malformed request. missing key \'%s\'' % key)
28+
self.api_version = exec_config['apiVersion']
29+
self.args = [exec_config['command']]
30+
if 'args' in exec_config:
31+
self.args.extend(exec_config['args'])
32+
self.env = os.environ.copy()
33+
if 'env' in exec_config:
34+
additional_vars = {}
35+
for item in exec_config['env']:
36+
name = item['name']
37+
value = item['value']
38+
additional_vars[name] = value
39+
self.env.update(additional_vars)
40+
41+
def run(self, previous_response=None):
42+
kubernetes_exec_info = {
43+
'apiVersion': self.api_version,
44+
'kind': 'ExecCredential',
45+
'spec': {
46+
'interactive': True
47+
}
48+
}
49+
if previous_response:
50+
kubernetes_exec_info['spec']['response'] = previous_response
51+
self.env['KUBERNETES_EXEC_INFO'] = json.dumps(kubernetes_exec_info)
52+
process = subprocess.Popen(
53+
self.args,
54+
stdout=subprocess.PIPE,
55+
stderr=subprocess.PIPE,
56+
env=self.env,
57+
universal_newlines=True)
58+
(stdout, stderr) = process.communicate()
59+
exit_code = process.wait()
60+
if exit_code != 0:
61+
msg = 'exec: process returned %d' % exit_code
62+
stderr = stderr.strip()
63+
if stderr:
64+
msg += '. %s' % stderr
65+
raise ConfigException(msg)
66+
try:
67+
data = json.loads(stdout)
68+
except ValueError as de:
69+
raise ConfigException(
70+
'exec: failed to decode process output: %s' % de)
71+
for key in ('apiVersion', 'kind', 'status'):
72+
if key not in data:
73+
raise ConfigException(
74+
'exec: malformed response. missing key \'%s\'' % key)
75+
if data['apiVersion'] != self.api_version:
76+
raise ConfigException(
77+
'exec: plugin api version %s does not match %s' %
78+
(data['apiVersion'], self.api_version))
79+
return data['status']

Diff for: config/exec_provider_test.py

+140
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# Copyright 2016 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
import unittest
17+
18+
import mock
19+
20+
from .config_exception import ConfigException
21+
from .exec_provider import ExecProvider
22+
23+
24+
class ExecProviderTest(unittest.TestCase):
25+
26+
def setUp(self):
27+
self.input_ok = {
28+
'command': 'aws-iam-authenticator token -i dummy',
29+
'apiVersion': 'client.authentication.k8s.io/v1alpha1'
30+
}
31+
self.output_ok = """
32+
{
33+
"apiVersion": "client.authentication.k8s.io/v1alpha1",
34+
"kind": "ExecCredential",
35+
"status": {
36+
"token": "dummy"
37+
}
38+
}
39+
"""
40+
41+
def test_missing_input_keys(self):
42+
exec_configs = [{}, {'command': ''}, {'apiVersion': ''}]
43+
for exec_config in exec_configs:
44+
with self.assertRaises(ConfigException) as context:
45+
ExecProvider(exec_config)
46+
self.assertIn('exec: malformed request. missing key',
47+
context.exception.args[0])
48+
49+
@mock.patch('subprocess.Popen')
50+
def test_error_code_returned(self, mock):
51+
instance = mock.return_value
52+
instance.wait.return_value = 1
53+
instance.communicate.return_value = ('', '')
54+
with self.assertRaises(ConfigException) as context:
55+
ep = ExecProvider(self.input_ok)
56+
ep.run()
57+
self.assertIn('exec: process returned %d' %
58+
instance.wait.return_value, context.exception.args[0])
59+
60+
@mock.patch('subprocess.Popen')
61+
def test_nonjson_output_returned(self, mock):
62+
instance = mock.return_value
63+
instance.wait.return_value = 0
64+
instance.communicate.return_value = ('', '')
65+
with self.assertRaises(ConfigException) as context:
66+
ep = ExecProvider(self.input_ok)
67+
ep.run()
68+
self.assertIn('exec: failed to decode process output',
69+
context.exception.args[0])
70+
71+
@mock.patch('subprocess.Popen')
72+
def test_missing_output_keys(self, mock):
73+
instance = mock.return_value
74+
instance.wait.return_value = 0
75+
outputs = [
76+
"""
77+
{
78+
"kind": "ExecCredential",
79+
"status": {
80+
"token": "dummy"
81+
}
82+
}
83+
""", """
84+
{
85+
"apiVersion": "client.authentication.k8s.io/v1alpha1",
86+
"status": {
87+
"token": "dummy"
88+
}
89+
}
90+
""", """
91+
{
92+
"apiVersion": "client.authentication.k8s.io/v1alpha1",
93+
"kind": "ExecCredential"
94+
}
95+
"""
96+
]
97+
for output in outputs:
98+
instance.communicate.return_value = (output, '')
99+
with self.assertRaises(ConfigException) as context:
100+
ep = ExecProvider(self.input_ok)
101+
ep.run()
102+
self.assertIn('exec: malformed response. missing key',
103+
context.exception.args[0])
104+
105+
@mock.patch('subprocess.Popen')
106+
def test_mismatched_api_version(self, mock):
107+
instance = mock.return_value
108+
instance.wait.return_value = 0
109+
wrong_api_version = 'client.authentication.k8s.io/v1'
110+
output = """
111+
{
112+
"apiVersion": "%s",
113+
"kind": "ExecCredential",
114+
"status": {
115+
"token": "dummy"
116+
}
117+
}
118+
""" % wrong_api_version
119+
instance.communicate.return_value = (output, '')
120+
with self.assertRaises(ConfigException) as context:
121+
ep = ExecProvider(self.input_ok)
122+
ep.run()
123+
self.assertIn(
124+
'exec: plugin api version %s does not match' %
125+
wrong_api_version,
126+
context.exception.args[0])
127+
128+
@mock.patch('subprocess.Popen')
129+
def test_ok_01(self, mock):
130+
instance = mock.return_value
131+
instance.wait.return_value = 0
132+
instance.communicate.return_value = (self.output_ok, '')
133+
ep = ExecProvider(self.input_ok)
134+
result = ep.run()
135+
self.assertTrue(isinstance(result, dict))
136+
self.assertTrue('token' in result)
137+
138+
139+
if __name__ == '__main__':
140+
unittest.main()

Diff for: config/kube_config.py

+16-5
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333

3434
from .config_exception import ConfigException
3535
from .dateutil import UTC, format_rfc3339, parse_rfc3339
36+
from .exec_provider import ExecProvider
3637

3738
EXPIRY_SKEW_PREVENTION_DELAY = datetime.timedelta(minutes=5)
3839
KUBE_CONFIG_DEFAULT_LOCATION = os.environ.get('KUBECONFIG', '~/.kube/config')
@@ -172,18 +173,19 @@ def _load_authentication(self):
172173
section of kube-config and stops if it finds a valid authentication
173174
method. The order of authentication methods is:
174175
175-
1. GCP auth-provider
176-
2. token_data
177-
3. token field (point to a token file)
178-
4. oidc auth-provider
179-
5. username/password
176+
1. auth-provider (gcp, azure, oidc)
177+
2. token field (point to a token file)
178+
3. exec provided plugin
179+
4. username/password
180180
"""
181181
if not self._user:
182182
return
183183
if self._load_auth_provider_token():
184184
return
185185
if self._load_user_token():
186186
return
187+
if self._load_from_exec_plugin():
188+
return
187189
self._load_user_pass_token()
188190

189191
def _load_auth_provider_token(self):
@@ -340,6 +342,15 @@ def _refresh_oidc(self, provider):
340342
provider['config'].value['id-token'] = refresh['id_token']
341343
provider['config'].value['refresh-token'] = refresh['refresh_token']
342344

345+
def _load_from_exec_plugin(self):
346+
if 'exec' not in self._user:
347+
return
348+
status = ExecProvider(self._user['exec']).run()
349+
if 'token' not in status:
350+
return
351+
self.token = "Bearer %s" % status['token']
352+
return True
353+
343354
def _load_user_token(self):
344355
token = FileOrData(
345356
self._user, 'tokenFile', 'token',

Diff for: config/kube_config_test.py

+31
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,13 @@ class TestKubeConfigLoader(BaseTestCase):
422422
"user": "non_existing_user"
423423
}
424424
},
425+
{
426+
"name": "exec_cred_user",
427+
"context": {
428+
"cluster": "default",
429+
"user": "exec_cred_user"
430+
}
431+
},
425432
],
426433
"clusters": [
427434
{
@@ -573,6 +580,16 @@ class TestKubeConfigLoader(BaseTestCase):
573580
"client-key-data": TEST_CLIENT_KEY_BASE64,
574581
}
575582
},
583+
{
584+
"name": "exec_cred_user",
585+
"user": {
586+
"exec": {
587+
"apiVersion": "client.authentication.k8s.io/v1alpha1",
588+
"command": "aws-iam-authenticator",
589+
"args": ["token", "-i", "dummy-cluster"]
590+
}
591+
}
592+
},
576593
]
577594
}
578595

@@ -849,6 +866,20 @@ def test_non_existing_user(self):
849866
active_context="non_existing_user").load_and_set(actual)
850867
self.assertEqual(expected, actual)
851868

869+
@mock.patch('kubernetes.config.kube_config.ExecProvider')
870+
def test_user_exec_auth(self, mock):
871+
instance = mock.return_value
872+
instance.run.return_value = {
873+
"token": "dummy"
874+
}
875+
expected = FakeConfig(host=TEST_HOST, api_key={
876+
"authorization": "Bearer dummy"})
877+
actual = FakeConfig()
878+
KubeConfigLoader(
879+
config_dict=self.TEST_KUBE_CONFIG,
880+
active_context="exec_cred_user").load_and_set(actual)
881+
self.assertEqual(expected, actual)
882+
852883

853884
if __name__ == '__main__':
854885
unittest.main()

0 commit comments

Comments
 (0)