[#923] Merge remote-tracking branch 'remotes/upstream/develop' into twitter_oauth
[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.Token
14
15 @session_opts [
16 store: :cookie,
17 key: "_test",
18 signing_salt: "cooldude"
19 ]
20
21 describe "in OAuth consumer mode, " do
22 setup do
23 oauth_consumer_strategies_path = [:auth, :oauth_consumer_strategies]
24 oauth_consumer_strategies = Pleroma.Config.get(oauth_consumer_strategies_path)
25 Pleroma.Config.put(oauth_consumer_strategies_path, ~w(twitter facebook))
26
27 on_exit(fn ->
28 Pleroma.Config.put(oauth_consumer_strategies_path, oauth_consumer_strategies)
29 end)
30
31 [
32 app: insert(:oauth_app),
33 conn:
34 build_conn()
35 |> Plug.Session.call(Plug.Session.init(@session_opts))
36 |> fetch_session()
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" => app.redirect_uris,
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 "scope" => "read follow",
72 "client_id" => app.client_id,
73 "redirect_uri" => app.redirect_uris,
74 "state" => "a_state"
75 }
76 )
77
78 assert response = html_response(conn, 302)
79
80 redirect_query = URI.parse(redirected_to(conn)).query
81 assert %{"state" => state_param} = URI.decode_query(redirect_query)
82 assert {:ok, state_components} = Poison.decode(state_param)
83
84 expected_client_id = app.client_id
85 expected_redirect_uri = app.redirect_uris
86
87 assert %{
88 "scope" => "read follow",
89 "client_id" => ^expected_client_id,
90 "redirect_uri" => ^expected_redirect_uri,
91 "state" => "a_state"
92 } = state_components
93 end
94
95 test "with user-bound registration, GET /oauth/<provider>/callback redirects to `redirect_uri` with `code`",
96 %{app: app, conn: conn} do
97 registration = insert(:registration)
98
99 state_params = %{
100 "scope" => Enum.join(app.scopes, " "),
101 "client_id" => app.client_id,
102 "redirect_uri" => app.redirect_uris,
103 "state" => ""
104 }
105
106 with_mock Pleroma.Web.Auth.Authenticator,
107 get_registration: fn _, _ -> {:ok, registration} end do
108 conn =
109 get(
110 conn,
111 "/oauth/twitter/callback",
112 %{
113 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
114 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
115 "provider" => "twitter",
116 "state" => Poison.encode!(state_params)
117 }
118 )
119
120 assert response = html_response(conn, 302)
121 assert redirected_to(conn) =~ ~r/#{app.redirect_uris}\?code=.+/
122 end
123 end
124
125 test "with user-unbound registration, GET /oauth/<provider>/callback renders registration_details page",
126 %{app: app, conn: conn} do
127 registration = insert(:registration, user: nil)
128
129 state_params = %{
130 "scope" => "read write",
131 "client_id" => app.client_id,
132 "redirect_uri" => app.redirect_uris,
133 "state" => "a_state"
134 }
135
136 with_mock Pleroma.Web.Auth.Authenticator,
137 get_registration: fn _, _ -> {:ok, registration} end do
138 conn =
139 get(
140 conn,
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 =~ Registration.email(registration)
154 assert response =~ Registration.nickname(registration)
155 end
156 end
157
158 test "on authentication error, GET /oauth/<provider>/callback redirects to `redirect_uri`", %{
159 app: app,
160 conn: conn
161 } do
162 state_params = %{
163 "scope" => Enum.join(app.scopes, " "),
164 "client_id" => app.client_id,
165 "redirect_uri" => app.redirect_uris,
166 "state" => ""
167 }
168
169 conn =
170 conn
171 |> assign(:ueberauth_failure, %{errors: [%{message: "(error description)"}]})
172 |> get(
173 "/oauth/twitter/callback",
174 %{
175 "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
176 "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
177 "provider" => "twitter",
178 "state" => Poison.encode!(state_params)
179 }
180 )
181
182 assert response = html_response(conn, 302)
183 assert redirected_to(conn) == app.redirect_uris
184 assert get_flash(conn, :error) == "Failed to authenticate: (error description)."
185 end
186
187 test "GET /oauth/registration_details renders registration details form", %{
188 app: app,
189 conn: conn
190 } do
191 conn =
192 get(
193 conn,
194 "/oauth/registration_details",
195 %{
196 "scopes" => app.scopes,
197 "client_id" => app.client_id,
198 "redirect_uri" => app.redirect_uris,
199 "state" => "a_state",
200 "nickname" => nil,
201 "email" => "john@doe.com"
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
217 conn =
218 conn
219 |> put_session(:registration_id, registration.id)
220 |> post(
221 "/oauth/register",
222 %{
223 "op" => "register",
224 "scopes" => app.scopes,
225 "client_id" => app.client_id,
226 "redirect_uri" => app.redirect_uris,
227 "state" => "a_state",
228 "nickname" => "availablenick",
229 "email" => "available@email.com"
230 }
231 )
232
233 assert response = html_response(conn, 302)
234 assert redirected_to(conn) =~ ~r/#{app.redirect_uris}\?code=.+/
235 end
236
237 test "with invalid params, POST /oauth/register?op=register renders registration_details page",
238 %{
239 app: app,
240 conn: conn
241 } do
242 another_user = insert(:user)
243 registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
244
245 params = %{
246 "op" => "register",
247 "scopes" => app.scopes,
248 "client_id" => app.client_id,
249 "redirect_uri" => app.redirect_uris,
250 "state" => "a_state",
251 "nickname" => "availablenickname",
252 "email" => "available@email.com"
253 }
254
255 for {bad_param, bad_param_value} <-
256 [{"nickname", another_user.nickname}, {"email", another_user.email}] do
257 bad_params = Map.put(params, bad_param, bad_param_value)
258
259 conn =
260 conn
261 |> put_session(:registration_id, registration.id)
262 |> post("/oauth/register", bad_params)
263
264 assert html_response(conn, 403) =~ ~r/name="op" type="submit" value="register"/
265 assert get_flash(conn, :error) == "Error: #{bad_param} has already been taken."
266 end
267 end
268
269 test "with valid params, POST /oauth/register?op=connect redirects to `redirect_uri` with `code`",
270 %{
271 app: app,
272 conn: conn
273 } do
274 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt("testpassword"))
275 registration = insert(:registration, user: nil)
276
277 conn =
278 conn
279 |> put_session(:registration_id, registration.id)
280 |> post(
281 "/oauth/register",
282 %{
283 "op" => "connect",
284 "scopes" => app.scopes,
285 "client_id" => app.client_id,
286 "redirect_uri" => app.redirect_uris,
287 "state" => "a_state",
288 "auth_name" => user.nickname,
289 "password" => "testpassword"
290 }
291 )
292
293 assert response = html_response(conn, 302)
294 assert redirected_to(conn) =~ ~r/#{app.redirect_uris}\?code=.+/
295 end
296
297 test "with invalid params, POST /oauth/register?op=connect renders registration_details page",
298 %{
299 app: app,
300 conn: conn
301 } do
302 user = insert(:user)
303 registration = insert(:registration, user: nil)
304
305 params = %{
306 "op" => "connect",
307 "scopes" => app.scopes,
308 "client_id" => app.client_id,
309 "redirect_uri" => app.redirect_uris,
310 "state" => "a_state",
311 "auth_name" => user.nickname,
312 "password" => "wrong password"
313 }
314
315 conn =
316 conn
317 |> put_session(:registration_id, registration.id)
318 |> post("/oauth/register", params)
319
320 assert html_response(conn, 401) =~ ~r/name="op" type="submit" value="connect"/
321 assert get_flash(conn, :error) == "Invalid Username/Password"
322 end
323 end
324
325 describe "GET /oauth/authorize" do
326 setup do
327 [
328 app: insert(:oauth_app, redirect_uris: "https://redirect.url"),
329 conn:
330 build_conn()
331 |> Plug.Session.call(Plug.Session.init(@session_opts))
332 |> fetch_session()
333 ]
334 end
335
336 test "renders authentication page", %{app: app, conn: conn} do
337 conn =
338 get(
339 conn,
340 "/oauth/authorize",
341 %{
342 "response_type" => "code",
343 "client_id" => app.client_id,
344 "redirect_uri" => app.redirect_uris,
345 "scope" => "read"
346 }
347 )
348
349 assert html_response(conn, 200) =~ ~s(type="submit")
350 end
351
352 test "renders authentication page if user is already authenticated but `force_login` is tru-ish",
353 %{app: app, conn: conn} do
354 token = insert(:oauth_token, app_id: app.id)
355
356 conn =
357 conn
358 |> put_session(:oauth_token, token.token)
359 |> get(
360 "/oauth/authorize",
361 %{
362 "response_type" => "code",
363 "client_id" => app.client_id,
364 "redirect_uri" => app.redirect_uris,
365 "scope" => "read",
366 "force_login" => "true"
367 }
368 )
369
370 assert html_response(conn, 200) =~ ~s(type="submit")
371 end
372
373 test "redirects to app if user is already authenticated", %{app: app, conn: conn} do
374 token = insert(:oauth_token, app_id: app.id)
375
376 conn =
377 conn
378 |> put_session(:oauth_token, token.token)
379 |> get(
380 "/oauth/authorize",
381 %{
382 "response_type" => "code",
383 "client_id" => app.client_id,
384 "redirect_uri" => app.redirect_uris,
385 "scope" => "read"
386 }
387 )
388
389 assert redirected_to(conn) == "https://redirect.url"
390 end
391 end
392
393 describe "POST /oauth/authorize" do
394 test "redirects with oauth authorization" do
395 user = insert(:user)
396 app = insert(:oauth_app, scopes: ["read", "write", "follow"])
397
398 conn =
399 build_conn()
400 |> post("/oauth/authorize", %{
401 "authorization" => %{
402 "name" => user.nickname,
403 "password" => "test",
404 "client_id" => app.client_id,
405 "redirect_uri" => app.redirect_uris,
406 "scope" => "read write",
407 "state" => "statepassed"
408 }
409 })
410
411 target = redirected_to(conn)
412 assert target =~ app.redirect_uris
413
414 query = URI.parse(target).query |> URI.query_decoder() |> Map.new()
415
416 assert %{"state" => "statepassed", "code" => code} = query
417 auth = Repo.get_by(Authorization, token: code)
418 assert auth
419 assert auth.scopes == ["read", "write"]
420 end
421
422 test "returns 401 for wrong credentials", %{conn: conn} do
423 user = insert(:user)
424 app = insert(:oauth_app)
425
426 result =
427 conn
428 |> post("/oauth/authorize", %{
429 "authorization" => %{
430 "name" => user.nickname,
431 "password" => "wrong",
432 "client_id" => app.client_id,
433 "redirect_uri" => app.redirect_uris,
434 "state" => "statepassed",
435 "scope" => Enum.join(app.scopes, " ")
436 }
437 })
438 |> html_response(:unauthorized)
439
440 # Keep the details
441 assert result =~ app.client_id
442 assert result =~ app.redirect_uris
443
444 # Error message
445 assert result =~ "Invalid Username/Password"
446 end
447
448 test "returns 401 for missing scopes", %{conn: conn} do
449 user = insert(:user)
450 app = insert(:oauth_app)
451
452 result =
453 conn
454 |> post("/oauth/authorize", %{
455 "authorization" => %{
456 "name" => user.nickname,
457 "password" => "test",
458 "client_id" => app.client_id,
459 "redirect_uri" => app.redirect_uris,
460 "state" => "statepassed",
461 "scope" => ""
462 }
463 })
464 |> html_response(:unauthorized)
465
466 # Keep the details
467 assert result =~ app.client_id
468 assert result =~ app.redirect_uris
469
470 # Error message
471 assert result =~ "This action is outside the authorized scopes"
472 end
473
474 test "returns 401 for scopes beyond app scopes", %{conn: conn} do
475 user = insert(:user)
476 app = insert(:oauth_app, scopes: ["read", "write"])
477
478 result =
479 conn
480 |> post("/oauth/authorize", %{
481 "authorization" => %{
482 "name" => user.nickname,
483 "password" => "test",
484 "client_id" => app.client_id,
485 "redirect_uri" => app.redirect_uris,
486 "state" => "statepassed",
487 "scope" => "read write follow"
488 }
489 })
490 |> html_response(:unauthorized)
491
492 # Keep the details
493 assert result =~ app.client_id
494 assert result =~ app.redirect_uris
495
496 # Error message
497 assert result =~ "This action is outside the authorized scopes"
498 end
499 end
500
501 describe "POST /oauth/token" do
502 test "issues a token for an all-body request" do
503 user = insert(:user)
504 app = insert(:oauth_app, scopes: ["read", "write"])
505
506 {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
507
508 conn =
509 build_conn()
510 |> post("/oauth/token", %{
511 "grant_type" => "authorization_code",
512 "code" => auth.token,
513 "redirect_uri" => app.redirect_uris,
514 "client_id" => app.client_id,
515 "client_secret" => app.client_secret
516 })
517
518 assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)
519
520 token = Repo.get_by(Token, token: token)
521 assert token
522 assert token.scopes == auth.scopes
523 assert user.ap_id == ap_id
524 end
525
526 test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
527 password = "testpassword"
528 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
529
530 app = insert(:oauth_app, scopes: ["read", "write"])
531
532 # Note: "scope" param is intentionally omitted
533 conn =
534 build_conn()
535 |> post("/oauth/token", %{
536 "grant_type" => "password",
537 "username" => user.nickname,
538 "password" => password,
539 "client_id" => app.client_id,
540 "client_secret" => app.client_secret
541 })
542
543 assert %{"access_token" => token} = json_response(conn, 200)
544
545 token = Repo.get_by(Token, token: token)
546 assert token
547 assert token.scopes == app.scopes
548 end
549
550 test "issues a token for request with HTTP basic auth client credentials" do
551 user = insert(:user)
552 app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])
553
554 {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
555 assert auth.scopes == ["scope1", "scope2"]
556
557 app_encoded =
558 (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
559 |> Base.encode64()
560
561 conn =
562 build_conn()
563 |> put_req_header("authorization", "Basic " <> app_encoded)
564 |> post("/oauth/token", %{
565 "grant_type" => "authorization_code",
566 "code" => auth.token,
567 "redirect_uri" => app.redirect_uris
568 })
569
570 assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)
571
572 assert scope == "scope1 scope2"
573
574 token = Repo.get_by(Token, token: token)
575 assert token
576 assert token.scopes == ["scope1", "scope2"]
577 end
578
579 test "rejects token exchange with invalid client credentials" do
580 user = insert(:user)
581 app = insert(:oauth_app)
582
583 {:ok, auth} = Authorization.create_authorization(app, user)
584
585 conn =
586 build_conn()
587 |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
588 |> post("/oauth/token", %{
589 "grant_type" => "authorization_code",
590 "code" => auth.token,
591 "redirect_uri" => app.redirect_uris
592 })
593
594 assert resp = json_response(conn, 400)
595 assert %{"error" => _} = resp
596 refute Map.has_key?(resp, "access_token")
597 end
598
599 test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
600 setting = Pleroma.Config.get([:instance, :account_activation_required])
601
602 unless setting do
603 Pleroma.Config.put([:instance, :account_activation_required], true)
604 on_exit(fn -> Pleroma.Config.put([:instance, :account_activation_required], setting) end)
605 end
606
607 password = "testpassword"
608 user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password))
609 info_change = Pleroma.User.Info.confirmation_changeset(user.info, :unconfirmed)
610
611 {:ok, user} =
612 user
613 |> Ecto.Changeset.change()
614 |> Ecto.Changeset.put_embed(:info, info_change)
615 |> Repo.update()
616
617 refute Pleroma.User.auth_active?(user)
618
619 app = insert(:oauth_app)
620
621 conn =
622 build_conn()
623 |> post("/oauth/token", %{
624 "grant_type" => "password",
625 "username" => user.nickname,
626 "password" => password,
627 "client_id" => app.client_id,
628 "client_secret" => app.client_secret
629 })
630
631 assert resp = json_response(conn, 403)
632 assert %{"error" => _} = resp
633 refute Map.has_key?(resp, "access_token")
634 end
635
636 test "rejects token exchange for valid credentials belonging to deactivated user" do
637 password = "testpassword"
638
639 user =
640 insert(:user,
641 password_hash: Comeonin.Pbkdf2.hashpwsalt(password),
642 info: %{deactivated: true}
643 )
644
645 app = insert(:oauth_app)
646
647 conn =
648 build_conn()
649 |> post("/oauth/token", %{
650 "grant_type" => "password",
651 "username" => user.nickname,
652 "password" => password,
653 "client_id" => app.client_id,
654 "client_secret" => app.client_secret
655 })
656
657 assert resp = json_response(conn, 403)
658 assert %{"error" => _} = resp
659 refute Map.has_key?(resp, "access_token")
660 end
661
662 test "rejects an invalid authorization code" do
663 app = insert(:oauth_app)
664
665 conn =
666 build_conn()
667 |> post("/oauth/token", %{
668 "grant_type" => "authorization_code",
669 "code" => "Imobviouslyinvalid",
670 "redirect_uri" => app.redirect_uris,
671 "client_id" => app.client_id,
672 "client_secret" => app.client_secret
673 })
674
675 assert resp = json_response(conn, 400)
676 assert %{"error" => _} = json_response(conn, 400)
677 refute Map.has_key?(resp, "access_token")
678 end
679 end
680 end