1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.OAuthControllerTest do
6 use Pleroma.Web.ConnCase
11 alias Pleroma.MFA.TOTP
14 alias Pleroma.Web.OAuth.Authorization
15 alias Pleroma.Web.OAuth.OAuthController
16 alias Pleroma.Web.OAuth.Token
21 signing_salt: "cooldude"
24 clear_config([:instance, :account_activation_required])
25 clear_config([:instance, :account_approval_required])
28 describe "in OAuth consumer mode, " do
31 app: insert(:oauth_app),
34 |> Plug.Session.call(Plug.Session.init(@session_opts))
39 setup do: clear_config([:auth, :oauth_consumer_strategies], ~w(twitter facebook))
41 test "GET /oauth/authorize renders auth forms, including OAuth consumer form", %{
50 "response_type" => "code",
51 "client_id" => app.client_id,
52 "redirect_uri" => OAuthController.default_redirect_uri(app),
57 assert response = html_response(conn, 200)
58 assert response =~ "Sign in with Twitter"
59 assert response =~ o_auth_path(conn, :prepare_request)
62 test "GET /oauth/prepare_request encodes parameters as `state` and redirects", %{
69 "/oauth/prepare_request",
71 "provider" => "twitter",
73 "scope" => "read follow",
74 "client_id" => app.client_id,
75 "redirect_uri" => OAuthController.default_redirect_uri(app),
81 assert html_response(conn, 302)
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)
87 expected_client_id = app.client_id
88 expected_redirect_uri = app.redirect_uris
91 "scope" => "read follow",
92 "client_id" => ^expected_client_id,
93 "redirect_uri" => ^expected_redirect_uri,
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)
104 "scope" => Enum.join(app.scopes, " "),
105 "client_id" => app.client_id,
106 "redirect_uri" => redirect_uri,
112 |> assign(:ueberauth_auth, %{provider: registration.provider, uid: registration.uid})
114 "/oauth/twitter/callback",
116 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
117 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
118 "provider" => "twitter",
119 "state" => Jason.encode!(state_params)
123 assert html_response(conn, 302)
124 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
127 test "with user-unbound registration, GET /oauth/<provider>/callback renders registration_details page",
128 %{app: app, conn: conn} do
132 "scope" => "read write",
133 "client_id" => app.client_id,
134 "redirect_uri" => OAuthController.default_redirect_uri(app),
140 |> assign(:ueberauth_auth, %{
143 info: %{nickname: user.nickname, email: user.email, name: user.name, description: nil}
146 "/oauth/twitter/callback",
148 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
149 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
150 "provider" => "twitter",
151 "state" => Jason.encode!(state_params)
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
162 test "on authentication error, GET /oauth/<provider>/callback redirects to `redirect_uri`", %{
167 "scope" => Enum.join(app.scopes, " "),
168 "client_id" => app.client_id,
169 "redirect_uri" => OAuthController.default_redirect_uri(app),
175 |> assign(:ueberauth_failure, %{errors: [%{message: "(error description)"}]})
177 "/oauth/twitter/callback",
179 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
180 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
181 "provider" => "twitter",
182 "state" => Jason.encode!(state_params)
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)."
191 test "GET /oauth/registration_details renders registration details form", %{
198 "/oauth/registration_details",
200 "authorization" => %{
201 "scopes" => app.scopes,
202 "client_id" => app.client_id,
203 "redirect_uri" => OAuthController.default_redirect_uri(app),
204 "state" => "a_state",
206 "email" => "john@doe.com"
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"/
216 test "with valid params, POST /oauth/register?op=register redirects to `redirect_uri` with `code`",
221 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
222 redirect_uri = OAuthController.default_redirect_uri(app)
226 |> put_session(:registration_id, registration.id)
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"
242 assert html_response(conn, 302)
243 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
246 test "with unlisted `redirect_uri`, POST /oauth/register?op=register results in HTTP 401",
251 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
252 unlisted_redirect_uri = "http://cross-site-request.com"
256 |> put_session(:registration_id, registration.id)
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"
272 assert html_response(conn, 401)
275 test "with invalid params, POST /oauth/register?op=register renders registration_details page",
280 another_user = insert(:user)
281 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
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"
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)
301 bad_params = Map.merge(params, bad_registration_attrs)
305 |> put_session(:registration_id, registration.id)
306 |> post("/oauth/register", bad_params)
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."
313 test "with valid params, POST /oauth/register?op=connect redirects to `redirect_uri` with `code`",
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)
324 |> put_session(:registration_id, registration.id)
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"
340 assert html_response(conn, 302)
341 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
344 test "with unlisted `redirect_uri`, POST /oauth/register?op=connect results in HTTP 401`",
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"
355 |> put_session(:registration_id, registration.id)
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"
371 assert html_response(conn, 401)
374 test "with invalid params, POST /oauth/register?op=connect renders registration_details page",
380 registration = insert(:registration, user: nil)
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"
396 |> put_session(:registration_id, registration.id)
397 |> post("/oauth/register", params)
399 assert html_response(conn, 401) =~ ~r/name="op" type="submit" value="connect"/
400 assert get_flash(conn, :error) == "Invalid Username/Password"
404 describe "GET /oauth/authorize" do
407 app: insert(:oauth_app, redirect_uris: "https://redirect.url"),
410 |> Plug.Session.call(Plug.Session.init(@session_opts))
415 test "renders authentication page", %{app: app, conn: conn} do
421 "response_type" => "code",
422 "client_id" => app.client_id,
423 "redirect_uri" => OAuthController.default_redirect_uri(app),
428 assert html_response(conn, 200) =~ ~s(type="submit")
431 test "properly handles internal calls with `authorization`-wrapped params", %{
440 "authorization" => %{
441 "response_type" => "code",
442 "client_id" => app.client_id,
443 "redirect_uri" => OAuthController.default_redirect_uri(app),
449 assert html_response(conn, 200) =~ ~s(type="submit")
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)
458 |> put_req_header("authorization", "Bearer #{token.token}")
462 "response_type" => "code",
463 "client_id" => app.client_id,
464 "redirect_uri" => OAuthController.default_redirect_uri(app),
466 "force_login" => "true"
470 assert html_response(conn, 200) =~ ~s(type="submit")
473 test "reuses authentication if the user is authenticated with another client",
479 app = insert(:oauth_app, redirect_uris: "https://redirect.url")
480 other_app = insert(:oauth_app, redirect_uris: "https://redirect.url")
482 token = insert(:oauth_token, user: user, app: app)
483 reusable_token = insert(:oauth_token, app: other_app, user: user)
487 |> put_req_header("authorization", "Bearer #{token.token}")
491 "response_type" => "code",
492 "client_id" => other_app.client_id,
493 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
498 assert URI.decode(redirected_to(conn)) ==
499 "https://redirect.url?access_token=#{reusable_token.token}"
502 test "does not reuse other people's tokens",
507 other_user = insert(:user)
509 app = insert(:oauth_app, redirect_uris: "https://redirect.url")
510 other_app = insert(:oauth_app, redirect_uris: "https://redirect.url")
512 token = insert(:oauth_token, user: user, app: app)
513 _not_reusable_token = insert(:oauth_token, app: other_app, user: other_user)
517 |> put_req_header("authorization", "Bearer #{token.token}")
521 "response_type" => "code",
522 "client_id" => other_app.client_id,
523 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
528 assert html_response(conn, 200) =~ ~s(type="submit")
531 test "does not reuse expired tokens",
537 app = insert(:oauth_app, redirect_uris: "https://redirect.url")
539 other_app = insert(:oauth_app, redirect_uris: "https://redirect.url")
541 token = insert(:oauth_token, user: user, app: app)
543 _not_reusable_token =
547 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -60 * 100)
552 |> put_req_header("authorization", "Bearer #{token.token}")
556 "response_type" => "code",
557 "client_id" => other_app.client_id,
558 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
563 assert html_response(conn, 200) =~ ~s(type="submit")
566 test "does not reuse tokens with the wrong scopes",
572 app = insert(:oauth_app, redirect_uris: "https://redirect.url")
574 other_app = insert(:oauth_app, redirect_uris: "https://redirect.url")
576 token = insert(:oauth_token, user: user, app: app, scopes: ["read"])
578 _not_reusable_token =
586 |> put_req_header("authorization", "Bearer #{token.token}")
590 "response_type" => "code",
591 "client_id" => other_app.client_id,
592 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
593 "scope" => "read write"
597 assert html_response(conn, 200) =~ ~s(type="submit")
600 test "with existing authentication and non-OOB `redirect_uri`, redirects to app with `token` and `state` params",
605 token = insert(:oauth_token, app: app)
609 |> put_req_header("authorization", "Bearer #{token.token}")
613 "response_type" => "code",
614 "client_id" => app.client_id,
615 "redirect_uri" => OAuthController.default_redirect_uri(app),
616 "state" => "specific_client_state",
621 assert URI.decode(redirected_to(conn)) ==
622 "https://redirect.url?access_token=#{token.token}&state=specific_client_state"
625 test "with existing authentication and unlisted non-OOB `redirect_uri`, redirects without credentials",
630 unlisted_redirect_uri = "http://cross-site-request.com"
631 token = insert(:oauth_token, app: app)
635 |> put_req_header("authorization", "Bearer #{token.token}")
639 "response_type" => "code",
640 "client_id" => app.client_id,
641 "redirect_uri" => unlisted_redirect_uri,
642 "state" => "specific_client_state",
647 assert redirected_to(conn) == unlisted_redirect_uri
650 test "with existing authentication and OOB `redirect_uri`, redirects to app with `token` and `state` params",
655 token = insert(:oauth_token, app: app)
659 |> put_req_header("authorization", "Bearer #{token.token}")
663 "response_type" => "code",
664 "client_id" => app.client_id,
665 "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
670 assert html_response(conn, 200) =~ "Authorization exists"
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)
681 non_admin = insert(:user, is_admin: false)
682 admin = insert(:user, is_admin: true)
683 scopes_subset = ["read:subscope", "write", "admin"]
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
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"
705 target = redirected_to(conn)
706 assert target =~ redirect_uri
708 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
710 assert %{"state" => "statepassed", "code" => code} = query
711 auth = Repo.get_by(Authorization, token: code)
713 assert auth.scopes == expected_scopes
717 test "redirect to on two-factor auth page" do
718 otp_secret = TOTP.generate_secret()
722 multi_factor_authentication_settings: %MFA.Settings{
724 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
728 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
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"
743 result = html_response(conn, 200)
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"
752 test "returns 401 for wrong credentials", %{conn: conn} do
754 app = insert(:oauth_app)
755 redirect_uri = OAuthController.default_redirect_uri(app)
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, " ")
769 |> html_response(:unauthorized)
772 assert result =~ app.client_id
773 assert result =~ redirect_uri
776 assert result =~ "Invalid Username/Password"
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)
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",
796 |> html_response(:unauthorized)
799 assert result =~ app.client_id
800 assert result =~ redirect_uri
803 assert result =~ "This action is outside the authorized scopes"
806 test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
808 app = insert(:oauth_app, scopes: ["read", "write"])
809 redirect_uri = OAuthController.default_redirect_uri(app)
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"
823 |> html_response(:unauthorized)
826 assert result =~ app.client_id
827 assert result =~ redirect_uri
830 assert result =~ "This action is outside the authorized scopes"
834 describe "POST /oauth/token" do
835 test "issues a token for an all-body request" do
837 app = insert(:oauth_app, scopes: ["read", "write"])
839 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
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
851 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
853 token = Repo.get_by(Token, token: token)
855 assert token.scopes == auth.scopes
856 assert user.ap_id == ap_id
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))
863 app = insert(:oauth_app, scopes: ["read", "write"])
865 # Note: "scope" param is intentionally omitted
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
876 assert %{"id" => id, "access_token" => access_token} = json_response(conn, 200)
878 token = Repo.get_by(Token, token: access_token)
880 assert token.id == id
881 assert token.token == access_token
882 assert token.scopes == app.scopes
885 test "issues a mfa token for `password` grant_type, when MFA enabled" do
886 password = "testpassword"
887 otp_secret = TOTP.generate_secret()
891 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
892 multi_factor_authentication_settings: %MFA.Settings{
894 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
898 app = insert(:oauth_app, scopes: ["read", "write"])
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
909 |> json_response(403)
913 "supported_challenge_types" => "totp",
915 "error" => "mfa_required"
920 token = Repo.get_by(MFA.Token, token: response["mfa_token"])
921 assert token.user_id == user.id
922 assert token.authorization_id
925 test "issues a token for request with HTTP basic auth client credentials" do
927 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
929 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
930 assert auth.scopes == ["scope1", "scope2"]
933 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
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)
945 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
947 assert scope == "scope1 scope2"
949 token = Repo.get_by(Token, token: token)
951 assert token.scopes == ["scope1", "scope2"]
954 test "issue a token for client_credentials grant type" do
955 app = insert(:oauth_app, scopes: ["read", "write"])
959 |> post("/oauth/token", %{
960 "grant_type" => "client_credentials",
961 "client_id" => app.client_id,
962 "client_secret" => app.client_secret
965 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
966 json_response(conn, 200)
969 token_from_db = Repo.get_by(Token, token: token)
972 assert scope == "read write"
975 test "rejects token exchange with invalid client credentials" do
977 app = insert(:oauth_app)
979 {:ok, auth} = Authorization.create_authorization(app, user)
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)
990 assert resp = json_response(conn, 400)
991 assert %{"error" => _} = resp
992 refute Map.has_key?(resp, "access_token")
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"
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()
1004 refute Pleroma.User.account_status(user) == :active
1006 app = insert(:oauth_app)
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
1018 assert resp = json_response(conn, 403)
1019 assert %{"error" => _} = resp
1020 refute Map.has_key?(resp, "access_token")
1023 test "rejects token exchange for valid credentials belonging to deactivated user" do
1024 password = "testpassword"
1028 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1032 app = insert(:oauth_app)
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
1043 |> json_response(403)
1046 "error" => "Your account is currently disabled",
1047 "identifier" => "account_is_disabled"
1051 test "rejects token exchange for user with password_reset_pending set to true" do
1052 password = "testpassword"
1056 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1057 password_reset_pending: true
1060 app = insert(:oauth_app, scopes: ["read", "write"])
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
1071 |> json_response(403)
1074 "error" => "Password reset is required",
1075 "identifier" => "password_reset_required"
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"
1085 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1089 app = insert(:oauth_app, scopes: ["read", "write"])
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
1100 |> json_response(403)
1103 "error" => "Your login is missing a confirmed e-mail address",
1104 "identifier" => "missing_confirmed_email"
1108 test "rejects token exchange for valid credentials belonging to an unapproved user" do
1109 password = "testpassword"
1113 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1117 refute Pleroma.User.account_status(user) == :active
1119 app = insert(:oauth_app)
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
1131 assert resp = json_response(conn, 403)
1132 assert %{"error" => _} = resp
1133 refute Map.has_key?(resp, "access_token")
1136 test "rejects an invalid authorization code" do
1137 app = insert(:oauth_app)
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
1149 assert resp = json_response(conn, 400)
1150 assert %{"error" => _} = json_response(conn, 400)
1151 refute Map.has_key?(resp, "access_token")
1155 describe "POST /oauth/token - refresh token" do
1156 setup do: clear_config([:oauth2, :issue_new_refresh_token])
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"])
1163 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1164 {:ok, token} = Token.exchange_token(app, auth)
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
1174 |> json_response(200)
1181 "token_type" => "Bearer",
1182 "access_token" => _,
1183 "refresh_token" => _,
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
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"])
1202 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1203 {:ok, token} = Token.exchange_token(app, auth)
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
1213 |> json_response(200)
1220 "token_type" => "Bearer",
1221 "access_token" => _,
1222 "refresh_token" => _,
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
1236 test "returns 400 if we try use access token" do
1237 user = insert(:user)
1238 app = insert(:oauth_app, scopes: ["read", "write"])
1240 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1241 {:ok, token} = Token.exchange_token(app, auth)
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
1251 |> json_response(400)
1253 assert %{"error" => "Invalid credentials"} == response
1256 test "returns 400 if refresh_token invalid" do
1257 app = insert(:oauth_app, scopes: ["read", "write"])
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
1267 |> json_response(400)
1269 assert %{"error" => "Invalid credentials"} == response
1272 test "issues a new token if token expired" do
1273 user = insert(:user)
1274 app = insert(:oauth_app, scopes: ["read", "write"])
1276 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1277 {:ok, token} = Token.exchange_token(app, auth)
1280 Ecto.Changeset.change(
1282 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1285 {:ok, access_token} = Repo.update(change)
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
1296 |> json_response(200)
1303 "token_type" => "Bearer",
1304 "access_token" => _,
1305 "refresh_token" => _,
1311 refute Repo.get_by(Token, token: token.token)
1312 token = Repo.get_by(Token, token: response["access_token"])
1314 assert token.scopes == auth.scopes
1315 assert token.user_id == user.id
1316 assert token.app_id == app.id
1320 describe "POST /oauth/token - bad request" do
1321 test "returns 500" do
1324 |> post("/oauth/token", %{})
1325 |> json_response(500)
1327 assert %{"error" => "Bad request"} == response
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)
1337 |> Plug.Session.call(Plug.Session.init(@session_opts))
1339 |> put_req_header("authorization", "Bearer #{oauth_token.token}")
1340 |> post("/oauth/revoke", %{"token" => oauth_token.token})
1342 assert json_response(conn, 200)
1344 assert Token.get_by_token(oauth_token.token) == {:error, :not_found}
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)
1355 |> Plug.Session.call(Plug.Session.init(@session_opts))
1357 |> put_req_header("authorization", "Bearer #{oauth_token.token}")
1358 |> post("/oauth/revoke", %{"token" => other_app_oauth_token.token})
1360 assert json_response(conn, 200)
1362 assert Token.get_by_token(other_app_oauth_token.token) == {:error, :not_found}
1365 test "returns 500 on bad request" do
1368 |> post("/oauth/revoke", %{})
1369 |> json_response(500)
1371 assert %{"error" => "Bad request"} == response