Debian Codegraph @

mistralclient/auth/keycloak.py

raw symbols SCIP
1 # Copyright 2016 - Nokia Networks
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 logging
16 import os
17 import pprint
18 import urllib
19
20 import requests
21
22 from mistralclient import auth
23
24
25 LOG = logging.getLogger(__name__)
26
27
28 class KeycloakAuthHandler(auth.AuthHandler):
29
30 def authenticate(self, req, session=None):
31 """Performs authentication using Keycloak OpenID Protocol.
32
33 :param req: Request dict containing list of parameters required
34 for Keycloak authentication.
35
36 * auth_url: Base authentication url of KeyCloak server (e.g.
37 "https://my.keycloak:8443/auth"
38 * client_id: Client ID (according to OpenID Connect protocol).
39 * client_secret: Client secret (according to OpenID Connect
40 protocol).
41 * project_name: KeyCloak realm name.
42 * username: User name (Optional, if None then access_token must be
43 provided).
44 * api_key: Password (Optional).
45 * access_token: Access token. If passed, username and password are
46 not used and this method just validates the token and refreshes
47 it if needed (Optional, if None then username must be
48 provided).
49 * cacert: SSL certificate file (Optional).
50 * insecure: If True, SSL certificate is not verified (Optional).
51
52 :param session: Keystone session object. Not used by this plugin.
53
54 """
55
56 if not isinstance(req, dict):
57 raise TypeError('The input "req" is not typeof dict.')
58
59 auth_url = req.get('auth_url')
60 client_id = req.get('client_id')
61 client_secret = req.get('client_secret')
62 realm_name = req.get('project_name')
63 username = req.get('username')
64 password = req.get('api_key')
65 access_token = req.get('access_token')
66 cacert = req.get('cacert')
67 insecure = req.get('insecure', False)
68
69 if not auth_url:
70 raise ValueError('Base authentication url is not provided.')
71
72 if not client_id:
73 raise ValueError('Client ID is not provided.')
74
75 if not realm_name:
76 raise ValueError('Project(realm) name is not provided.')
77
78 if username and access_token:
79 raise ValueError(
80 "User name and access token can't be "
81 "provided at the same time."
82 )
83
84 if not username and not access_token:
85 raise ValueError(
86 'Either user name or access token must be provided.'
87 )
88
89 if access_token:
90 response = self._authenticate_with_token(
91 auth_url,
92 client_id,
93 client_secret,
94 access_token,
95 cacert,
96 insecure
97 )
98 else:
99 response = self._authenticate_with_password(
100 auth_url,
101 client_id,
102 client_secret,
103 realm_name,
104 username,
105 password,
106 cacert,
107 insecure
108 )
109
110 return {'auth_token': response, 'project_id': realm_name}
111
112 @staticmethod
113 def _authenticate_with_token(auth_url, client_id, client_secret,
114 auth_token, cacert=None, insecure=None):
115 # TODO(rakhmerov): Implement.
116 raise NotImplementedError
117
118 @staticmethod
119 def _authenticate_with_password(auth_url, client_id, client_secret,
120 realm_name, username, password,
121 cacert=None, insecure=None):
122 access_token_endpoint = (
123 "%s/realms/%s/protocol/openid-connect/token" %
124 (auth_url, realm_name)
125 )
126
127 verify = None
128 if urllib.parse.urlparse(access_token_endpoint).scheme == "https":
129 verify = False if insecure else cacert if cacert else True
130
131 body = {
132 'grant_type': 'password',
133 'username': username,
134 'password': password,
135 'client_id': client_id,
136 'scope': 'profile'
137 }
138
139 if client_secret:
140 body['client_secret'] = client_secret,
141
142 resp = requests.post(
143 access_token_endpoint,
144 data=body,
145 verify=verify
146 )
147
148 try:
149 resp.raise_for_status()
150 except Exception as e:
151 raise Exception("Failed to get access token:\n %s" % str(e))
152
153 LOG.debug("HTTP response from OIDC provider: %s",
154 pprint.pformat(resp.json()))
155
156 return resp.json()['access_token']
157
158
159 def get_system_ca_file():
160 """Return path to system default CA file."""
161 # Standard CA file locations for Debian/Ubuntu, RedHat/Fedora,
162 # Suse, FreeBSD/OpenBSD, MacOSX, and the bundled ca
163 ca_path = ['/etc/ssl/certs/ca-certificates.crt',
164 '/etc/pki/tls/certs/ca-bundle.crt',
165 '/etc/ssl/ca-bundle.pem',
166 '/etc/ssl/cert.pem',
167 '/System/Library/OpenSSL/certs/cacert.pem',
168 requests.certs.where()]
169 for ca in ca_path:
170 LOG.debug("Looking for ca file %s", ca)
171 if os.path.exists(ca):
172 LOG.debug("Using ca file %s", ca)
173 return ca
174 LOG.warning("System ca file could not be found.")
175
176
177 # An example of working curl request to keycloak
178 # curl -d "client_id=admin-cli" -d "client_secret=secret"
179 # -d "username=admin" -d "password=qwerty" -d "grant_type=password"
180 # "http://localhost:8080/auth/realms/master/protocol/openid-connect/token"
181
182 # An example of using KeyCloak OpenID authentication.
183 if __name__ == '__main__':
184 print("Using username/password to get access token from KeyCloak...")
185
186 auth_handler = KeycloakAuthHandler()
187
188 a_token = auth_handler.authenticate(
189 dict(
190 "https://my.keycloak:8443/auth",
191 client_id="mistral_client",
192 client_secret="secret",
193 project_name="mistral",
194 username="user",
195 api_key="secret",
196 insecure=True
197 )
198 )['auth_token']
199
200 print("Auth token: %s" % a_token)