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