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
10 alias Pleroma.Helpers.AuthHelper
12 alias Pleroma.MFA.TOTP
15 alias Pleroma.Web.OAuth.Authorization
16 alias Pleroma.Web.OAuth.OAuthController
17 alias Pleroma.Web.OAuth.Token
22 signing_salt: "cooldude"
25 clear_config([:instance, :account_activation_required])
26 clear_config([:instance, :account_approval_required])
29 describe "in OAuth consumer mode, " do
32 app: insert(:oauth_app),
35 |> Plug.Session.call(Plug.Session.init(@session_opts))
40 setup do: clear_config([:auth, :oauth_consumer_strategies], ~w(twitter facebook))
42 test "GET /oauth/authorize renders auth forms, including OAuth consumer form", %{
51 "response_type" => "code",
52 "client_id" => app.client_id,
53 "redirect_uri" => OAuthController.default_redirect_uri(app),
58 assert response = html_response(conn, 200)
59 assert response =~ "Sign in with Twitter"
60 assert response =~ o_auth_path(conn, :prepare_request)
63 test "GET /oauth/prepare_request encodes parameters as `state` and redirects", %{
70 "/oauth/prepare_request",
72 "provider" => "twitter",
74 "scope" => "read follow",
75 "client_id" => app.client_id,
76 "redirect_uri" => OAuthController.default_redirect_uri(app),
82 assert html_response(conn, 302)
84 redirect_query = URI.parse(redirected_to(conn)).query
85 assert %{"state" => state_param} = URI.decode_query(redirect_query)
86 assert {:ok, state_components} = Jason.decode(state_param)
88 expected_client_id = app.client_id
89 expected_redirect_uri = app.redirect_uris
92 "scope" => "read follow",
93 "client_id" => ^expected_client_id,
94 "redirect_uri" => ^expected_redirect_uri,
99 test "with user-bound registration, GET /oauth/<provider>/callback redirects to `redirect_uri` with `code`",
100 %{app: app, conn: conn} do
101 registration = insert(:registration)
102 redirect_uri = OAuthController.default_redirect_uri(app)
105 "scope" => Enum.join(app.scopes, " "),
106 "client_id" => app.client_id,
107 "redirect_uri" => redirect_uri,
113 |> assign(:ueberauth_auth, %{provider: registration.provider, uid: registration.uid})
115 "/oauth/twitter/callback",
117 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
118 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
119 "provider" => "twitter",
120 "state" => Jason.encode!(state_params)
124 assert html_response(conn, 302)
125 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
128 test "with user-unbound registration, GET /oauth/<provider>/callback renders registration_details page",
129 %{app: app, conn: conn} do
133 "scope" => "read write",
134 "client_id" => app.client_id,
135 "redirect_uri" => OAuthController.default_redirect_uri(app),
141 |> assign(:ueberauth_auth, %{
144 info: %{nickname: user.nickname, email: user.email, name: user.name, description: nil}
147 "/oauth/twitter/callback",
149 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
150 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
151 "provider" => "twitter",
152 "state" => Jason.encode!(state_params)
156 assert response = html_response(conn, 200)
157 assert response =~ ~r/name="op" type="submit" value="register"/
158 assert response =~ ~r/name="op" type="submit" value="connect"/
159 assert response =~ user.email
160 assert response =~ user.nickname
163 test "on authentication error, GET /oauth/<provider>/callback redirects to `redirect_uri`", %{
168 "scope" => Enum.join(app.scopes, " "),
169 "client_id" => app.client_id,
170 "redirect_uri" => OAuthController.default_redirect_uri(app),
176 |> assign(:ueberauth_failure, %{errors: [%{message: "(error description)"}]})
178 "/oauth/twitter/callback",
180 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
181 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
182 "provider" => "twitter",
183 "state" => Jason.encode!(state_params)
187 assert html_response(conn, 302)
188 assert redirected_to(conn) == app.redirect_uris
189 assert get_flash(conn, :error) == "Failed to authenticate: (error description)."
192 test "GET /oauth/registration_details renders registration details form", %{
199 "/oauth/registration_details",
201 "authorization" => %{
202 "scopes" => app.scopes,
203 "client_id" => app.client_id,
204 "redirect_uri" => OAuthController.default_redirect_uri(app),
205 "state" => "a_state",
207 "email" => "john@doe.com"
212 assert response = html_response(conn, 200)
213 assert response =~ ~r/name="op" type="submit" value="register"/
214 assert response =~ ~r/name="op" type="submit" value="connect"/
217 test "with valid params, POST /oauth/register?op=register redirects to `redirect_uri` with `code`",
222 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
223 redirect_uri = OAuthController.default_redirect_uri(app)
227 |> put_session(:registration_id, registration.id)
232 "authorization" => %{
233 "scopes" => app.scopes,
234 "client_id" => app.client_id,
235 "redirect_uri" => redirect_uri,
236 "state" => "a_state",
237 "nickname" => "availablenick",
238 "email" => "available@email.com"
243 assert html_response(conn, 302)
244 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
247 test "with unlisted `redirect_uri`, POST /oauth/register?op=register results in HTTP 401",
252 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
253 unlisted_redirect_uri = "http://cross-site-request.com"
257 |> put_session(:registration_id, registration.id)
262 "authorization" => %{
263 "scopes" => app.scopes,
264 "client_id" => app.client_id,
265 "redirect_uri" => unlisted_redirect_uri,
266 "state" => "a_state",
267 "nickname" => "availablenick",
268 "email" => "available@email.com"
273 assert html_response(conn, 401)
276 test "with invalid params, POST /oauth/register?op=register renders registration_details page",
281 another_user = insert(:user)
282 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
286 "authorization" => %{
287 "scopes" => app.scopes,
288 "client_id" => app.client_id,
289 "redirect_uri" => OAuthController.default_redirect_uri(app),
290 "state" => "a_state",
291 "nickname" => "availablenickname",
292 "email" => "available@email.com"
296 for {bad_param, bad_param_value} <-
297 [{"nickname", another_user.nickname}, {"email", another_user.email}] do
298 bad_registration_attrs = %{
299 "authorization" => Map.put(params["authorization"], bad_param, bad_param_value)
302 bad_params = Map.merge(params, bad_registration_attrs)
306 |> put_session(:registration_id, registration.id)
307 |> post("/oauth/register", bad_params)
309 assert html_response(conn, 403) =~ ~r/name="op" type="submit" value="register"/
310 assert get_flash(conn, :error) == "Error: #{bad_param} has already been taken."
314 test "with valid params, POST /oauth/register?op=connect redirects to `redirect_uri` with `code`",
319 user = insert(:user, password_hash: Pleroma.Password.hash_pwd_salt("testpassword"))
320 registration = insert(:registration, user: nil)
321 redirect_uri = OAuthController.default_redirect_uri(app)
325 |> put_session(:registration_id, registration.id)
330 "authorization" => %{
331 "scopes" => app.scopes,
332 "client_id" => app.client_id,
333 "redirect_uri" => redirect_uri,
334 "state" => "a_state",
335 "name" => user.nickname,
336 "password" => "testpassword"
341 assert html_response(conn, 302)
342 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
345 test "with unlisted `redirect_uri`, POST /oauth/register?op=connect results in HTTP 401`",
350 user = insert(:user, password_hash: Pleroma.Password.hash_pwd_salt("testpassword"))
351 registration = insert(:registration, user: nil)
352 unlisted_redirect_uri = "http://cross-site-request.com"
356 |> put_session(:registration_id, registration.id)
361 "authorization" => %{
362 "scopes" => app.scopes,
363 "client_id" => app.client_id,
364 "redirect_uri" => unlisted_redirect_uri,
365 "state" => "a_state",
366 "name" => user.nickname,
367 "password" => "testpassword"
372 assert html_response(conn, 401)
375 test "with invalid params, POST /oauth/register?op=connect renders registration_details page",
381 registration = insert(:registration, user: nil)
385 "authorization" => %{
386 "scopes" => app.scopes,
387 "client_id" => app.client_id,
388 "redirect_uri" => OAuthController.default_redirect_uri(app),
389 "state" => "a_state",
390 "name" => user.nickname,
391 "password" => "wrong password"
397 |> put_session(:registration_id, registration.id)
398 |> post("/oauth/register", params)
400 assert html_response(conn, 401) =~ ~r/name="op" type="submit" value="connect"/
401 assert get_flash(conn, :error) == "Invalid Username/Password"
405 describe "GET /oauth/authorize" do
408 app: insert(:oauth_app, redirect_uris: "https://redirect.url"),
411 |> Plug.Session.call(Plug.Session.init(@session_opts))
416 test "renders authentication page", %{app: app, conn: conn} do
422 "response_type" => "code",
423 "client_id" => app.client_id,
424 "redirect_uri" => OAuthController.default_redirect_uri(app),
429 assert html_response(conn, 200) =~ ~s(type="submit")
432 test "properly handles internal calls with `authorization`-wrapped params", %{
441 "authorization" => %{
442 "response_type" => "code",
443 "client_id" => app.client_id,
444 "redirect_uri" => OAuthController.default_redirect_uri(app),
450 assert html_response(conn, 200) =~ ~s(type="submit")
453 test "renders authentication page if user is already authenticated but `force_login` is tru-ish",
454 %{app: app, conn: conn} do
455 token = insert(:oauth_token, app: app)
459 |> AuthHelper.put_session_token(token.token)
463 "response_type" => "code",
464 "client_id" => app.client_id,
465 "redirect_uri" => OAuthController.default_redirect_uri(app),
467 "force_login" => "true"
471 assert html_response(conn, 200) =~ ~s(type="submit")
474 test "renders authentication page if user is already authenticated but user request with another client",
479 token = insert(:oauth_token, app: app)
483 |> AuthHelper.put_session_token(token.token)
487 "response_type" => "code",
488 "client_id" => "another_client_id",
489 "redirect_uri" => OAuthController.default_redirect_uri(app),
494 assert html_response(conn, 200) =~ ~s(type="submit")
497 test "allows access if the user has a prior authorization but is authenticated with another client",
503 token = insert(:oauth_token, app: app, user: user)
505 other_app = insert(:oauth_app, redirect_uris: "https://other_redirect.url")
506 authorization = insert(:oauth_authorization, user: user, app: other_app)
507 _reusable_token = insert(:oauth_token, app: other_app, user: user)
511 |> AuthHelper.put_session_token(token.token)
512 |> AuthHelper.put_session_user(user.id)
516 "response_type" => "code",
517 "client_id" => other_app.client_id,
518 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
523 assert URI.decode(redirected_to(conn)) ==
524 "https://other_redirect.url?code=#{authorization.token}"
527 test "renders login page if the user has an authorization but no token",
533 token = insert(:oauth_token, app: app, user: user)
535 other_app = insert(:oauth_app, redirect_uris: "https://other_redirect.url")
536 _authorization = insert(:oauth_authorization, user: user, app: other_app)
540 |> AuthHelper.put_session_token(token.token)
541 |> AuthHelper.put_session_user(user.id)
545 "response_type" => "code",
546 "client_id" => other_app.client_id,
547 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
552 assert html_response(conn, 200) =~ ~s(type="submit")
555 test "does not reuse other people's tokens",
561 other_user = insert(:user)
562 token = insert(:oauth_token, app: app, user: user)
564 other_app = insert(:oauth_app, redirect_uris: "https://other_redirect.url")
565 _authorization = insert(:oauth_authorization, user: other_user, app: other_app)
566 _reusable_token = insert(:oauth_token, app: other_app, user: other_user)
570 |> AuthHelper.put_session_token(token.token)
571 |> AuthHelper.put_session_user(user.id)
575 "response_type" => "code",
576 "client_id" => other_app.client_id,
577 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
582 assert html_response(conn, 200) =~ ~s(type="submit")
585 test "does not reuse expired tokens",
591 token = insert(:oauth_token, app: app, user: user)
593 other_app = insert(:oauth_app, redirect_uris: "https://other_redirect.url")
594 _authorization = insert(:oauth_authorization, user: user, app: other_app)
600 valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -100)
605 |> AuthHelper.put_session_token(token.token)
606 |> AuthHelper.put_session_user(user.id)
610 "response_type" => "code",
611 "client_id" => other_app.client_id,
612 "redirect_uri" => OAuthController.default_redirect_uri(other_app),
617 assert html_response(conn, 200) =~ ~s(type="submit")
620 test "with existing authentication and non-OOB `redirect_uri`, redirects to app with `token` and `state` params",
625 token = insert(:oauth_token, app: app)
629 |> AuthHelper.put_session_token(token.token)
633 "response_type" => "code",
634 "client_id" => app.client_id,
635 "redirect_uri" => OAuthController.default_redirect_uri(app),
636 "state" => "specific_client_state",
641 assert URI.decode(redirected_to(conn)) ==
642 "https://redirect.url?access_token=#{token.token}&state=specific_client_state"
645 test "with existing authentication and unlisted non-OOB `redirect_uri`, redirects without credentials",
650 unlisted_redirect_uri = "http://cross-site-request.com"
651 token = insert(:oauth_token, app: app)
655 |> AuthHelper.put_session_token(token.token)
659 "response_type" => "code",
660 "client_id" => app.client_id,
661 "redirect_uri" => unlisted_redirect_uri,
662 "state" => "specific_client_state",
667 assert redirected_to(conn) == unlisted_redirect_uri
670 test "with existing authentication and OOB `redirect_uri`, redirects to app with `token` and `state` params",
675 token = insert(:oauth_token, app: app)
679 |> AuthHelper.put_session_token(token.token)
683 "response_type" => "code",
684 "client_id" => app.client_id,
685 "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
690 assert html_response(conn, 200) =~ "Authorization exists"
694 describe "POST /oauth/authorize" do
695 test "redirects with oauth authorization, " <>
696 "granting requested app-supported scopes to admin users" do
697 app_scopes = ["read", "write", "admin", "secret_scope"]
698 app = insert(:oauth_app, scopes: app_scopes)
699 redirect_uri = OAuthController.default_redirect_uri(app)
700 scopes_subset = ["read:subscope", "write", "admin"]
701 admin = insert(:user, is_admin: true)
703 # In case scope param is missing, expecting _all_ app-supported scopes to be granted
709 "authorization" => %{
710 "name" => admin.nickname,
711 "password" => "test",
712 "client_id" => app.client_id,
713 "redirect_uri" => redirect_uri,
714 "scope" => scopes_subset,
715 "state" => "statepassed"
720 target = redirected_to(conn)
721 assert target =~ redirect_uri
723 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
725 assert %{"state" => "statepassed", "code" => code} = query
726 auth = Repo.get_by(Authorization, token: code)
728 assert auth.scopes == scopes_subset
731 test "redirects with oauth authorization, " <>
732 "granting requested app-supported scopes to moderators" do
733 app_scopes = ["read", "write", "admin", "secret_scope"]
734 app = insert(:oauth_app, scopes: app_scopes)
735 redirect_uri = OAuthController.default_redirect_uri(app)
736 scopes_subset = ["read:subscope", "write", "admin"]
737 admin = insert(:user, is_moderator: true)
739 # In case scope param is missing, expecting _all_ app-supported scopes to be granted
745 "authorization" => %{
746 "name" => admin.nickname,
747 "password" => "test",
748 "client_id" => app.client_id,
749 "redirect_uri" => redirect_uri,
750 "scope" => scopes_subset,
751 "state" => "statepassed"
756 target = redirected_to(conn)
757 assert target =~ redirect_uri
759 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
761 assert %{"state" => "statepassed", "code" => code} = query
762 auth = Repo.get_by(Authorization, token: code)
764 assert auth.scopes == scopes_subset
767 test "redirects with oauth authorization, " <>
768 "granting requested app-supported scopes for non-admin users" do
769 app_scopes = ["read", "write", "secret_scope", "admin"]
770 app = insert(:oauth_app, scopes: app_scopes)
771 redirect_uri = OAuthController.default_redirect_uri(app)
773 non_admin = insert(:user, is_admin: false)
774 scopes_subset = ["read:subscope", "write", "admin", "admin:metrics"]
776 # In case scope param is missing, expecting _all_ app-supported scopes to be granted
782 "authorization" => %{
783 "name" => non_admin.nickname,
784 "password" => "test",
785 "client_id" => app.client_id,
786 "redirect_uri" => redirect_uri,
787 "scope" => scopes_subset,
788 "state" => "statepassed"
793 target = redirected_to(conn)
794 assert target =~ redirect_uri
796 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
798 assert %{"state" => "statepassed", "code" => code} = query
799 auth = Repo.get_by(Authorization, token: code)
801 assert auth.scopes == ["read:subscope", "write"]
804 test "authorize from cookie" do
806 app = insert(:oauth_app)
807 oauth_token = insert(:oauth_token, user: user, app: app)
808 redirect_uri = OAuthController.default_redirect_uri(app)
812 |> Plug.Session.call(Plug.Session.init(@session_opts))
814 |> AuthHelper.put_session_token(oauth_token.token)
818 "authorization" => %{
819 "name" => user.nickname,
820 "client_id" => app.client_id,
821 "redirect_uri" => redirect_uri,
822 "scope" => app.scopes,
823 "state" => "statepassed"
828 target = redirected_to(conn)
829 assert target =~ redirect_uri
831 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
833 assert %{"state" => "statepassed", "code" => code} = query
834 auth = Repo.get_by(Authorization, token: code)
836 assert auth.scopes == app.scopes
839 test "redirect to on two-factor auth page" do
840 otp_secret = TOTP.generate_secret()
844 multi_factor_authentication_settings: %MFA.Settings{
846 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
850 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
854 |> post("/oauth/authorize", %{
855 "authorization" => %{
856 "name" => user.nickname,
857 "password" => "test",
858 "client_id" => app.client_id,
859 "redirect_uri" => app.redirect_uris,
860 "scope" => "read write",
861 "state" => "statepassed"
865 result = html_response(conn, 200)
867 mfa_token = Repo.get_by(MFA.Token, user_id: user.id)
868 assert result =~ app.redirect_uris
869 assert result =~ "statepassed"
870 assert result =~ mfa_token.token
871 assert result =~ "Two-factor authentication"
874 test "returns 401 for wrong credentials", %{conn: conn} do
876 app = insert(:oauth_app)
877 redirect_uri = OAuthController.default_redirect_uri(app)
881 |> post("/oauth/authorize", %{
882 "authorization" => %{
883 "name" => user.nickname,
884 "password" => "wrong",
885 "client_id" => app.client_id,
886 "redirect_uri" => redirect_uri,
887 "state" => "statepassed",
888 "scope" => Enum.join(app.scopes, " ")
891 |> html_response(:unauthorized)
894 assert result =~ app.client_id
895 assert result =~ redirect_uri
898 assert result =~ "Invalid Username/Password"
901 test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
903 app = insert(:oauth_app, scopes: ["read", "write"])
904 redirect_uri = OAuthController.default_redirect_uri(app)
908 |> post("/oauth/authorize", %{
909 "authorization" => %{
910 "name" => user.nickname,
911 "password" => "test",
912 "client_id" => app.client_id,
913 "redirect_uri" => redirect_uri,
914 "state" => "statepassed",
915 "scope" => "read write follow"
918 |> html_response(:unauthorized)
921 assert result =~ app.client_id
922 assert result =~ redirect_uri
925 assert result =~ "This action is outside of authorized scopes"
929 describe "POST /oauth/token" do
930 test "issues a token for an all-body request" do
932 app = insert(:oauth_app, scopes: ["read", "write"])
934 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
938 |> post("/oauth/token", %{
939 "grant_type" => "authorization_code",
940 "code" => auth.token,
941 "redirect_uri" => OAuthController.default_redirect_uri(app),
942 "client_id" => app.client_id,
943 "client_secret" => app.client_secret
946 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
948 token = Repo.get_by(Token, token: token)
950 assert token.scopes == auth.scopes
951 assert user.ap_id == ap_id
954 test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
955 password = "testpassword"
956 user = insert(:user, password_hash: Pleroma.Password.hash_pwd_salt(password))
958 app = insert(:oauth_app, scopes: ["read", "write"])
960 # Note: "scope" param is intentionally omitted
963 |> post("/oauth/token", %{
964 "grant_type" => "password",
965 "username" => user.nickname,
966 "password" => password,
967 "client_id" => app.client_id,
968 "client_secret" => app.client_secret
971 assert %{"id" => id, "access_token" => access_token} = json_response(conn, 200)
973 token = Repo.get_by(Token, token: access_token)
975 assert token.id == id
976 assert token.token == access_token
977 assert token.scopes == app.scopes
980 test "issues a mfa token for `password` grant_type, when MFA enabled" do
981 password = "testpassword"
982 otp_secret = TOTP.generate_secret()
986 password_hash: Pleroma.Password.hash_pwd_salt(password),
987 multi_factor_authentication_settings: %MFA.Settings{
989 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
993 app = insert(:oauth_app, scopes: ["read", "write"])
997 |> post("/oauth/token", %{
998 "grant_type" => "password",
999 "username" => user.nickname,
1000 "password" => password,
1001 "client_id" => app.client_id,
1002 "client_secret" => app.client_secret
1004 |> json_response(403)
1008 "supported_challenge_types" => "totp",
1010 "error" => "mfa_required"
1015 token = Repo.get_by(MFA.Token, token: response["mfa_token"])
1016 assert token.user_id == user.id
1017 assert token.authorization_id
1020 test "issues a token for request with HTTP basic auth client credentials" do
1021 user = insert(:user)
1022 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
1024 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
1025 assert auth.scopes == ["scope1", "scope2"]
1028 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
1033 |> put_req_header("authorization", "Basic " <> app_encoded)
1034 |> post("/oauth/token", %{
1035 "grant_type" => "authorization_code",
1036 "code" => auth.token,
1037 "redirect_uri" => OAuthController.default_redirect_uri(app)
1040 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
1042 assert scope == "scope1 scope2"
1044 token = Repo.get_by(Token, token: token)
1046 assert token.scopes == ["scope1", "scope2"]
1049 test "issue a token for client_credentials grant type" do
1050 app = insert(:oauth_app, scopes: ["read", "write"])
1054 |> post("/oauth/token", %{
1055 "grant_type" => "client_credentials",
1056 "client_id" => app.client_id,
1057 "client_secret" => app.client_secret
1060 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
1061 json_response(conn, 200)
1064 token_from_db = Repo.get_by(Token, token: token)
1065 assert token_from_db
1067 assert scope == "read write"
1070 test "rejects token exchange with invalid client credentials" do
1071 user = insert(:user)
1072 app = insert(:oauth_app)
1074 {:ok, auth} = Authorization.create_authorization(app, user)
1078 |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
1079 |> post("/oauth/token", %{
1080 "grant_type" => "authorization_code",
1081 "code" => auth.token,
1082 "redirect_uri" => OAuthController.default_redirect_uri(app)
1085 assert resp = json_response(conn, 400)
1086 assert %{"error" => _} = resp
1087 refute Map.has_key?(resp, "access_token")
1090 test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
1091 clear_config([:instance, :account_activation_required], true)
1092 password = "testpassword"
1095 insert(:user, password_hash: Pleroma.Password.hash_pwd_salt(password))
1096 |> User.confirmation_changeset(set_confirmation: false)
1097 |> User.update_and_set_cache()
1099 refute Pleroma.User.account_status(user) == :active
1101 app = insert(:oauth_app)
1105 |> post("/oauth/token", %{
1106 "grant_type" => "password",
1107 "username" => user.nickname,
1108 "password" => password,
1109 "client_id" => app.client_id,
1110 "client_secret" => app.client_secret
1113 assert resp = json_response(conn, 403)
1114 assert %{"error" => _} = resp
1115 refute Map.has_key?(resp, "access_token")
1118 test "rejects token exchange for valid credentials belonging to deactivated user" do
1119 password = "testpassword"
1123 password_hash: Pleroma.Password.hash_pwd_salt(password),
1127 app = insert(:oauth_app)
1131 |> post("/oauth/token", %{
1132 "grant_type" => "password",
1133 "username" => user.nickname,
1134 "password" => password,
1135 "client_id" => app.client_id,
1136 "client_secret" => app.client_secret
1138 |> json_response(403)
1141 "error" => "Your account is currently disabled",
1142 "identifier" => "account_is_disabled"
1146 test "rejects token exchange for user with password_reset_pending set to true" do
1147 password = "testpassword"
1151 password_hash: Pleroma.Password.hash_pwd_salt(password),
1152 password_reset_pending: true
1155 app = insert(:oauth_app, scopes: ["read", "write"])
1159 |> post("/oauth/token", %{
1160 "grant_type" => "password",
1161 "username" => user.nickname,
1162 "password" => password,
1163 "client_id" => app.client_id,
1164 "client_secret" => app.client_secret
1166 |> json_response(403)
1169 "error" => "Password reset is required",
1170 "identifier" => "password_reset_required"
1174 test "rejects token exchange for user with confirmation_pending set to true" do
1175 clear_config([:instance, :account_activation_required], true)
1176 password = "testpassword"
1180 password_hash: Pleroma.Password.hash_pwd_salt(password),
1184 app = insert(:oauth_app, scopes: ["read", "write"])
1188 |> post("/oauth/token", %{
1189 "grant_type" => "password",
1190 "username" => user.nickname,
1191 "password" => password,
1192 "client_id" => app.client_id,
1193 "client_secret" => app.client_secret
1195 |> json_response(403)
1198 "error" => "Your login is missing a confirmed e-mail address",
1199 "identifier" => "missing_confirmed_email"
1203 test "rejects token exchange for valid credentials belonging to an unapproved user" do
1204 password = "testpassword"
1208 password_hash: Pleroma.Password.hash_pwd_salt(password),
1212 refute Pleroma.User.account_status(user) == :active
1214 app = insert(:oauth_app)
1218 |> post("/oauth/token", %{
1219 "grant_type" => "password",
1220 "username" => user.nickname,
1221 "password" => password,
1222 "client_id" => app.client_id,
1223 "client_secret" => app.client_secret
1226 assert resp = json_response(conn, 403)
1227 assert %{"error" => _} = resp
1228 refute Map.has_key?(resp, "access_token")
1231 test "rejects an invalid authorization code" do
1232 app = insert(:oauth_app)
1236 |> post("/oauth/token", %{
1237 "grant_type" => "authorization_code",
1238 "code" => "Imobviouslyinvalid",
1239 "redirect_uri" => OAuthController.default_redirect_uri(app),
1240 "client_id" => app.client_id,
1241 "client_secret" => app.client_secret
1244 assert resp = json_response(conn, 400)
1245 assert %{"error" => _} = json_response(conn, 400)
1246 refute Map.has_key?(resp, "access_token")
1250 describe "POST /oauth/token - refresh token" do
1251 setup do: clear_config([:oauth2, :issue_new_refresh_token])
1253 test "issues a new access token with keep fresh token" do
1254 clear_config([:oauth2, :issue_new_refresh_token], true)
1255 user = insert(:user)
1256 app = insert(:oauth_app, scopes: ["read", "write"])
1258 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1259 {:ok, token} = Token.exchange_token(app, auth)
1263 |> post("/oauth/token", %{
1264 "grant_type" => "refresh_token",
1265 "refresh_token" => token.refresh_token,
1266 "client_id" => app.client_id,
1267 "client_secret" => app.client_secret
1269 |> json_response(200)
1276 "token_type" => "Bearer",
1277 "access_token" => _,
1278 "refresh_token" => _,
1284 refute Repo.get_by(Token, token: token.token)
1285 new_token = Repo.get_by(Token, token: response["access_token"])
1286 assert new_token.refresh_token == token.refresh_token
1287 assert new_token.scopes == auth.scopes
1288 assert new_token.user_id == user.id
1289 assert new_token.app_id == app.id
1292 test "issues a new access token with new fresh token" do
1293 clear_config([:oauth2, :issue_new_refresh_token], false)
1294 user = insert(:user)
1295 app = insert(:oauth_app, scopes: ["read", "write"])
1297 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1298 {:ok, token} = Token.exchange_token(app, auth)
1302 |> post("/oauth/token", %{
1303 "grant_type" => "refresh_token",
1304 "refresh_token" => token.refresh_token,
1305 "client_id" => app.client_id,
1306 "client_secret" => app.client_secret
1308 |> json_response(200)
1315 "token_type" => "Bearer",
1316 "access_token" => _,
1317 "refresh_token" => _,
1323 refute Repo.get_by(Token, token: token.token)
1324 new_token = Repo.get_by(Token, token: response["access_token"])
1325 refute new_token.refresh_token == token.refresh_token
1326 assert new_token.scopes == auth.scopes
1327 assert new_token.user_id == user.id
1328 assert new_token.app_id == app.id
1331 test "returns 400 if we try use access token" do
1332 user = insert(:user)
1333 app = insert(:oauth_app, scopes: ["read", "write"])
1335 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1336 {:ok, token} = Token.exchange_token(app, auth)
1340 |> post("/oauth/token", %{
1341 "grant_type" => "refresh_token",
1342 "refresh_token" => token.token,
1343 "client_id" => app.client_id,
1344 "client_secret" => app.client_secret
1346 |> json_response(400)
1348 assert %{"error" => "Invalid credentials"} == response
1351 test "returns 400 if refresh_token invalid" do
1352 app = insert(:oauth_app, scopes: ["read", "write"])
1356 |> post("/oauth/token", %{
1357 "grant_type" => "refresh_token",
1358 "refresh_token" => "token.refresh_token",
1359 "client_id" => app.client_id,
1360 "client_secret" => app.client_secret
1362 |> json_response(400)
1364 assert %{"error" => "Invalid credentials"} == response
1367 test "issues a new token if token expired" do
1368 user = insert(:user)
1369 app = insert(:oauth_app, scopes: ["read", "write"])
1371 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1372 {:ok, token} = Token.exchange_token(app, auth)
1375 Ecto.Changeset.change(
1377 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1380 {:ok, access_token} = Repo.update(change)
1384 |> post("/oauth/token", %{
1385 "grant_type" => "refresh_token",
1386 "refresh_token" => access_token.refresh_token,
1387 "client_id" => app.client_id,
1388 "client_secret" => app.client_secret
1390 |> json_response(200)
1397 "token_type" => "Bearer",
1398 "access_token" => _,
1399 "refresh_token" => _,
1405 refute Repo.get_by(Token, token: token.token)
1406 token = Repo.get_by(Token, token: response["access_token"])
1408 assert token.scopes == auth.scopes
1409 assert token.user_id == user.id
1410 assert token.app_id == app.id
1414 describe "POST /oauth/token - bad request" do
1415 test "returns 500" do
1418 |> post("/oauth/token", %{})
1419 |> json_response(500)
1421 assert %{"error" => "Bad request"} == response
1425 describe "POST /oauth/revoke" do
1426 test "when authenticated with request token, revokes it and clears it from session" do
1427 oauth_token = insert(:oauth_token)
1431 |> Plug.Session.call(Plug.Session.init(@session_opts))
1433 |> AuthHelper.put_session_token(oauth_token.token)
1434 |> post("/oauth/revoke", %{"token" => oauth_token.token})
1436 assert json_response(conn, 200)
1438 refute AuthHelper.get_session_token(conn)
1439 assert Token.get_by_token(oauth_token.token) == {:error, :not_found}
1442 test "if request is authenticated with a different token, " <>
1443 "revokes requested token but keeps session token" do
1444 user = insert(:user)
1445 oauth_token = insert(:oauth_token, user: user)
1446 other_app_oauth_token = insert(:oauth_token, user: user)
1450 |> Plug.Session.call(Plug.Session.init(@session_opts))
1452 |> AuthHelper.put_session_token(oauth_token.token)
1453 |> post("/oauth/revoke", %{"token" => other_app_oauth_token.token})
1455 assert json_response(conn, 200)
1457 assert AuthHelper.get_session_token(conn) == oauth_token.token
1458 assert Token.get_by_token(other_app_oauth_token.token) == {:error, :not_found}
1461 test "returns 500 on bad request" do
1464 |> post("/oauth/revoke", %{})
1465 |> json_response(500)
1467 assert %{"error" => "Bad request"} == response