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