1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 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.Web.OAuth.Authorization
11 alias Pleroma.Web.OAuth.OAuthController
12 alias Pleroma.Web.OAuth.Token
17 signing_salt: "cooldude"
19 clear_config_all([:instance, :account_activation_required])
21 describe "in OAuth consumer mode, " do
24 app: insert(:oauth_app),
27 |> Plug.Session.call(Plug.Session.init(@session_opts))
32 clear_config([:auth, :oauth_consumer_strategies]) do
34 [:auth, :oauth_consumer_strategies],
39 test "GET /oauth/authorize renders auth forms, including OAuth consumer form", %{
48 "response_type" => "code",
49 "client_id" => app.client_id,
50 "redirect_uri" => OAuthController.default_redirect_uri(app),
55 assert response = html_response(conn, 200)
56 assert response =~ "Sign in with Twitter"
57 assert response =~ o_auth_path(conn, :prepare_request)
60 test "GET /oauth/prepare_request encodes parameters as `state` and redirects", %{
67 "/oauth/prepare_request",
69 "provider" => "twitter",
71 "scope" => "read follow",
72 "client_id" => app.client_id,
73 "redirect_uri" => OAuthController.default_redirect_uri(app),
79 assert response = html_response(conn, 302)
81 redirect_query = URI.parse(redirected_to(conn)).query
82 assert %{"state" => state_param} = URI.decode_query(redirect_query)
83 assert {:ok, state_components} = Poison.decode(state_param)
85 expected_client_id = app.client_id
86 expected_redirect_uri = app.redirect_uris
89 "scope" => "read follow",
90 "client_id" => ^expected_client_id,
91 "redirect_uri" => ^expected_redirect_uri,
96 test "with user-bound registration, GET /oauth/<provider>/callback redirects to `redirect_uri` with `code`",
97 %{app: app, conn: conn} do
98 registration = insert(:registration)
99 redirect_uri = OAuthController.default_redirect_uri(app)
102 "scope" => Enum.join(app.scopes, " "),
103 "client_id" => app.client_id,
104 "redirect_uri" => redirect_uri,
110 |> assign(:ueberauth_auth, %{provider: registration.provider, uid: registration.uid})
112 "/oauth/twitter/callback",
114 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
115 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
116 "provider" => "twitter",
117 "state" => Poison.encode!(state_params)
121 assert response = html_response(conn, 302)
122 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
125 test "with user-unbound registration, GET /oauth/<provider>/callback renders registration_details page",
126 %{app: app, conn: conn} do
130 "scope" => "read write",
131 "client_id" => app.client_id,
132 "redirect_uri" => OAuthController.default_redirect_uri(app),
138 |> assign(:ueberauth_auth, %{
141 info: %{nickname: user.nickname, email: user.email, name: user.name, description: nil}
144 "/oauth/twitter/callback",
146 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
147 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
148 "provider" => "twitter",
149 "state" => Poison.encode!(state_params)
153 assert response = html_response(conn, 200)
154 assert response =~ ~r/name="op" type="submit" value="register"/
155 assert response =~ ~r/name="op" type="submit" value="connect"/
156 assert response =~ user.email
157 assert response =~ user.nickname
160 test "on authentication error, GET /oauth/<provider>/callback redirects to `redirect_uri`", %{
165 "scope" => Enum.join(app.scopes, " "),
166 "client_id" => app.client_id,
167 "redirect_uri" => OAuthController.default_redirect_uri(app),
173 |> assign(:ueberauth_failure, %{errors: [%{message: "(error description)"}]})
175 "/oauth/twitter/callback",
177 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
178 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
179 "provider" => "twitter",
180 "state" => Poison.encode!(state_params)
184 assert response = html_response(conn, 302)
185 assert redirected_to(conn) == app.redirect_uris
186 assert get_flash(conn, :error) == "Failed to authenticate: (error description)."
189 test "GET /oauth/registration_details renders registration details form", %{
196 "/oauth/registration_details",
198 "authorization" => %{
199 "scopes" => app.scopes,
200 "client_id" => app.client_id,
201 "redirect_uri" => OAuthController.default_redirect_uri(app),
202 "state" => "a_state",
204 "email" => "john@doe.com"
209 assert response = html_response(conn, 200)
210 assert response =~ ~r/name="op" type="submit" value="register"/
211 assert response =~ ~r/name="op" type="submit" value="connect"/
214 test "with valid params, POST /oauth/register?op=register redirects to `redirect_uri` with `code`",
219 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
220 redirect_uri = OAuthController.default_redirect_uri(app)
224 |> put_session(:registration_id, registration.id)
229 "authorization" => %{
230 "scopes" => app.scopes,
231 "client_id" => app.client_id,
232 "redirect_uri" => redirect_uri,
233 "state" => "a_state",
234 "nickname" => "availablenick",
235 "email" => "available@email.com"
240 assert response = html_response(conn, 302)
241 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
244 test "with unlisted `redirect_uri`, POST /oauth/register?op=register results in HTTP 401",
249 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
250 unlisted_redirect_uri = "http://cross-site-request.com"
254 |> put_session(:registration_id, registration.id)
259 "authorization" => %{
260 "scopes" => app.scopes,
261 "client_id" => app.client_id,
262 "redirect_uri" => unlisted_redirect_uri,
263 "state" => "a_state",
264 "nickname" => "availablenick",
265 "email" => "available@email.com"
270 assert response = html_response(conn, 401)
273 test "with invalid params, POST /oauth/register?op=register renders registration_details page",
278 another_user = insert(:user)
279 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
283 "authorization" => %{
284 "scopes" => app.scopes,
285 "client_id" => app.client_id,
286 "redirect_uri" => OAuthController.default_redirect_uri(app),
287 "state" => "a_state",
288 "nickname" => "availablenickname",
289 "email" => "available@email.com"
293 for {bad_param, bad_param_value} <-
294 [{"nickname", another_user.nickname}, {"email", another_user.email}] do
295 bad_registration_attrs = %{
296 "authorization" => Map.put(params["authorization"], bad_param, bad_param_value)
299 bad_params = Map.merge(params, bad_registration_attrs)
303 |> put_session(:registration_id, registration.id)
304 |> post("/oauth/register", bad_params)
306 assert html_response(conn, 403) =~ ~r/name="op" type="submit" value="register"/
307 assert get_flash(conn, :error) == "Error: #{bad_param} has already been taken."
311 test "with valid params, POST /oauth/register?op=connect redirects to `redirect_uri` with `code`",
316 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("testpassword"))
317 registration = insert(:registration, user: nil)
318 redirect_uri = OAuthController.default_redirect_uri(app)
322 |> put_session(:registration_id, registration.id)
327 "authorization" => %{
328 "scopes" => app.scopes,
329 "client_id" => app.client_id,
330 "redirect_uri" => redirect_uri,
331 "state" => "a_state",
332 "name" => user.nickname,
333 "password" => "testpassword"
338 assert response = html_response(conn, 302)
339 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
342 test "with unlisted `redirect_uri`, POST /oauth/register?op=connect results in HTTP 401`",
347 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("testpassword"))
348 registration = insert(:registration, user: nil)
349 unlisted_redirect_uri = "http://cross-site-request.com"
353 |> put_session(:registration_id, registration.id)
358 "authorization" => %{
359 "scopes" => app.scopes,
360 "client_id" => app.client_id,
361 "redirect_uri" => unlisted_redirect_uri,
362 "state" => "a_state",
363 "name" => user.nickname,
364 "password" => "testpassword"
369 assert response = html_response(conn, 401)
372 test "with invalid params, POST /oauth/register?op=connect renders registration_details page",
378 registration = insert(:registration, user: nil)
382 "authorization" => %{
383 "scopes" => app.scopes,
384 "client_id" => app.client_id,
385 "redirect_uri" => OAuthController.default_redirect_uri(app),
386 "state" => "a_state",
387 "name" => user.nickname,
388 "password" => "wrong password"
394 |> put_session(:registration_id, registration.id)
395 |> post("/oauth/register", params)
397 assert html_response(conn, 401) =~ ~r/name="op" type="submit" value="connect"/
398 assert get_flash(conn, :error) == "Invalid Username/Password"
402 describe "GET /oauth/authorize" do
405 app: insert(:oauth_app, redirect_uris: "https://redirect.url"),
408 |> Plug.Session.call(Plug.Session.init(@session_opts))
413 test "renders authentication page", %{app: app, conn: conn} do
419 "response_type" => "code",
420 "client_id" => app.client_id,
421 "redirect_uri" => OAuthController.default_redirect_uri(app),
426 assert html_response(conn, 200) =~ ~s(type="submit")
429 test "properly handles internal calls with `authorization`-wrapped params", %{
438 "authorization" => %{
439 "response_type" => "code",
440 "client_id" => app.client_id,
441 "redirect_uri" => OAuthController.default_redirect_uri(app),
447 assert html_response(conn, 200) =~ ~s(type="submit")
450 test "renders authentication page if user is already authenticated but `force_login` is tru-ish",
451 %{app: app, conn: conn} do
452 token = insert(:oauth_token, app_id: app.id)
456 |> put_session(:oauth_token, token.token)
460 "response_type" => "code",
461 "client_id" => app.client_id,
462 "redirect_uri" => OAuthController.default_redirect_uri(app),
464 "force_login" => "true"
468 assert html_response(conn, 200) =~ ~s(type="submit")
471 test "renders authentication page if user is already authenticated but user request with another client",
476 token = insert(:oauth_token, app_id: app.id)
480 |> put_session(:oauth_token, token.token)
484 "response_type" => "code",
485 "client_id" => "another_client_id",
486 "redirect_uri" => OAuthController.default_redirect_uri(app),
491 assert html_response(conn, 200) =~ ~s(type="submit")
494 test "with existing authentication and non-OOB `redirect_uri`, redirects to app with `token` and `state` params",
499 token = insert(:oauth_token, app_id: app.id)
503 |> put_session(:oauth_token, token.token)
507 "response_type" => "code",
508 "client_id" => app.client_id,
509 "redirect_uri" => OAuthController.default_redirect_uri(app),
510 "state" => "specific_client_state",
515 assert URI.decode(redirected_to(conn)) ==
516 "https://redirect.url?access_token=#{token.token}&state=specific_client_state"
519 test "with existing authentication and unlisted non-OOB `redirect_uri`, redirects without credentials",
524 unlisted_redirect_uri = "http://cross-site-request.com"
525 token = insert(:oauth_token, app_id: app.id)
529 |> put_session(:oauth_token, token.token)
533 "response_type" => "code",
534 "client_id" => app.client_id,
535 "redirect_uri" => unlisted_redirect_uri,
536 "state" => "specific_client_state",
541 assert redirected_to(conn) == unlisted_redirect_uri
544 test "with existing authentication and OOB `redirect_uri`, redirects to app with `token` and `state` params",
549 token = insert(:oauth_token, app_id: app.id)
553 |> put_session(:oauth_token, token.token)
557 "response_type" => "code",
558 "client_id" => app.client_id,
559 "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
564 assert html_response(conn, 200) =~ "Authorization exists"
568 describe "POST /oauth/authorize" do
569 test "redirects with oauth authorization" do
571 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
572 redirect_uri = OAuthController.default_redirect_uri(app)
576 |> post("/oauth/authorize", %{
577 "authorization" => %{
578 "name" => user.nickname,
579 "password" => "test",
580 "client_id" => app.client_id,
581 "redirect_uri" => redirect_uri,
582 "scope" => "read write",
583 "state" => "statepassed"
587 target = redirected_to(conn)
588 assert target =~ redirect_uri
590 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
592 assert %{"state" => "statepassed", "code" => code} = query
593 auth = Repo.get_by(Authorization, token: code)
595 assert auth.scopes == ["read", "write"]
598 test "returns 401 for wrong credentials", %{conn: conn} do
600 app = insert(:oauth_app)
601 redirect_uri = OAuthController.default_redirect_uri(app)
605 |> post("/oauth/authorize", %{
606 "authorization" => %{
607 "name" => user.nickname,
608 "password" => "wrong",
609 "client_id" => app.client_id,
610 "redirect_uri" => redirect_uri,
611 "state" => "statepassed",
612 "scope" => Enum.join(app.scopes, " ")
615 |> html_response(:unauthorized)
618 assert result =~ app.client_id
619 assert result =~ redirect_uri
622 assert result =~ "Invalid Username/Password"
625 test "returns 401 for missing scopes", %{conn: conn} do
627 app = insert(:oauth_app)
628 redirect_uri = OAuthController.default_redirect_uri(app)
632 |> post("/oauth/authorize", %{
633 "authorization" => %{
634 "name" => user.nickname,
635 "password" => "test",
636 "client_id" => app.client_id,
637 "redirect_uri" => redirect_uri,
638 "state" => "statepassed",
642 |> html_response(:unauthorized)
645 assert result =~ app.client_id
646 assert result =~ redirect_uri
649 assert result =~ "This action is outside the authorized scopes"
652 test "returns 401 for scopes beyond app scopes", %{conn: conn} do
654 app = insert(:oauth_app, scopes: ["read", "write"])
655 redirect_uri = OAuthController.default_redirect_uri(app)
659 |> post("/oauth/authorize", %{
660 "authorization" => %{
661 "name" => user.nickname,
662 "password" => "test",
663 "client_id" => app.client_id,
664 "redirect_uri" => redirect_uri,
665 "state" => "statepassed",
666 "scope" => "read write follow"
669 |> html_response(:unauthorized)
672 assert result =~ app.client_id
673 assert result =~ redirect_uri
676 assert result =~ "This action is outside the authorized scopes"
680 describe "POST /oauth/token" do
681 test "issues a token for an all-body request" do
683 app = insert(:oauth_app, scopes: ["read", "write"])
685 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
689 |> post("/oauth/token", %{
690 "grant_type" => "authorization_code",
691 "code" => auth.token,
692 "redirect_uri" => OAuthController.default_redirect_uri(app),
693 "client_id" => app.client_id,
694 "client_secret" => app.client_secret
697 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
699 token = Repo.get_by(Token, token: token)
701 assert token.scopes == auth.scopes
702 assert user.ap_id == ap_id
705 test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
706 password = "testpassword"
707 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
709 app = insert(:oauth_app, scopes: ["read", "write"])
711 # Note: "scope" param is intentionally omitted
714 |> post("/oauth/token", %{
715 "grant_type" => "password",
716 "username" => user.nickname,
717 "password" => password,
718 "client_id" => app.client_id,
719 "client_secret" => app.client_secret
722 assert %{"access_token" => token} = json_response(conn, 200)
724 token = Repo.get_by(Token, token: token)
726 assert token.scopes == app.scopes
729 test "issues a token for request with HTTP basic auth client credentials" do
731 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
733 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
734 assert auth.scopes == ["scope1", "scope2"]
737 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
742 |> put_req_header("authorization", "Basic " <> app_encoded)
743 |> post("/oauth/token", %{
744 "grant_type" => "authorization_code",
745 "code" => auth.token,
746 "redirect_uri" => OAuthController.default_redirect_uri(app)
749 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
751 assert scope == "scope1 scope2"
753 token = Repo.get_by(Token, token: token)
755 assert token.scopes == ["scope1", "scope2"]
758 test "issue a token for client_credentials grant type" do
759 app = insert(:oauth_app, scopes: ["read", "write"])
763 |> post("/oauth/token", %{
764 "grant_type" => "client_credentials",
765 "client_id" => app.client_id,
766 "client_secret" => app.client_secret
769 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
770 json_response(conn, 200)
773 token_from_db = Repo.get_by(Token, token: token)
776 assert scope == "read write"
779 test "rejects token exchange with invalid client credentials" do
781 app = insert(:oauth_app)
783 {:ok, auth} = Authorization.create_authorization(app, user)
787 |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
788 |> post("/oauth/token", %{
789 "grant_type" => "authorization_code",
790 "code" => auth.token,
791 "redirect_uri" => OAuthController.default_redirect_uri(app)
794 assert resp = json_response(conn, 400)
795 assert %{"error" => _} = resp
796 refute Map.has_key?(resp, "access_token")
799 test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
800 Pleroma.Config.put([:instance, :account_activation_required], true)
802 password = "testpassword"
803 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
804 info_change = Pleroma.User.Info.confirmation_changeset(user.info, need_confirmation: true)
808 |> Ecto.Changeset.change()
809 |> Ecto.Changeset.put_embed(:info, info_change)
812 refute Pleroma.User.auth_active?(user)
814 app = insert(:oauth_app)
818 |> post("/oauth/token", %{
819 "grant_type" => "password",
820 "username" => user.nickname,
821 "password" => password,
822 "client_id" => app.client_id,
823 "client_secret" => app.client_secret
826 assert resp = json_response(conn, 403)
827 assert %{"error" => _} = resp
828 refute Map.has_key?(resp, "access_token")
831 test "rejects token exchange for valid credentials belonging to deactivated user" do
832 password = "testpassword"
836 password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
837 info: %{deactivated: true}
840 app = insert(:oauth_app)
844 |> post("/oauth/token", %{
845 "grant_type" => "password",
846 "username" => user.nickname,
847 "password" => password,
848 "client_id" => app.client_id,
849 "client_secret" => app.client_secret
852 assert resp = json_response(conn, 403)
853 assert %{"error" => _} = resp
854 refute Map.has_key?(resp, "access_token")
857 test "rejects an invalid authorization code" do
858 app = insert(:oauth_app)
862 |> post("/oauth/token", %{
863 "grant_type" => "authorization_code",
864 "code" => "Imobviouslyinvalid",
865 "redirect_uri" => OAuthController.default_redirect_uri(app),
866 "client_id" => app.client_id,
867 "client_secret" => app.client_secret
870 assert resp = json_response(conn, 400)
871 assert %{"error" => _} = json_response(conn, 400)
872 refute Map.has_key?(resp, "access_token")
876 describe "POST /oauth/token - refresh token" do
877 clear_config([:oauth2, :issue_new_refresh_token])
879 test "issues a new access token with keep fresh token" do
880 Pleroma.Config.put([:oauth2, :issue_new_refresh_token], true)
882 app = insert(:oauth_app, scopes: ["read", "write"])
884 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
885 {:ok, token} = Token.exchange_token(app, auth)
889 |> post("/oauth/token", %{
890 "grant_type" => "refresh_token",
891 "refresh_token" => token.refresh_token,
892 "client_id" => app.client_id,
893 "client_secret" => app.client_secret
895 |> json_response(200)
902 "token_type" => "Bearer",
905 "refresh_token" => _,
911 refute Repo.get_by(Token, token: token.token)
912 new_token = Repo.get_by(Token, token: response["access_token"])
913 assert new_token.refresh_token == token.refresh_token
914 assert new_token.scopes == auth.scopes
915 assert new_token.user_id == user.id
916 assert new_token.app_id == app.id
919 test "issues a new access token with new fresh token" do
920 Pleroma.Config.put([:oauth2, :issue_new_refresh_token], false)
922 app = insert(:oauth_app, scopes: ["read", "write"])
924 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
925 {:ok, token} = Token.exchange_token(app, auth)
929 |> post("/oauth/token", %{
930 "grant_type" => "refresh_token",
931 "refresh_token" => token.refresh_token,
932 "client_id" => app.client_id,
933 "client_secret" => app.client_secret
935 |> json_response(200)
942 "token_type" => "Bearer",
945 "refresh_token" => _,
951 refute Repo.get_by(Token, token: token.token)
952 new_token = Repo.get_by(Token, token: response["access_token"])
953 refute new_token.refresh_token == token.refresh_token
954 assert new_token.scopes == auth.scopes
955 assert new_token.user_id == user.id
956 assert new_token.app_id == app.id
959 test "returns 400 if we try use access token" do
961 app = insert(:oauth_app, scopes: ["read", "write"])
963 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
964 {:ok, token} = Token.exchange_token(app, auth)
968 |> post("/oauth/token", %{
969 "grant_type" => "refresh_token",
970 "refresh_token" => token.token,
971 "client_id" => app.client_id,
972 "client_secret" => app.client_secret
974 |> json_response(400)
976 assert %{"error" => "Invalid credentials"} == response
979 test "returns 400 if refresh_token invalid" do
980 app = insert(:oauth_app, scopes: ["read", "write"])
984 |> post("/oauth/token", %{
985 "grant_type" => "refresh_token",
986 "refresh_token" => "token.refresh_token",
987 "client_id" => app.client_id,
988 "client_secret" => app.client_secret
990 |> json_response(400)
992 assert %{"error" => "Invalid credentials"} == response
995 test "issues a new token if token expired" do
997 app = insert(:oauth_app, scopes: ["read", "write"])
999 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1000 {:ok, token} = Token.exchange_token(app, auth)
1003 Ecto.Changeset.change(
1005 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1008 {:ok, access_token} = Repo.update(change)
1012 |> post("/oauth/token", %{
1013 "grant_type" => "refresh_token",
1014 "refresh_token" => access_token.refresh_token,
1015 "client_id" => app.client_id,
1016 "client_secret" => app.client_secret
1018 |> json_response(200)
1025 "token_type" => "Bearer",
1026 "expires_in" => 600,
1027 "access_token" => _,
1028 "refresh_token" => _,
1034 refute Repo.get_by(Token, token: token.token)
1035 token = Repo.get_by(Token, token: response["access_token"])
1037 assert token.scopes == auth.scopes
1038 assert token.user_id == user.id
1039 assert token.app_id == app.id
1043 describe "POST /oauth/token - bad request" do
1044 test "returns 500" do
1047 |> post("/oauth/token", %{})
1048 |> json_response(500)
1050 assert %{"error" => "Bad request"} == response
1054 describe "POST /oauth/revoke - bad request" do
1055 test "returns 500" do
1058 |> post("/oauth/revoke", %{})
1059 |> json_response(500)
1061 assert %{"error" => "Bad request"} == response