Merge branch 'chores/bump-copyright' into 'develop'
[akkoma] / test / pleroma / web / o_auth / o_auth_controller_test.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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} = Jason.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" => Jason.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" => Jason.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" => Jason.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 "authorize from cookie" do
615 user = insert(:user)
616 app = insert(:oauth_app)
617 oauth_token = insert(:oauth_token, user: user, app: app)
618 redirect_uri = OAuthController.default_redirect_uri(app)
619
620 conn =
621 build_conn()
622 |> Plug.Session.call(Plug.Session.init(@session_opts))
623 |> fetch_session()
624 |> AuthHelper.put_session_token(oauth_token.token)
625 |> post(
626 "/oauth/authorize",
627 %{
628 "authorization" => %{
629 "name" => user.nickname,
630 "client_id" => app.client_id,
631 "redirect_uri" => redirect_uri,
632 "scope" => app.scopes,
633 "state" => "statepassed"
634 }
635 }
636 )
637
638 target = redirected_to(conn)
639 assert target =~ redirect_uri
640
641 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
642
643 assert %{"state" => "statepassed", "code" => code} = query
644 auth = Repo.get_by(Authorization, token: code)
645 assert auth
646 assert auth.scopes == app.scopes
647 end
648
649 test "redirect to on two-factor auth page" do
650 otp_secret = TOTP.generate_secret()
651
652 user =
653 insert(:user,
654 multi_factor_authentication_settings: %MFA.Settings{
655 enabled: true,
656 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
657 }
658 )
659
660 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
661
662 conn =
663 build_conn()
664 |> post("/oauth/authorize", %{
665 "authorization" => %{
666 "name" => user.nickname,
667 "password" => "test",
668 "client_id" => app.client_id,
669 "redirect_uri" => app.redirect_uris,
670 "scope" => "read write",
671 "state" => "statepassed"
672 }
673 })
674
675 result = html_response(conn, 200)
676
677 mfa_token = Repo.get_by(MFA.Token, user_id: user.id)
678 assert result =~ app.redirect_uris
679 assert result =~ "statepassed"
680 assert result =~ mfa_token.token
681 assert result =~ "Two-factor authentication"
682 end
683
684 test "returns 401 for wrong credentials", %{conn: conn} do
685 user = insert(:user)
686 app = insert(:oauth_app)
687 redirect_uri = OAuthController.default_redirect_uri(app)
688
689 result =
690 conn
691 |> post("/oauth/authorize", %{
692 "authorization" => %{
693 "name" => user.nickname,
694 "password" => "wrong",
695 "client_id" => app.client_id,
696 "redirect_uri" => redirect_uri,
697 "state" => "statepassed",
698 "scope" => Enum.join(app.scopes, " ")
699 }
700 })
701 |> html_response(:unauthorized)
702
703 # Keep the details
704 assert result =~ app.client_id
705 assert result =~ redirect_uri
706
707 # Error message
708 assert result =~ "Invalid Username/Password"
709 end
710
711 test "returns 401 for missing scopes" do
712 user = insert(:user, is_admin: false)
713 app = insert(:oauth_app, scopes: ["read", "write", "admin"])
714 redirect_uri = OAuthController.default_redirect_uri(app)
715
716 result =
717 build_conn()
718 |> post("/oauth/authorize", %{
719 "authorization" => %{
720 "name" => user.nickname,
721 "password" => "test",
722 "client_id" => app.client_id,
723 "redirect_uri" => redirect_uri,
724 "state" => "statepassed",
725 "scope" => ""
726 }
727 })
728 |> html_response(:unauthorized)
729
730 # Keep the details
731 assert result =~ app.client_id
732 assert result =~ redirect_uri
733
734 # Error message
735 assert result =~ "This action is outside the authorized scopes"
736 end
737
738 test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
739 user = insert(:user)
740 app = insert(:oauth_app, scopes: ["read", "write"])
741 redirect_uri = OAuthController.default_redirect_uri(app)
742
743 result =
744 conn
745 |> post("/oauth/authorize", %{
746 "authorization" => %{
747 "name" => user.nickname,
748 "password" => "test",
749 "client_id" => app.client_id,
750 "redirect_uri" => redirect_uri,
751 "state" => "statepassed",
752 "scope" => "read write follow"
753 }
754 })
755 |> html_response(:unauthorized)
756
757 # Keep the details
758 assert result =~ app.client_id
759 assert result =~ redirect_uri
760
761 # Error message
762 assert result =~ "This action is outside the authorized scopes"
763 end
764 end
765
766 describe "POST /oauth/token" do
767 test "issues a token for an all-body request" do
768 user = insert(:user)
769 app = insert(:oauth_app, scopes: ["read", "write"])
770
771 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
772
773 conn =
774 build_conn()
775 |> post("/oauth/token", %{
776 "grant_type" => "authorization_code",
777 "code" => auth.token,
778 "redirect_uri" => OAuthController.default_redirect_uri(app),
779 "client_id" => app.client_id,
780 "client_secret" => app.client_secret
781 })
782
783 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
784
785 token = Repo.get_by(Token, token: token)
786 assert token
787 assert token.scopes == auth.scopes
788 assert user.ap_id == ap_id
789 end
790
791 test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
792 password = "testpassword"
793 user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
794
795 app = insert(:oauth_app, scopes: ["read", "write"])
796
797 # Note: "scope" param is intentionally omitted
798 conn =
799 build_conn()
800 |> post("/oauth/token", %{
801 "grant_type" => "password",
802 "username" => user.nickname,
803 "password" => password,
804 "client_id" => app.client_id,
805 "client_secret" => app.client_secret
806 })
807
808 assert %{"access_token" => token} = json_response(conn, 200)
809
810 token = Repo.get_by(Token, token: token)
811 assert token
812 assert token.scopes == app.scopes
813 end
814
815 test "issues a mfa token for `password` grant_type, when MFA enabled" do
816 password = "testpassword"
817 otp_secret = TOTP.generate_secret()
818
819 user =
820 insert(:user,
821 password_hash: Pbkdf2.hash_pwd_salt(password),
822 multi_factor_authentication_settings: %MFA.Settings{
823 enabled: true,
824 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
825 }
826 )
827
828 app = insert(:oauth_app, scopes: ["read", "write"])
829
830 response =
831 build_conn()
832 |> post("/oauth/token", %{
833 "grant_type" => "password",
834 "username" => user.nickname,
835 "password" => password,
836 "client_id" => app.client_id,
837 "client_secret" => app.client_secret
838 })
839 |> json_response(403)
840
841 assert match?(
842 %{
843 "supported_challenge_types" => "totp",
844 "mfa_token" => _,
845 "error" => "mfa_required"
846 },
847 response
848 )
849
850 token = Repo.get_by(MFA.Token, token: response["mfa_token"])
851 assert token.user_id == user.id
852 assert token.authorization_id
853 end
854
855 test "issues a token for request with HTTP basic auth client credentials" do
856 user = insert(:user)
857 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
858
859 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
860 assert auth.scopes == ["scope1", "scope2"]
861
862 app_encoded =
863 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
864 |> Base.encode64()
865
866 conn =
867 build_conn()
868 |> put_req_header("authorization", "Basic " <> app_encoded)
869 |> post("/oauth/token", %{
870 "grant_type" => "authorization_code",
871 "code" => auth.token,
872 "redirect_uri" => OAuthController.default_redirect_uri(app)
873 })
874
875 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
876
877 assert scope == "scope1 scope2"
878
879 token = Repo.get_by(Token, token: token)
880 assert token
881 assert token.scopes == ["scope1", "scope2"]
882 end
883
884 test "issue a token for client_credentials grant type" do
885 app = insert(:oauth_app, scopes: ["read", "write"])
886
887 conn =
888 build_conn()
889 |> post("/oauth/token", %{
890 "grant_type" => "client_credentials",
891 "client_id" => app.client_id,
892 "client_secret" => app.client_secret
893 })
894
895 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
896 json_response(conn, 200)
897
898 assert token
899 token_from_db = Repo.get_by(Token, token: token)
900 assert token_from_db
901 assert refresh
902 assert scope == "read write"
903 end
904
905 test "rejects token exchange with invalid client credentials" do
906 user = insert(:user)
907 app = insert(:oauth_app)
908
909 {:ok, auth} = Authorization.create_authorization(app, user)
910
911 conn =
912 build_conn()
913 |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
914 |> post("/oauth/token", %{
915 "grant_type" => "authorization_code",
916 "code" => auth.token,
917 "redirect_uri" => OAuthController.default_redirect_uri(app)
918 })
919
920 assert resp = json_response(conn, 400)
921 assert %{"error" => _} = resp
922 refute Map.has_key?(resp, "access_token")
923 end
924
925 test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
926 Pleroma.Config.put([:instance, :account_activation_required], true)
927 password = "testpassword"
928
929 {:ok, user} =
930 insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password))
931 |> User.confirmation_changeset(need_confirmation: true)
932 |> User.update_and_set_cache()
933
934 refute Pleroma.User.account_status(user) == :active
935
936 app = insert(:oauth_app)
937
938 conn =
939 build_conn()
940 |> post("/oauth/token", %{
941 "grant_type" => "password",
942 "username" => user.nickname,
943 "password" => password,
944 "client_id" => app.client_id,
945 "client_secret" => app.client_secret
946 })
947
948 assert resp = json_response(conn, 403)
949 assert %{"error" => _} = resp
950 refute Map.has_key?(resp, "access_token")
951 end
952
953 test "rejects token exchange for valid credentials belonging to deactivated user" do
954 password = "testpassword"
955
956 user =
957 insert(:user,
958 password_hash: Pbkdf2.hash_pwd_salt(password),
959 deactivated: true
960 )
961
962 app = insert(:oauth_app)
963
964 resp =
965 build_conn()
966 |> post("/oauth/token", %{
967 "grant_type" => "password",
968 "username" => user.nickname,
969 "password" => password,
970 "client_id" => app.client_id,
971 "client_secret" => app.client_secret
972 })
973 |> json_response(403)
974
975 assert resp == %{
976 "error" => "Your account is currently disabled",
977 "identifier" => "account_is_disabled"
978 }
979 end
980
981 test "rejects token exchange for user with password_reset_pending set to true" do
982 password = "testpassword"
983
984 user =
985 insert(:user,
986 password_hash: Pbkdf2.hash_pwd_salt(password),
987 password_reset_pending: true
988 )
989
990 app = insert(:oauth_app, scopes: ["read", "write"])
991
992 resp =
993 build_conn()
994 |> post("/oauth/token", %{
995 "grant_type" => "password",
996 "username" => user.nickname,
997 "password" => password,
998 "client_id" => app.client_id,
999 "client_secret" => app.client_secret
1000 })
1001 |> json_response(403)
1002
1003 assert resp == %{
1004 "error" => "Password reset is required",
1005 "identifier" => "password_reset_required"
1006 }
1007 end
1008
1009 test "rejects token exchange for user with confirmation_pending set to true" do
1010 Pleroma.Config.put([:instance, :account_activation_required], true)
1011 password = "testpassword"
1012
1013 user =
1014 insert(:user,
1015 password_hash: Pbkdf2.hash_pwd_salt(password),
1016 confirmation_pending: true
1017 )
1018
1019 app = insert(:oauth_app, scopes: ["read", "write"])
1020
1021 resp =
1022 build_conn()
1023 |> post("/oauth/token", %{
1024 "grant_type" => "password",
1025 "username" => user.nickname,
1026 "password" => password,
1027 "client_id" => app.client_id,
1028 "client_secret" => app.client_secret
1029 })
1030 |> json_response(403)
1031
1032 assert resp == %{
1033 "error" => "Your login is missing a confirmed e-mail address",
1034 "identifier" => "missing_confirmed_email"
1035 }
1036 end
1037
1038 test "rejects token exchange for valid credentials belonging to an unapproved user" do
1039 password = "testpassword"
1040
1041 user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password), approval_pending: true)
1042
1043 refute Pleroma.User.account_status(user) == :active
1044
1045 app = insert(:oauth_app)
1046
1047 conn =
1048 build_conn()
1049 |> post("/oauth/token", %{
1050 "grant_type" => "password",
1051 "username" => user.nickname,
1052 "password" => password,
1053 "client_id" => app.client_id,
1054 "client_secret" => app.client_secret
1055 })
1056
1057 assert resp = json_response(conn, 403)
1058 assert %{"error" => _} = resp
1059 refute Map.has_key?(resp, "access_token")
1060 end
1061
1062 test "rejects an invalid authorization code" do
1063 app = insert(:oauth_app)
1064
1065 conn =
1066 build_conn()
1067 |> post("/oauth/token", %{
1068 "grant_type" => "authorization_code",
1069 "code" => "Imobviouslyinvalid",
1070 "redirect_uri" => OAuthController.default_redirect_uri(app),
1071 "client_id" => app.client_id,
1072 "client_secret" => app.client_secret
1073 })
1074
1075 assert resp = json_response(conn, 400)
1076 assert %{"error" => _} = json_response(conn, 400)
1077 refute Map.has_key?(resp, "access_token")
1078 end
1079 end
1080
1081 describe "POST /oauth/token - refresh token" do
1082 setup do: clear_config([:oauth2, :issue_new_refresh_token])
1083
1084 test "issues a new access token with keep fresh token" do
1085 Pleroma.Config.put([:oauth2, :issue_new_refresh_token], true)
1086 user = insert(:user)
1087 app = insert(:oauth_app, scopes: ["read", "write"])
1088
1089 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1090 {:ok, token} = Token.exchange_token(app, auth)
1091
1092 response =
1093 build_conn()
1094 |> post("/oauth/token", %{
1095 "grant_type" => "refresh_token",
1096 "refresh_token" => token.refresh_token,
1097 "client_id" => app.client_id,
1098 "client_secret" => app.client_secret
1099 })
1100 |> json_response(200)
1101
1102 ap_id = user.ap_id
1103
1104 assert match?(
1105 %{
1106 "scope" => "write",
1107 "token_type" => "Bearer",
1108 "access_token" => _,
1109 "refresh_token" => _,
1110 "me" => ^ap_id
1111 },
1112 response
1113 )
1114
1115 refute Repo.get_by(Token, token: token.token)
1116 new_token = Repo.get_by(Token, token: response["access_token"])
1117 assert new_token.refresh_token == token.refresh_token
1118 assert new_token.scopes == auth.scopes
1119 assert new_token.user_id == user.id
1120 assert new_token.app_id == app.id
1121 end
1122
1123 test "issues a new access token with new fresh token" do
1124 Pleroma.Config.put([:oauth2, :issue_new_refresh_token], false)
1125 user = insert(:user)
1126 app = insert(:oauth_app, scopes: ["read", "write"])
1127
1128 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1129 {:ok, token} = Token.exchange_token(app, auth)
1130
1131 response =
1132 build_conn()
1133 |> post("/oauth/token", %{
1134 "grant_type" => "refresh_token",
1135 "refresh_token" => token.refresh_token,
1136 "client_id" => app.client_id,
1137 "client_secret" => app.client_secret
1138 })
1139 |> json_response(200)
1140
1141 ap_id = user.ap_id
1142
1143 assert match?(
1144 %{
1145 "scope" => "write",
1146 "token_type" => "Bearer",
1147 "access_token" => _,
1148 "refresh_token" => _,
1149 "me" => ^ap_id
1150 },
1151 response
1152 )
1153
1154 refute Repo.get_by(Token, token: token.token)
1155 new_token = Repo.get_by(Token, token: response["access_token"])
1156 refute new_token.refresh_token == token.refresh_token
1157 assert new_token.scopes == auth.scopes
1158 assert new_token.user_id == user.id
1159 assert new_token.app_id == app.id
1160 end
1161
1162 test "returns 400 if we try use access token" do
1163 user = insert(:user)
1164 app = insert(:oauth_app, scopes: ["read", "write"])
1165
1166 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1167 {:ok, token} = Token.exchange_token(app, auth)
1168
1169 response =
1170 build_conn()
1171 |> post("/oauth/token", %{
1172 "grant_type" => "refresh_token",
1173 "refresh_token" => token.token,
1174 "client_id" => app.client_id,
1175 "client_secret" => app.client_secret
1176 })
1177 |> json_response(400)
1178
1179 assert %{"error" => "Invalid credentials"} == response
1180 end
1181
1182 test "returns 400 if refresh_token invalid" do
1183 app = insert(:oauth_app, scopes: ["read", "write"])
1184
1185 response =
1186 build_conn()
1187 |> post("/oauth/token", %{
1188 "grant_type" => "refresh_token",
1189 "refresh_token" => "token.refresh_token",
1190 "client_id" => app.client_id,
1191 "client_secret" => app.client_secret
1192 })
1193 |> json_response(400)
1194
1195 assert %{"error" => "Invalid credentials"} == response
1196 end
1197
1198 test "issues a new token if token expired" do
1199 user = insert(:user)
1200 app = insert(:oauth_app, scopes: ["read", "write"])
1201
1202 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1203 {:ok, token} = Token.exchange_token(app, auth)
1204
1205 change =
1206 Ecto.Changeset.change(
1207 token,
1208 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1209 )
1210
1211 {:ok, access_token} = Repo.update(change)
1212
1213 response =
1214 build_conn()
1215 |> post("/oauth/token", %{
1216 "grant_type" => "refresh_token",
1217 "refresh_token" => access_token.refresh_token,
1218 "client_id" => app.client_id,
1219 "client_secret" => app.client_secret
1220 })
1221 |> json_response(200)
1222
1223 ap_id = user.ap_id
1224
1225 assert match?(
1226 %{
1227 "scope" => "write",
1228 "token_type" => "Bearer",
1229 "access_token" => _,
1230 "refresh_token" => _,
1231 "me" => ^ap_id
1232 },
1233 response
1234 )
1235
1236 refute Repo.get_by(Token, token: token.token)
1237 token = Repo.get_by(Token, token: response["access_token"])
1238 assert token
1239 assert token.scopes == auth.scopes
1240 assert token.user_id == user.id
1241 assert token.app_id == app.id
1242 end
1243 end
1244
1245 describe "POST /oauth/token - bad request" do
1246 test "returns 500" do
1247 response =
1248 build_conn()
1249 |> post("/oauth/token", %{})
1250 |> json_response(500)
1251
1252 assert %{"error" => "Bad request"} == response
1253 end
1254 end
1255
1256 describe "POST /oauth/revoke" do
1257 test "when authenticated with request token, revokes it and clears it from session" do
1258 oauth_token = insert(:oauth_token)
1259
1260 conn =
1261 build_conn()
1262 |> Plug.Session.call(Plug.Session.init(@session_opts))
1263 |> fetch_session()
1264 |> AuthHelper.put_session_token(oauth_token.token)
1265 |> post("/oauth/revoke", %{"token" => oauth_token.token})
1266
1267 assert json_response(conn, 200)
1268
1269 refute AuthHelper.get_session_token(conn)
1270 assert Token.get_by_token(oauth_token.token) == {:error, :not_found}
1271 end
1272
1273 test "if request is authenticated with a different token, " <>
1274 "revokes requested token but keeps session token" do
1275 user = insert(:user)
1276 oauth_token = insert(:oauth_token, user: user)
1277 other_app_oauth_token = insert(:oauth_token, user: user)
1278
1279 conn =
1280 build_conn()
1281 |> Plug.Session.call(Plug.Session.init(@session_opts))
1282 |> fetch_session()
1283 |> AuthHelper.put_session_token(oauth_token.token)
1284 |> post("/oauth/revoke", %{"token" => other_app_oauth_token.token})
1285
1286 assert json_response(conn, 200)
1287
1288 assert AuthHelper.get_session_token(conn) == oauth_token.token
1289 assert Token.get_by_token(other_app_oauth_token.token) == {:error, :not_found}
1290 end
1291
1292 test "returns 500 on bad request" do
1293 response =
1294 build_conn()
1295 |> post("/oauth/revoke", %{})
1296 |> json_response(500)
1297
1298 assert %{"error" => "Bad request"} == response
1299 end
1300 end
1301 end