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 "renders authentication page if user is already authenticated but user request with another client",
478 token = insert(:oauth_token, app: app)
482 |> put_req_header("authorization", "Bearer #{token.token}")
486 "response_type" => "code",
487 "client_id" => "another_client_id",
488 "redirect_uri" => OAuthController.default_redirect_uri(app),
493 assert html_response(conn, 200) =~ ~s(type="submit")
496 test "with existing authentication and non-OOB `redirect_uri`, redirects to app with `token` and `state` params",
501 token = insert(:oauth_token, app: app)
505 |> put_req_header("authorization", "Bearer #{token.token}")
509 "response_type" => "code",
510 "client_id" => app.client_id,
511 "redirect_uri" => OAuthController.default_redirect_uri(app),
512 "state" => "specific_client_state",
517 assert URI.decode(redirected_to(conn)) ==
518 "https://redirect.url?access_token=#{token.token}&state=specific_client_state"
521 test "with existing authentication and unlisted non-OOB `redirect_uri`, redirects without credentials",
526 unlisted_redirect_uri = "http://cross-site-request.com"
527 token = insert(:oauth_token, app: app)
531 |> put_req_header("authorization", "Bearer #{token.token}")
535 "response_type" => "code",
536 "client_id" => app.client_id,
537 "redirect_uri" => unlisted_redirect_uri,
538 "state" => "specific_client_state",
543 assert redirected_to(conn) == unlisted_redirect_uri
546 test "with existing authentication and OOB `redirect_uri`, redirects to app with `token` and `state` params",
551 token = insert(:oauth_token, app: app)
555 |> put_req_header("authorization", "Bearer #{token.token}")
559 "response_type" => "code",
560 "client_id" => app.client_id,
561 "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
566 assert html_response(conn, 200) =~ "Authorization exists"
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)
577 non_admin = insert(:user, is_admin: false)
578 admin = insert(:user, is_admin: true)
579 scopes_subset = ["read:subscope", "write", "admin"]
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
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"
601 target = redirected_to(conn)
602 assert target =~ redirect_uri
604 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
606 assert %{"state" => "statepassed", "code" => code} = query
607 auth = Repo.get_by(Authorization, token: code)
609 assert auth.scopes == expected_scopes
613 test "redirect to on two-factor auth page" do
614 otp_secret = TOTP.generate_secret()
618 multi_factor_authentication_settings: %MFA.Settings{
620 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
624 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
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"
639 result = html_response(conn, 200)
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"
648 test "returns 401 for wrong credentials", %{conn: conn} do
650 app = insert(:oauth_app)
651 redirect_uri = OAuthController.default_redirect_uri(app)
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, " ")
665 |> html_response(:unauthorized)
668 assert result =~ app.client_id
669 assert result =~ redirect_uri
672 assert result =~ "Invalid Username/Password"
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)
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",
692 |> html_response(:unauthorized)
695 assert result =~ app.client_id
696 assert result =~ redirect_uri
699 assert result =~ "This action is outside the authorized scopes"
702 test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
704 app = insert(:oauth_app, scopes: ["read", "write"])
705 redirect_uri = OAuthController.default_redirect_uri(app)
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"
719 |> html_response(:unauthorized)
722 assert result =~ app.client_id
723 assert result =~ redirect_uri
726 assert result =~ "This action is outside the authorized scopes"
730 describe "POST /oauth/token" do
731 test "issues a token for an all-body request" do
733 app = insert(:oauth_app, scopes: ["read", "write"])
735 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
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
747 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
749 token = Repo.get_by(Token, token: token)
751 assert token.scopes == auth.scopes
752 assert user.ap_id == ap_id
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))
759 app = insert(:oauth_app, scopes: ["read", "write"])
761 # Note: "scope" param is intentionally omitted
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
772 assert %{"id" => id, "access_token" => access_token} = json_response(conn, 200)
774 token = Repo.get_by(Token, token: access_token)
776 assert token.id == id
777 assert token.token == access_token
778 assert token.scopes == app.scopes
781 test "issues a mfa token for `password` grant_type, when MFA enabled" do
782 password = "testpassword"
783 otp_secret = TOTP.generate_secret()
787 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
788 multi_factor_authentication_settings: %MFA.Settings{
790 totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
794 app = insert(:oauth_app, scopes: ["read", "write"])
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
805 |> json_response(403)
809 "supported_challenge_types" => "totp",
811 "error" => "mfa_required"
816 token = Repo.get_by(MFA.Token, token: response["mfa_token"])
817 assert token.user_id == user.id
818 assert token.authorization_id
821 test "issues a token for request with HTTP basic auth client credentials" do
823 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
825 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
826 assert auth.scopes == ["scope1", "scope2"]
829 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
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)
841 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
843 assert scope == "scope1 scope2"
845 token = Repo.get_by(Token, token: token)
847 assert token.scopes == ["scope1", "scope2"]
850 test "issue a token for client_credentials grant type" do
851 app = insert(:oauth_app, scopes: ["read", "write"])
855 |> post("/oauth/token", %{
856 "grant_type" => "client_credentials",
857 "client_id" => app.client_id,
858 "client_secret" => app.client_secret
861 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
862 json_response(conn, 200)
865 token_from_db = Repo.get_by(Token, token: token)
868 assert scope == "read write"
871 test "rejects token exchange with invalid client credentials" do
873 app = insert(:oauth_app)
875 {:ok, auth} = Authorization.create_authorization(app, user)
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)
886 assert resp = json_response(conn, 400)
887 assert %{"error" => _} = resp
888 refute Map.has_key?(resp, "access_token")
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"
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()
900 refute Pleroma.User.account_status(user) == :active
902 app = insert(:oauth_app)
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
914 assert resp = json_response(conn, 403)
915 assert %{"error" => _} = resp
916 refute Map.has_key?(resp, "access_token")
919 test "rejects token exchange for valid credentials belonging to deactivated user" do
920 password = "testpassword"
924 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
928 app = insert(:oauth_app)
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
939 |> json_response(403)
942 "error" => "Your account is currently disabled",
943 "identifier" => "account_is_disabled"
947 test "rejects token exchange for user with password_reset_pending set to true" do
948 password = "testpassword"
952 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
953 password_reset_pending: true
956 app = insert(:oauth_app, scopes: ["read", "write"])
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
967 |> json_response(403)
970 "error" => "Password reset is required",
971 "identifier" => "password_reset_required"
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"
981 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
985 app = insert(:oauth_app, scopes: ["read", "write"])
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
996 |> json_response(403)
999 "error" => "Your login is missing a confirmed e-mail address",
1000 "identifier" => "missing_confirmed_email"
1004 test "rejects token exchange for valid credentials belonging to an unapproved user" do
1005 password = "testpassword"
1009 password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
1013 refute Pleroma.User.account_status(user) == :active
1015 app = insert(:oauth_app)
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
1027 assert resp = json_response(conn, 403)
1028 assert %{"error" => _} = resp
1029 refute Map.has_key?(resp, "access_token")
1032 test "rejects an invalid authorization code" do
1033 app = insert(:oauth_app)
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
1045 assert resp = json_response(conn, 400)
1046 assert %{"error" => _} = json_response(conn, 400)
1047 refute Map.has_key?(resp, "access_token")
1051 describe "POST /oauth/token - refresh token" do
1052 setup do: clear_config([:oauth2, :issue_new_refresh_token])
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"])
1059 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1060 {:ok, token} = Token.exchange_token(app, auth)
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
1070 |> json_response(200)
1077 "token_type" => "Bearer",
1078 "access_token" => _,
1079 "refresh_token" => _,
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
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"])
1098 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1099 {:ok, token} = Token.exchange_token(app, auth)
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
1109 |> json_response(200)
1116 "token_type" => "Bearer",
1117 "access_token" => _,
1118 "refresh_token" => _,
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
1132 test "returns 400 if we try use access token" do
1133 user = insert(:user)
1134 app = insert(:oauth_app, scopes: ["read", "write"])
1136 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1137 {:ok, token} = Token.exchange_token(app, auth)
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
1147 |> json_response(400)
1149 assert %{"error" => "Invalid credentials"} == response
1152 test "returns 400 if refresh_token invalid" do
1153 app = insert(:oauth_app, scopes: ["read", "write"])
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
1163 |> json_response(400)
1165 assert %{"error" => "Invalid credentials"} == response
1168 test "issues a new token if token expired" do
1169 user = insert(:user)
1170 app = insert(:oauth_app, scopes: ["read", "write"])
1172 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1173 {:ok, token} = Token.exchange_token(app, auth)
1176 Ecto.Changeset.change(
1178 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1181 {:ok, access_token} = Repo.update(change)
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
1192 |> json_response(200)
1199 "token_type" => "Bearer",
1200 "access_token" => _,
1201 "refresh_token" => _,
1207 refute Repo.get_by(Token, token: token.token)
1208 token = Repo.get_by(Token, token: response["access_token"])
1210 assert token.scopes == auth.scopes
1211 assert token.user_id == user.id
1212 assert token.app_id == app.id
1216 describe "POST /oauth/token - bad request" do
1217 test "returns 500" do
1220 |> post("/oauth/token", %{})
1221 |> json_response(500)
1223 assert %{"error" => "Bad request"} == response
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)
1233 |> Plug.Session.call(Plug.Session.init(@session_opts))
1235 |> put_req_header("authorization", "Bearer #{oauth_token.token}")
1236 |> post("/oauth/revoke", %{"token" => oauth_token.token})
1238 assert json_response(conn, 200)
1240 assert Token.get_by_token(oauth_token.token) == {:error, :not_found}
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)
1251 |> Plug.Session.call(Plug.Session.init(@session_opts))
1253 |> put_req_header("authorization", "Bearer #{oauth_token.token}")
1254 |> post("/oauth/revoke", %{"token" => other_app_oauth_token.token})
1256 assert json_response(conn, 200)
1258 assert Token.get_by_token(other_app_oauth_token.token) == {:error, :not_found}
1261 test "returns 500 on bad request" do
1264 |> post("/oauth/revoke", %{})
1265 |> json_response(500)
1267 assert %{"error" => "Bad request"} == response