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