forked from jupyterhub/oauthenticator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openshift.py
199 lines (162 loc) · 6.52 KB
/
openshift.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
"""
A JupyterHub authenticator class for use with OpenShift as an identity provider.
"""
import concurrent.futures
import json
import os
from jupyterhub.auth import LocalAuthenticator
from tornado.httpclient import HTTPClient, HTTPRequest
from traitlets import Bool, Set, Unicode, default
from oauthenticator.oauth2 import OAuthenticator
class OpenShiftOAuthenticator(OAuthenticator):
user_auth_state_key = "openshift_user"
@default("scope")
def _scope_default(self):
return ["user:info"]
@default("login_service")
def _login_service_default(self):
return os.environ.get("LOGIN_SERVICE", "OpenShift")
@default("username_claim")
def _username_claim_default(self):
return "name"
@default("http_request_kwargs")
def _http_request_kwargs_default(self):
ca_cert_file = "/run/secrets/kubernetes.io/serviceaccount/ca.crt"
if self.validate_server_cert and os.path.exists(ca_cert_file):
return {"ca_certs": ca_cert_file}
return {}
openshift_url = Unicode(
os.environ.get('OPENSHIFT_URL')
or 'https://openshift.default.svc.cluster.local',
config=True,
help="""
Used to determine the default values for `openshift_auth_api_url` and
`openshift_rest_api_url`.
""",
)
allowed_groups = Set(
config=True,
help="""
Allow members of selected OpenShift groups to sign in.
""",
)
admin_groups = Set(
config=True,
help="""
Allow members of selected OpenShift groups to sign in and consider them
as JupyterHub admins.
If this is set and a user isn't part of one of these groups or listed in
`admin_users`, a user signing in will have their admin status revoked.
""",
)
openshift_auth_api_url = Unicode(
config=True,
help="""
Used to determine the default values for `authorize_url` and
`token_url`.
By default, this is determined on startup by a request to the
`openshift_url` appended with "/.well-known/oauth-authorization-server",
where "issuer" is extracted from the response.
For more context, see the `Obtaining Authorization Server Metadata
section <https://datatracker.ietf.org/doc/html/rfc8414#section-3>`_ in
an OAuth2 standard document.
""",
)
@default("openshift_auth_api_url")
def _openshift_auth_api_url_default(self):
auth_info_url = f"{self.openshift_url}/.well-known/oauth-authorization-server"
# This code run during startup when we can't yet use async
# functionality. Due to this, Tornado's HTTPClient instead of
# AsyncHTTPClient is used. With HTTPClient we can still re-use
# `http_request_args` specific to Tornado's HTTP clients.
#
# A dedicated thread is used for HTTPClient because of
# https://github.com/tornadoweb/tornado/issues/2325#issuecomment-375972739.
#
def fetch_auth_info():
client = HTTPClient()
req = HTTPRequest(auth_info_url, **self.http_request_kwargs)
resp = client.fetch(req)
resp_json = json.loads(resp.body.decode("utf8", "replace"))
return resp_json
with concurrent.futures.ThreadPoolExecutor(1) as executor:
future = executor.submit(fetch_auth_info)
return_value = future.result()
return return_value.get("issuer")
@default("authorize_url")
def _authorize_url_default(self):
return f"{self.openshift_auth_api_url}/oauth/authorize"
@default("token_url")
def _token_url_default(self):
return f"{self.openshift_auth_api_url}/oauth/token"
openshift_rest_api_url = Unicode(
config=True,
help="""
Used to determine the default value for `userdata_url`.
Defaults to the `openshift_url`.
""",
)
@default("openshift_rest_api_url")
def _openshift_rest_api_url_default(self):
return self.openshift_url
@default("userdata_url")
def _userdata_url_default(self):
return f"{self.openshift_rest_api_url}/apis/user.openshift.io/v1/users/~"
# _deprecated_oauth_aliases is used by deprecation logic in OAuthenticator
_deprecated_oauth_aliases = {
"ca_certs": ("http_request_kwargs", "16.0.0", False),
"validate_cert": ("validate_server_cert", "16.0.0"),
**OAuthenticator._deprecated_oauth_aliases,
}
ca_certs = Unicode(
config=True,
help="""
.. versionremoved:: 16.0
Use :attr:`http_request_kwargs`.
""",
)
validate_cert = Bool(
config=True,
help="""
.. deprecated:: 16.0
Use :attr:`validate_server_cert`.
""",
)
def user_info_to_username(self, user_info):
"""
Overrides OAuthenticator.user_info_to_username instead of setting
username_claim as the username is nested inside another dictionary.
"""
return user_info['metadata']['name']
async def update_auth_model(self, auth_model):
"""
Sets admin status to True or False if `admin_groups` is configured and
the user isn't part of `admin_users`. Note that leaving it at None makes
users able to retain an admin status while setting it to False makes it
be revoked.
"""
if auth_model["admin"]:
# auth_model["admin"] being True means the user was in admin_users
return auth_model
if self.admin_groups:
# admin status should in this case be True or False, not None
user_info = auth_model["auth_state"][self.user_auth_state_key]
user_groups = set(user_info["groups"])
auth_model["admin"] = bool(user_groups & self.admin_groups)
return auth_model
async def check_allowed(self, username, auth_model):
"""
Overrides OAuthenticator.check_allowed to also allow users part of
`allowed_groups`.
"""
if await super().check_allowed(username, auth_model):
return True
if self.allowed_groups:
user_info = auth_model["auth_state"][self.user_auth_state_key]
user_groups = set(user_info["groups"])
if user_groups & self.allowed_groups:
return True
# users should be explicitly allowed via config, otherwise they aren't
return False
class LocalOpenShiftOAuthenticator(LocalAuthenticator, OpenShiftOAuthenticator):
"""A version that mixes in local system user creation"""