Newer
Older
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
# Copyright 2015, Wichert Akkerman <wichert@wiggy.net>
# Copyright 2022 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import datetime
import logging
import time
import warnings
from json import JSONEncoder
import jwt
from pyramid.renderers import JSON
from webob.cookies import CookieProfile
from zope.interface import implementer
from pyramid.authentication import CallbackAuthenticationPolicy
from pyramid.interfaces import IAuthenticationPolicy, IRendererFactory
from pyramid.request import Request
from pyramid.response import Response
log = logging.getLogger(__name__)
marker = []
# Adapted from https://github.com/wichert/pyramid_jwt
# A custom cookie serializer was created to prevent the token to be base64 encoded
class IdentitySerializer:
"""
A custom serializer which simply returns the given value
Needed as the JWT token is already base64 encoded
"""
def dumps(self, value):
return value
def loads(self, value):
return value
class PyramidJSONEncoderFactory(JSON):
def __init__(self, pyramid_registry=None, **kw):
super().__init__(**kw)
self.registry = pyramid_registry
def __call__(self, *args, **kwargs):
json_renderer = None
if self.registry is not None:
json_renderer = self.registry.queryUtility(
IRendererFactory, "cubicweb_api_json", default=JSONEncoder
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
)
request = kwargs.get("request")
if not kwargs.get("default") and isinstance(json_renderer, JSON):
self.components = json_renderer.components
kwargs["default"] = self._make_default(request)
return JSONEncoder(*args, **kwargs)
json_encoder_factory = PyramidJSONEncoderFactory(None)
@implementer(IAuthenticationPolicy)
class JWTAuthenticationPolicy(CallbackAuthenticationPolicy):
def __init__(
self,
private_key,
public_key=None,
algorithm="HS512",
leeway=0,
expiration=None,
default_claims=None,
http_header="Authorization",
auth_type="JWT",
callback=None,
json_encoder=None,
audience=None,
):
self.private_key = private_key
self.public_key = public_key if public_key is not None else private_key
self.algorithm = algorithm
self.leeway = leeway
self.default_claims = default_claims if default_claims else {}
self.http_header = http_header
self.auth_type = auth_type
if expiration:
if not isinstance(expiration, datetime.timedelta):
expiration = datetime.timedelta(seconds=expiration)
self.expiration = expiration
else:
self.expiration = None
if audience:
self.audience = audience
else:
self.audience = None
self.callback = callback
if json_encoder is None:
json_encoder = json_encoder_factory
self.json_encoder = json_encoder
self.jwt_std_claims = ("sub", "iat", "exp", "aud")
def create_token(self, principal, expiration=None, audience=None, **claims):
payload = self.default_claims.copy()
payload.update(claims)
payload["sub"] = principal
payload["iat"] = iat = datetime.datetime.utcnow()
expiration = expiration or self.expiration
audience = audience or self.audience
if expiration:
if not isinstance(expiration, datetime.timedelta):
expiration = datetime.timedelta(seconds=expiration)
payload["exp"] = iat + expiration
if audience:
payload["aud"] = audience
token = jwt.encode(
payload,
self.private_key,
algorithm=self.algorithm,
json_encoder=self.json_encoder,
)
if not isinstance(token, str): # Python3 unicode madness
token = token.decode("ascii")
return token
def get_claims(self, request: Request):
if self.http_header == "Authorization":
try:
if request.authorization is None:
return {}
except ValueError: # Invalid Authorization header
return {}
(auth_type, token) = request.authorization
if auth_type != self.auth_type:
return {}
else:
token = request.headers.get(self.http_header)
if not token:
return {}
return self.jwt_decode(request, token)
def jwt_decode(self, request: Request, token: str):
try:
claims = jwt.decode(
token,
self.public_key,
algorithms=[self.algorithm],
leeway=self.leeway,
audience=self.audience,
)
return claims
except jwt.InvalidTokenError as e:
log.warning("Invalid JWT token from %s: %s", request.remote_addr, e)
return {}
def unauthenticated_userid(self, request: Request):
return request.jwt_claims.get("sub")
def remember(self, request: Request, principal, **kw):
warnings.warn(
"JWT tokens need to be returned by an API. Using remember() "
"has no effect.",
stacklevel=3,
)
return []
def forget(self, request: Request):
warnings.warn(
"JWT tokens are managed by API (users) manually. Using forget() "
"has no effect.",
stacklevel=3,
)
return []
class ReissueError(Exception):
pass
@implementer(IAuthenticationPolicy)
class JWTCookieAuthenticationPolicy(JWTAuthenticationPolicy):
def __init__(
self,
private_key,
public_key=None,
algorithm="HS512",
leeway=0,
expiration=None,
default_claims=None,
http_header="Authorization",
auth_type="JWT",
callback=None,
json_encoder=None,
audience=None,
cookie_name=None,
https_only=True,
reissue_time=None,
cookie_path=None,
):
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
private_key,
public_key,
algorithm,
leeway,
expiration,
default_claims,
http_header,
auth_type,
callback,
json_encoder,
audience,
)
self.https_only = https_only
self.cookie_name = cookie_name or "Authorization"
self.max_age = self.expiration and self.expiration.total_seconds()
if reissue_time and isinstance(reissue_time, datetime.timedelta):
reissue_time = reissue_time.total_seconds()
self.reissue_time = reissue_time
self.cookie_profile = CookieProfile(
cookie_name=self.cookie_name,
secure=self.https_only,
max_age=self.max_age,
httponly=True,
path=cookie_path,
serializer=IdentitySerializer(),
)
@staticmethod
def make_from(policy, **kwargs):
if not isinstance(policy, JWTAuthenticationPolicy):
pol_type = policy.__class__.__name__
raise ValueError(f"Invalid policy type {pol_type}")
return JWTCookieAuthenticationPolicy(
private_key=policy.private_key,
public_key=policy.public_key,
algorithm=policy.algorithm,
leeway=policy.leeway,
expiration=policy.expiration,
default_claims=policy.default_claims,
http_header=policy.http_header,
auth_type=policy.auth_type,
callback=policy.callback,
json_encoder=policy.json_encoder,
audience=policy.audience,
**kwargs,
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
)
def _get_cookies(self, request: Request, value, max_age=None, domains=None):
profile = self.cookie_profile(request)
if domains is None:
domains = [request.domain]
kw = {"domains": domains}
if max_age is not None:
kw["max_age"] = max_age
headers = profile.get_headers(value, **kw)
return headers
def remember(self, request: Request, principal, **kw):
token = self.create_token(principal, self.expiration, self.audience, **kw)
if hasattr(request, "_jwt_cookie_reissued"):
request._jwt_cookie_reissue_revoked = True
domains = kw.get("domains")
return self._get_cookies(request, token, self.max_age, domains=domains)
def forget(self, request: Request):
request._jwt_cookie_reissue_revoked = True
return self._get_cookies(request, None)
def get_claims(self, request: Request):
profile = self.cookie_profile.bind(request)
cookie = profile.get_value()
reissue = self.reissue_time is not None
if cookie is None:
return {}
claims = self.jwt_decode(request, cookie)
if reissue and not hasattr(request, "_jwt_cookie_reissued"):
self._handle_reissue(request, claims)
return claims
def _handle_reissue(self, request: Request, claims: dict):
if not request or not claims:
raise ValueError("Cannot handle JWT reissue: insufficient arguments")
if "iat" not in claims:
raise ReissueError("Token claim's is missing IAT")
if "sub" not in claims:
raise ReissueError("Token claim's is missing SUB")
token_dt = claims["iat"]
principal = claims["sub"]
now = time.time()
if now < token_dt + self.reissue_time:
# Token not yet eligible for reissuing
return
extra_claims = dict(
filter(lambda item: item[0] not in self.jwt_std_claims, claims.items())
)
headers = self.remember(request, principal, **extra_claims)
def reissue_jwt_cookie(inner_request: Request, inner_response: Response):
if not hasattr(inner_request, "_jwt_cookie_reissue_revoked"):
for k, v in headers:
inner_response.headerlist.append((k, v))
request.add_response_callback(reissue_jwt_cookie)
request._jwt_cookie_reissued = True