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