Session token setting on token exchange. Auth-related refactoring.
[akkoma] / test / pleroma / web / o_auth / o_auth_controller_test.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.OAuth.OAuthControllerTest do
6 use Pleroma.Web.ConnCase
7
8 import Pleroma.Factory
9
10 alias Pleroma.Helpers.AuthHelper
11 alias Pleroma.MFA
12 alias Pleroma.MFA.TOTP
13 alias Pleroma.Repo
14 alias Pleroma.User
15 alias Pleroma.Web.OAuth.Authorization
16 alias Pleroma.Web.OAuth.OAuthController
17 alias Pleroma.Web.OAuth.Token
18
19 @session_opts [
20 store: :cookie,
21 key: "_test",
22 signing_salt: "cooldude"
23 ]
24 setup do
25 clear_config([:instance, :account_activation_required])
26 clear_config([:instance, :account_approval_required])
27 end
28
29 describe "in OAuth consumer mode, " do
30 setup do
31 [
32 app: insert(:oauth_app),
33 conn:
34 build_conn()
35 |> Plug.Session.call(Plug.Session.init(@session_opts))
36 |> fetch_session()
37 ]
38 end
39
40 setup do: clear_config([:auth, :oauth_consumer_strategies], ~w(twitter facebook))
41
42 test "GET /oauth/authorize renders auth forms, including OAuth consumer form", %{
43 app: app,
44 conn: conn
45 } do
46 conn =
47 get(
48 conn,
49 "/oauth/authorize",
50 %{
51 "response_type" => "code",
52 "client_id" => app.client_id,
53 "redirect_uri" => OAuthController.default_redirect_uri(app),
54 "scope" => "read"
55 }
56 )
57
58 assert response = html_response(conn, 200)
59 assert response =~ "Sign in with Twitter"
60 assert response =~ o_auth_path(conn, :prepare_request)
61 end
62
63 test "GET /oauth/prepare_request encodes parameters as `state` and redirects", %{
64 app: app,
65 conn: conn
66 } do
67 conn =
68 get(
69 conn,
70 "/oauth/prepare_request",
71 %{
72 "provider" => "twitter",
73 "authorization" => %{
74 "scope" => "read follow",
75 "client_id" => app.client_id,
76 "redirect_uri" => OAuthController.default_redirect_uri(app),
77 "state" => "a_state"
78 }
79 }
80 )
81
82 assert html_response(conn, 302)
83
84 redirect_query = URI.parse(redirected_to(conn)).query
85 assert %{"state" => state_param} = URI.decode_query(redirect_query)
86 assert {:ok, state_components} = Poison.decode(state_param)
87
88 expected_client_id = app.client_id
89 expected_redirect_uri = app.redirect_uris
90
91 assert %{
92 "scope" => "read follow",
93 "client_id" => ^expected_client_id,
94 "redirect_uri" => ^expected_redirect_uri,
95 "state" => "a_state"
96 } = state_components
97 end
98
99 test "with user-bound registration, GET /oauth/<provider>/callback redirects to `redirect_uri` with `code`",
100 %{app: app, conn: conn} do
101 registration = insert(:registration)
102 redirect_uri = OAuthController.default_redirect_uri(app)
103
104 state_params = %{
105 "scope" => Enum.join(app.scopes, " "),
106 "client_id" => app.client_id,
107 "redirect_uri" => redirect_uri,
108 "state" => ""
109 }
110
111 conn =
112 conn
113 |> assign(:ueberauth_auth, %{provider: registration.provider, uid: registration.uid})
114 |> get(
115 "/oauth/twitter/callback",
116 %{
117 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
118 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
119 "provider" => "twitter",
120 "state" => Poison.encode!(state_params)
121 }
122 )
123
124 assert html_response(conn, 302)
125 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
126 end
127
128 test "with user-unbound registration, GET /oauth/<provider>/callback renders registration_details page",
129 %{app: app, conn: conn} do
130 user = insert(:user)
131
132 state_params = %{
133 "scope" => "read write",
134 "client_id" => app.client_id,
135 "redirect_uri" => OAuthController.default_redirect_uri(app),
136 "state" => "a_state"
137 }
138
139 conn =
140 conn
141 |> assign(:ueberauth_auth, %{
142 provider: "twitter",
143 uid: "171799000",
144 info: %{nickname: user.nickname, email: user.email, name: user.name, description: nil}
145 })
146 |> get(
147 "/oauth/twitter/callback",
148 %{
149 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
150 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
151 "provider" => "twitter",
152 "state" => Poison.encode!(state_params)
153 }
154 )
155
156 assert response = html_response(conn, 200)
157 assert response =~ ~r/name="op" type="submit" value="register"/
158 assert response =~ ~r/name="op" type="submit" value="connect"/
159 assert response =~ user.email
160 assert response =~ user.nickname
161 end
162
163 test "on authentication error, GET /oauth/<provider>/callback redirects to `redirect_uri`", %{
164 app: app,
165 conn: conn
166 } do
167 state_params = %{
168 "scope" => Enum.join(app.scopes, " "),
169 "client_id" => app.client_id,
170 "redirect_uri" => OAuthController.default_redirect_uri(app),
171 "state" => ""
172 }
173
174 conn =
175 conn
176 |> assign(:ueberauth_failure, %{errors: [%{message: "(error description)"}]})
177 |> get(
178 "/oauth/twitter/callback",
179 %{
180 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
181 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
182 "provider" => "twitter",
183 "state" => Poison.encode!(state_params)
184 }
185 )
186
187 assert html_response(conn, 302)
188 assert redirected_to(conn) == app.redirect_uris
189 assert get_flash(conn, :error) == "Failed to authenticate: (error description)."
190 end
191
192 test "GET /oauth/registration_details renders registration details form", %{
193 app: app,
194 conn: conn
195 } do
196 conn =
197 get(
198 conn,
199 "/oauth/registration_details",
200 %{
201 "authorization" => %{
202 "scopes" => app.scopes,
203 "client_id" => app.client_id,
204 "redirect_uri" => OAuthController.default_redirect_uri(app),
205 "state" => "a_state",
206 "nickname" => nil,
207 "email" => "john@doe.com"
208 }
209 }
210 )
211
212 assert response = html_response(conn, 200)
213 assert response =~ ~r/name="op" type="submit" value="register"/
214 assert response =~ ~r/name="op" type="submit" value="connect"/
215 end
216
217 test "with valid params, POST /oauth/register?op=register redirects to `redirect_uri` with `code`",
218 %{
219 app: app,
220 conn: conn
221 } do
222 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
223 redirect_uri = OAuthController.default_redirect_uri(app)
224
225 conn =
226 conn
227 |> put_session(:registration_id, registration.id)
228 |> post(
229 "/oauth/register",
230 %{
231 "op" => "register",
232 "authorization" => %{
233 "scopes" => app.scopes,
234 "client_id" => app.client_id,
235 "redirect_uri" => redirect_uri,
236 "state" => "a_state",
237 "nickname" => "availablenick",
238 "email" => "available@email.com"
239 }
240 }
241 )
242
243 assert html_response(conn, 302)
244 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
245 end
246
247 test "with unlisted `redirect_uri`, POST /oauth/register?op=register results in HTTP 401",
248 %{
249 app: app,
250 conn: conn
251 } do
252 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
253 unlisted_redirect_uri = "http://cross-site-request.com"
254
255 conn =
256 conn
257 |> put_session(:registration_id, registration.id)
258 |> post(
259 "/oauth/register",
260 %{
261 "op" => "register",
262 "authorization" => %{
263 "scopes" => app.scopes,
264 "client_id" => app.client_id,
265 "redirect_uri" => unlisted_redirect_uri,
266 "state" => "a_state",
267 "nickname" => "availablenick",
268 "email" => "available@email.com"
269 }
270 }
271 )
272
273 assert html_response(conn, 401)
274 end
275
276 test "with invalid params, POST /oauth/register?op=register renders registration_details page",
277 %{
278 app: app,
279 conn: conn
280 } do
281 another_user = insert(:user)
282 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
283
284 params = %{
285 "op" => "register",
286 "authorization" => %{
287 "scopes" => app.scopes,
288 "client_id" => app.client_id,
289 "redirect_uri" => OAuthController.default_redirect_uri(app),
290 "state" => "a_state",
291 "nickname" => "availablenickname",
292 "email" => "available@email.com"
293 }
294 }
295
296 for {bad_param, bad_param_value} <-
297 [{"nickname", another_user.nickname}, {"email", another_user.email}] do
298 bad_registration_attrs = %{
299 "authorization" => Map.put(params["authorization"], bad_param, bad_param_value)
300 }
301
302 bad_params = Map.merge(params, bad_registration_attrs)
303
304 conn =
305 conn
306 |> put_session(:registration_id, registration.id)
307 |> post("/oauth/register", bad_params)
308
309 assert html_response(conn, 403) =~ ~r/name="op" type="submit" value="register"/
310 assert get_flash(conn, :error) == "Error: #{bad_param} has already been taken."
311 end
312 end
313
314 test "with valid params, POST /oauth/register?op=connect redirects to `redirect_uri` with `code`",
315 %{
316 app: app,
317 conn: conn
318 } do
319 user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt("testpassword"))
320 registration = insert(:registration, user: nil)
321 redirect_uri = OAuthController.default_redirect_uri(app)
322
323 conn =
324 conn
325 |> put_session(:registration_id, registration.id)
326 |> post(
327 "/oauth/register",
328 %{
329 "op" => "connect",
330 "authorization" => %{
331 "scopes" => app.scopes,
332 "client_id" => app.client_id,
333 "redirect_uri" => redirect_uri,
334 "state" => "a_state",
335 "name" => user.nickname,
336 "password" => "testpassword"
337 }
338 }
339 )
340
341 assert html_response(conn, 302)
342 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
343 end
344
345 test "with unlisted `redirect_uri`, POST /oauth/register?op=connect results in HTTP 401`",
346 %{
347 app: app,
348 conn: conn
349 } do
350 user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt("testpassword"))
351 registration = insert(:registration, user: nil)
352 unlisted_redirect_uri = "http://cross-site-request.com"
353
354 conn =
355 conn
356 |> put_session(:registration_id, registration.id)
357 |> post(
358 "/oauth/register",
359 %{
360 "op" => "connect",
361 "authorization" => %{
362 "scopes" => app.scopes,
363 "client_id" => app.client_id,
364 "redirect_uri" => unlisted_redirect_uri,
365 "state" => "a_state",
366 "name" => user.nickname,
367 "password" => "testpassword"
368 }
369 }
370 )
371
372 assert html_response(conn, 401)
373 end
374
375 test "with invalid params, POST /oauth/register?op=connect renders registration_details page",
376 %{
377 app: app,
378 conn: conn
379 } do
380 user = insert(:user)
381 registration = insert(:registration, user: nil)
382
383 params = %{
384 "op" => "connect",
385 "authorization" => %{
386 "scopes" => app.scopes,
387 "client_id" => app.client_id,
388 "redirect_uri" => OAuthController.default_redirect_uri(app),
389 "state" => "a_state",
390 "name" => user.nickname,
391 "password" => "wrong password"
392 }
393 }
394
395 conn =
396 conn
397 |> put_session(:registration_id, registration.id)
398 |> post("/oauth/register", params)
399
400 assert html_response(conn, 401) =~ ~r/name="op" type="submit" value="connect"/
401 assert get_flash(conn, :error) == "Invalid Username/Password"
402 end
403 end
404
405 describe "GET /oauth/authorize" do
406 setup do
407 [
408 app: insert(:oauth_app, redirect_uris: "https://redirect.url"),
409 conn:
410 build_conn()
411 |> Plug.Session.call(Plug.Session.init(@session_opts))
412 |> fetch_session()
413 ]
414 end
415
416 test "renders authentication page", %{app: app, conn: conn} do
417 conn =
418 get(
419 conn,
420 "/oauth/authorize",
421 %{
422 "response_type" => "code",
423 "client_id" => app.client_id,
424 "redirect_uri" => OAuthController.default_redirect_uri(app),
425 "scope" => "read"
426 }
427 )
428
429 assert html_response(conn, 200) =~ ~s(type="submit")
430 end
431
432 test "properly handles internal calls with `authorization`-wrapped params", %{
433 app: app,
434 conn: conn
435 } do
436 conn =
437 get(
438 conn,
439 "/oauth/authorize",
440 %{
441 "authorization" => %{
442 "response_type" => "code",
443 "client_id" => app.client_id,
444 "redirect_uri" => OAuthController.default_redirect_uri(app),
445 "scope" => "read"
446 }
447 }
448 )
449
450 assert html_response(conn, 200) =~ ~s(type="submit")
451 end
452
453 test "renders authentication page if user is already authenticated but `force_login` is tru-ish",
454 %{app: app, conn: conn} do
455 token = insert(:oauth_token, app: app)
456
457 conn =
458 conn
459 |> AuthHelper.put_session_token(token.token)
460 |> get(
461 "/oauth/authorize",
462 %{
463 "response_type" => "code",
464 "client_id" => app.client_id,
465 "redirect_uri" => OAuthController.default_redirect_uri(app),
466 "scope" => "read",
467 "force_login" => "true"
468 }
469 )
470
471 assert html_response(conn, 200) =~ ~s(type="submit")
472 end
473
474 test "renders authentication page if user is already authenticated but user request with another client",
475 %{
476 app: app,
477 conn: conn
478 } do
479 token = insert(:oauth_token, app: app)
480
481 conn =
482 conn
483 |> AuthHelper.put_session_token(token.token)
484 |> get(
485 "/oauth/authorize",
486 %{
487 "response_type" => "code",
488 "client_id" => "another_client_id",
489 "redirect_uri" => OAuthController.default_redirect_uri(app),
490 "scope" => "read"
491 }
492 )
493
494 assert html_response(conn, 200) =~ ~s(type="submit")
495 end
496
497 test "with existing authentication and non-OOB `redirect_uri`, redirects to app with `token` and `state` params",
498 %{
499 app: app,
500 conn: conn
501 } do
502 token = insert(:oauth_token, app: app)
503
504 conn =
505 conn
506 |> AuthHelper.put_session_token(token.token)
507 |> get(
508 "/oauth/authorize",
509 %{
510 "response_type" => "code",
511 "client_id" => app.client_id,
512 "redirect_uri" => OAuthController.default_redirect_uri(app),
513 "state" => "specific_client_state",
514 "scope" => "read"
515 }
516 )
517
518 assert URI.decode(redirected_to(conn)) ==
519 "https://redirect.url?access_token=#{token.token}&state=specific_client_state"
520 end
521
522 test "with existing authentication and unlisted non-OOB `redirect_uri`, redirects without credentials",
523 %{
524 app: app,
525 conn: conn
526 } do
527 unlisted_redirect_uri = "http://cross-site-request.com"
528 token = insert(:oauth_token, app: app)
529
530 conn =
531 conn
532 |> AuthHelper.put_session_token(token.token)
533 |> get(
534 "/oauth/authorize",
535 %{
536 "response_type" => "code",
537 "client_id" => app.client_id,
538 "redirect_uri" => unlisted_redirect_uri,
539 "state" => "specific_client_state",
540 "scope" => "read"
541 }
542 )
543
544 assert redirected_to(conn) == unlisted_redirect_uri
545 end
546
547 test "with existing authentication and OOB `redirect_uri`, redirects to app with `token` and `state` params",
548 %{
549 app: app,
550 conn: conn
551 } do
552 token = insert(:oauth_token, app: app)
553
554 conn =
555 conn
556 |> AuthHelper.put_session_token(token.token)
557 |> get(
558 "/oauth/authorize",
559 %{
560 "response_type" => "code",
561 "client_id" => app.client_id,
562 "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
563 "scope" => "read"
564 }
565 )
566
567 assert html_response(conn, 200) =~ "Authorization exists"
568 end
569 end
570
571 describe "POST /oauth/authorize" do
572 test "redirects with oauth authorization, " <>
573 "granting requested app-supported scopes to both admin- and non-admin users" do
574 app_scopes = ["read", "write", "admin", "secret_scope"]
575 app = insert(:oauth_app, scopes: app_scopes)
576 redirect_uri = OAuthController.default_redirect_uri(app)
577
578 non_admin = insert(:user, is_admin: false)
579 admin = insert(:user, is_admin: true)
580 scopes_subset = ["read:subscope", "write", "admin"]
581
582 # In case scope param is missing, expecting _all_ app-supported scopes to be granted
583 for user <- [non_admin, admin],
584 {requested_scopes, expected_scopes} <-
585 %{scopes_subset => scopes_subset, nil: app_scopes} do
586 conn =
587 post(
588 build_conn(),
589 "/oauth/authorize",
590 %{
591 "authorization" => %{
592 "name" => user.nickname,
593 "password" => "test",
594 "client_id" => app.client_id,
595 "redirect_uri" => redirect_uri,
596 "scope" => requested_scopes,
597 "state" => "statepassed"
598 }
599 }
600 )
601
602 target = redirected_to(conn)
603 assert target =~ redirect_uri
604
605 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
606
607 assert %{"state" => "statepassed", "code" => code} = query
608 auth = Repo.get_by(Authorization, token: code)
609 assert auth
610 assert auth.scopes == expected_scopes
611 end
612 end
613
614 test "redirect to on two-factor auth page" do
615 otp_secret = TOTP.generate_secret()
616
617 user =
618 insert(:user,
619 multi_factor_authentication_settings: %MFA.Settings{
620 enabled: true,
621 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
622 }
623 )
624
625 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
626
627 conn =
628 build_conn()
629 |> post("/oauth/authorize", %{
630 "authorization" => %{
631 "name" => user.nickname,
632 "password" => "test",
633 "client_id" => app.client_id,
634 "redirect_uri" => app.redirect_uris,
635 "scope" => "read write",
636 "state" => "statepassed"
637 }
638 })
639
640 result = html_response(conn, 200)
641
642 mfa_token = Repo.get_by(MFA.Token, user_id: user.id)
643 assert result =~ app.redirect_uris
644 assert result =~ "statepassed"
645 assert result =~ mfa_token.token
646 assert result =~ "Two-factor authentication"
647 end
648
649 test "returns 401 for wrong credentials", %{conn: conn} do
650 user = insert(:user)
651 app = insert(:oauth_app)
652 redirect_uri = OAuthController.default_redirect_uri(app)
653
654 result =
655 conn
656 |> post("/oauth/authorize", %{
657 "authorization" => %{
658 "name" => user.nickname,
659 "password" => "wrong",
660 "client_id" => app.client_id,
661 "redirect_uri" => redirect_uri,
662 "state" => "statepassed",
663 "scope" => Enum.join(app.scopes, " ")
664 }
665 })
666 |> html_response(:unauthorized)
667
668 # Keep the details
669 assert result =~ app.client_id
670 assert result =~ redirect_uri
671
672 # Error message
673 assert result =~ "Invalid Username/Password"
674 end
675
676 test "returns 401 for missing scopes" do
677 user = insert(:user, is_admin: false)
678 app = insert(:oauth_app, scopes: ["read", "write", "admin"])
679 redirect_uri = OAuthController.default_redirect_uri(app)
680
681 result =
682 build_conn()
683 |> post("/oauth/authorize", %{
684 "authorization" => %{
685 "name" => user.nickname,
686 "password" => "test",
687 "client_id" => app.client_id,
688 "redirect_uri" => redirect_uri,
689 "state" => "statepassed",
690 "scope" => ""
691 }
692 })
693 |> html_response(:unauthorized)
694
695 # Keep the details
696 assert result =~ app.client_id
697 assert result =~ redirect_uri
698
699 # Error message
700 assert result =~ "This action is outside the authorized scopes"
701 end
702
703 test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
704 user = insert(:user)
705 app = insert(:oauth_app, scopes: ["read", "write"])
706 redirect_uri = OAuthController.default_redirect_uri(app)
707
708 result =
709 conn
710 |> post("/oauth/authorize", %{
711 "authorization" => %{
712 "name" => user.nickname,
713 "password" => "test",
714 "client_id" => app.client_id,
715 "redirect_uri" => redirect_uri,
716 "state" => "statepassed",
717 "scope" => "read write follow"
718 }
719 })
720 |> html_response(:unauthorized)
721
722 # Keep the details
723 assert result =~ app.client_id
724 assert result =~ redirect_uri
725
726 # Error message
727 assert result =~ "This action is outside the authorized scopes"
728 end
729 end
730
731 describe "POST /oauth/token" do
732 test "issues a token for an all-body request" do
733 user = insert(:user)
734 app = insert(:oauth_app, scopes: ["read", "write"])
735
736 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
737
738 conn =
739 build_conn()
740 |> post("/oauth/token", %{
741 "grant_type" => "authorization_code",
742 "code" => auth.token,
743 "redirect_uri" => OAuthController.default_redirect_uri(app),
744 "client_id" => app.client_id,
745 "client_secret" => app.client_secret
746 })
747
748 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
749
750 token = Repo.get_by(Token, token: token)
751 assert token
752 assert token.scopes == auth.scopes
753 assert user.ap_id == ap_id
754 end
755
756 test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
757 password = "testpassword"
758 user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
759
760 app = insert(:oauth_app, scopes: ["read", "write"])
761
762 # Note: "scope" param is intentionally omitted
763 conn =
764 build_conn()
765 |> post("/oauth/token", %{
766 "grant_type" => "password",
767 "username" => user.nickname,
768 "password" => password,
769 "client_id" => app.client_id,
770 "client_secret" => app.client_secret
771 })
772
773 assert %{"access_token" => token} = json_response(conn, 200)
774
775 token = Repo.get_by(Token, token: token)
776 assert token
777 assert token.scopes == app.scopes
778 end
779
780 test "issues a mfa token for `password` grant_type, when MFA enabled" do
781 password = "testpassword"
782 otp_secret = TOTP.generate_secret()
783
784 user =
785 insert(:user,
786 password_hash: Pbkdf2.hash_pwd_salt(password),
787 multi_factor_authentication_settings: %MFA.Settings{
788 enabled: true,
789 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
790 }
791 )
792
793 app = insert(:oauth_app, scopes: ["read", "write"])
794
795 response =
796 build_conn()
797 |> post("/oauth/token", %{
798 "grant_type" => "password",
799 "username" => user.nickname,
800 "password" => password,
801 "client_id" => app.client_id,
802 "client_secret" => app.client_secret
803 })
804 |> json_response(403)
805
806 assert match?(
807 %{
808 "supported_challenge_types" => "totp",
809 "mfa_token" => _,
810 "error" => "mfa_required"
811 },
812 response
813 )
814
815 token = Repo.get_by(MFA.Token, token: response["mfa_token"])
816 assert token.user_id == user.id
817 assert token.authorization_id
818 end
819
820 test "issues a token for request with HTTP basic auth client credentials" do
821 user = insert(:user)
822 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
823
824 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
825 assert auth.scopes == ["scope1", "scope2"]
826
827 app_encoded =
828 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
829 |> Base.encode64()
830
831 conn =
832 build_conn()
833 |> put_req_header("authorization", "Basic " <> app_encoded)
834 |> post("/oauth/token", %{
835 "grant_type" => "authorization_code",
836 "code" => auth.token,
837 "redirect_uri" => OAuthController.default_redirect_uri(app)
838 })
839
840 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
841
842 assert scope == "scope1 scope2"
843
844 token = Repo.get_by(Token, token: token)
845 assert token
846 assert token.scopes == ["scope1", "scope2"]
847 end
848
849 test "issue a token for client_credentials grant type" do
850 app = insert(:oauth_app, scopes: ["read", "write"])
851
852 conn =
853 build_conn()
854 |> post("/oauth/token", %{
855 "grant_type" => "client_credentials",
856 "client_id" => app.client_id,
857 "client_secret" => app.client_secret
858 })
859
860 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
861 json_response(conn, 200)
862
863 assert token
864 token_from_db = Repo.get_by(Token, token: token)
865 assert token_from_db
866 assert refresh
867 assert scope == "read write"
868 end
869
870 test "rejects token exchange with invalid client credentials" do
871 user = insert(:user)
872 app = insert(:oauth_app)
873
874 {:ok, auth} = Authorization.create_authorization(app, user)
875
876 conn =
877 build_conn()
878 |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
879 |> post("/oauth/token", %{
880 "grant_type" => "authorization_code",
881 "code" => auth.token,
882 "redirect_uri" => OAuthController.default_redirect_uri(app)
883 })
884
885 assert resp = json_response(conn, 400)
886 assert %{"error" => _} = resp
887 refute Map.has_key?(resp, "access_token")
888 end
889
890 test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
891 Pleroma.Config.put([:instance, :account_activation_required], true)
892 password = "testpassword"
893
894 {:ok, user} =
895 insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
896 |> User.confirmation_changeset(need_confirmation: true)
897 |> User.update_and_set_cache()
898
899 refute Pleroma.User.account_status(user) == :active
900
901 app = insert(:oauth_app)
902
903 conn =
904 build_conn()
905 |> post("/oauth/token", %{
906 "grant_type" => "password",
907 "username" => user.nickname,
908 "password" => password,
909 "client_id" => app.client_id,
910 "client_secret" => app.client_secret
911 })
912
913 assert resp = json_response(conn, 403)
914 assert %{"error" => _} = resp
915 refute Map.has_key?(resp, "access_token")
916 end
917
918 test "rejects token exchange for valid credentials belonging to deactivated user" do
919 password = "testpassword"
920
921 user =
922 insert(:user,
923 password_hash: Pbkdf2.hash_pwd_salt(password),
924 deactivated: true
925 )
926
927 app = insert(:oauth_app)
928
929 resp =
930 build_conn()
931 |> post("/oauth/token", %{
932 "grant_type" => "password",
933 "username" => user.nickname,
934 "password" => password,
935 "client_id" => app.client_id,
936 "client_secret" => app.client_secret
937 })
938 |> json_response(403)
939
940 assert resp == %{
941 "error" => "Your account is currently disabled",
942 "identifier" => "account_is_disabled"
943 }
944 end
945
946 test "rejects token exchange for user with password_reset_pending set to true" do
947 password = "testpassword"
948
949 user =
950 insert(:user,
951 password_hash: Pbkdf2.hash_pwd_salt(password),
952 password_reset_pending: true
953 )
954
955 app = insert(:oauth_app, scopes: ["read", "write"])
956
957 resp =
958 build_conn()
959 |> post("/oauth/token", %{
960 "grant_type" => "password",
961 "username" => user.nickname,
962 "password" => password,
963 "client_id" => app.client_id,
964 "client_secret" => app.client_secret
965 })
966 |> json_response(403)
967
968 assert resp == %{
969 "error" => "Password reset is required",
970 "identifier" => "password_reset_required"
971 }
972 end
973
974 test "rejects token exchange for user with confirmation_pending set to true" do
975 Pleroma.Config.put([:instance, :account_activation_required], true)
976 password = "testpassword"
977
978 user =
979 insert(:user,
980 password_hash: Pbkdf2.hash_pwd_salt(password),
981 confirmation_pending: true
982 )
983
984 app = insert(:oauth_app, scopes: ["read", "write"])
985
986 resp =
987 build_conn()
988 |> post("/oauth/token", %{
989 "grant_type" => "password",
990 "username" => user.nickname,
991 "password" => password,
992 "client_id" => app.client_id,
993 "client_secret" => app.client_secret
994 })
995 |> json_response(403)
996
997 assert resp == %{
998 "error" => "Your login is missing a confirmed e-mail address",
999 "identifier" => "missing_confirmed_email"
1000 }
1001 end
1002
1003 test "rejects token exchange for valid credentials belonging to an unapproved user" do
1004 password = "testpassword"
1005
1006 user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password), approval_pending: true)
1007
1008 refute Pleroma.User.account_status(user) == :active
1009
1010 app = insert(:oauth_app)
1011
1012 conn =
1013 build_conn()
1014 |> post("/oauth/token", %{
1015 "grant_type" => "password",
1016 "username" => user.nickname,
1017 "password" => password,
1018 "client_id" => app.client_id,
1019 "client_secret" => app.client_secret
1020 })
1021
1022 assert resp = json_response(conn, 403)
1023 assert %{"error" => _} = resp
1024 refute Map.has_key?(resp, "access_token")
1025 end
1026
1027 test "rejects an invalid authorization code" do
1028 app = insert(:oauth_app)
1029
1030 conn =
1031 build_conn()
1032 |> post("/oauth/token", %{
1033 "grant_type" => "authorization_code",
1034 "code" => "Imobviouslyinvalid",
1035 "redirect_uri" => OAuthController.default_redirect_uri(app),
1036 "client_id" => app.client_id,
1037 "client_secret" => app.client_secret
1038 })
1039
1040 assert resp = json_response(conn, 400)
1041 assert %{"error" => _} = json_response(conn, 400)
1042 refute Map.has_key?(resp, "access_token")
1043 end
1044 end
1045
1046 describe "POST /oauth/token - refresh token" do
1047 setup do: clear_config([:oauth2, :issue_new_refresh_token])
1048
1049 test "issues a new access token with keep fresh token" do
1050 Pleroma.Config.put([:oauth2, :issue_new_refresh_token], true)
1051 user = insert(:user)
1052 app = insert(:oauth_app, scopes: ["read", "write"])
1053
1054 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1055 {:ok, token} = Token.exchange_token(app, auth)
1056
1057 response =
1058 build_conn()
1059 |> post("/oauth/token", %{
1060 "grant_type" => "refresh_token",
1061 "refresh_token" => token.refresh_token,
1062 "client_id" => app.client_id,
1063 "client_secret" => app.client_secret
1064 })
1065 |> json_response(200)
1066
1067 ap_id = user.ap_id
1068
1069 assert match?(
1070 %{
1071 "scope" => "write",
1072 "token_type" => "Bearer",
1073 "expires_in" => 600,
1074 "access_token" => _,
1075 "refresh_token" => _,
1076 "me" => ^ap_id
1077 },
1078 response
1079 )
1080
1081 refute Repo.get_by(Token, token: token.token)
1082 new_token = Repo.get_by(Token, token: response["access_token"])
1083 assert new_token.refresh_token == token.refresh_token
1084 assert new_token.scopes == auth.scopes
1085 assert new_token.user_id == user.id
1086 assert new_token.app_id == app.id
1087 end
1088
1089 test "issues a new access token with new fresh token" do
1090 Pleroma.Config.put([:oauth2, :issue_new_refresh_token], false)
1091 user = insert(:user)
1092 app = insert(:oauth_app, scopes: ["read", "write"])
1093
1094 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1095 {:ok, token} = Token.exchange_token(app, auth)
1096
1097 response =
1098 build_conn()
1099 |> post("/oauth/token", %{
1100 "grant_type" => "refresh_token",
1101 "refresh_token" => token.refresh_token,
1102 "client_id" => app.client_id,
1103 "client_secret" => app.client_secret
1104 })
1105 |> json_response(200)
1106
1107 ap_id = user.ap_id
1108
1109 assert match?(
1110 %{
1111 "scope" => "write",
1112 "token_type" => "Bearer",
1113 "expires_in" => 600,
1114 "access_token" => _,
1115 "refresh_token" => _,
1116 "me" => ^ap_id
1117 },
1118 response
1119 )
1120
1121 refute Repo.get_by(Token, token: token.token)
1122 new_token = Repo.get_by(Token, token: response["access_token"])
1123 refute new_token.refresh_token == token.refresh_token
1124 assert new_token.scopes == auth.scopes
1125 assert new_token.user_id == user.id
1126 assert new_token.app_id == app.id
1127 end
1128
1129 test "returns 400 if we try use access token" do
1130 user = insert(:user)
1131 app = insert(:oauth_app, scopes: ["read", "write"])
1132
1133 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1134 {:ok, token} = Token.exchange_token(app, auth)
1135
1136 response =
1137 build_conn()
1138 |> post("/oauth/token", %{
1139 "grant_type" => "refresh_token",
1140 "refresh_token" => token.token,
1141 "client_id" => app.client_id,
1142 "client_secret" => app.client_secret
1143 })
1144 |> json_response(400)
1145
1146 assert %{"error" => "Invalid credentials"} == response
1147 end
1148
1149 test "returns 400 if refresh_token invalid" do
1150 app = insert(:oauth_app, scopes: ["read", "write"])
1151
1152 response =
1153 build_conn()
1154 |> post("/oauth/token", %{
1155 "grant_type" => "refresh_token",
1156 "refresh_token" => "token.refresh_token",
1157 "client_id" => app.client_id,
1158 "client_secret" => app.client_secret
1159 })
1160 |> json_response(400)
1161
1162 assert %{"error" => "Invalid credentials"} == response
1163 end
1164
1165 test "issues a new token if token expired" do
1166 user = insert(:user)
1167 app = insert(:oauth_app, scopes: ["read", "write"])
1168
1169 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1170 {:ok, token} = Token.exchange_token(app, auth)
1171
1172 change =
1173 Ecto.Changeset.change(
1174 token,
1175 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1176 )
1177
1178 {:ok, access_token} = Repo.update(change)
1179
1180 response =
1181 build_conn()
1182 |> post("/oauth/token", %{
1183 "grant_type" => "refresh_token",
1184 "refresh_token" => access_token.refresh_token,
1185 "client_id" => app.client_id,
1186 "client_secret" => app.client_secret
1187 })
1188 |> json_response(200)
1189
1190 ap_id = user.ap_id
1191
1192 assert match?(
1193 %{
1194 "scope" => "write",
1195 "token_type" => "Bearer",
1196 "expires_in" => 600,
1197 "access_token" => _,
1198 "refresh_token" => _,
1199 "me" => ^ap_id
1200 },
1201 response
1202 )
1203
1204 refute Repo.get_by(Token, token: token.token)
1205 token = Repo.get_by(Token, token: response["access_token"])
1206 assert token
1207 assert token.scopes == auth.scopes
1208 assert token.user_id == user.id
1209 assert token.app_id == app.id
1210 end
1211 end
1212
1213 describe "POST /oauth/token - bad request" do
1214 test "returns 500" do
1215 response =
1216 build_conn()
1217 |> post("/oauth/token", %{})
1218 |> json_response(500)
1219
1220 assert %{"error" => "Bad request"} == response
1221 end
1222 end
1223
1224 describe "POST /oauth/revoke - bad request" do
1225 test "returns 500" do
1226 response =
1227 build_conn()
1228 |> post("/oauth/revoke", %{})
1229 |> json_response(500)
1230
1231 assert %{"error" => "Bad request"} == response
1232 end
1233 end
1234 end