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