Merge pull request 'metrics' (#375) from stats 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: 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 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 scopes_subset = ["read:subscope", "write", "admin"]
701 admin = insert(:user, is_admin: true)
702
703 # In case scope param is missing, expecting _all_ app-supported scopes to be granted
704 conn =
705 post(
706 build_conn(),
707 "/oauth/authorize",
708 %{
709 "authorization" => %{
710 "name" => admin.nickname,
711 "password" => "test",
712 "client_id" => app.client_id,
713 "redirect_uri" => redirect_uri,
714 "scope" => scopes_subset,
715 "state" => "statepassed"
716 }
717 }
718 )
719
720 target = redirected_to(conn)
721 assert target =~ redirect_uri
722
723 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
724
725 assert %{"state" => "statepassed", "code" => code} = query
726 auth = Repo.get_by(Authorization, token: code)
727 assert auth
728 assert auth.scopes == scopes_subset
729 end
730
731 test "redirects with oauth authorization, " <>
732 "granting requested app-supported scopes for non-admin users" do
733 app_scopes = ["read", "write", "secret_scope", "admin"]
734 app = insert(:oauth_app, scopes: app_scopes)
735 redirect_uri = OAuthController.default_redirect_uri(app)
736
737 non_admin = insert(:user, is_admin: false)
738 scopes_subset = ["read:subscope", "write"]
739
740 # In case scope param is missing, expecting _all_ app-supported scopes to be granted
741 conn =
742 post(
743 build_conn(),
744 "/oauth/authorize",
745 %{
746 "authorization" => %{
747 "name" => non_admin.nickname,
748 "password" => "test",
749 "client_id" => app.client_id,
750 "redirect_uri" => redirect_uri,
751 "scope" => scopes_subset,
752 "state" => "statepassed"
753 }
754 }
755 )
756
757 target = redirected_to(conn)
758 assert target =~ redirect_uri
759
760 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
761
762 assert %{"state" => "statepassed", "code" => code} = query
763 auth = Repo.get_by(Authorization, token: code)
764 assert auth
765 assert auth.scopes == scopes_subset
766 end
767
768 test "authorize from cookie" do
769 user = insert(:user)
770 app = insert(:oauth_app)
771 oauth_token = insert(:oauth_token, user: user, app: app)
772 redirect_uri = OAuthController.default_redirect_uri(app)
773
774 conn =
775 build_conn()
776 |> Plug.Session.call(Plug.Session.init(@session_opts))
777 |> fetch_session()
778 |> AuthHelper.put_session_token(oauth_token.token)
779 |> post(
780 "/oauth/authorize",
781 %{
782 "authorization" => %{
783 "name" => user.nickname,
784 "client_id" => app.client_id,
785 "redirect_uri" => redirect_uri,
786 "scope" => app.scopes,
787 "state" => "statepassed"
788 }
789 }
790 )
791
792 target = redirected_to(conn)
793 assert target =~ redirect_uri
794
795 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
796
797 assert %{"state" => "statepassed", "code" => code} = query
798 auth = Repo.get_by(Authorization, token: code)
799 assert auth
800 assert auth.scopes == app.scopes
801 end
802
803 test "redirect to on two-factor auth page" do
804 otp_secret = TOTP.generate_secret()
805
806 user =
807 insert(:user,
808 multi_factor_authentication_settings: %MFA.Settings{
809 enabled: true,
810 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
811 }
812 )
813
814 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
815
816 conn =
817 build_conn()
818 |> post("/oauth/authorize", %{
819 "authorization" => %{
820 "name" => user.nickname,
821 "password" => "test",
822 "client_id" => app.client_id,
823 "redirect_uri" => app.redirect_uris,
824 "scope" => "read write",
825 "state" => "statepassed"
826 }
827 })
828
829 result = html_response(conn, 200)
830
831 mfa_token = Repo.get_by(MFA.Token, user_id: user.id)
832 assert result =~ app.redirect_uris
833 assert result =~ "statepassed"
834 assert result =~ mfa_token.token
835 assert result =~ "Two-factor authentication"
836 end
837
838 test "returns 401 for wrong credentials", %{conn: conn} do
839 user = insert(:user)
840 app = insert(:oauth_app)
841 redirect_uri = OAuthController.default_redirect_uri(app)
842
843 result =
844 conn
845 |> post("/oauth/authorize", %{
846 "authorization" => %{
847 "name" => user.nickname,
848 "password" => "wrong",
849 "client_id" => app.client_id,
850 "redirect_uri" => redirect_uri,
851 "state" => "statepassed",
852 "scope" => Enum.join(app.scopes, " ")
853 }
854 })
855 |> html_response(:unauthorized)
856
857 # Keep the details
858 assert result =~ app.client_id
859 assert result =~ redirect_uri
860
861 # Error message
862 assert result =~ "Invalid Username/Password"
863 end
864
865 test "returns 401 when attempting to use an admin scope with a non-admin", %{conn: conn} do
866 user = insert(:user)
867 app = insert(:oauth_app, scopes: ["admin"])
868 redirect_uri = OAuthController.default_redirect_uri(app)
869
870 result =
871 conn
872 |> post("/oauth/authorize", %{
873 "authorization" => %{
874 "name" => user.nickname,
875 "password" => "test",
876 "client_id" => app.client_id,
877 "redirect_uri" => redirect_uri,
878 "state" => "statepassed",
879 "scope" => Enum.join(app.scopes, " ")
880 }
881 })
882 |> html_response(:unauthorized)
883
884 # Keep the details
885 assert result =~ app.client_id
886 assert result =~ redirect_uri
887
888 # Error message
889 assert result =~ "outside of authorized scopes"
890 end
891
892 test "returns 401 for missing scopes" do
893 user = insert(:user, is_admin: false)
894 app = insert(:oauth_app, scopes: ["read", "write", "admin"])
895 redirect_uri = OAuthController.default_redirect_uri(app)
896
897 result =
898 build_conn()
899 |> post("/oauth/authorize", %{
900 "authorization" => %{
901 "name" => user.nickname,
902 "password" => "test",
903 "client_id" => app.client_id,
904 "redirect_uri" => redirect_uri,
905 "state" => "statepassed",
906 "scope" => ""
907 }
908 })
909 |> html_response(:unauthorized)
910
911 # Keep the details
912 assert result =~ app.client_id
913 assert result =~ redirect_uri
914
915 # Error message
916 assert result =~ "This action is outside of authorized scopes"
917 end
918
919 test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
920 user = insert(:user)
921 app = insert(:oauth_app, scopes: ["read", "write"])
922 redirect_uri = OAuthController.default_redirect_uri(app)
923
924 result =
925 conn
926 |> post("/oauth/authorize", %{
927 "authorization" => %{
928 "name" => user.nickname,
929 "password" => "test",
930 "client_id" => app.client_id,
931 "redirect_uri" => redirect_uri,
932 "state" => "statepassed",
933 "scope" => "read write follow"
934 }
935 })
936 |> html_response(:unauthorized)
937
938 # Keep the details
939 assert result =~ app.client_id
940 assert result =~ redirect_uri
941
942 # Error message
943 assert result =~ "This action is outside of authorized scopes"
944 end
945 end
946
947 describe "POST /oauth/token" do
948 test "issues a token for an all-body request" do
949 user = insert(:user)
950 app = insert(:oauth_app, scopes: ["read", "write"])
951
952 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
953
954 conn =
955 build_conn()
956 |> post("/oauth/token", %{
957 "grant_type" => "authorization_code",
958 "code" => auth.token,
959 "redirect_uri" => OAuthController.default_redirect_uri(app),
960 "client_id" => app.client_id,
961 "client_secret" => app.client_secret
962 })
963
964 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
965
966 token = Repo.get_by(Token, token: token)
967 assert token
968 assert token.scopes == auth.scopes
969 assert user.ap_id == ap_id
970 end
971
972 test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
973 password = "testpassword"
974 user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))
975
976 app = insert(:oauth_app, scopes: ["read", "write"])
977
978 # Note: "scope" param is intentionally omitted
979 conn =
980 build_conn()
981 |> post("/oauth/token", %{
982 "grant_type" => "password",
983 "username" => user.nickname,
984 "password" => password,
985 "client_id" => app.client_id,
986 "client_secret" => app.client_secret
987 })
988
989 assert %{"id" => id, "access_token" => access_token} = json_response(conn, 200)
990
991 token = Repo.get_by(Token, token: access_token)
992 assert token
993 assert token.id == id
994 assert token.token == access_token
995 assert token.scopes == app.scopes
996 end
997
998 test "issues a mfa token for `password` grant_type, when MFA enabled" do
999 password = "testpassword"
1000 otp_secret = TOTP.generate_secret()
1001
1002 user =
1003 insert(:user,
1004 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1005 multi_factor_authentication_settings: %MFA.Settings{
1006 enabled: true,
1007 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
1008 }
1009 )
1010
1011 app = insert(:oauth_app, scopes: ["read", "write"])
1012
1013 response =
1014 build_conn()
1015 |> post("/oauth/token", %{
1016 "grant_type" => "password",
1017 "username" => user.nickname,
1018 "password" => password,
1019 "client_id" => app.client_id,
1020 "client_secret" => app.client_secret
1021 })
1022 |> json_response(403)
1023
1024 assert match?(
1025 %{
1026 "supported_challenge_types" => "totp",
1027 "mfa_token" => _,
1028 "error" => "mfa_required"
1029 },
1030 response
1031 )
1032
1033 token = Repo.get_by(MFA.Token, token: response["mfa_token"])
1034 assert token.user_id == user.id
1035 assert token.authorization_id
1036 end
1037
1038 test "issues a token for request with HTTP basic auth client credentials" do
1039 user = insert(:user)
1040 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
1041
1042 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
1043 assert auth.scopes == ["scope1", "scope2"]
1044
1045 app_encoded =
1046 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
1047 |> Base.encode64()
1048
1049 conn =
1050 build_conn()
1051 |> put_req_header("authorization", "Basic " <> app_encoded)
1052 |> post("/oauth/token", %{
1053 "grant_type" => "authorization_code",
1054 "code" => auth.token,
1055 "redirect_uri" => OAuthController.default_redirect_uri(app)
1056 })
1057
1058 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
1059
1060 assert scope == "scope1 scope2"
1061
1062 token = Repo.get_by(Token, token: token)
1063 assert token
1064 assert token.scopes == ["scope1", "scope2"]
1065 end
1066
1067 test "issue a token for client_credentials grant type" do
1068 app = insert(:oauth_app, scopes: ["read", "write"])
1069
1070 conn =
1071 build_conn()
1072 |> post("/oauth/token", %{
1073 "grant_type" => "client_credentials",
1074 "client_id" => app.client_id,
1075 "client_secret" => app.client_secret
1076 })
1077
1078 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
1079 json_response(conn, 200)
1080
1081 assert token
1082 token_from_db = Repo.get_by(Token, token: token)
1083 assert token_from_db
1084 assert refresh
1085 assert scope == "read write"
1086 end
1087
1088 test "rejects token exchange with invalid client credentials" do
1089 user = insert(:user)
1090 app = insert(:oauth_app)
1091
1092 {:ok, auth} = Authorization.create_authorization(app, user)
1093
1094 conn =
1095 build_conn()
1096 |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
1097 |> post("/oauth/token", %{
1098 "grant_type" => "authorization_code",
1099 "code" => auth.token,
1100 "redirect_uri" => OAuthController.default_redirect_uri(app)
1101 })
1102
1103 assert resp = json_response(conn, 400)
1104 assert %{"error" => _} = resp
1105 refute Map.has_key?(resp, "access_token")
1106 end
1107
1108 test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
1109 clear_config([:instance, :account_activation_required], true)
1110 password = "testpassword"
1111
1112 {:ok, user} =
1113 insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))
1114 |> User.confirmation_changeset(set_confirmation: false)
1115 |> User.update_and_set_cache()
1116
1117 refute Pleroma.User.account_status(user) == :active
1118
1119 app = insert(:oauth_app)
1120
1121 conn =
1122 build_conn()
1123 |> post("/oauth/token", %{
1124 "grant_type" => "password",
1125 "username" => user.nickname,
1126 "password" => password,
1127 "client_id" => app.client_id,
1128 "client_secret" => app.client_secret
1129 })
1130
1131 assert resp = json_response(conn, 403)
1132 assert %{"error" => _} = resp
1133 refute Map.has_key?(resp, "access_token")
1134 end
1135
1136 test "rejects token exchange for valid credentials belonging to deactivated user" do
1137 password = "testpassword"
1138
1139 user =
1140 insert(:user,
1141 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1142 is_active: false
1143 )
1144
1145 app = insert(:oauth_app)
1146
1147 resp =
1148 build_conn()
1149 |> post("/oauth/token", %{
1150 "grant_type" => "password",
1151 "username" => user.nickname,
1152 "password" => password,
1153 "client_id" => app.client_id,
1154 "client_secret" => app.client_secret
1155 })
1156 |> json_response(403)
1157
1158 assert resp == %{
1159 "error" => "Your account is currently disabled",
1160 "identifier" => "account_is_disabled"
1161 }
1162 end
1163
1164 test "rejects token exchange for user with password_reset_pending set to true" do
1165 password = "testpassword"
1166
1167 user =
1168 insert(:user,
1169 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1170 password_reset_pending: true
1171 )
1172
1173 app = insert(:oauth_app, scopes: ["read", "write"])
1174
1175 resp =
1176 build_conn()
1177 |> post("/oauth/token", %{
1178 "grant_type" => "password",
1179 "username" => user.nickname,
1180 "password" => password,
1181 "client_id" => app.client_id,
1182 "client_secret" => app.client_secret
1183 })
1184 |> json_response(403)
1185
1186 assert resp == %{
1187 "error" => "Password reset is required",
1188 "identifier" => "password_reset_required"
1189 }
1190 end
1191
1192 test "rejects token exchange for user with confirmation_pending set to true" do
1193 clear_config([:instance, :account_activation_required], true)
1194 password = "testpassword"
1195
1196 user =
1197 insert(:user,
1198 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1199 is_confirmed: false
1200 )
1201
1202 app = insert(:oauth_app, scopes: ["read", "write"])
1203
1204 resp =
1205 build_conn()
1206 |> post("/oauth/token", %{
1207 "grant_type" => "password",
1208 "username" => user.nickname,
1209 "password" => password,
1210 "client_id" => app.client_id,
1211 "client_secret" => app.client_secret
1212 })
1213 |> json_response(403)
1214
1215 assert resp == %{
1216 "error" => "Your login is missing a confirmed e-mail address",
1217 "identifier" => "missing_confirmed_email"
1218 }
1219 end
1220
1221 test "rejects token exchange for valid credentials belonging to an unapproved user" do
1222 password = "testpassword"
1223
1224 user =
1225 insert(:user,
1226 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1227 is_approved: false
1228 )
1229
1230 refute Pleroma.User.account_status(user) == :active
1231
1232 app = insert(:oauth_app)
1233
1234 conn =
1235 build_conn()
1236 |> post("/oauth/token", %{
1237 "grant_type" => "password",
1238 "username" => user.nickname,
1239 "password" => password,
1240 "client_id" => app.client_id,
1241 "client_secret" => app.client_secret
1242 })
1243
1244 assert resp = json_response(conn, 403)
1245 assert %{"error" => _} = resp
1246 refute Map.has_key?(resp, "access_token")
1247 end
1248
1249 test "rejects an invalid authorization code" do
1250 app = insert(:oauth_app)
1251
1252 conn =
1253 build_conn()
1254 |> post("/oauth/token", %{
1255 "grant_type" => "authorization_code",
1256 "code" => "Imobviouslyinvalid",
1257 "redirect_uri" => OAuthController.default_redirect_uri(app),
1258 "client_id" => app.client_id,
1259 "client_secret" => app.client_secret
1260 })
1261
1262 assert resp = json_response(conn, 400)
1263 assert %{"error" => _} = json_response(conn, 400)
1264 refute Map.has_key?(resp, "access_token")
1265 end
1266 end
1267
1268 describe "POST /oauth/token - refresh token" do
1269 setup do: clear_config([:oauth2, :issue_new_refresh_token])
1270
1271 test "issues a new access token with keep fresh token" do
1272 clear_config([:oauth2, :issue_new_refresh_token], true)
1273 user = insert(:user)
1274 app = insert(:oauth_app, scopes: ["read", "write"])
1275
1276 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1277 {:ok, token} = Token.exchange_token(app, auth)
1278
1279 response =
1280 build_conn()
1281 |> post("/oauth/token", %{
1282 "grant_type" => "refresh_token",
1283 "refresh_token" => token.refresh_token,
1284 "client_id" => app.client_id,
1285 "client_secret" => app.client_secret
1286 })
1287 |> json_response(200)
1288
1289 ap_id = user.ap_id
1290
1291 assert match?(
1292 %{
1293 "scope" => "write",
1294 "token_type" => "Bearer",
1295 "access_token" => _,
1296 "refresh_token" => _,
1297 "me" => ^ap_id
1298 },
1299 response
1300 )
1301
1302 refute Repo.get_by(Token, token: token.token)
1303 new_token = Repo.get_by(Token, token: response["access_token"])
1304 assert new_token.refresh_token == token.refresh_token
1305 assert new_token.scopes == auth.scopes
1306 assert new_token.user_id == user.id
1307 assert new_token.app_id == app.id
1308 end
1309
1310 test "issues a new access token with new fresh token" do
1311 clear_config([:oauth2, :issue_new_refresh_token], false)
1312 user = insert(:user)
1313 app = insert(:oauth_app, scopes: ["read", "write"])
1314
1315 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1316 {:ok, token} = Token.exchange_token(app, auth)
1317
1318 response =
1319 build_conn()
1320 |> post("/oauth/token", %{
1321 "grant_type" => "refresh_token",
1322 "refresh_token" => token.refresh_token,
1323 "client_id" => app.client_id,
1324 "client_secret" => app.client_secret
1325 })
1326 |> json_response(200)
1327
1328 ap_id = user.ap_id
1329
1330 assert match?(
1331 %{
1332 "scope" => "write",
1333 "token_type" => "Bearer",
1334 "access_token" => _,
1335 "refresh_token" => _,
1336 "me" => ^ap_id
1337 },
1338 response
1339 )
1340
1341 refute Repo.get_by(Token, token: token.token)
1342 new_token = Repo.get_by(Token, token: response["access_token"])
1343 refute new_token.refresh_token == token.refresh_token
1344 assert new_token.scopes == auth.scopes
1345 assert new_token.user_id == user.id
1346 assert new_token.app_id == app.id
1347 end
1348
1349 test "returns 400 if we try use access token" do
1350 user = insert(:user)
1351 app = insert(:oauth_app, scopes: ["read", "write"])
1352
1353 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1354 {:ok, token} = Token.exchange_token(app, auth)
1355
1356 response =
1357 build_conn()
1358 |> post("/oauth/token", %{
1359 "grant_type" => "refresh_token",
1360 "refresh_token" => token.token,
1361 "client_id" => app.client_id,
1362 "client_secret" => app.client_secret
1363 })
1364 |> json_response(400)
1365
1366 assert %{"error" => "Invalid credentials"} == response
1367 end
1368
1369 test "returns 400 if refresh_token invalid" do
1370 app = insert(:oauth_app, scopes: ["read", "write"])
1371
1372 response =
1373 build_conn()
1374 |> post("/oauth/token", %{
1375 "grant_type" => "refresh_token",
1376 "refresh_token" => "token.refresh_token",
1377 "client_id" => app.client_id,
1378 "client_secret" => app.client_secret
1379 })
1380 |> json_response(400)
1381
1382 assert %{"error" => "Invalid credentials"} == response
1383 end
1384
1385 test "issues a new token if token expired" do
1386 user = insert(:user)
1387 app = insert(:oauth_app, scopes: ["read", "write"])
1388
1389 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1390 {:ok, token} = Token.exchange_token(app, auth)
1391
1392 change =
1393 Ecto.Changeset.change(
1394 token,
1395 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1396 )
1397
1398 {:ok, access_token} = Repo.update(change)
1399
1400 response =
1401 build_conn()
1402 |> post("/oauth/token", %{
1403 "grant_type" => "refresh_token",
1404 "refresh_token" => access_token.refresh_token,
1405 "client_id" => app.client_id,
1406 "client_secret" => app.client_secret
1407 })
1408 |> json_response(200)
1409
1410 ap_id = user.ap_id
1411
1412 assert match?(
1413 %{
1414 "scope" => "write",
1415 "token_type" => "Bearer",
1416 "access_token" => _,
1417 "refresh_token" => _,
1418 "me" => ^ap_id
1419 },
1420 response
1421 )
1422
1423 refute Repo.get_by(Token, token: token.token)
1424 token = Repo.get_by(Token, token: response["access_token"])
1425 assert token
1426 assert token.scopes == auth.scopes
1427 assert token.user_id == user.id
1428 assert token.app_id == app.id
1429 end
1430 end
1431
1432 describe "POST /oauth/token - bad request" do
1433 test "returns 500" do
1434 response =
1435 build_conn()
1436 |> post("/oauth/token", %{})
1437 |> json_response(500)
1438
1439 assert %{"error" => "Bad request"} == response
1440 end
1441 end
1442
1443 describe "POST /oauth/revoke" do
1444 test "when authenticated with request token, revokes it and clears it from session" do
1445 oauth_token = insert(:oauth_token)
1446
1447 conn =
1448 build_conn()
1449 |> Plug.Session.call(Plug.Session.init(@session_opts))
1450 |> fetch_session()
1451 |> AuthHelper.put_session_token(oauth_token.token)
1452 |> post("/oauth/revoke", %{"token" => oauth_token.token})
1453
1454 assert json_response(conn, 200)
1455
1456 refute AuthHelper.get_session_token(conn)
1457 assert Token.get_by_token(oauth_token.token) == {:error, :not_found}
1458 end
1459
1460 test "if request is authenticated with a different token, " <>
1461 "revokes requested token but keeps session token" do
1462 user = insert(:user)
1463 oauth_token = insert(:oauth_token, user: user)
1464 other_app_oauth_token = insert(:oauth_token, user: user)
1465
1466 conn =
1467 build_conn()
1468 |> Plug.Session.call(Plug.Session.init(@session_opts))
1469 |> fetch_session()
1470 |> AuthHelper.put_session_token(oauth_token.token)
1471 |> post("/oauth/revoke", %{"token" => other_app_oauth_token.token})
1472
1473 assert json_response(conn, 200)
1474
1475 assert AuthHelper.get_session_token(conn) == oauth_token.token
1476 assert Token.get_by_token(other_app_oauth_token.token) == {:error, :not_found}
1477 end
1478
1479 test "returns 500 on bad request" do
1480 response =
1481 build_conn()
1482 |> post("/oauth/revoke", %{})
1483 |> json_response(500)
1484
1485 assert %{"error" => "Bad request"} == response
1486 end
1487 end
1488 end