Merge branch 'config/benchmark' into 'develop'
[akkoma] / test / web / oauth / oauth_controller_test.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.OAuth.OAuthControllerTest do
6 use Pleroma.Web.ConnCase
7 import Pleroma.Factory
8
9 alias Pleroma.Repo
10 alias Pleroma.User
11 alias Pleroma.Web.OAuth.Authorization
12 alias Pleroma.Web.OAuth.OAuthController
13 alias Pleroma.Web.OAuth.Token
14
15 @session_opts [
16 store: :cookie,
17 key: "_test",
18 signing_salt: "cooldude"
19 ]
20 clear_config_all([:instance, :account_activation_required])
21
22 describe "in OAuth consumer mode, " do
23 setup do
24 [
25 app: insert(:oauth_app),
26 conn:
27 build_conn()
28 |> Plug.Session.call(Plug.Session.init(@session_opts))
29 |> fetch_session()
30 ]
31 end
32
33 clear_config([:auth, :oauth_consumer_strategies]) do
34 Pleroma.Config.put(
35 [:auth, :oauth_consumer_strategies],
36 ~w(twitter facebook)
37 )
38 end
39
40 test "GET /oauth/authorize renders auth forms, including OAuth consumer form", %{
41 app: app,
42 conn: conn
43 } do
44 conn =
45 get(
46 conn,
47 "/oauth/authorize",
48 %{
49 "response_type" => "code",
50 "client_id" => app.client_id,
51 "redirect_uri" => OAuthController.default_redirect_uri(app),
52 "scope" => "read"
53 }
54 )
55
56 assert response = html_response(conn, 200)
57 assert response =~ "Sign in with Twitter"
58 assert response =~ o_auth_path(conn, :prepare_request)
59 end
60
61 test "GET /oauth/prepare_request encodes parameters as `state` and redirects", %{
62 app: app,
63 conn: conn
64 } do
65 conn =
66 get(
67 conn,
68 "/oauth/prepare_request",
69 %{
70 "provider" => "twitter",
71 "authorization" => %{
72 "scope" => "read follow",
73 "client_id" => app.client_id,
74 "redirect_uri" => OAuthController.default_redirect_uri(app),
75 "state" => "a_state"
76 }
77 }
78 )
79
80 assert response = html_response(conn, 302)
81
82 redirect_query = URI.parse(redirected_to(conn)).query
83 assert %{"state" => state_param} = URI.decode_query(redirect_query)
84 assert {:ok, state_components} = Poison.decode(state_param)
85
86 expected_client_id = app.client_id
87 expected_redirect_uri = app.redirect_uris
88
89 assert %{
90 "scope" => "read follow",
91 "client_id" => ^expected_client_id,
92 "redirect_uri" => ^expected_redirect_uri,
93 "state" => "a_state"
94 } = state_components
95 end
96
97 test "with user-bound registration, GET /oauth/<provider>/callback redirects to `redirect_uri` with `code`",
98 %{app: app, conn: conn} do
99 registration = insert(:registration)
100 redirect_uri = OAuthController.default_redirect_uri(app)
101
102 state_params = %{
103 "scope" => Enum.join(app.scopes, " "),
104 "client_id" => app.client_id,
105 "redirect_uri" => redirect_uri,
106 "state" => ""
107 }
108
109 conn =
110 conn
111 |> assign(:ueberauth_auth, %{provider: registration.provider, uid: registration.uid})
112 |> get(
113 "/oauth/twitter/callback",
114 %{
115 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
116 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
117 "provider" => "twitter",
118 "state" => Poison.encode!(state_params)
119 }
120 )
121
122 assert response = html_response(conn, 302)
123 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
124 end
125
126 test "with user-unbound registration, GET /oauth/<provider>/callback renders registration_details page",
127 %{app: app, conn: conn} do
128 user = insert(:user)
129
130 state_params = %{
131 "scope" => "read write",
132 "client_id" => app.client_id,
133 "redirect_uri" => OAuthController.default_redirect_uri(app),
134 "state" => "a_state"
135 }
136
137 conn =
138 conn
139 |> assign(:ueberauth_auth, %{
140 provider: "twitter",
141 uid: "171799000",
142 info: %{nickname: user.nickname, email: user.email, name: user.name, description: nil}
143 })
144 |> get(
145 "/oauth/twitter/callback",
146 %{
147 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
148 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
149 "provider" => "twitter",
150 "state" => Poison.encode!(state_params)
151 }
152 )
153
154 assert response = html_response(conn, 200)
155 assert response =~ ~r/name="op" type="submit" value="register"/
156 assert response =~ ~r/name="op" type="submit" value="connect"/
157 assert response =~ user.email
158 assert response =~ user.nickname
159 end
160
161 test "on authentication error, GET /oauth/<provider>/callback redirects to `redirect_uri`", %{
162 app: app,
163 conn: conn
164 } do
165 state_params = %{
166 "scope" => Enum.join(app.scopes, " "),
167 "client_id" => app.client_id,
168 "redirect_uri" => OAuthController.default_redirect_uri(app),
169 "state" => ""
170 }
171
172 conn =
173 conn
174 |> assign(:ueberauth_failure, %{errors: [%{message: "(error description)"}]})
175 |> get(
176 "/oauth/twitter/callback",
177 %{
178 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
179 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
180 "provider" => "twitter",
181 "state" => Poison.encode!(state_params)
182 }
183 )
184
185 assert response = html_response(conn, 302)
186 assert redirected_to(conn) == app.redirect_uris
187 assert get_flash(conn, :error) == "Failed to authenticate: (error description)."
188 end
189
190 test "GET /oauth/registration_details renders registration details form", %{
191 app: app,
192 conn: conn
193 } do
194 conn =
195 get(
196 conn,
197 "/oauth/registration_details",
198 %{
199 "authorization" => %{
200 "scopes" => app.scopes,
201 "client_id" => app.client_id,
202 "redirect_uri" => OAuthController.default_redirect_uri(app),
203 "state" => "a_state",
204 "nickname" => nil,
205 "email" => "john@doe.com"
206 }
207 }
208 )
209
210 assert response = html_response(conn, 200)
211 assert response =~ ~r/name="op" type="submit" value="register"/
212 assert response =~ ~r/name="op" type="submit" value="connect"/
213 end
214
215 test "with valid params, POST /oauth/register?op=register redirects to `redirect_uri` with `code`",
216 %{
217 app: app,
218 conn: conn
219 } do
220 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
221 redirect_uri = OAuthController.default_redirect_uri(app)
222
223 conn =
224 conn
225 |> put_session(:registration_id, registration.id)
226 |> post(
227 "/oauth/register",
228 %{
229 "op" => "register",
230 "authorization" => %{
231 "scopes" => app.scopes,
232 "client_id" => app.client_id,
233 "redirect_uri" => redirect_uri,
234 "state" => "a_state",
235 "nickname" => "availablenick",
236 "email" => "available@email.com"
237 }
238 }
239 )
240
241 assert response = html_response(conn, 302)
242 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
243 end
244
245 test "with unlisted `redirect_uri`, POST /oauth/register?op=register results in HTTP 401",
246 %{
247 app: app,
248 conn: conn
249 } do
250 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
251 unlisted_redirect_uri = "http://cross-site-request.com"
252
253 conn =
254 conn
255 |> put_session(:registration_id, registration.id)
256 |> post(
257 "/oauth/register",
258 %{
259 "op" => "register",
260 "authorization" => %{
261 "scopes" => app.scopes,
262 "client_id" => app.client_id,
263 "redirect_uri" => unlisted_redirect_uri,
264 "state" => "a_state",
265 "nickname" => "availablenick",
266 "email" => "available@email.com"
267 }
268 }
269 )
270
271 assert response = html_response(conn, 401)
272 end
273
274 test "with invalid params, POST /oauth/register?op=register renders registration_details page",
275 %{
276 app: app,
277 conn: conn
278 } do
279 another_user = insert(:user)
280 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
281
282 params = %{
283 "op" => "register",
284 "authorization" => %{
285 "scopes" => app.scopes,
286 "client_id" => app.client_id,
287 "redirect_uri" => OAuthController.default_redirect_uri(app),
288 "state" => "a_state",
289 "nickname" => "availablenickname",
290 "email" => "available@email.com"
291 }
292 }
293
294 for {bad_param, bad_param_value} <-
295 [{"nickname", another_user.nickname}, {"email", another_user.email}] do
296 bad_registration_attrs = %{
297 "authorization" => Map.put(params["authorization"], bad_param, bad_param_value)
298 }
299
300 bad_params = Map.merge(params, bad_registration_attrs)
301
302 conn =
303 conn
304 |> put_session(:registration_id, registration.id)
305 |> post("/oauth/register", bad_params)
306
307 assert html_response(conn, 403) =~ ~r/name="op" type="submit" value="register"/
308 assert get_flash(conn, :error) == "Error: #{bad_param} has already been taken."
309 end
310 end
311
312 test "with valid params, POST /oauth/register?op=connect redirects to `redirect_uri` with `code`",
313 %{
314 app: app,
315 conn: conn
316 } do
317 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("testpassword"))
318 registration = insert(:registration, user: nil)
319 redirect_uri = OAuthController.default_redirect_uri(app)
320
321 conn =
322 conn
323 |> put_session(:registration_id, registration.id)
324 |> post(
325 "/oauth/register",
326 %{
327 "op" => "connect",
328 "authorization" => %{
329 "scopes" => app.scopes,
330 "client_id" => app.client_id,
331 "redirect_uri" => redirect_uri,
332 "state" => "a_state",
333 "name" => user.nickname,
334 "password" => "testpassword"
335 }
336 }
337 )
338
339 assert response = html_response(conn, 302)
340 assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
341 end
342
343 test "with unlisted `redirect_uri`, POST /oauth/register?op=connect results in HTTP 401`",
344 %{
345 app: app,
346 conn: conn
347 } do
348 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("testpassword"))
349 registration = insert(:registration, user: nil)
350 unlisted_redirect_uri = "http://cross-site-request.com"
351
352 conn =
353 conn
354 |> put_session(:registration_id, registration.id)
355 |> post(
356 "/oauth/register",
357 %{
358 "op" => "connect",
359 "authorization" => %{
360 "scopes" => app.scopes,
361 "client_id" => app.client_id,
362 "redirect_uri" => unlisted_redirect_uri,
363 "state" => "a_state",
364 "name" => user.nickname,
365 "password" => "testpassword"
366 }
367 }
368 )
369
370 assert response = html_response(conn, 401)
371 end
372
373 test "with invalid params, POST /oauth/register?op=connect renders registration_details page",
374 %{
375 app: app,
376 conn: conn
377 } do
378 user = insert(:user)
379 registration = insert(:registration, user: nil)
380
381 params = %{
382 "op" => "connect",
383 "authorization" => %{
384 "scopes" => app.scopes,
385 "client_id" => app.client_id,
386 "redirect_uri" => OAuthController.default_redirect_uri(app),
387 "state" => "a_state",
388 "name" => user.nickname,
389 "password" => "wrong password"
390 }
391 }
392
393 conn =
394 conn
395 |> put_session(:registration_id, registration.id)
396 |> post("/oauth/register", params)
397
398 assert html_response(conn, 401) =~ ~r/name="op" type="submit" value="connect"/
399 assert get_flash(conn, :error) == "Invalid Username/Password"
400 end
401 end
402
403 describe "GET /oauth/authorize" do
404 setup do
405 [
406 app: insert(:oauth_app, redirect_uris: "https://redirect.url"),
407 conn:
408 build_conn()
409 |> Plug.Session.call(Plug.Session.init(@session_opts))
410 |> fetch_session()
411 ]
412 end
413
414 test "renders authentication page", %{app: app, conn: conn} do
415 conn =
416 get(
417 conn,
418 "/oauth/authorize",
419 %{
420 "response_type" => "code",
421 "client_id" => app.client_id,
422 "redirect_uri" => OAuthController.default_redirect_uri(app),
423 "scope" => "read"
424 }
425 )
426
427 assert html_response(conn, 200) =~ ~s(type="submit")
428 end
429
430 test "properly handles internal calls with `authorization`-wrapped params", %{
431 app: app,
432 conn: conn
433 } do
434 conn =
435 get(
436 conn,
437 "/oauth/authorize",
438 %{
439 "authorization" => %{
440 "response_type" => "code",
441 "client_id" => app.client_id,
442 "redirect_uri" => OAuthController.default_redirect_uri(app),
443 "scope" => "read"
444 }
445 }
446 )
447
448 assert html_response(conn, 200) =~ ~s(type="submit")
449 end
450
451 test "renders authentication page if user is already authenticated but `force_login` is tru-ish",
452 %{app: app, conn: conn} do
453 token = insert(:oauth_token, app: app)
454
455 conn =
456 conn
457 |> put_session(:oauth_token, token.token)
458 |> get(
459 "/oauth/authorize",
460 %{
461 "response_type" => "code",
462 "client_id" => app.client_id,
463 "redirect_uri" => OAuthController.default_redirect_uri(app),
464 "scope" => "read",
465 "force_login" => "true"
466 }
467 )
468
469 assert html_response(conn, 200) =~ ~s(type="submit")
470 end
471
472 test "renders authentication page if user is already authenticated but user request with another client",
473 %{
474 app: app,
475 conn: conn
476 } do
477 token = insert(:oauth_token, app: app)
478
479 conn =
480 conn
481 |> put_session(:oauth_token, token.token)
482 |> get(
483 "/oauth/authorize",
484 %{
485 "response_type" => "code",
486 "client_id" => "another_client_id",
487 "redirect_uri" => OAuthController.default_redirect_uri(app),
488 "scope" => "read"
489 }
490 )
491
492 assert html_response(conn, 200) =~ ~s(type="submit")
493 end
494
495 test "with existing authentication and non-OOB `redirect_uri`, redirects to app with `token` and `state` params",
496 %{
497 app: app,
498 conn: conn
499 } do
500 token = insert(:oauth_token, app: app)
501
502 conn =
503 conn
504 |> put_session(:oauth_token, token.token)
505 |> get(
506 "/oauth/authorize",
507 %{
508 "response_type" => "code",
509 "client_id" => app.client_id,
510 "redirect_uri" => OAuthController.default_redirect_uri(app),
511 "state" => "specific_client_state",
512 "scope" => "read"
513 }
514 )
515
516 assert URI.decode(redirected_to(conn)) ==
517 "https://redirect.url?access_token=#{token.token}&state=specific_client_state"
518 end
519
520 test "with existing authentication and unlisted non-OOB `redirect_uri`, redirects without credentials",
521 %{
522 app: app,
523 conn: conn
524 } do
525 unlisted_redirect_uri = "http://cross-site-request.com"
526 token = insert(:oauth_token, app: app)
527
528 conn =
529 conn
530 |> put_session(:oauth_token, token.token)
531 |> get(
532 "/oauth/authorize",
533 %{
534 "response_type" => "code",
535 "client_id" => app.client_id,
536 "redirect_uri" => unlisted_redirect_uri,
537 "state" => "specific_client_state",
538 "scope" => "read"
539 }
540 )
541
542 assert redirected_to(conn) == unlisted_redirect_uri
543 end
544
545 test "with existing authentication and OOB `redirect_uri`, redirects to app with `token` and `state` params",
546 %{
547 app: app,
548 conn: conn
549 } do
550 token = insert(:oauth_token, app: app)
551
552 conn =
553 conn
554 |> put_session(:oauth_token, token.token)
555 |> get(
556 "/oauth/authorize",
557 %{
558 "response_type" => "code",
559 "client_id" => app.client_id,
560 "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
561 "scope" => "read"
562 }
563 )
564
565 assert html_response(conn, 200) =~ "Authorization exists"
566 end
567 end
568
569 describe "POST /oauth/authorize" do
570 test "redirects with oauth authorization, " <>
571 "keeping only non-admin scopes for non-admin user" do
572 app = insert(:oauth_app, scopes: ["read", "write", "admin"])
573 redirect_uri = OAuthController.default_redirect_uri(app)
574
575 non_admin = insert(:user, is_admin: false)
576 admin = insert(:user, is_admin: true)
577
578 for {user, expected_scopes} <- %{
579 non_admin => ["read:subscope", "write"],
580 admin => ["read:subscope", "write", "admin"]
581 } do
582 conn =
583 build_conn()
584 |> post("/oauth/authorize", %{
585 "authorization" => %{
586 "name" => user.nickname,
587 "password" => "test",
588 "client_id" => app.client_id,
589 "redirect_uri" => redirect_uri,
590 "scope" => "read:subscope write admin",
591 "state" => "statepassed"
592 }
593 })
594
595 target = redirected_to(conn)
596 assert target =~ redirect_uri
597
598 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
599
600 assert %{"state" => "statepassed", "code" => code} = query
601 auth = Repo.get_by(Authorization, token: code)
602 assert auth
603 assert auth.scopes == expected_scopes
604 end
605 end
606
607 test "returns 401 for wrong credentials", %{conn: conn} do
608 user = insert(:user)
609 app = insert(:oauth_app)
610 redirect_uri = OAuthController.default_redirect_uri(app)
611
612 result =
613 conn
614 |> post("/oauth/authorize", %{
615 "authorization" => %{
616 "name" => user.nickname,
617 "password" => "wrong",
618 "client_id" => app.client_id,
619 "redirect_uri" => redirect_uri,
620 "state" => "statepassed",
621 "scope" => Enum.join(app.scopes, " ")
622 }
623 })
624 |> html_response(:unauthorized)
625
626 # Keep the details
627 assert result =~ app.client_id
628 assert result =~ redirect_uri
629
630 # Error message
631 assert result =~ "Invalid Username/Password"
632 end
633
634 test "returns 401 for missing scopes " <>
635 "(including all admin-only scopes for non-admin user)" do
636 user = insert(:user, is_admin: false)
637 app = insert(:oauth_app, scopes: ["read", "write", "admin"])
638 redirect_uri = OAuthController.default_redirect_uri(app)
639
640 for scope_param <- ["", "admin:read admin:write"] do
641 result =
642 build_conn()
643 |> post("/oauth/authorize", %{
644 "authorization" => %{
645 "name" => user.nickname,
646 "password" => "test",
647 "client_id" => app.client_id,
648 "redirect_uri" => redirect_uri,
649 "state" => "statepassed",
650 "scope" => scope_param
651 }
652 })
653 |> html_response(:unauthorized)
654
655 # Keep the details
656 assert result =~ app.client_id
657 assert result =~ redirect_uri
658
659 # Error message
660 assert result =~ "This action is outside the authorized scopes"
661 end
662 end
663
664 test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
665 user = insert(:user)
666 app = insert(:oauth_app, scopes: ["read", "write"])
667 redirect_uri = OAuthController.default_redirect_uri(app)
668
669 result =
670 conn
671 |> post("/oauth/authorize", %{
672 "authorization" => %{
673 "name" => user.nickname,
674 "password" => "test",
675 "client_id" => app.client_id,
676 "redirect_uri" => redirect_uri,
677 "state" => "statepassed",
678 "scope" => "read write follow"
679 }
680 })
681 |> html_response(:unauthorized)
682
683 # Keep the details
684 assert result =~ app.client_id
685 assert result =~ redirect_uri
686
687 # Error message
688 assert result =~ "This action is outside the authorized scopes"
689 end
690 end
691
692 describe "POST /oauth/token" do
693 test "issues a token for an all-body request" do
694 user = insert(:user)
695 app = insert(:oauth_app, scopes: ["read", "write"])
696
697 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
698
699 conn =
700 build_conn()
701 |> post("/oauth/token", %{
702 "grant_type" => "authorization_code",
703 "code" => auth.token,
704 "redirect_uri" => OAuthController.default_redirect_uri(app),
705 "client_id" => app.client_id,
706 "client_secret" => app.client_secret
707 })
708
709 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
710
711 token = Repo.get_by(Token, token: token)
712 assert token
713 assert token.scopes == auth.scopes
714 assert user.ap_id == ap_id
715 end
716
717 test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
718 password = "testpassword"
719 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
720
721 app = insert(:oauth_app, scopes: ["read", "write"])
722
723 # Note: "scope" param is intentionally omitted
724 conn =
725 build_conn()
726 |> post("/oauth/token", %{
727 "grant_type" => "password",
728 "username" => user.nickname,
729 "password" => password,
730 "client_id" => app.client_id,
731 "client_secret" => app.client_secret
732 })
733
734 assert %{"access_token" => token} = json_response(conn, 200)
735
736 token = Repo.get_by(Token, token: token)
737 assert token
738 assert token.scopes == app.scopes
739 end
740
741 test "issues a token for request with HTTP basic auth client credentials" do
742 user = insert(:user)
743 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
744
745 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
746 assert auth.scopes == ["scope1", "scope2"]
747
748 app_encoded =
749 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
750 |> Base.encode64()
751
752 conn =
753 build_conn()
754 |> put_req_header("authorization", "Basic " <> app_encoded)
755 |> post("/oauth/token", %{
756 "grant_type" => "authorization_code",
757 "code" => auth.token,
758 "redirect_uri" => OAuthController.default_redirect_uri(app)
759 })
760
761 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
762
763 assert scope == "scope1 scope2"
764
765 token = Repo.get_by(Token, token: token)
766 assert token
767 assert token.scopes == ["scope1", "scope2"]
768 end
769
770 test "issue a token for client_credentials grant type" do
771 app = insert(:oauth_app, scopes: ["read", "write"])
772
773 conn =
774 build_conn()
775 |> post("/oauth/token", %{
776 "grant_type" => "client_credentials",
777 "client_id" => app.client_id,
778 "client_secret" => app.client_secret
779 })
780
781 assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
782 json_response(conn, 200)
783
784 assert token
785 token_from_db = Repo.get_by(Token, token: token)
786 assert token_from_db
787 assert refresh
788 assert scope == "read write"
789 end
790
791 test "rejects token exchange with invalid client credentials" do
792 user = insert(:user)
793 app = insert(:oauth_app)
794
795 {:ok, auth} = Authorization.create_authorization(app, user)
796
797 conn =
798 build_conn()
799 |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
800 |> post("/oauth/token", %{
801 "grant_type" => "authorization_code",
802 "code" => auth.token,
803 "redirect_uri" => OAuthController.default_redirect_uri(app)
804 })
805
806 assert resp = json_response(conn, 400)
807 assert %{"error" => _} = resp
808 refute Map.has_key?(resp, "access_token")
809 end
810
811 test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
812 Pleroma.Config.put([:instance, :account_activation_required], true)
813 password = "testpassword"
814
815 {:ok, user} =
816 insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
817 |> User.confirmation_changeset(need_confirmation: true)
818 |> User.update_and_set_cache()
819
820 refute Pleroma.User.auth_active?(user)
821
822 app = insert(:oauth_app)
823
824 conn =
825 build_conn()
826 |> post("/oauth/token", %{
827 "grant_type" => "password",
828 "username" => user.nickname,
829 "password" => password,
830 "client_id" => app.client_id,
831 "client_secret" => app.client_secret
832 })
833
834 assert resp = json_response(conn, 403)
835 assert %{"error" => _} = resp
836 refute Map.has_key?(resp, "access_token")
837 end
838
839 test "rejects token exchange for valid credentials belonging to deactivated user" do
840 password = "testpassword"
841
842 user =
843 insert(:user,
844 password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
845 deactivated: true
846 )
847
848 app = insert(:oauth_app)
849
850 conn =
851 build_conn()
852 |> post("/oauth/token", %{
853 "grant_type" => "password",
854 "username" => user.nickname,
855 "password" => password,
856 "client_id" => app.client_id,
857 "client_secret" => app.client_secret
858 })
859
860 assert resp = json_response(conn, 403)
861 assert %{"error" => _} = resp
862 refute Map.has_key?(resp, "access_token")
863 end
864
865 test "rejects token exchange for user with password_reset_pending set to true" do
866 password = "testpassword"
867
868 user =
869 insert(:user,
870 password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
871 password_reset_pending: true
872 )
873
874 app = insert(:oauth_app, scopes: ["read", "write"])
875
876 conn =
877 build_conn()
878 |> post("/oauth/token", %{
879 "grant_type" => "password",
880 "username" => user.nickname,
881 "password" => password,
882 "client_id" => app.client_id,
883 "client_secret" => app.client_secret
884 })
885
886 assert resp = json_response(conn, 403)
887
888 assert resp["error"] == "Password reset is required"
889 assert resp["identifier"] == "password_reset_required"
890 refute Map.has_key?(resp, "access_token")
891 end
892
893 test "rejects an invalid authorization code" do
894 app = insert(:oauth_app)
895
896 conn =
897 build_conn()
898 |> post("/oauth/token", %{
899 "grant_type" => "authorization_code",
900 "code" => "Imobviouslyinvalid",
901 "redirect_uri" => OAuthController.default_redirect_uri(app),
902 "client_id" => app.client_id,
903 "client_secret" => app.client_secret
904 })
905
906 assert resp = json_response(conn, 400)
907 assert %{"error" => _} = json_response(conn, 400)
908 refute Map.has_key?(resp, "access_token")
909 end
910 end
911
912 describe "POST /oauth/token - refresh token" do
913 clear_config([:oauth2, :issue_new_refresh_token])
914
915 test "issues a new access token with keep fresh token" do
916 Pleroma.Config.put([:oauth2, :issue_new_refresh_token], true)
917 user = insert(:user)
918 app = insert(:oauth_app, scopes: ["read", "write"])
919
920 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
921 {:ok, token} = Token.exchange_token(app, auth)
922
923 response =
924 build_conn()
925 |> post("/oauth/token", %{
926 "grant_type" => "refresh_token",
927 "refresh_token" => token.refresh_token,
928 "client_id" => app.client_id,
929 "client_secret" => app.client_secret
930 })
931 |> json_response(200)
932
933 ap_id = user.ap_id
934
935 assert match?(
936 %{
937 "scope" => "write",
938 "token_type" => "Bearer",
939 "expires_in" => 600,
940 "access_token" => _,
941 "refresh_token" => _,
942 "me" => ^ap_id
943 },
944 response
945 )
946
947 refute Repo.get_by(Token, token: token.token)
948 new_token = Repo.get_by(Token, token: response["access_token"])
949 assert new_token.refresh_token == token.refresh_token
950 assert new_token.scopes == auth.scopes
951 assert new_token.user_id == user.id
952 assert new_token.app_id == app.id
953 end
954
955 test "issues a new access token with new fresh token" do
956 Pleroma.Config.put([:oauth2, :issue_new_refresh_token], false)
957 user = insert(:user)
958 app = insert(:oauth_app, scopes: ["read", "write"])
959
960 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
961 {:ok, token} = Token.exchange_token(app, auth)
962
963 response =
964 build_conn()
965 |> post("/oauth/token", %{
966 "grant_type" => "refresh_token",
967 "refresh_token" => token.refresh_token,
968 "client_id" => app.client_id,
969 "client_secret" => app.client_secret
970 })
971 |> json_response(200)
972
973 ap_id = user.ap_id
974
975 assert match?(
976 %{
977 "scope" => "write",
978 "token_type" => "Bearer",
979 "expires_in" => 600,
980 "access_token" => _,
981 "refresh_token" => _,
982 "me" => ^ap_id
983 },
984 response
985 )
986
987 refute Repo.get_by(Token, token: token.token)
988 new_token = Repo.get_by(Token, token: response["access_token"])
989 refute new_token.refresh_token == token.refresh_token
990 assert new_token.scopes == auth.scopes
991 assert new_token.user_id == user.id
992 assert new_token.app_id == app.id
993 end
994
995 test "returns 400 if we try use access token" do
996 user = insert(:user)
997 app = insert(:oauth_app, scopes: ["read", "write"])
998
999 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1000 {:ok, token} = Token.exchange_token(app, auth)
1001
1002 response =
1003 build_conn()
1004 |> post("/oauth/token", %{
1005 "grant_type" => "refresh_token",
1006 "refresh_token" => token.token,
1007 "client_id" => app.client_id,
1008 "client_secret" => app.client_secret
1009 })
1010 |> json_response(400)
1011
1012 assert %{"error" => "Invalid credentials"} == response
1013 end
1014
1015 test "returns 400 if refresh_token invalid" do
1016 app = insert(:oauth_app, scopes: ["read", "write"])
1017
1018 response =
1019 build_conn()
1020 |> post("/oauth/token", %{
1021 "grant_type" => "refresh_token",
1022 "refresh_token" => "token.refresh_token",
1023 "client_id" => app.client_id,
1024 "client_secret" => app.client_secret
1025 })
1026 |> json_response(400)
1027
1028 assert %{"error" => "Invalid credentials"} == response
1029 end
1030
1031 test "issues a new token if token expired" do
1032 user = insert(:user)
1033 app = insert(:oauth_app, scopes: ["read", "write"])
1034
1035 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
1036 {:ok, token} = Token.exchange_token(app, auth)
1037
1038 change =
1039 Ecto.Changeset.change(
1040 token,
1041 %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
1042 )
1043
1044 {:ok, access_token} = Repo.update(change)
1045
1046 response =
1047 build_conn()
1048 |> post("/oauth/token", %{
1049 "grant_type" => "refresh_token",
1050 "refresh_token" => access_token.refresh_token,
1051 "client_id" => app.client_id,
1052 "client_secret" => app.client_secret
1053 })
1054 |> json_response(200)
1055
1056 ap_id = user.ap_id
1057
1058 assert match?(
1059 %{
1060 "scope" => "write",
1061 "token_type" => "Bearer",
1062 "expires_in" => 600,
1063 "access_token" => _,
1064 "refresh_token" => _,
1065 "me" => ^ap_id
1066 },
1067 response
1068 )
1069
1070 refute Repo.get_by(Token, token: token.token)
1071 token = Repo.get_by(Token, token: response["access_token"])
1072 assert token
1073 assert token.scopes == auth.scopes
1074 assert token.user_id == user.id
1075 assert token.app_id == app.id
1076 end
1077 end
1078
1079 describe "POST /oauth/token - bad request" do
1080 test "returns 500" do
1081 response =
1082 build_conn()
1083 |> post("/oauth/token", %{})
1084 |> json_response(500)
1085
1086 assert %{"error" => "Bad request"} == response
1087 end
1088 end
1089
1090 describe "POST /oauth/revoke - bad request" do
1091 test "returns 500" do
1092 response =
1093 build_conn()
1094 |> post("/oauth/revoke", %{})
1095 |> json_response(500)
1096
1097 assert %{"error" => "Bad request"} == response
1098 end
1099 end
1100 end