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