Debian Codegraph @

tests/consumer/test_oauth2.py

raw
1 import json
2 import re
3 from unittest import mock
4 from urllib.parse import parse_qsl
5
6 import flask
7 import pytest
8 import responses
9 from freezegun import freeze_time
10 from oauthlib.oauth2 import MissingCodeError
11 from oauthlib.oauth2.rfc6749.clients import Client as OAuth2Client
12 from urlobject import URLObject
13 from werkzeug.middleware.proxy_fix import ProxyFix
14
15 from flask_dance.consumer import (
16 OAuth2ConsumerBlueprint,
17 oauth_authorized,
18 oauth_before_login,
19 oauth_error,
20 )
21 from flask_dance.consumer.requests import OAuth2Session
22 from flask_dance.consumer.storage import MemoryStorage
23
24 try:
25 import blinker
26 except ImportError:
27 blinker = None
28 requires_blinker = pytest.mark.skipif(not blinker, reason="requires blinker")
29
30
31 def make_app(login_url=None, debug=False, **kwargs):
32 blueprint = OAuth2ConsumerBlueprint(
33 "test-service",
34 __name__,
35 client_id="client_id",
36 client_secret="client_secret",
37 scope="admin",
38 state="random-string",
39 base_url="https://example.com",
40 authorization_url="https://example.com/oauth/authorize",
41 token_url="https://example.com/oauth/access_token",
42 redirect_to="index",
43 login_url=login_url,
44 **kwargs,
45 )
46 app = flask.Flask(__name__)
47 app.secret_key = "secret"
48 app.register_blueprint(blueprint, url_prefix="/login")
49 app.debug = debug
50 app.config["SERVER_NAME"] = "a.b.c"
51
52 @app.route("/")
53 def index():
54 return "index"
55
56 return app, blueprint
57
58
59 def test_generate_login_url():
60 app, _ = make_app()
61 with app.test_request_context("/"):
62 login_url = flask.url_for("test-service.login")
63 assert login_url == "/login/test-service"
64
65
66 def test_override_login_url():
67 app, _ = make_app(login_url="/crazy/custom/url")
68 with app.test_request_context("/"):
69 login_url = flask.url_for("test-service.login")
70 assert login_url == "/login/crazy/custom/url"
71
72
73 @responses.activate
74 def test_login_url():
75 app, _ = make_app()
76 with app.test_client() as client:
77 resp = client.get(
78 "/login/test-service", base_url="https://a.b.c", follow_redirects=False
79 )
80 # check that we saved the state in the session
81 assert flask.session["test-service_oauth_state"] == "random-string"
82 # check that we redirected the client
83 assert resp.status_code == 302
84 location = URLObject(resp.headers["Location"])
85 assert location.without_query() == "https://example.com/oauth/authorize"
86 assert location.query_dict["client_id"] == "client_id"
87 assert (
88 location.query_dict["redirect_uri"]
89 == "https://a.b.c/login/test-service/authorized"
90 )
91 assert location.query_dict["scope"] == "admin"
92 assert location.query_dict["state"] == "random-string"
93
94
95 @responses.activate
96 def test_login_url_with_pkce():
97 code_challenge_method = "S256" # That should be a default value
98 app, _ = make_app(use_pkce=True)
99 with app.test_client() as client:
100 resp = client.get(
101 "/login/test-service", base_url="https://a.b.c", follow_redirects=False
102 )
103 # check that we saved the code verifier in the session
104 assert "test-service_oauth_code_verifier" in flask.session
105 code_verifier = flask.session["test-service_oauth_code_verifier"]
106 assert 43 <= len(code_verifier) <= 128 # RFC7636 section 4.1
107 code_challenge = OAuth2Client("123").create_code_challenge(
108 code_verifier, code_challenge_method
109 )
110
111 # check that we redirected the client
112 assert resp.status_code == 302
113 location = URLObject(resp.headers["Location"])
114 assert location.without_query() == "https://example.com/oauth/authorize"
115 # check PKCE specific query parameters
116 assert location.query_dict["code_challenge_method"] == code_challenge_method
117 assert location.query_dict["code_challenge"] == code_challenge
118
119
120 @responses.activate
121 def test_login_url_with_invalid_code_challenge_method():
122 app, _ = make_app(use_pkce=True, code_challenge_method="MD5")
123 with app.test_client() as client:
124 resp = client.get(
125 "/login/test-service", base_url="https://a.b.c", follow_redirects=False
126 )
127 # the code verifier is saved in the session ...
128 assert "test-service_oauth_code_verifier" in flask.session
129
130 location = URLObject(resp.headers["Location"])
131 assert location.without_query() == "https://example.com/oauth/authorize"
132 # ... but because the "code challenge method" was invalid it was not added to the query parameters
133 assert "code_challenge_method" not in location.query_dict
134 assert "code_challenge" not in location.query_dict
135
136
137 @responses.activate
138 def test_login_url_forwarded_proto():
139 app, _ = make_app()
140 app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1)
141 with app.test_client() as client:
142 resp = client.get(
143 "/login/test-service",
144 base_url="http://a.b.c",
145 headers={"X-Forwarded-Proto": "https"},
146 follow_redirects=False,
147 )
148 # check that we redirected the client with a https redirect_uri
149 assert resp.status_code == 302
150 location = URLObject(resp.headers["Location"])
151 assert (
152 location.query_dict["redirect_uri"]
153 == "https://a.b.c/login/test-service/authorized"
154 )
155
156
157 @responses.activate
158 def test_authorized_url():
159 responses.add(
160 responses.POST,
161 "https://example.com/oauth/access_token",
162 body='{"access_token":"foobar","token_type":"bearer","scope":"admin"}',
163 )
164 app, _ = make_app()
165 with app.test_client() as client:
166 # reset the session before the request
167 with client.session_transaction() as sess:
168 sess["test-service_oauth_state"] = "random-string"
169 # make the request
170 resp = client.get(
171 "/login/test-service/authorized?code=secret-code&state=random-string",
172 base_url="https://a.b.c",
173 )
174 # check that we redirected the client
175 assert resp.status_code == 302
176 assert resp.headers["Location"] in ("https://a.b.c/", "/")
177 # check that we obtained an access token
178 assert len(responses.calls) == 1
179 request_data = dict(parse_qsl(responses.calls[0].request.body))
180 assert (
181 request_data["redirect_uri"]
182 == "https://a.b.c/login/test-service/authorized"
183 )
184 # check that we stored the access token in the session
185 assert flask.session["test-service_oauth_token"] == {
186 "access_token": "foobar",
187 "scope": ["admin"],
188 "token_type": "bearer",
189 }
190
191
192 def test_authorized_url_no_state():
193 app, _ = make_app()
194 with app.test_client() as client:
195 # make the request, without resetting the session beforehand
196 resp = client.get(
197 "/login/test-service/authorized?code=secret-code&state=random-string",
198 base_url="https://a.b.c",
199 )
200 # check that we redirected the client back to login view
201 assert resp.status_code == 302
202 assert resp.headers["Location"] in (
203 "https://a.b.c/login/test-service",
204 "/login/test-service",
205 )
206 # check that there's nothing in the session
207 assert "test-service_oauth_token" not in flask.session
208
209
210 @responses.activate
211 def test_authorized_url_behind_proxy():
212 responses.add(
213 responses.POST,
214 "https://example.com/oauth/access_token",
215 body='{"access_token":"foobar","token_type":"bearer","scope":"admin"}',
216 )
217 app, _ = make_app()
218 app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1)
219 with app.test_client() as client:
220 # reset the session before the request
221 with client.session_transaction() as sess:
222 sess["test-service_oauth_state"] = "random-string"
223 # make the request
224 resp = client.get(
225 "/login/test-service/authorized?code=secret-code&state=random-string",
226 base_url="http://a.b.c",
227 headers={"X-Forwarded-Proto": "https"},
228 )
229 request_data = dict(parse_qsl(responses.calls[0].request.body))
230 # this should be https
231 assert (
232 request_data["redirect_uri"]
233 == "https://a.b.c/login/test-service/authorized"
234 )
235
236
237 def test_authorized_url_invalid_response():
238 app, _ = make_app(debug=True)
239 with app.test_client() as client:
240 # reset the session before the request
241 with client.session_transaction() as sess:
242 sess["test-service_oauth_state"] = "random-string"
243 # make the request
244 with pytest.raises(MissingCodeError) as missingError:
245 client.get(
246 "/login/test-service/authorized?state=random-string&error_code=1349048&error_message=IMUSEFUL",
247 base_url="https://a.b.c",
248 )
249 match = re.search(r"{[^}]*}", str(missingError.value))
250 err_dict = json.loads(match.group(0))
251 assert err_dict == {
252 "state": "random-string",
253 "error_message": "IMUSEFUL",
254 "error_code": "1349048",
255 }
256
257
258 @responses.activate
259 @freeze_time("2016-01-01 12:00:01")
260 def test_authorized_url_token_lifetime():
261 responses.add(
262 responses.POST,
263 "https://example.com/oauth/access_token",
264 body='{"access_token":"foobar","token_type":"bearer","expires_in":300}',
265 )
266 app, _ = make_app()
267
268 with app.test_client() as client:
269 # reset the session before the request
270 with client.session_transaction() as sess:
271 sess["test-service_oauth_state"] = "random-string"
272 # make the request
273 resp = client.get(
274 "/login/test-service/authorized?code=secret-code&state=random-string",
275 base_url="https://a.b.c",
276 )
277 # check that we redirected the client
278 assert resp.status_code == 302
279 assert resp.headers["Location"] in ("https://a.b.c/", "/")
280 # check that we obtained an access token
281 assert len(responses.calls) == 1
282 request_data = dict(parse_qsl(responses.calls[0].request.body))
283 assert (
284 request_data["redirect_uri"]
285 == "https://a.b.c/login/test-service/authorized"
286 )
287 # check that we stored the access token and expiration date in the session
288 expected_stored_token = {
289 "access_token": "foobar",
290 "token_type": "bearer",
291 "expires_in": 300,
292 "expires_at": 1451649901,
293 }
294 assert flask.session["test-service_oauth_token"] == expected_stored_token
295
296
297 @responses.activate
298 def test_authorized_url_with_pkce():
299 responses.add(
300 responses.POST,
301 "https://example.com/oauth/access_token",
302 body='{"access_token":"foobar","token_type":"bearer","scope":"admin"}',
303 )
304 app, _ = make_app(use_pkce=True)
305
306 _state = "random-string"
307 _code_verifier = "random-code-very-secure"
308 with app.test_client() as client:
309 # reset the session before the request
310 with client.session_transaction() as sess:
311 sess["test-service_oauth_state"] = _state
312 sess[f"test-service_oauth_code_verifier"] = _code_verifier
313 # make the request
314 resp = client.get(
315 f"/login/test-service/authorized?code=secret-code&state={_state}&code_verifier={_code_verifier}",
316 base_url="https://a.b.c",
317 )
318 # check that we redirected the client
319 assert resp.status_code == 302
320 assert resp.headers["Location"] in ("https://a.b.c/", "/")
321 # check that we obtained an access token
322 assert len(responses.calls) == 1
323 request_data = dict(parse_qsl(responses.calls[0].request.body))
324 assert (
325 request_data["redirect_uri"]
326 == "https://a.b.c/login/test-service/authorized"
327 )
328 assert request_data["code_verifier"] == _code_verifier
329 # check that we stored the access token in the session
330 assert flask.session["test-service_oauth_token"] == {
331 "access_token": "foobar",
332 "scope": ["admin"],
333 "token_type": "bearer",
334 }
335
336
337 def test_authorized_url_pkce_flow_no_code_verifier():
338 app, _ = make_app(use_pkce=True)
339 with app.test_client() as client:
340 # make the request, without adding the code_verifier to the session
341 with client.session_transaction() as sess:
342 sess["test-service_oauth_state"] = "random-string"
343 resp = client.get(
344 "/login/test-service/authorized?code=secret-code&state=random-string",
345 base_url="https://a.b.c",
346 )
347 # check that we redirected the client back to login view
348 assert resp.status_code == 302
349 assert resp.headers["Location"] in (
350 "https://a.b.c/login/test-service",
351 "/login/test-service",
352 )
353 # check that there's nothing in the session
354 assert "test-service_oauth_token" not in flask.session
355
356
357 def test_return_expired_token(request):
358 app, bp = make_app()
359 time1 = "2016-01-01 12:00:01"
360 time2 = "2016-01-01 12:05:00" # 299 sec in future
361 time3 = "2016-01-01 12:10:01" # 600 sec in future
362 token = {
363 "access_token": "foobar",
364 "token_type": "bearer",
365 "expires_in": 300, # expires in 300 seconds
366 }
367 ctx = app.test_request_context("/")
368 request.addfinalizer(ctx.pop)
369 ctx.push()
370
371 with freeze_time(time1):
372 bp.token = token
373 modified1 = token.copy()
374 modified1["expires_at"] = 1451649901
375 assert bp.token == modified1
376
377 with freeze_time(time2):
378 modified2 = token.copy()
379 modified2["expires_in"] = 1
380 modified2["expires_at"] = 1451649901
381 assert bp.token == modified2
382
383 with freeze_time(time3):
384 modified3 = token.copy()
385 modified3["expires_in"] = -300
386 modified3["expires_at"] = 1451649901
387 assert bp.token == modified3
388
389
390 @responses.activate
391 def test_provider_error():
392 app, _ = make_app()
393 with app.test_client() as client:
394 # make the request
395 resp = client.get(
396 "/login/test-service/authorized?"
397 "error=invalid_redirect&"
398 "error_description=Invalid+redirect_URI&"
399 "error_uri=https%3a%2f%2fexample.com%2fdocs%2fhelp",
400 base_url="https://a.b.c",
401 )
402 # even though there was an error, we should still redirect the client
403 assert resp.status_code == 302
404 assert resp.headers["Location"] in ("https://a.b.c/", "/")
405 # shouldn't even try getting an access token, though
406 assert len(responses.calls) == 0
407
408
409 @responses.activate
410 def test_redirect_url():
411 responses.add(
412 responses.POST,
413 "https://example.com/oauth/access_token",
414 body='{"access_token":"foobar","token_type":"bearer","scope":"admin"}',
415 )
416 blueprint = OAuth2ConsumerBlueprint(
417 "test-service",
418 __name__,
419 client_id="client_id",
420 client_secret="client_secret",
421 state="random-string",
422 base_url="https://example.com",
423 authorization_url="https://example.com/oauth/authorize",
424 token_url="https://example.com/oauth/access_token",
425 redirect_url="http://mysite.cool/whoa?query=basketball",
426 )
427 app = flask.Flask(__name__)
428 app.secret_key = "secret"
429 app.config["SERVER_NAME"] = "a.b.c"
430 app.register_blueprint(blueprint, url_prefix="/login")
431
432 with app.test_client() as client:
433 # reset the session before the request
434 with client.session_transaction() as sess:
435 sess["test-service_oauth_state"] = "random-string"
436 # make the request
437 resp = client.get(
438 "/login/test-service/authorized?code=secret-code&state=random-string",
439 base_url="https://a.b.c",
440 )
441 # check that we redirected the client
442 assert resp.status_code == 302
443 assert resp.headers["Location"] == "http://mysite.cool/whoa?query=basketball"
444
445
446 @responses.activate
447 def test_redirect_to():
448 responses.add(
449 responses.POST,
450 "https://example.com/oauth/access_token",
451 body='{"access_token":"foobar","token_type":"bearer","scope":"admin"}',
452 )
453 blueprint = OAuth2ConsumerBlueprint(
454 "test-service",
455 __name__,
456 client_id="client_id",
457 client_secret="client_secret",
458 state="random-string",
459 base_url="https://example.com",
460 authorization_url="https://example.com/oauth/authorize",
461 token_url="https://example.com/oauth/access_token",
462 redirect_to="my_view",
463 )
464 app = flask.Flask(__name__)
465 app.secret_key = "secret"
466 app.config["SERVER_NAME"] = "a.b.c"
467 app.register_blueprint(blueprint, url_prefix="/login")
468
469 @app.route("/blargl")
470 def my_view():
471 return "check out my url"
472
473 with app.test_client() as client:
474 # reset the session before the request
475 with client.session_transaction() as sess:
476 sess["test-service_oauth_state"] = "random-string"
477 # make the request
478 resp = client.get(
479 "/login/test-service/authorized?code=secret-code&state=random-string",
480 base_url="https://a.b.c",
481 )
482 # check that we redirected the client
483 assert resp.status_code == 302
484 assert resp.headers["Location"] in ("https://a.b.c/blargl", "/blargl")
485
486
487 @responses.activate
488 def test_redirect_fallback():
489 responses.add(
490 responses.POST,
491 "https://example.com/oauth/access_token",
492 body='{"access_token":"foobar","token_type":"bearer","scope":"admin"}',
493 )
494 blueprint = OAuth2ConsumerBlueprint(
495 "test-service",
496 __name__,
497 client_id="client_id",
498 client_secret="client_secret",
499 state="random-string",
500 base_url="https://example.com",
501 authorization_url="https://example.com/oauth/authorize",
502 token_url="https://example.com/oauth/access_token",
503 )
504 app = flask.Flask(__name__)
505 app.secret_key = "secret"
506 app.config["SERVER_NAME"] = "a.b.c"
507 app.register_blueprint(blueprint, url_prefix="/login")
508
509 @app.route("/blargl")
510 def my_view():
511 return "check out my url"
512
513 with app.test_client() as client:
514 # reset the session before the request
515 with client.session_transaction() as sess:
516 sess["test-service_oauth_state"] = "random-string"
517 # make the request
518 resp = client.get(
519 "/login/test-service/authorized?code=secret-code&state=random-string",
520 base_url="https://a.b.c",
521 )
522 # check that we redirected the client
523 assert resp.status_code == 302
524 assert resp.headers["Location"] in ("https://a.b.c/", "/")
525
526
527 def test_authorization_required_decorator_allowed():
528 app, blueprint = make_app()
529
530 @app.route("/restricted")
531 @blueprint.session.authorization_required
532 def restricted_view():
533 return "allowed"
534
535 blueprint.storage = MemoryStorage({"access_token": "faketoken"})
536
537 with app.test_client() as client:
538 resp = client.get("/restricted", base_url="https://a.b.c")
539 assert resp.status_code == 200
540 text = resp.get_data(as_text=True)
541 assert text == "allowed"
542
543
544 def test_authorization_required_decorator_redirect():
545 app, blueprint = make_app()
546
547 @app.route("/restricted")
548 @blueprint.session.authorization_required
549 def restricted_view():
550 return "allowed"
551
552 with app.test_client() as client:
553 resp = client.get("/restricted", base_url="https://a.b.c")
554 # check that we redirected the client
555 assert resp.status_code == 302
556 assert resp.headers["Location"] in (
557 "https://a.b.c/login/test-service",
558 "/login/test-service",
559 )
560
561
562 @requires_blinker
563 def test_signal_oauth_authorized(request):
564 app, bp = make_app()
565
566 calls = []
567
568 def callback(*args, **kwargs):
569 calls.append((args, kwargs))
570
571 oauth_authorized.connect(callback)
572 request.addfinalizer(lambda: oauth_authorized.disconnect(callback))
573 fake_token = {"access_token": "test-token"}
574
575 with app.test_client() as client:
576 with client.session_transaction() as sess:
577 sess["test-service_oauth_state"] = "random-string"
578
579 bp.session.fetch_token = mock.Mock(return_value=fake_token)
580 resp = client.get(
581 "/login/test-service/authorized?code=secret-code&state=random-string"
582 )
583 assert resp.status_code == 302
584 # check that we stored the token
585 assert flask.session["test-service_oauth_token"] == fake_token
586
587 assert len(calls) == 1
588 assert calls[0][0] == (bp,)
589 assert calls[0][1] == {"token": fake_token}
590
591
592 @requires_blinker
593 def test_signal_oauth_before_login(request):
594 app, bp = make_app()
595
596 def callback(*args, **kwargs):
597 del flask.session["user_id"]
598
599 oauth_before_login.connect(callback)
600 request.addfinalizer(lambda: oauth_before_login.disconnect(callback))
601 with app.test_request_context():
602 with app.test_client() as client:
603 flask.session["user_id"] = 1
604 assert flask.session["user_id"] == 1
605 client.get("/login/test-service")
606 assert "user_id" not in flask.session
607
608
609 @requires_blinker
610 def test_signal_oauth_authorized_abort(request):
611 app, bp = make_app()
612
613 calls = []
614
615 def callback(*args, **kwargs):
616 calls.append((args, kwargs))
617 return False
618
619 oauth_authorized.connect(callback)
620 request.addfinalizer(lambda: oauth_authorized.disconnect(callback))
621 fake_token = {"access_token": "test-token"}
622
623 with app.test_client() as client:
624 with client.session_transaction() as sess:
625 sess["test-service_oauth_state"] = "random-string"
626
627 bp.session.fetch_token = mock.Mock(return_value=fake_token)
628
629 resp = client.get(
630 "/login/test-service/authorized?code=secret-code&state=random-string"
631 )
632 # check that we did NOT store the token
633 assert "test-service_oauth_token" not in flask.session
634
635 # callback still should have been called
636 assert len(calls) == 1
637
638
639 @requires_blinker
640 def test_signal_oauth_authorized_response(request):
641 app, bp = make_app()
642
643 calls = []
644
645 def callback(*args, **kwargs):
646 calls.append((args, kwargs))
647 return flask.redirect("/url")
648
649 oauth_authorized.connect(callback)
650 request.addfinalizer(lambda: oauth_authorized.disconnect(callback))
651 fake_token = {"access_token": "test-token"}
652
653 with app.test_client() as client:
654 with client.session_transaction() as sess:
655 sess["test-service_oauth_state"] = "random-string"
656
657 bp.session.fetch_token = mock.Mock(return_value=fake_token)
658
659 resp = client.get(
660 "/login/test-service/authorized?code=secret-code&state=random-string"
661 )
662 assert resp.status_code == 302
663 assert resp.headers["Location"] in ("/url", "http://localhost/url")
664 # check that we did NOT store the token
665 assert "test-service_oauth_token" not in flask.session
666
667 # callback still should have been called
668 assert len(calls) == 1
669
670
671 @requires_blinker
672 def test_signal_sender_oauth_authorized(request):
673 app, bp = make_app()
674 bp2 = OAuth2ConsumerBlueprint(
675 "test2",
676 __name__,
677 client_id="client_id",
678 client_secret="client_secret",
679 scope="admin",
680 state="random-string",
681 base_url="https://example.com",
682 authorization_url="https://example.com/oauth/authorize",
683 token_url="https://example.com/oauth/access_token",
684 redirect_to="index",
685 )
686 app.register_blueprint(bp2, url_prefix="/login")
687
688 calls = []
689
690 def callback(*args, **kwargs):
691 calls.append((args, kwargs))
692
693 oauth_authorized.connect(callback, sender=bp)
694 request.addfinalizer(lambda: oauth_authorized.disconnect(callback, sender=bp))
695 fake_token = {"access_token": "test-token"}
696 fake_token2 = {"access_token": "test-token2"}
697
698 with app.test_client() as client:
699 with client.session_transaction() as sess:
700 sess["test-service_oauth_state"] = "random-string"
701
702 bp.session.fetch_token = mock.Mock(return_value=fake_token)
703 bp2.session.fetch_token = mock.Mock(return_value=fake_token2)
704
705 resp = client.get(
706 "/login/test2/authorized?code=secret-code&state=random-string"
707 )
708
709 assert len(calls) == 0
710
711 with app.test_client() as client:
712 with client.session_transaction() as sess:
713 sess["test-service_oauth_state"] = "random-string"
714
715 bp.session.fetch_token = mock.Mock(return_value="test-token")
716 bp2.session.fetch_token = mock.Mock(return_value="test2-token")
717
718 resp = client.get(
719 "/login/test-service/authorized?code=secret-code&state=random-string"
720 )
721
722 assert len(calls) == 1
723 assert calls[0][0] == (bp,)
724 assert calls[0][1] == {"token": "test-token"}
725
726 with app.test_client() as client:
727 with client.session_transaction() as sess:
728 sess["test-service_oauth_state"] = "random-string"
729
730 bp.session.fetch_token = mock.Mock(return_value=fake_token)
731 bp2.session.fetch_token = mock.Mock(return_value=fake_token2)
732
733 resp = client.get(
734 "/login/test2/authorized?code=secret-code&state=random-string"
735 )
736
737 assert len(calls) == 1 # unchanged
738
739
740 @requires_blinker
741 def test_signal_oauth_error(request):
742 app, bp = make_app()
743
744 calls = []
745
746 def callback(*args, **kwargs):
747 calls.append((args, kwargs))
748
749 oauth_error.connect(callback)
750 request.addfinalizer(lambda: oauth_error.disconnect(callback))
751
752 with app.test_client() as client:
753 resp = client.get(
754 "/login/test-service/authorized?"
755 "error=unauthorized_client&"
756 "error_description=Invalid+redirect+URI&"
757 "error_uri=https%3a%2f%2fexample.com%2fdocs%2fhelp",
758 base_url="https://a.b.c",
759 )
760
761 assert len(calls) == 1
762 assert calls[0][0] == (bp,)
763 assert calls[0][1] == {
764 "error": "unauthorized_client",
765 "error_description": "Invalid redirect URI",
766 "error_uri": "https://example.com/docs/help",
767 }
768 assert resp.status_code == 302
769
770
771 @requires_blinker
772 def test_signal_oauth_error_response(request):
773 app, bp = make_app()
774
775 calls = []
776
777 def callback(*args, **kwargs):
778 calls.append((args, kwargs))
779 return flask.redirect("/url")
780
781 oauth_error.connect(callback)
782 request.addfinalizer(lambda: oauth_error.disconnect(callback))
783
784 with app.test_client() as client:
785 resp = client.get(
786 "/login/test-service/authorized?"
787 "error=unauthorized_client&"
788 "error_description=Invalid+redirect+URI&"
789 "error_uri=https%3a%2f%2fexample.com%2fdocs%2fhelp",
790 base_url="https://a.b.c",
791 )
792
793 assert resp.status_code == 302
794 assert resp.headers["Location"] in ("/url", "http://localhost/url")
795
796 assert len(calls) == 1
797 assert calls[0] == (
798 (bp,),
799 {
800 "error": "unauthorized_client",
801 "error_description": "Invalid redirect URI",
802 "error_uri": "https://example.com/docs/help",
803 },
804 )
805
806
807 class CustomOAuth2Session(OAuth2Session):
808 my_attr = "foobar"
809
810
811 def test_custom_session_class():
812 bp = OAuth2ConsumerBlueprint(
813 "test",
814 __name__,
815 client_id="client_id",
816 client_secret="client_secret",
817 scope="admin",
818 state="random-string",
819 base_url="https://example.com",
820 authorization_url="https://example.com/oauth/authorize",
821 token_url="https://example.com/oauth/access_token",
822 redirect_to="index",
823 session_class=CustomOAuth2Session,
824 )
825 assert isinstance(bp.session, CustomOAuth2Session)
826 assert bp.session.my_attr == "foobar"
827
828
829 def test_rule_kwargs():
830 blueprint = OAuth2ConsumerBlueprint(
831 "test-service",
832 __name__,
833 client_id="client_id",
834 client_secret="client_secret",
835 state="random-string",
836 base_url="https://example.com",
837 authorization_url="https://example.com/oauth/authorize",
838 token_url="https://example.com/oauth/access_token",
839 redirect_url="http://mysite.cool/whoa?query=basketball",
840 rule_kwargs={"host": "example2.com"},
841 )
842 app = flask.Flask(__name__)
843 app.secret_key = "secret"
844 app.register_blueprint(blueprint, url_prefix="/login")
845 rules = [
846 rule
847 for rule in app.url_map.iter_rules()
848 if rule.endpoint.startswith("test-service.")
849 ]
850 assert all(rule.host == "example2.com" for rule in rules)
851 assert len(rules) == 2