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