5a1258ec31b460302dfcb1d04be838470ef8d8a7
[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: Pleroma.Password.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: Pleroma.Password.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 "allows access if the user has a prior authorization but is authenticated with another client",
498 %{
499 app: app,
500 conn: conn
501 } do
502 user = insert(:user)
503 token = insert(:oauth_token, app: app, user: user)
504
505 other_app = insert(:oauth_app, redirect_uris: "https://other_redirect.url")
506 authorization = insert(:oauth_authorization, user: user, app: other_app)
507 _reusable_token = insert(:oauth_token, app: other_app, user: user)
508
509 conn =
510 conn
511 |> AuthHelper.put_session_token(token.token)
512 |> AuthHelper.put_session_user(user.id)
513 |> get(
514 "/oauth/authorize",
515 %{
516 "response_type" => "code",
517 "client_id" => other_app.client_id,
518 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
519 "scope" => "read"
520 }
521 )
522
523 assert URI.decode(redirected_to(conn)) ==
524 "https://other_redirect.url?code=#{authorization.token}"
525 end
526
527 test "renders login page if the user has an authorization but no token",
528 %{
529 app: app,
530 conn: conn
531 } do
532 user = insert(:user)
533 token = insert(:oauth_token, app: app, user: user)
534
535 other_app = insert(:oauth_app, redirect_uris: "https://other_redirect.url")
536 _authorization = insert(:oauth_authorization, user: user, app: other_app)
537
538 conn =
539 conn
540 |> AuthHelper.put_session_token(token.token)
541 |> AuthHelper.put_session_user(user.id)
542 |> get(
543 "/oauth/authorize",
544 %{
545 "response_type" => "code",
546 "client_id" => other_app.client_id,
547 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
548 "scope" => "read"
549 }
550 )
551
552 assert html_response(conn, 200) =~ ~s(type="submit")
553 end
554
555 test "does not reuse other people's tokens",
556 %{
557 app: app,
558 conn: conn
559 } do
560 user = insert(:user)
561 other_user = insert(:user)
562 token = insert(:oauth_token, app: app, user: user)
563
564 other_app = insert(:oauth_app, redirect_uris: "https://other_redirect.url")
565 _authorization = insert(:oauth_authorization, user: other_user, app: other_app)
566 _reusable_token = insert(:oauth_token, app: other_app, user: other_user)
567
568 conn =
569 conn
570 |> AuthHelper.put_session_token(token.token)
571 |> AuthHelper.put_session_user(user.id)
572 |> get(
573 "/oauth/authorize",
574 %{
575 "response_type" => "code",
576 "client_id" => other_app.client_id,
577 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
578 "scope" => "read"
579 }
580 )
581
582 assert html_response(conn, 200) =~ ~s(type="submit")
583 end
584
585 test "does not reuse expired tokens",
586 %{
587 app: app,
588 conn: conn
589 } do
590 user = insert(:user)
591 token = insert(:oauth_token, app: app, user: user)
592
593 other_app = insert(:oauth_app, redirect_uris: "https://other_redirect.url")
594 _authorization = insert(:oauth_authorization, user: user, app: other_app)
595
596 _reusable_token =
597 insert(:oauth_token,
598 app: other_app,
599 user: user,
600 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -100)
601 )
602
603 conn =
604 conn
605 |> AuthHelper.put_session_token(token.token)
606 |> AuthHelper.put_session_user(user.id)
607 |> get(
608 "/oauth/authorize",
609 %{
610 "response_type" => "code",
611 "client_id" => other_app.client_id,
612 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
613 "scope" => "read"
614 }
615 )
616
617 assert html_response(conn, 200) =~ ~s(type="submit")
618 end
619
620 test "with existing authentication and non-OOB `redirect_uri`, redirects to app with `token` and `state` params",
621 %{
622 app: app,
623 conn: conn
624 } do
625 token = insert(:oauth_token, app: app)
626
627 conn =
628 conn
629 |> AuthHelper.put_session_token(token.token)
630 |> get(
631 "/oauth/authorize",
632 %{
633 "response_type" => "code",
634 "client_id" => app.client_id,
635 "redirect_uri" => OAuthController.default_redirect_uri(app),
636 "state" => "specific_client_state",
637 "scope" => "read"
638 }
639 )
640
641 assert URI.decode(redirected_to(conn)) ==
642 "https://redirect.url?access_token=#{token.token}&state=specific_client_state"
643 end
644
645 test "with existing authentication and unlisted non-OOB `redirect_uri`, redirects without credentials",
646 %{
647 app: app,
648 conn: conn
649 } do
650 unlisted_redirect_uri = "http://cross-site-request.com"
651 token = insert(:oauth_token, app: app)
652
653 conn =
654 conn
655 |> AuthHelper.put_session_token(token.token)
656 |> get(
657 "/oauth/authorize",
658 %{
659 "response_type" => "code",
660 "client_id" => app.client_id,
661 "redirect_uri" => unlisted_redirect_uri,
662 "state" => "specific_client_state",
663 "scope" => "read"
664 }
665 )
666
667 assert redirected_to(conn) == unlisted_redirect_uri
668 end
669
670 test "with existing authentication and OOB `redirect_uri`, redirects to app with `token` and `state` params",
671 %{
672 app: app,
673 conn: conn
674 } do
675 token = insert(:oauth_token, app: app)
676
677 conn =
678 conn
679 |> AuthHelper.put_session_token(token.token)
680 |> get(
681 "/oauth/authorize",
682 %{
683 "response_type" => "code",
684 "client_id" => app.client_id,
685 "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
686 "scope" => "read"
687 }
688 )
689
690 assert html_response(conn, 200) =~ "Authorization exists"
691 end
692 end
693
694 describe "POST /oauth/authorize" do
695 test "redirects with oauth authorization, " <>
696 "granting requested app-supported scopes to both admin- and non-admin users" do
697 app_scopes = ["read", "write", "admin", "secret_scope"]
698 app = insert(:oauth_app, scopes: app_scopes)
699 redirect_uri = OAuthController.default_redirect_uri(app)
700
701 non_admin = insert(:user, is_admin: false)
702 admin = insert(:user, is_admin: true)
703 scopes_subset = ["read:subscope", "write", "admin"]
704
705 # In case scope param is missing, expecting _all_ app-supported scopes to be granted
706 for user <- [non_admin, admin],
707 {requested_scopes, expected_scopes} <-
708 %{scopes_subset => scopes_subset, nil: app_scopes} do
709 conn =
710 post(
711 build_conn(),
712 "/oauth/authorize",
713 %{
714 "authorization" => %{
715 "name" => user.nickname,
716 "password" => "test",
717 "client_id" => app.client_id,
718 "redirect_uri" => redirect_uri,
719 "scope" => requested_scopes,
720 "state" => "statepassed"
721 }
722 }
723 )
724
725 target = redirected_to(conn)
726 assert target =~ redirect_uri
727
728 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
729
730 assert %{"state" => "statepassed", "code" => code} = query
731 auth = Repo.get_by(Authorization, token: code)
732 assert auth
733 assert auth.scopes == expected_scopes
734 end
735 end
736
737 test "authorize from cookie" do
738 user = insert(:user)
739 app = insert(:oauth_app)
740 oauth_token = insert(:oauth_token, user: user, app: app)
741 redirect_uri = OAuthController.default_redirect_uri(app)
742
743 conn =
744 build_conn()
745 |> Plug.Session.call(Plug.Session.init(@session_opts))
746 |> fetch_session()
747 |> AuthHelper.put_session_token(oauth_token.token)
748 |> post(
749 "/oauth/authorize",
750 %{
751 "authorization" => %{
752 "name" => user.nickname,
753 "client_id" => app.client_id,
754 "redirect_uri" => redirect_uri,
755 "scope" => app.scopes,
756 "state" => "statepassed"
757 }
758 }
759 )
760
761 target = redirected_to(conn)
762 assert target =~ redirect_uri
763
764 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
765
766 assert %{"state" => "statepassed", "code" => code} = query
767 auth = Repo.get_by(Authorization, token: code)
768 assert auth
769 assert auth.scopes == app.scopes
770 end
771
772 test "redirect to on two-factor auth page" do
773 otp_secret = TOTP.generate_secret()
774
775 user =
776 insert(:user,
777 multi_factor_authentication_settings: %MFA.Settings{
778 enabled: true,
779 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
780 }
781 )
782
783 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
784
785 conn =
786 build_conn()
787 |> post("/oauth/authorize", %{
788 "authorization" => %{
789 "name" => user.nickname,
790 "password" => "test",
791 "client_id" => app.client_id,
792 "redirect_uri" => app.redirect_uris,
793 "scope" => "read write",
794 "state" => "statepassed"
795 }
796 })
797
798 result = html_response(conn, 200)
799
800 mfa_token = Repo.get_by(MFA.Token, user_id: user.id)
801 assert result =~ app.redirect_uris
802 assert result =~ "statepassed"
803 assert result =~ mfa_token.token
804 assert result =~ "Two-factor authentication"
805 end
806
807 test "returns 401 for wrong credentials", %{conn: conn} do
808 user = insert(:user)
809 app = insert(:oauth_app)
810 redirect_uri = OAuthController.default_redirect_uri(app)
811
812 result =
813 conn
814 |> post("/oauth/authorize", %{
815 "authorization" => %{
816 "name" => user.nickname,
817 "password" => "wrong",
818 "client_id" => app.client_id,
819 "redirect_uri" => redirect_uri,
820 "state" => "statepassed",
821 "scope" => Enum.join(app.scopes, " ")
822 }
823 })
824 |> html_response(:unauthorized)
825
826 # Keep the details
827 assert result =~ app.client_id
828 assert result =~ redirect_uri
829
830 # Error message
831 assert result =~ "Invalid Username/Password"
832 end
833
834 test "returns 401 for missing scopes" do
835 user = insert(:user, is_admin: false)
836 app = insert(:oauth_app, scopes: ["read", "write", "admin"])
837 redirect_uri = OAuthController.default_redirect_uri(app)
838
839 result =
840 build_conn()
841 |> post("/oauth/authorize", %{
842 "authorization" => %{
843 "name" => user.nickname,
844 "password" => "test",
845 "client_id" => app.client_id,
846 "redirect_uri" => redirect_uri,
847 "state" => "statepassed",
848 "scope" => ""
849 }
850 })
851 |> html_response(:unauthorized)
852
853 # Keep the details
854 assert result =~ app.client_id
855 assert result =~ redirect_uri
856
857 # Error message
858 assert result =~ "This action is outside the authorized scopes"
859 end
860
861 test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
862 user = insert(:user)
863 app = insert(:oauth_app, scopes: ["read", "write"])
864 redirect_uri = OAuthController.default_redirect_uri(app)
865
866 result =
867 conn
868 |> post("/oauth/authorize", %{
869 "authorization" => %{
870 "name" => user.nickname,
871 "password" => "test",
872 "client_id" => app.client_id,
873 "redirect_uri" => redirect_uri,
874 "state" => "statepassed",
875 "scope" => "read write follow"
876 }
877 })
878 |> html_response(:unauthorized)
879
880 # Keep the details
881 assert result =~ app.client_id
882 assert result =~ redirect_uri
883
884 # Error message
885 assert result =~ "This action is outside the authorized scopes"
886 end
887 end
888
889 describe "POST /oauth/token" do
890 test "issues a token for an all-body request" do
891 user = insert(:user)
892 app = insert(:oauth_app, scopes: ["read", "write"])
893
894 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
895
896 conn =
897 build_conn()
898 |> post("/oauth/token", %{
899 "grant_type" => "authorization_code",
900 "code" => auth.token,
901 "redirect_uri" => OAuthController.default_redirect_uri(app),
902 "client_id" => app.client_id,
903 "client_secret" => app.client_secret
904 })
905
906 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
907
908 token = Repo.get_by(Token, token: token)
909 assert token
910 assert token.scopes == auth.scopes
911 assert user.ap_id == ap_id
912 end
913
914 test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
915 password = "testpassword"
916 user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))
917
918 app = insert(:oauth_app, scopes: ["read", "write"])
919
920 # Note: "scope" param is intentionally omitted
921 conn =
922 build_conn()
923 |> post("/oauth/token", %{
924 "grant_type" => "password",
925 "username" => user.nickname,
926 "password" => password,
927 "client_id" => app.client_id,
928 "client_secret" => app.client_secret
929 })
930
931 assert %{"id" => id, "access_token" => access_token} = json_response(conn, 200)
932
933 token = Repo.get_by(Token, token: access_token)
934 assert token
935 assert token.id == id
936 assert token.token == access_token
937 assert token.scopes == app.scopes
938 end
939
940 test "issues a mfa token for `password` grant_type, when MFA enabled" do
941 password = "testpassword"
942 otp_secret = TOTP.generate_secret()
943
944 user =
945 insert(:user,
946 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
947 multi_factor_authentication_settings: %MFA.Settings{
948 enabled: true,
949 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
950 }
951 )
952
953 app = insert(:oauth_app, scopes: ["read", "write"])
954
955 response =
956 build_conn()
957 |> post("/oauth/token", %{
958 "grant_type" => "password",
959 "username" => user.nickname,
960 "password" => password,
961 "client_id" => app.client_id,
962 "client_secret" => app.client_secret
963 })
964 |> json_response(403)
965
966 assert match?(
967 %{
968 "supported_challenge_types" => "totp",
969 "mfa_token" => _,
970 "error" => "mfa_required"
971 },
972 response
973 )
974
975 token = Repo.get_by(MFA.Token, token: response["mfa_token"])
976 assert token.user_id == user.id
977 assert token.authorization_id
978 end
979
980 test "issues a token for request with HTTP basic auth client credentials" do
981 user = insert(:user)
982 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
983
984 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
985 assert auth.scopes == ["scope1", "scope2"]
986
987 app_encoded =
988 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
989 |> Base.encode64()
990
991 conn =
992 build_conn()
993 |> put_req_header("authorization", "Basic " <> app_encoded)
994 |> post("/oauth/token", %{
995 "grant_type" => "authorization_code",
996 "code" => auth.token,
997 "redirect_uri" => OAuthController.default_redirect_uri(app)
998 })
999
1000 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
1001
1002 assert scope == "scope1 scope2"
1003
1004 token = Repo.get_by(Token, token: token)
1005 assert token
1006 assert token.scopes == ["scope1", "scope2"]
1007 end
1008
1009 test "issue a token for client_credentials grant type" do
1010 app = insert(:oauth_app, scopes: ["read", "write"])
1011
1012 conn =
1013 build_conn()
1014 |> post("/oauth/token", %{
1015 "grant_type" => "client_credentials",
1016 "client_id" => app.client_id,
1017 "client_secret" => app.client_secret
1018 })
1019
1020 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
1021 json_response(conn, 200)
1022
1023 assert token
1024 token_from_db = Repo.get_by(Token, token: token)
1025 assert token_from_db
1026 assert refresh
1027 assert scope == "read write"
1028 end
1029
1030 test "rejects token exchange with invalid client credentials" do
1031 user = insert(:user)
1032 app = insert(:oauth_app)
1033
1034 {:ok, auth} = Authorization.create_authorization(app, user)
1035
1036 conn =
1037 build_conn()
1038 |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
1039 |> post("/oauth/token", %{
1040 "grant_type" => "authorization_code",
1041 "code" => auth.token,
1042 "redirect_uri" => OAuthController.default_redirect_uri(app)
1043 })
1044
1045 assert resp = json_response(conn, 400)
1046 assert %{"error" => _} = resp
1047 refute Map.has_key?(resp, "access_token")
1048 end
1049
1050 test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
1051 clear_config([:instance, :account_activation_required], true)
1052 password = "testpassword"
1053
1054 {:ok, user} =
1055 insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))
1056 |> User.confirmation_changeset(set_confirmation: false)
1057 |> User.update_and_set_cache()
1058
1059 refute Pleroma.User.account_status(user) == :active
1060
1061 app = insert(:oauth_app)
1062
1063 conn =
1064 build_conn()
1065 |> post("/oauth/token", %{
1066 "grant_type" => "password",
1067 "username" => user.nickname,
1068 "password" => password,
1069 "client_id" => app.client_id,
1070 "client_secret" => app.client_secret
1071 })
1072
1073 assert resp = json_response(conn, 403)
1074 assert %{"error" => _} = resp
1075 refute Map.has_key?(resp, "access_token")
1076 end
1077
1078 test "rejects token exchange for valid credentials belonging to deactivated user" do
1079 password = "testpassword"
1080
1081 user =
1082 insert(:user,
1083 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1084 is_active: false
1085 )
1086
1087 app = insert(:oauth_app)
1088
1089 resp =
1090 build_conn()
1091 |> post("/oauth/token", %{
1092 "grant_type" => "password",
1093 "username" => user.nickname,
1094 "password" => password,
1095 "client_id" => app.client_id,
1096 "client_secret" => app.client_secret
1097 })
1098 |> json_response(403)
1099
1100 assert resp == %{
1101 "error" => "Your account is currently disabled",
1102 "identifier" => "account_is_disabled"
1103 }
1104 end
1105
1106 test "rejects token exchange for user with password_reset_pending set to true" do
1107 password = "testpassword"
1108
1109 user =
1110 insert(:user,
1111 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1112 password_reset_pending: true
1113 )
1114
1115 app = insert(:oauth_app, scopes: ["read", "write"])
1116
1117 resp =
1118 build_conn()
1119 |> post("/oauth/token", %{
1120 "grant_type" => "password",
1121 "username" => user.nickname,
1122 "password" => password,
1123 "client_id" => app.client_id,
1124 "client_secret" => app.client_secret
1125 })
1126 |> json_response(403)
1127
1128 assert resp == %{
1129 "error" => "Password reset is required",
1130 "identifier" => "password_reset_required"
1131 }
1132 end
1133
1134 test "rejects token exchange for user with confirmation_pending set to true" do
1135 clear_config([:instance, :account_activation_required], true)
1136 password = "testpassword"
1137
1138 user =
1139 insert(:user,
1140 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1141 is_confirmed: false
1142 )
1143
1144 app = insert(:oauth_app, scopes: ["read", "write"])
1145
1146 resp =
1147 build_conn()
1148 |> post("/oauth/token", %{
1149 "grant_type" => "password",
1150 "username" => user.nickname,
1151 "password" => password,
1152 "client_id" => app.client_id,
1153 "client_secret" => app.client_secret
1154 })
1155 |> json_response(403)
1156
1157 assert resp == %{
1158 "error" => "Your login is missing a confirmed e-mail address",
1159 "identifier" => "missing_confirmed_email"
1160 }
1161 end
1162
1163 test "rejects token exchange for valid credentials belonging to an unapproved user" do
1164 password = "testpassword"
1165
1166 user =
1167 insert(:user,
1168 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1169 is_approved: false
1170 )
1171
1172 refute Pleroma.User.account_status(user) == :active
1173
1174 app = insert(:oauth_app)
1175
1176 conn =
1177 build_conn()
1178 |> post("/oauth/token", %{
1179 "grant_type" => "password",
1180 "username" => user.nickname,
1181 "password" => password,
1182 "client_id" => app.client_id,
1183 "client_secret" => app.client_secret
1184 })
1185
1186 assert resp = json_response(conn, 403)
1187 assert %{"error" => _} = resp
1188 refute Map.has_key?(resp, "access_token")
1189 end
1190
1191 test "rejects an invalid authorization code" do
1192 app = insert(:oauth_app)
1193
1194 conn =
1195 build_conn()
1196 |> post("/oauth/token", %{
1197 "grant_type" => "authorization_code",
1198 "code" => "Imobviouslyinvalid",
1199 "redirect_uri" => OAuthController.default_redirect_uri(app),
1200 "client_id" => app.client_id,
1201 "client_secret" => app.client_secret
1202 })
1203
1204 assert resp = json_response(conn, 400)
1205 assert %{"error" => _} = json_response(conn, 400)
1206 refute Map.has_key?(resp, "access_token")
1207 end
1208 end
1209
1210 describe "POST /oauth/token - refresh token" do
1211 setup do: clear_config([:oauth2, :issue_new_refresh_token])
1212
1213 test "issues a new access token with keep fresh token" do
1214 clear_config([:oauth2, :issue_new_refresh_token], true)
1215 user = insert(:user)
1216 app = insert(:oauth_app, scopes: ["read", "write"])
1217
1218 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1219 {:ok, token} = Token.exchange_token(app, auth)
1220
1221 response =
1222 build_conn()
1223 |> post("/oauth/token", %{
1224 "grant_type" => "refresh_token",
1225 "refresh_token" => token.refresh_token,
1226 "client_id" => app.client_id,
1227 "client_secret" => app.client_secret
1228 })
1229 |> json_response(200)
1230
1231 ap_id = user.ap_id
1232
1233 assert match?(
1234 %{
1235 "scope" => "write",
1236 "token_type" => "Bearer",
1237 "access_token" => _,
1238 "refresh_token" => _,
1239 "me" => ^ap_id
1240 },
1241 response
1242 )
1243
1244 refute Repo.get_by(Token, token: token.token)
1245 new_token = Repo.get_by(Token, token: response["access_token"])
1246 assert new_token.refresh_token == token.refresh_token
1247 assert new_token.scopes == auth.scopes
1248 assert new_token.user_id == user.id
1249 assert new_token.app_id == app.id
1250 end
1251
1252 test "issues a new access token with new fresh token" do
1253 clear_config([:oauth2, :issue_new_refresh_token], false)
1254 user = insert(:user)
1255 app = insert(:oauth_app, scopes: ["read", "write"])
1256
1257 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1258 {:ok, token} = Token.exchange_token(app, auth)
1259
1260 response =
1261 build_conn()
1262 |> post("/oauth/token", %{
1263 "grant_type" => "refresh_token",
1264 "refresh_token" => token.refresh_token,
1265 "client_id" => app.client_id,
1266 "client_secret" => app.client_secret
1267 })
1268 |> json_response(200)
1269
1270 ap_id = user.ap_id
1271
1272 assert match?(
1273 %{
1274 "scope" => "write",
1275 "token_type" => "Bearer",
1276 "access_token" => _,
1277 "refresh_token" => _,
1278 "me" => ^ap_id
1279 },
1280 response
1281 )
1282
1283 refute Repo.get_by(Token, token: token.token)
1284 new_token = Repo.get_by(Token, token: response["access_token"])
1285 refute new_token.refresh_token == token.refresh_token
1286 assert new_token.scopes == auth.scopes
1287 assert new_token.user_id == user.id
1288 assert new_token.app_id == app.id
1289 end
1290
1291 test "returns 400 if we try use access token" do
1292 user = insert(:user)
1293 app = insert(:oauth_app, scopes: ["read", "write"])
1294
1295 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1296 {:ok, token} = Token.exchange_token(app, auth)
1297
1298 response =
1299 build_conn()
1300 |> post("/oauth/token", %{
1301 "grant_type" => "refresh_token",
1302 "refresh_token" => token.token,
1303 "client_id" => app.client_id,
1304 "client_secret" => app.client_secret
1305 })
1306 |> json_response(400)
1307
1308 assert %{"error" => "Invalid credentials"} == response
1309 end
1310
1311 test "returns 400 if refresh_token invalid" do
1312 app = insert(:oauth_app, scopes: ["read", "write"])
1313
1314 response =
1315 build_conn()
1316 |> post("/oauth/token", %{
1317 "grant_type" => "refresh_token",
1318 "refresh_token" => "token.refresh_token",
1319 "client_id" => app.client_id,
1320 "client_secret" => app.client_secret
1321 })
1322 |> json_response(400)
1323
1324 assert %{"error" => "Invalid credentials"} == response
1325 end
1326
1327 test "issues a new token if token expired" do
1328 user = insert(:user)
1329 app = insert(:oauth_app, scopes: ["read", "write"])
1330
1331 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1332 {:ok, token} = Token.exchange_token(app, auth)
1333
1334 change =
1335 Ecto.Changeset.change(
1336 token,
1337 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1338 )
1339
1340 {:ok, access_token} = Repo.update(change)
1341
1342 response =
1343 build_conn()
1344 |> post("/oauth/token", %{
1345 "grant_type" => "refresh_token",
1346 "refresh_token" => access_token.refresh_token,
1347 "client_id" => app.client_id,
1348 "client_secret" => app.client_secret
1349 })
1350 |> json_response(200)
1351
1352 ap_id = user.ap_id
1353
1354 assert match?(
1355 %{
1356 "scope" => "write",
1357 "token_type" => "Bearer",
1358 "access_token" => _,
1359 "refresh_token" => _,
1360 "me" => ^ap_id
1361 },
1362 response
1363 )
1364
1365 refute Repo.get_by(Token, token: token.token)
1366 token = Repo.get_by(Token, token: response["access_token"])
1367 assert token
1368 assert token.scopes == auth.scopes
1369 assert token.user_id == user.id
1370 assert token.app_id == app.id
1371 end
1372 end
1373
1374 describe "POST /oauth/token - bad request" do
1375 test "returns 500" do
1376 response =
1377 build_conn()
1378 |> post("/oauth/token", %{})
1379 |> json_response(500)
1380
1381 assert %{"error" => "Bad request"} == response
1382 end
1383 end
1384
1385 describe "POST /oauth/revoke" do
1386 test "when authenticated with request token, revokes it and clears it from session" do
1387 oauth_token = insert(:oauth_token)
1388
1389 conn =
1390 build_conn()
1391 |> Plug.Session.call(Plug.Session.init(@session_opts))
1392 |> fetch_session()
1393 |> AuthHelper.put_session_token(oauth_token.token)
1394 |> post("/oauth/revoke", %{"token" => oauth_token.token})
1395
1396 assert json_response(conn, 200)
1397
1398 refute AuthHelper.get_session_token(conn)
1399 assert Token.get_by_token(oauth_token.token) == {:error, :not_found}
1400 end
1401
1402 test "if request is authenticated with a different token, " <>
1403 "revokes requested token but keeps session token" do
1404 user = insert(:user)
1405 oauth_token = insert(:oauth_token, user: user)
1406 other_app_oauth_token = insert(:oauth_token, user: user)
1407
1408 conn =
1409 build_conn()
1410 |> Plug.Session.call(Plug.Session.init(@session_opts))
1411 |> fetch_session()
1412 |> AuthHelper.put_session_token(oauth_token.token)
1413 |> post("/oauth/revoke", %{"token" => other_app_oauth_token.token})
1414
1415 assert json_response(conn, 200)
1416
1417 assert AuthHelper.get_session_token(conn) == oauth_token.token
1418 assert Token.get_by_token(other_app_oauth_token.token) == {:error, :not_found}
1419 end
1420
1421 test "returns 500 on bad request" do
1422 response =
1423 build_conn()
1424 |> post("/oauth/revoke", %{})
1425 |> json_response(500)
1426
1427 assert %{"error" => "Bad request"} == response
1428 end
1429 end
1430 end