-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathplugin.py
354 lines (290 loc) · 14.1 KB
/
plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# coding=utf-8
# Copyright 2016 Spanish National Research Council
# Copyright 2016 INDIGO-DataCloud
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pkce
import socket
import webbrowser
import uuid
from keystoneauth1 import _utils as utils
from keystoneauth1 import access
from keystoneauth1.identity.v3 import federation
from keystoneauth1.identity.v3 import oidc
from positional import positional
from six.moves import BaseHTTPServer
from six.moves import urllib
from six.moves.urllib import parse as urlparse
from keystoneauth_oidc import exceptions
_logger = utils.get_logger(__name__)
class _ClientCallbackServer(BaseHTTPServer.HTTPServer):
"""HTTP server to handle the OpenID Connect callback to localhost.
This server will wait for a single request, storing the authorization code
obtained from the incoming request into the 'code' attribute.
"""
code = None
def server_bind(self):
"""Override original bind and set a timeout.
Authentication may fail and we could get stuck here forever, so this
method sets up a sane timeout.
"""
# NOTE(aloga): cannot call super here, as HTTPServer does not have
# object as an ancestor
BaseHTTPServer.HTTPServer.server_bind(self)
self.socket.settimeout(60)
class _ClientCallbackHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""HTTP request handler for the OpenID Connect redirect callback.
The OpenID Connect authorization code grant type is a redirection based
flow where the client needs to be capable of receiving incoming requests
(via redirection), where the access code will be obtained.
This class implements a request handler that will process a single request
and store the obtained code into the server's 'code' attribute
"""
def do_GET(self):
"""Handle a GET request and obtain an authorization code.
This method will process the query parameters and get an
authorization code from them, if any, storing it in the
server's `code` attribute.
"""
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(
b"<html><head><title>Authentication Status OK</title></head>"
b"<body><p>The authentication flow has been completed.</p>"
b"<p>You can close this window.</p>"
b"</body></html>")
parsed = urlparse.urlparse(self.path)
query = urlparse.parse_qs(parsed.query)
code = query.get("code", [None])[0]
state = query.get("state", [None])[0]
self.server.code = code
self.server.state = state
def log_message(self, format, *args):
"""Do not log messages to stdout."""
def _wait_for_code(redirect_host, redirect_port):
"""Spawn an HTTP server and wait for the auth code.
:param redirect_host: The hostname where the authorization request will
be redirected. This normally is localhost. This
indicates the hostname where the callback http
server will listen.
:type redirect_host: string
:param redirect_port: The port where the authorization request will
be redirected. This indicates the port where the
callback http server will bind to.
:type redirect_port: int
"""
server_address = (redirect_host, redirect_port)
try:
httpd = _ClientCallbackServer(server_address,
_ClientCallbackHandler)
except socket.error:
_logger.error("Cannot spawn the callback server on port "
"%s, please specify a different port." %
redirect_port)
raise
httpd.handle_request()
if httpd.code is not None:
return httpd.code, httpd.state
else:
raise exceptions.MissingOidcAuthorizationCode()
class OidcAuthorizationCode(oidc._OidcBase):
"""Implementation for OpenID Connect Authorization Code."""
grant_type = 'authorization_code'
@positional(4)
def __init__(self, auth_url, identity_provider, protocol, client_id,
client_secret=None,
access_token_endpoint=None,
authorization_endpoint=None,
discovery_endpoint=None,
access_token_type='access_token',
redirect_host="localhost", redirect_port=8080,
**kwargs):
"""The OpenID Authorization Code plugin expects the following.
:param redirect_host: The hostname where the authorization request will
be redirected. This normally is localhost. This
indicates the hostname where the callback http
server will listen.
:type redirect_host: string
:param redirect_port: The port where the authorization request will
be redirected. This indicates the port where the
callback http server will bind to.
:type redirect_port: int
"""
super(OidcAuthorizationCode, self).__init__(
auth_url=auth_url,
identity_provider=identity_provider,
protocol=protocol,
client_id=client_id,
client_secret=client_secret,
access_token_endpoint=access_token_endpoint,
discovery_endpoint=discovery_endpoint,
access_token_type=access_token_type,
**kwargs)
self.authorization_endpoint = authorization_endpoint
self.redirect_host = redirect_host
self.redirect_port = int(redirect_port)
self.redirect_uri = "http://%s:%s" % (self.redirect_host, self.redirect_port)
self.code_verifier = None
self.code_challenge = None
self.state = uuid.uuid4().hex
if client_secret in ['', None]:
self.code_verifier, self.code_challenge = pkce.generate_pkce_pair()
def _get_authorization_endpoint(self, session):
"""Get the "authorization_endpoint" for the OpenID Connect flow.
This method will return the correct authorization endpoint to be used.
If the user has explicitly passed an authoriation_token_endpoint to the
constructor that will be returned. If there is no explicit endpoint and
a discovery url is provided, it will try to get it from the discovery
document. If nothing is found, an exception will be raised.
:param session: a session object to send out HTTP requests.
:type session: keystoneauth1.session.Session
:return: the endpoint to use
:rtype: string or None if no endpoint is found
"""
if self.authorization_endpoint is not None:
return self.authorization_endpoint
discovery = self._get_discovery_document(session)
endpoint = discovery.get("authorization_endpoint")
if endpoint is None:
raise exceptions.OidcAuthorizationEndpointNotFound()
return endpoint
def _get_authorization_code(self, session):
"""Get an authorization code from the authorization endpoint.
:param session: a session object to send out HTTP requests.
:type session: keystoneauth1.session.Session
"""
payload = {"client_id": self.client_id,
"response_type": "code",
"scope": self.scope,
"redirect_uri": self.redirect_uri,
"state": self.state}
if self.code_challenge is not None:
payload.update({
'code_challenge': self.code_challenge,
'code_challenge_method': 'S256'
})
url = "%s?%s" % (self._get_authorization_endpoint(session),
urllib.parse.urlencode(payload))
webbrowser.open(url, new=1, autoraise=True)
code, _ = _wait_for_code(self.redirect_host, self.redirect_port)
return code
def _get_access_token(self, session, payload):
"""Exchange a variety of user supplied values for an access token.
:param session: a session object to send out HTTP requests.
:type session: keystoneauth1.session.Session
:param payload: a dict containing various OpenID Connect values, for
example::
{'grant_type': 'password', 'username': self.username,
'password': self.password, 'scope': self.scope}
:type payload: dict
"""
access_token_endpoint = self._get_access_token_endpoint(session)
if self.code_verifier is not None:
client_auth = None
else:
client_auth = (self.client_id, self.client_secret)
op_response = session.post(access_token_endpoint,
requests_auth=client_auth,
data=payload,
authenticated=False)
access_token = op_response.json()[self.access_token_type]
return access_token
def get_payload(self, session):
"""Get an authorization grant for the "authorization_code" grant type.
:param session: a session object to send out HTTP requests.
:type session: keystoneauth1.session.Session
:returns: a python dictionary containing the payload to be exchanged
:rtype: dict
"""
code = self._get_authorization_code(session)
payload = {'redirect_uri': self.redirect_uri, 'code': code,
'scope': self.scope}
if self.code_verifier is not None:
payload.update({
'client_id': self.client_id,
'code_verifier': self.code_verifier
})
return payload
class OpenIDConnect(federation.FederationBaseAuth):
"""Implementation for OpenID Connect authentication."""
@positional(3)
def __init__(self, auth_url, identity_provider, protocol,
redirect_host="localhost", redirect_port=8080,
**kwargs):
"""The OpenID Connect plugin expects the following arguments.
:param redirect_host: The hostname where the authorization request will
be redirected. This normally is localhost. This
indicates the hostname where the callback http
server will listen.
:type redirect_host: string
:param redirect_port: The port where the authorization request will
be redirected. This indicates the port where the
callback http server will bind to.
:type redirect_port: int
"""
super(OpenIDConnect, self).__init__(
auth_url=auth_url,
identity_provider=identity_provider,
protocol=protocol,
**kwargs)
self.redirect_host = redirect_host
self.redirect_port = int(redirect_port)
self.redirect_uri = "http://%s:%s" % (self.redirect_host,
self.redirect_port)
def _get_keystone_token(self, session):
# We initiate the auth request to Keystone. We indicate the oscli=1
# query param so as to start and out-of-bound authentication.
auth_response = session.post(self.federated_token_url + "?oscli=1",
redirect=False,
authenticated=False)
# Keystone will return a 302 redirect. We need to point the user to
# that URL so that the auth request is authorized.
redirect_url = auth_response.headers["location"]
webbrowser.open(redirect_url, new=1, autoraise=True)
code, state = _wait_for_code(self.redirect_host, self.redirect_port)
# Now that we have the code and state, we can finish the token request
# by sending them back to the Keystone auth endpoing, finishing the
# out-of-bound authentication
params = {
"code": code,
"state": state,
"oscli": 1,
}
auth_response = session.get(self.federated_token_url,
params=params,
authenticated=False)
return auth_response
def get_unscoped_auth_ref(self, session):
"""Authenticate with a Keystone server with OpenID Connect.
This plugin expects that the OpenID Connect Client is the Keystone
server, not the OpenStack or Keystone client. No OpenID credentials
need to be configured.
This plugin initiates an auth request to Keystone (to the federation
endpoint) with an special query parameter (oscli=1), indicating that
the OpenID Connect redirection should not be made to the Keystone
server configured URL, but to http://localhost:8080. This way we can
perform out-of-bound authentication as follows: When the Keystone
server returns the redirection, we intercept it and, instead of
following it, we open a web browser, so that the user can authorize the
request, spawning a web server on locahost:8080. After the user has
authorized the auth request, the web browser is redirected to
http://localhost:8080 where we can get the auth code, and send it back
to Keystone to complete the authentication.
:param session: a session object to send out HTTP requests.
:type session: keystoneauth1.session.Session
:returns: a token data representation
:rtype: :py:class:`keystoneauth1.access.AccessInfoV3`
"""
response = self._get_keystone_token(session)
return access.create(resp=response)