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