Debian Codegraph @

tests/test_oauthglue.py

raw
1 """
2 test_oauthglue.py
3 ~~~~~~~~~~~~~~~~~
4
5 OAuth glue tests - oauthglue is a very thin shim between FS and authlib
6
7 :copyright: (c) 2022-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9 """
10
11 import pytest
12 import urllib.parse
13 from urllib.parse import parse_qsl, urlsplit
14
15 from flask import redirect
16 from flask_wtf import CSRFProtect
17
18 from flask_security import FsOAuthProvider
19 from tests.test_utils import (
20 authenticate,
21 capture_flashes,
22 check_location,
23 get_csrf_token,
24 get_form_action,
25 get_form_input_value,
26 get_session,
27 init_app_with_options,
28 is_authenticated,
29 json_authenticate,
30 logout,
31 reset_fresh,
32 setup_tf_sms,
33 )
34
35 pytestmark = pytest.mark.oauth()
36
37
38 class MockRequestsResponse:
39 # authlib returns a Requests Response
40 def __init__(self, contents):
41 self.contents = contents
42
43 def json(self):
44 return self.contents
45
46
47 class MockProvider:
48 def __init__(self, name):
49 self.name = name
50 self.raise_exception = None
51 self.identity = "[email protected]"
52
53 def set_exception(self, raise_exception):
54 self.raise_exception = raise_exception
55
56 def set_identity(self, email):
57 self.identity = email
58
59 def get(self, field, token):
60 resp = MockRequestsResponse({"email": self.identity})
61 return resp
62
63 def authorize_access_token(self):
64 if self.raise_exception:
65 raise self.raise_exception
66 return "token"
67
68 def authorize_redirect(self, uri):
69 redirect_url = f"/whatever?redirect_uri={uri}"
70 return redirect(urllib.parse.quote(redirect_url))
71
72
73 class MockAuthlibFlaskClient:
74 def __init__(self):
75 pass
76
77 def register(self, name, **kwargs):
78 setattr(self, name, MockProvider(name))
79
80
81 @pytest.mark.settings(oauth_enable=True, post_login_view="/post_login")
82 @pytest.mark.app_settings(wtf_csrf_enabled=True)
83 def test_github(app, sqlalchemy_datastore, get_message):
84 CSRFProtect(app)
85 init_app_with_options(
86 app,
87 sqlalchemy_datastore,
88 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
89 )
90 client = app.test_client()
91 response = client.get("/login")
92 github_url = get_form_action(response, 1)
93 csrf_token = get_form_input_value(response, field_id="github_csrf_token")
94
95 # make sure required CSRF
96 response = client.post(github_url, follow_redirects=False)
97 assert b"The CSRF token is missing" in response.data
98
99 response = client.post(
100 github_url, data=dict(csrf_token=csrf_token), follow_redirects=False
101 )
102 assert "/whatever" in response.location
103
104 response = client.get("/login/oauthresponse/github", follow_redirects=False)
105 assert response.status_code in [302, 303]
106 assert "/post_login" in response.location
107 # verify logged in
108 response = client.get("/profile", follow_redirects=False)
109 assert response.status_code == 200
110
111
112 @pytest.mark.settings(
113 oauth_enable=True, post_login_view="/post_login", csrf_ignore_unauth_endpoints=True
114 )
115 @pytest.mark.app_settings(wtf_csrf_enabled=True, wtf_csrf_check_default=False)
116 def test_github_nocsrf(app, sqlalchemy_datastore, get_message):
117 # Test if ignore_unauth_endpoints is true - doesn't require CSRF
118 CSRFProtect(app)
119 init_app_with_options(
120 app,
121 sqlalchemy_datastore,
122 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
123 )
124 client = app.test_client()
125 response = client.get("/login")
126 github_url = get_form_action(response, 1)
127 response = client.post(github_url, follow_redirects=False)
128 assert "/whatever" in response.location
129
130
131 @pytest.mark.settings(oauth_enable=True, post_login_view="/post_login")
132 def test_outside_register(app, sqlalchemy_datastore, get_message):
133 def myoauth_fetch_identity(oauth, token):
134 resp = oauth.myoauth.get("user", token=token)
135 profile = resp.json()
136 return "email", profile["email"]
137
138 authlib_oauth = MockAuthlibFlaskClient()
139 authlib_oauth.register("myoauth")
140 init_app_with_options(
141 app, sqlalchemy_datastore, **{"security_args": {"oauth": authlib_oauth}}
142 )
143 # Have to register with Oauthglue.
144 app.security.oauthglue.register_provider("myoauth", None, myoauth_fetch_identity)
145
146 client = app.test_client()
147 response = client.get("/login")
148 myoauth_url = get_form_action(response, 2)
149
150 response = client.post(myoauth_url, follow_redirects=False)
151 assert "/whatever" in response.location
152
153 response = client.get("/login/oauthresponse/myoauth", follow_redirects=False)
154 assert response.status_code in [302, 303]
155 assert "/post_login" in response.location
156 # verify logged in
157 response = client.get("/profile", follow_redirects=False)
158 assert response.status_code == 200
159
160
161 @pytest.mark.settings(oauth_enable=True)
162 def test_bad_api(app, sqlalchemy_datastore, get_message):
163 init_app_with_options(
164 app,
165 sqlalchemy_datastore,
166 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
167 )
168 client = app.test_client()
169
170 response = client.post("/login/oauthstart/foobar")
171 assert response.status_code == 404
172
173 response = client.get("/login/oauthresponse/foobar")
174 assert response.status_code == 404
175
176 from authlib.integrations.base_client.errors import MismatchingStateError
177
178 oauth_app = app.security.oauthglue.oauth_app
179 oauth_app.github.set_exception(MismatchingStateError)
180 response = client.get("/login/oauthresponse/github", follow_redirects=True)
181 assert response.status_code == 200
182 assert (
183 get_message(
184 "OAUTH_HANDSHAKE_ERROR",
185 exerror="mismatching_state",
186 exdesc="CSRF Warning! State not equal in request and response.",
187 )
188 in response.data
189 )
190
191
192 @pytest.mark.settings(oauth_enable=True)
193 def test_unknown_user(app, sqlalchemy_datastore, get_message):
194 init_app_with_options(
195 app,
196 sqlalchemy_datastore,
197 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
198 )
199 client = app.test_client()
200 oauth_app = app.security.oauthglue.oauth_app
201 oauth_app.github.set_identity("[email protected]")
202 response = client.get("/login/oauthresponse/github", follow_redirects=True)
203 assert get_message("IDENTITY_NOT_REGISTERED", id="[email protected]") in response.data
204
205
206 @pytest.mark.settings(oauth_enable=True)
207 def test_disabled_user(app, sqlalchemy_datastore, get_message):
208 init_app_with_options(
209 app,
210 sqlalchemy_datastore,
211 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
212 )
213 client = app.test_client()
214 oauth_app = app.security.oauthglue.oauth_app
215 oauth_app.github.set_identity("[email protected]") # disabled account
216 response = client.get("/login/oauthresponse/github", follow_redirects=True)
217 assert check_location(app, response.request.path, "/login")
218 assert get_message("DISABLED_ACCOUNT") in response.data # should be in flash
219
220
221 @pytest.mark.settings(oauth_enable=True)
222 def test_unicode_email(app, sqlalchemy_datastore, get_message):
223 # Test that we normalize email response from oauth provider
224 init_app_with_options(
225 app,
226 sqlalchemy_datastore,
227 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
228 )
229 client = app.test_client()
230 oauth_app = app.security.oauthglue.oauth_app
231 oauth_app.github.set_identity(
232 "matt@\N{FULLWIDTH LATIN SMALL LETTER L}\N{FULLWIDTH LATIN SMALL LETTER P}.com"
233 )
234 client.get("/login/oauthresponse/github", follow_redirects=True)
235 assert is_authenticated(client, get_message)
236
237
238 @pytest.mark.settings(
239 oauth_enable=True,
240 USER_IDENTITY_ATTRIBUTES=[
241 {"username": {"mapper": lambda x: x}},
242 ],
243 )
244 def test_email_not_identity(app, sqlalchemy_datastore, get_message):
245 # Test that if email isn't an identity attribute - can't use oauth to log in
246 init_app_with_options(
247 app,
248 sqlalchemy_datastore,
249 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
250 )
251 client = app.test_client()
252 response = client.get("/login/oauthresponse/github", follow_redirects=True)
253 assert (
254 b": (Config error - Invalid identity attribute: email). Please try again."
255 in response.data
256 )
257
258
259 def _locked(self, form_error):
260 if self.email == "[email protected]":
261 form_error.append("You are not allowed to do that")
262 return True
263 return False
264
265
266 @pytest.mark.app_settings(TESTING_USER_INJECT=dict(is_locked=_locked))
267 @pytest.mark.settings(oauth_enable=True)
268 def test_override_user_locked(app, sqlalchemy_datastore, get_message):
269 init_app_with_options(
270 app,
271 sqlalchemy_datastore,
272 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
273 )
274 client = app.test_client()
275 oauth_app = app.security.oauthglue.oauth_app
276 oauth_app.github.set_identity("[email protected]") # disabled account
277 response = client.get("/login/oauthresponse/github", follow_redirects=True)
278 assert check_location(app, response.request.path, "/login")
279 assert b"You are not allowed to do that" in response.data # should be in flash
280
281
282 @pytest.mark.two_factor()
283 @pytest.mark.settings(oauth_enable=True)
284 def test_tf(app, sqlalchemy_datastore, get_message):
285 init_app_with_options(
286 app,
287 sqlalchemy_datastore,
288 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
289 )
290 client = app.test_client()
291 authenticate(client)
292 sms_sender = setup_tf_sms(client)
293 logout(client)
294
295 response = client.get("/login?next=/profile")
296 github_url = get_form_action(response, 1)
297
298 response = client.post(github_url, follow_redirects=False)
299 assert "/whatever" in response.location
300 redirect_url = urllib.parse.urlsplit(urllib.parse.unquote(response.location))
301 local_redirect = urllib.parse.parse_qs(redirect_url.query)["redirect_uri"][0]
302
303 response = client.get(local_redirect, follow_redirects=True)
304 sendcode_url = get_form_action(response, 0)
305
306 response = client.post(
307 sendcode_url,
308 data=dict(code=sms_sender.messages[0].split()[-1]),
309 follow_redirects=True,
310 )
311 assert b"Profile Page" in response.data
312
313
314 @pytest.mark.settings(
315 oauth_enable=True,
316 redirect_host="myui.com:8090",
317 redirect_behavior="spa",
318 login_error_view="/login-error",
319 post_oauth_login_view="/post-login",
320 csrf_ignore_unauth_endpoints=False,
321 )
322 @pytest.mark.app_settings(wtf_csrf_enabled=True)
323 def test_spa(app, sqlalchemy_datastore, get_message):
324 CSRFProtect(app)
325 headers = {"Accept": "application/json", "Content-Type": "application/json"}
326
327 init_app_with_options(
328 app,
329 sqlalchemy_datastore,
330 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
331 )
332 client = app.test_client()
333 csrf_token = get_csrf_token(client)
334 headers["X-CSRF-Token"] = csrf_token
335
336 response = client.post("/login/oauthstart/github", headers=headers)
337 assert "/whatever" in response.location
338 redirect_url = urllib.parse.urlsplit(urllib.parse.unquote(response.location))
339 local_redirect = urllib.parse.parse_qs(redirect_url.query)["redirect_uri"][0]
340
341 response = client.get(local_redirect, headers=headers)
342 assert response.status_code in [302, 303]
343
344 split = urlsplit(response.location)
345 assert "myui.com:8090" == split.netloc
346 assert "/post-login" == split.path
347 qparams = dict(parse_qsl(split.query))
348 assert qparams["email"] == "[email protected]"
349
350 # try unknown user - should redirect to login_error_view
351 oauth_app = app.security.oauthglue.oauth_app
352 oauth_app.github.set_identity("[email protected]")
353 response = client.get("/login/oauthresponse/github", follow_redirects=False)
354 split = urlsplit(response.location)
355 assert "/login-error" == split.path
356 qparams = dict(parse_qsl(split.query))
357 assert (
358 qparams["error"]
359 == get_message("IDENTITY_NOT_REGISTERED", id="[email protected]").decode()
360 )
361
362 # try fake oauth exception
363 from authlib.integrations.base_client.errors import MismatchingStateError
364
365 oauth_app.github.set_exception(MismatchingStateError)
366 response = client.get("/login/oauthresponse/github", follow_redirects=False)
367 split = urlsplit(response.location)
368 assert "/login-error" == split.path
369 qparams = dict(parse_qsl(split.query))
370 msg = get_message(
371 "OAUTH_HANDSHAKE_ERROR",
372 exerror="mismatching_state",
373 exdesc="CSRF Warning! State not equal in request and response.",
374 )
375 assert qparams["error"] == msg.decode()
376
377
378 @pytest.mark.settings(oauth_enable=True, post_login_view="/post-login")
379 def test_already_auth(app, sqlalchemy_datastore, get_message):
380 headers = {"Accept": "application/json", "Content-Type": "application/json"}
381 init_app_with_options(
382 app,
383 sqlalchemy_datastore,
384 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
385 )
386 client = app.test_client()
387 authenticate(client)
388 assert is_authenticated(client, get_message)
389
390 # json
391 response = client.post("/login/oauthstart/github", headers=headers)
392 assert response.status_code == 400
393
394 # forms
395 response = client.post("/login/oauthstart/github", follow_redirects=False)
396 assert response.status_code in [302, 303]
397 check_location(app, response.location, "/post-login")
398
399
400 @pytest.mark.settings(oauth_enable=True, post_login_view="/post-login")
401 def test_simple_next(app, sqlalchemy_datastore, get_message):
402 # For oauth we stash 'next' in the session since we can't really
403 # send it all around the oauth providers.
404 init_app_with_options(
405 app,
406 sqlalchemy_datastore,
407 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
408 )
409 client = app.test_client()
410 response = client.get("/profile", follow_redirects=True)
411 github_url = get_form_action(response, 1)
412
413 response = client.post(github_url, follow_redirects=False)
414 assert "/whatever" in response.location
415 session = get_session(response)
416 assert "fs_oauth_next" in session
417
418 response = client.get("/login/oauthresponse/github", follow_redirects=False)
419 assert response.status_code in [302, 303]
420 assert check_location(app, response.location, "/profile")
421 session = get_session(response)
422 assert "fs_oauth_next" not in session
423
424
425 @pytest.mark.settings(oauth_enable=True, post_login_view="/post_login")
426 def test_provider_class(app, sqlalchemy_datastore, get_message):
427 from authlib.integrations.base_client.errors import MismatchingStateError
428
429 class MyOauthProvider(FsOAuthProvider):
430 def fetch_identity_cb(self, oauth, token):
431 resp = oauth.myoauth.get("user", token=token)
432 profile = resp.json()
433 return "email", profile["email"]
434
435 def oauth_response_failure(self, error_view, e):
436 assert isinstance(e, MismatchingStateError)
437 return redirect("/uh-oh")
438
439 init_app_with_options(
440 app,
441 sqlalchemy_datastore,
442 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
443 )
444 # Have to register with Oauthglue.
445 app.security.oauthglue.register_provider_ext(MyOauthProvider("myoauth"))
446
447 client = app.test_client()
448 response = client.get("/login")
449 myoauth_url = get_form_action(response, 2)
450
451 response = client.post(myoauth_url, follow_redirects=False)
452 assert "/whatever" in response.location
453
454 # test error - and that our handler is called
455 oauth_app = app.security.oauthglue.oauth_app
456 oauth_app.myoauth.set_exception(MismatchingStateError)
457 response = client.get("/login/oauthresponse/myoauth", follow_redirects=False)
458 assert response.status_code in [302, 303]
459 assert check_location(app, response.location, "/uh-oh")
460
461 # now log in successfully
462 oauth_app.myoauth.set_exception(None)
463
464 response = client.get("/login/oauthresponse/myoauth", follow_redirects=False)
465 assert response.status_code in [302, 303]
466 assert check_location(app, response.location, "/post_login")
467 assert is_authenticated(client, get_message)
468
469
470 @pytest.mark.settings(oauth_enable=True, post_verify_view="/post_verify")
471 def test_verify(app, sqlalchemy_datastore, get_message):
472 init_app_with_options(
473 app,
474 sqlalchemy_datastore,
475 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
476 )
477 client = app.test_client()
478
479 # just authenticate using github
480 client.get("/login/oauthresponse/github", follow_redirects=False)
481 assert is_authenticated(client, get_message)
482
483 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
484 # This will return the /verify form
485 response = client.get("/fresh", follow_redirects=True)
486 github_url = get_form_action(response, 1)
487 assert "oauth-verify-start" in github_url
488 response = client.post(github_url, follow_redirects=False)
489 assert "/whatever" in response.location
490 session = get_session(response)
491 assert "fs_oauth_next" in session
492
493 with capture_flashes() as flashes:
494 response = client.get(
495 "/login/oauth-verify-response/github", follow_redirects=True
496 )
497 assert flashes[0]["category"] == "info"
498 assert flashes[0]["message"].encode("utf-8") == get_message(
499 "REAUTHENTICATION_SUCCESSFUL"
500 )
501 assert b"Fresh Only" in response.data
502 session = get_session(response)
503 assert "fs_oauth_next" not in session
504
505
506 @pytest.mark.settings(oauth_enable=True)
507 def test_verify_unknown_user(app, sqlalchemy_datastore, get_message):
508 init_app_with_options(
509 app,
510 sqlalchemy_datastore,
511 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
512 )
513 client = app.test_client()
514 authenticate(client)
515 oauth_app = app.security.oauthglue.oauth_app
516 oauth_app.github.set_identity("[email protected]") # this will cause response to fail
517
518 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
519 response = client.get("/fresh", follow_redirects=True)
520 github_url = get_form_action(response, 1)
521 response = client.post(github_url, follow_redirects=False)
522
523 with capture_flashes() as flashes:
524 redirect_url = urllib.parse.urlsplit(urllib.parse.unquote(response.location))
525 local_redirect = urllib.parse.parse_qs(redirect_url.query)["redirect_uri"][0]
526 response = client.get(local_redirect, follow_redirects=True)
527 assert flashes[0]["category"] == "error"
528 assert flashes[0]["message"].encode("utf-8") == get_message(
529 "IDENTITY_NOT_REGISTERED", id="[email protected]"
530 )
531 assert b"Reauthenticate" in response.data
532 session = get_session(response)
533 assert "fs_oauth_next" not in session
534
535
536 @pytest.mark.settings(oauth_enable=True)
537 def test_verify_evil_user(app, sqlalchemy_datastore, get_message):
538 # Ensure a valid (evil) user can't use their oauth credentials to 'verify'
539 # another user.
540 init_app_with_options(
541 app,
542 sqlalchemy_datastore,
543 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
544 )
545 client = app.test_client()
546 authenticate(client) # authenticate as [email protected]
547 oauth_app = app.security.oauthglue.oauth_app
548 oauth_app.github.set_identity("[email protected]") # a valid user
549
550 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
551 response = client.get("/fresh", follow_redirects=True)
552 github_url = get_form_action(response, 1)
553 response = client.post(github_url, follow_redirects=False)
554
555 with capture_flashes() as flashes:
556 redirect_url = urllib.parse.urlsplit(urllib.parse.unquote(response.location))
557 local_redirect = urllib.parse.parse_qs(redirect_url.query)["redirect_uri"][0]
558 response = client.get(local_redirect, follow_redirects=True)
559 assert flashes[0]["category"] == "error"
560 assert flashes[0]["message"].encode("utf-8") == get_message(
561 "IDENTITY_NOT_REGISTERED", id="[email protected]"
562 )
563 assert b"Reauthenticate" in response.data
564 session = get_session(response)
565 assert "fs_oauth_next" not in session
566
567
568 @pytest.mark.settings(
569 oauth_enable=True,
570 oauth_builtin_providers=["github"],
571 post_oauth_verify_view="/post_oauth_verify",
572 redirect_host="myui.com:8090",
573 redirect_behavior="spa",
574 )
575 def test_verify_spa(app, sqlalchemy_datastore, get_message):
576 headers = {"Accept": "application/json", "Content-Type": "application/json"}
577 init_app_with_options(
578 app,
579 sqlalchemy_datastore,
580 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
581 )
582 client = app.test_client()
583 json_authenticate(client)
584
585 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
586 response = client.get("/fresh", headers=headers)
587 assert response.json["response"]["reauth_required"]
588 assert response.json["response"]["oauth_enabled"]
589 assert response.json["response"]["oauth_providers"] == ["github"]
590
591 response = client.post("/login/oauth-verify-start/github", follow_redirects=False)
592 assert "/whatever" in response.location
593
594 # this is what github would call
595 response = client.get("/login/oauth-verify-response/github", follow_redirects=False)
596 assert (
597 response.location == "//myui.com:8090/post_oauth_verify?"
598 "email=matt%40lp.com&identity=matt%40lp.com"
599 )
600
601
602 @pytest.mark.settings(
603 oauth_enable=True, redirect_behavior="spa", verify_error_view="/verify-error"
604 )
605 def test_verify_unknown_user_spa(app, sqlalchemy_datastore, get_message):
606 init_app_with_options(
607 app,
608 sqlalchemy_datastore,
609 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
610 )
611 client = app.test_client()
612 json_authenticate(client)
613
614 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
615 oauth_app = app.security.oauthglue.oauth_app
616 oauth_app.github.set_identity("[email protected]")
617
618 # what github would have called
619 response = client.get("/login/oauth-verify-response/github")
620 assert "/verify-error" in response.location
621 assert "not+registered" in response.location
622
623
624 @pytest.mark.settings(
625 oauth_enable=True, redirect_behavior="spa", verify_error_view="/verify-error"
626 )
627 def test_verify_spa_exc(app, sqlalchemy_datastore, get_message):
628 init_app_with_options(
629 app,
630 sqlalchemy_datastore,
631 **{"security_args": {"oauth": MockAuthlibFlaskClient()}},
632 )
633 client = app.test_client()
634 json_authenticate(client)
635 # try fake oauth exception
636 from authlib.integrations.base_client.errors import MismatchingStateError
637
638 oauth_app = app.security.oauthglue.oauth_app
639 oauth_app.github.set_exception(MismatchingStateError)
640 response = client.get("/login/oauth-verify-response/github", follow_redirects=False)
641 split = urlsplit(response.location)
642 assert "/verify-error" == split.path
643 qparams = dict(parse_qsl(split.query))
644 msg = get_message(
645 "OAUTH_HANDSHAKE_ERROR",
646 exerror="mismatching_state",
647 exdesc="CSRF Warning! State not equal in request and response.",
648 )
649 assert qparams["error"] == msg.decode()