giant massive dep upgrade and dialyxir-found error emporium (#371)
[akkoma] / lib / pleroma / web / o_auth / o_auth_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.OAuth.OAuthController do
6 use Pleroma.Web, :controller
7
8 alias Pleroma.Helpers.AuthHelper
9 alias Pleroma.Helpers.UriHelper
10 alias Pleroma.Maps
11 alias Pleroma.MFA
12 alias Pleroma.Registration
13 alias Pleroma.Repo
14 alias Pleroma.User
15 alias Pleroma.Web.Auth.WrapperAuthenticator, as: Authenticator
16 alias Pleroma.Web.OAuth.App
17 alias Pleroma.Web.OAuth.Authorization
18 alias Pleroma.Web.OAuth.MFAController
19 alias Pleroma.Web.OAuth.MFAView
20 alias Pleroma.Web.OAuth.OAuthView
21 alias Pleroma.Web.OAuth.Scopes
22 alias Pleroma.Web.OAuth.Token
23 alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
24 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
25 alias Pleroma.Web.Plugs.RateLimiter
26 alias Pleroma.Web.Utils.Params
27
28 require Logger
29
30 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
31
32 plug(:fetch_session)
33 plug(:fetch_flash)
34
35 plug(:skip_auth)
36
37 plug(RateLimiter, [name: :authentication] when action == :create_authorization)
38
39 action_fallback(Pleroma.Web.OAuth.FallbackController)
40
41 @oob_token_redirect_uri "urn:ietf:wg:oauth:2.0:oob"
42
43 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
44 def authorize(%Plug.Conn{} = conn, %{"authorization" => _} = params) do
45 {auth_attrs, params} = Map.pop(params, "authorization")
46 authorize(conn, Map.merge(params, auth_attrs))
47 end
48
49 def authorize(%Plug.Conn{assigns: %{token: %Token{}}} = conn, %{"force_login" => _} = params) do
50 if Params.truthy_param?(params["force_login"]) do
51 do_authorize(conn, params)
52 else
53 handle_existing_authorization(conn, params)
54 end
55 end
56
57 # Note: the token is set in oauth_plug, but the token and client do not always go together.
58 # For example, MastodonFE's token is set if user requests with another client,
59 # after user already authorized to MastodonFE.
60 # So we have to check client and token.
61 def authorize(
62 %Plug.Conn{assigns: %{token: %Token{} = token, user: %User{} = user}} = conn,
63 %{"client_id" => client_id} = params
64 ) do
65 with %Token{} = t <- Repo.get_by(Token, token: token.token) |> Repo.preload(:app),
66 ^client_id <- t.app.client_id do
67 handle_existing_authorization(conn, params)
68 else
69 _ ->
70 maybe_reuse_token(conn, params, user.id)
71 end
72 end
73
74 def authorize(%Plug.Conn{} = conn, params) do
75 # if we have a user in the session, attempt to authenticate as them
76 # otherwise show the login form
77 maybe_reuse_token(conn, params, AuthHelper.get_session_user(conn))
78 end
79
80 defp maybe_reuse_token(conn, params, user_id) when is_binary(user_id) do
81 with %User{} = user <- User.get_cached_by_id(user_id),
82 %App{} = app <- Repo.get_by(App, client_id: params["client_id"]),
83 {:ok, %Token{} = token} <- Token.get_preeexisting_by_app_and_user(app, user),
84 {:ok, %Authorization{} = auth} <-
85 Authorization.get_preeexisting_by_app_and_user(app, user) do
86 conn
87 |> assign(:token, token)
88 |> after_create_authorization(auth, %{"authorization" => params})
89 else
90 _ -> do_authorize(conn, params)
91 end
92 end
93
94 defp maybe_reuse_token(conn, params, _user), do: do_authorize(conn, params)
95
96 defp do_authorize(%Plug.Conn{} = conn, params) do
97 app = Repo.get_by(App, client_id: params["client_id"])
98 available_scopes = (app && app.scopes) || []
99 scopes = Scopes.fetch_scopes(params, available_scopes)
100
101 user =
102 with %{assigns: %{user: %User{} = user}} <- conn do
103 user
104 else
105 _ -> nil
106 end
107
108 scopes =
109 if scopes == [] do
110 available_scopes
111 else
112 scopes
113 end
114
115 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
116 render(conn, Authenticator.auth_template(), %{
117 user: user,
118 app: app && Map.delete(app, :client_secret),
119 response_type: params["response_type"],
120 client_id: params["client_id"],
121 available_scopes: available_scopes,
122 scopes: scopes,
123 redirect_uri: params["redirect_uri"],
124 state: params["state"],
125 params: params,
126 view_module: OAuthView
127 })
128 end
129
130 defp handle_existing_authorization(
131 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
132 %{"redirect_uri" => @oob_token_redirect_uri}
133 ) do
134 render(conn, "oob_token_exists.html", %{token: token})
135 end
136
137 defp handle_existing_authorization(
138 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
139 %{} = params
140 ) do
141 app = Repo.preload(token, :app).app
142
143 redirect_uri =
144 if is_binary(params["redirect_uri"]) do
145 params["redirect_uri"]
146 else
147 default_redirect_uri(app)
148 end
149
150 if redirect_uri in String.split(app.redirect_uris) do
151 redirect_uri = redirect_uri(conn, redirect_uri)
152 url_params = %{access_token: token.token}
153 url_params = Maps.put_if_present(url_params, :state, params["state"])
154 url = UriHelper.modify_uri_params(redirect_uri, url_params)
155 redirect(conn, external: url)
156 else
157 conn
158 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
159 |> redirect(external: redirect_uri(conn, redirect_uri))
160 end
161 end
162
163 def create_authorization(_, _, opts \\ [])
164
165 def create_authorization(%Plug.Conn{assigns: %{user: %User{} = user}} = conn, params, []) do
166 create_authorization(conn, params, user: user)
167 end
168
169 def create_authorization(%Plug.Conn{} = conn, %{"authorization" => _} = params, opts) do
170 with {:ok, auth, user} <- do_create_authorization(conn, params, opts[:user]),
171 {:mfa_required, _, _, false} <- {:mfa_required, user, auth, MFA.require?(user)} do
172 conn
173 |> AuthHelper.put_session_user(user.id)
174 |> after_create_authorization(auth, params)
175 else
176 error ->
177 handle_create_authorization_error(conn, error, params)
178 end
179 end
180
181 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
182 "authorization" => %{"redirect_uri" => @oob_token_redirect_uri}
183 }) do
184 # Enforcing the view to reuse the template when calling from other controllers
185 conn
186 |> put_view(OAuthView)
187 |> render("oob_authorization_created.html", %{auth: auth, view_module: OAuthView})
188 end
189
190 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
191 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
192 }) do
193 app = Repo.preload(auth, :app).app
194
195 # An extra safety measure before we redirect (also done in `do_create_authorization/2`)
196 if redirect_uri in String.split(app.redirect_uris) do
197 redirect_uri = redirect_uri(conn, redirect_uri)
198 url_params = %{code: auth.token}
199 url_params = Maps.put_if_present(url_params, :state, auth_attrs["state"])
200 url = UriHelper.modify_uri_params(redirect_uri, url_params)
201 redirect(conn, external: url)
202 else
203 conn
204 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
205 |> redirect(external: redirect_uri(conn, redirect_uri))
206 end
207 end
208
209 defp handle_create_authorization_error(
210 %Plug.Conn{} = conn,
211 {:error, scopes_issue},
212 %{"authorization" => _} = params
213 )
214 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
215 # Per https://github.com/tootsuite/mastodon/blob/
216 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
217 conn
218 |> put_flash(:error, dgettext("errors", "This action is outside the authorized scopes"))
219 |> put_status(:unauthorized)
220 |> authorize(params)
221 end
222
223 defp handle_create_authorization_error(
224 %Plug.Conn{} = conn,
225 {:account_status, :confirmation_pending},
226 %{"authorization" => _} = params
227 ) do
228 conn
229 |> put_flash(:error, dgettext("errors", "Your login is missing a confirmed e-mail address"))
230 |> put_status(:forbidden)
231 |> authorize(params)
232 end
233
234 defp handle_create_authorization_error(
235 %Plug.Conn{} = conn,
236 {:mfa_required, user, auth, _},
237 params
238 ) do
239 {:ok, token} = MFA.Token.create(user, auth)
240
241 data = %{
242 "mfa_token" => token.token,
243 "redirect_uri" => params["authorization"]["redirect_uri"],
244 "state" => params["authorization"]["state"]
245 }
246
247 MFAController.show(conn, data)
248 end
249
250 defp handle_create_authorization_error(
251 %Plug.Conn{} = conn,
252 {:account_status, :password_reset_pending},
253 %{"authorization" => _} = params
254 ) do
255 conn
256 |> put_flash(:error, dgettext("errors", "Password reset is required"))
257 |> put_status(:forbidden)
258 |> authorize(params)
259 end
260
261 defp handle_create_authorization_error(
262 %Plug.Conn{} = conn,
263 {:account_status, :deactivated},
264 %{"authorization" => _} = params
265 ) do
266 conn
267 |> put_flash(:error, dgettext("errors", "Your account is currently disabled"))
268 |> put_status(:forbidden)
269 |> authorize(params)
270 end
271
272 defp handle_create_authorization_error(%Plug.Conn{} = conn, error, %{"authorization" => _}) do
273 Authenticator.handle_error(conn, error)
274 end
275
276 @doc "Renew access_token with refresh_token"
277 def token_exchange(
278 %Plug.Conn{} = conn,
279 %{"grant_type" => "refresh_token", "refresh_token" => token} = _params
280 ) do
281 with {:ok, app} <- Token.Utils.fetch_app(conn),
282 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
283 {:ok, token} <- RefreshToken.grant(token) do
284 after_token_exchange(conn, %{user: user, token: token})
285 else
286 _error -> render_invalid_credentials_error(conn)
287 end
288 end
289
290 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "authorization_code"} = params) do
291 with {:ok, app} <- Token.Utils.fetch_app(conn),
292 fixed_token = Token.Utils.fix_padding(params["code"]),
293 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
294 %User{} = user <- User.get_cached_by_id(auth.user_id),
295 {:ok, token} <- Token.get_or_exchange_token(auth, app, user) do
296 after_token_exchange(conn, %{user: user, token: token})
297 else
298 error ->
299 handle_token_exchange_error(conn, error)
300 end
301 end
302
303 def token_exchange(
304 %Plug.Conn{} = conn,
305 %{"grant_type" => "password"} = params
306 ) do
307 with {:ok, %User{} = user} <- Authenticator.get_user(conn),
308 {:ok, app} <- Token.Utils.fetch_app(conn),
309 requested_scopes <- Scopes.fetch_scopes(params, app.scopes),
310 {:ok, token} <- login(user, app, requested_scopes) do
311 after_token_exchange(conn, %{user: user, token: token})
312 else
313 error ->
314 handle_token_exchange_error(conn, error)
315 end
316 end
317
318 def token_exchange(
319 %Plug.Conn{} = conn,
320 %{"grant_type" => "password", "name" => name, "password" => _password} = params
321 ) do
322 params =
323 params
324 |> Map.delete("name")
325 |> Map.put("username", name)
326
327 token_exchange(conn, params)
328 end
329
330 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "client_credentials"} = _params) do
331 with {:ok, app} <- Token.Utils.fetch_app(conn),
332 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
333 {:ok, token} <- Token.exchange_token(app, auth) do
334 after_token_exchange(conn, %{token: token})
335 else
336 _error ->
337 handle_token_exchange_error(conn, :invalid_credentails)
338 end
339 end
340
341 # Bad request
342 def token_exchange(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
343
344 def after_token_exchange(%Plug.Conn{} = conn, %{token: token} = view_params) do
345 conn
346 |> AuthHelper.put_session_token(token.token)
347 |> AuthHelper.put_session_user(token.user_id)
348 |> json(OAuthView.render("token.json", view_params))
349 end
350
351 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:mfa_required, user, auth, _}) do
352 conn
353 |> put_status(:forbidden)
354 |> json(build_and_response_mfa_token(user, auth))
355 end
356
357 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :deactivated}) do
358 render_error(
359 conn,
360 :forbidden,
361 "Your account is currently disabled",
362 %{},
363 "account_is_disabled"
364 )
365 end
366
367 defp handle_token_exchange_error(
368 %Plug.Conn{} = conn,
369 {:account_status, :password_reset_pending}
370 ) do
371 render_error(
372 conn,
373 :forbidden,
374 "Password reset is required",
375 %{},
376 "password_reset_required"
377 )
378 end
379
380 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :confirmation_pending}) do
381 render_error(
382 conn,
383 :forbidden,
384 "Your login is missing a confirmed e-mail address",
385 %{},
386 "missing_confirmed_email"
387 )
388 end
389
390 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :approval_pending}) do
391 render_error(
392 conn,
393 :forbidden,
394 "Your account is awaiting approval.",
395 %{},
396 "awaiting_approval"
397 )
398 end
399
400 defp handle_token_exchange_error(%Plug.Conn{} = conn, _error) do
401 render_invalid_credentials_error(conn)
402 end
403
404 def token_revoke(%Plug.Conn{} = conn, %{"token" => token}) do
405 with {:ok, %Token{} = oauth_token} <- Token.get_by_token(token),
406 {:ok, oauth_token} <- RevokeToken.revoke(oauth_token) do
407 conn =
408 with session_token = AuthHelper.get_session_token(conn),
409 %Token{token: ^session_token} <- oauth_token do
410 AuthHelper.delete_session_token(conn)
411 else
412 _ -> conn
413 end
414
415 json(conn, %{})
416 else
417 _error ->
418 # RFC 7009: invalid tokens [in the request] do not cause an error response
419 json(conn, %{})
420 end
421 end
422
423 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
424
425 # Response for bad request
426 defp bad_request(%Plug.Conn{} = conn, _) do
427 render_error(conn, :internal_server_error, "Bad request")
428 end
429
430 @doc "Prepares OAuth request to provider for Ueberauth"
431 def prepare_request(%Plug.Conn{} = conn, %{
432 "provider" => provider,
433 "authorization" => auth_attrs
434 }) do
435 scope =
436 auth_attrs
437 |> Scopes.fetch_scopes([])
438 |> Scopes.to_string()
439
440 state =
441 auth_attrs
442 |> Map.delete("scopes")
443 |> Map.put("scope", scope)
444 |> Jason.encode!()
445
446 params =
447 auth_attrs
448 |> Map.drop(~w(scope scopes client_id redirect_uri))
449 |> Map.put("state", state)
450
451 # Handing the request to Ueberauth
452 redirect(conn, to: Routes.o_auth_path(conn, :request, provider, params))
453 end
454
455 def request(%Plug.Conn{} = conn, params) do
456 message =
457 if params["provider"] do
458 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
459 provider: params["provider"]
460 )
461 else
462 dgettext("errors", "Bad OAuth request.")
463 end
464
465 conn
466 |> put_flash(:error, message)
467 |> redirect(to: "/")
468 end
469
470 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
471 params = callback_params(params)
472 messages = for e <- Map.get(failure, :errors, []), do: e.message
473 message = Enum.join(messages, "; ")
474
475 conn
476 |> put_flash(
477 :error,
478 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
479 )
480 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
481 end
482
483 def callback(%Plug.Conn{} = conn, params) do
484 params = callback_params(params)
485
486 with {:ok, registration} <- Authenticator.get_registration(conn) do
487 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
488
489 case Repo.get_assoc(registration, :user) do
490 {:ok, user} ->
491 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
492
493 _ ->
494 registration_params =
495 Map.merge(auth_attrs, %{
496 "nickname" => Registration.nickname(registration),
497 "email" => Registration.email(registration)
498 })
499
500 conn
501 |> put_session_registration_id(registration.id)
502 |> registration_details(%{"authorization" => registration_params})
503 end
504 else
505 error ->
506 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
507
508 conn
509 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
510 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
511 end
512 end
513
514 defp callback_params(%{"state" => state} = params) do
515 Map.merge(params, Jason.decode!(state))
516 end
517
518 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
519 render(conn, "register.html", %{
520 client_id: auth_attrs["client_id"],
521 redirect_uri: auth_attrs["redirect_uri"],
522 state: auth_attrs["state"],
523 scopes: Scopes.fetch_scopes(auth_attrs, []),
524 nickname: auth_attrs["nickname"],
525 email: auth_attrs["email"]
526 })
527 end
528
529 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
530 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
531 %Registration{} = registration <- Repo.get(Registration, registration_id),
532 {_, {:ok, auth, _user}} <-
533 {:create_authorization, do_create_authorization(conn, params)},
534 %User{} = user <- Repo.preload(auth, :user).user,
535 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
536 conn
537 |> put_session_registration_id(nil)
538 |> after_create_authorization(auth, params)
539 else
540 {:create_authorization, error} ->
541 {:register, handle_create_authorization_error(conn, error, params)}
542
543 _ ->
544 {:register, :generic_error}
545 end
546 end
547
548 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
549 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
550 %Registration{} = registration <- Repo.get(Registration, registration_id),
551 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
552 conn
553 |> put_session_registration_id(nil)
554 |> create_authorization(
555 params,
556 user: user
557 )
558 else
559 {:error, changeset} ->
560 message =
561 Enum.map_join(changeset.errors, "; ", fn {field, {error, _}} ->
562 "#{field} #{error}"
563 end)
564
565 message =
566 String.replace(
567 message,
568 "ap_id has already been taken",
569 "nickname has already been taken"
570 )
571
572 conn
573 |> put_status(:forbidden)
574 |> put_flash(:error, "Error: #{message}.")
575 |> registration_details(params)
576
577 _ ->
578 {:register, :generic_error}
579 end
580 end
581
582 defp do_create_authorization(conn, auth_attrs, user \\ nil)
583
584 defp do_create_authorization(
585 %Plug.Conn{} = conn,
586 %{
587 "authorization" =>
588 %{
589 "client_id" => client_id,
590 "redirect_uri" => redirect_uri
591 } = auth_attrs
592 },
593 user
594 ) do
595 with {_, {:ok, %User{} = user}} <-
596 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
597 %App{} = app <- Repo.get_by(App, client_id: client_id),
598 true <- redirect_uri in String.split(app.redirect_uris),
599 requested_scopes <- Scopes.fetch_scopes(auth_attrs, app.scopes),
600 {:ok, auth} <- do_create_authorization(user, app, requested_scopes) do
601 {:ok, auth, user}
602 end
603 end
604
605 defp do_create_authorization(%User{} = user, %App{} = app, requested_scopes)
606 when is_list(requested_scopes) do
607 with {:account_status, :active} <- {:account_status, User.account_status(user)},
608 {:ok, scopes} <- validate_scopes(app, requested_scopes),
609 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
610 {:ok, auth}
611 end
612 end
613
614 # Note: intended to be a private function but opened for AccountController that logs in on signup
615 @doc "If checks pass, creates authorization and token for given user, app and requested scopes."
616 def login(%User{} = user, %App{} = app, requested_scopes) when is_list(requested_scopes) do
617 with {:ok, auth} <- do_create_authorization(user, app, requested_scopes),
618 {:mfa_required, _, _, false} <- {:mfa_required, user, auth, MFA.require?(user)},
619 {:ok, token} <- Token.exchange_token(app, auth) do
620 {:ok, token}
621 end
622 end
623
624 # Special case: Local MastodonFE
625 defp redirect_uri(%Plug.Conn{} = conn, "."), do: Routes.auth_url(conn, :login)
626
627 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
628
629 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
630
631 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
632 do: put_session(conn, :registration_id, registration_id)
633
634 defp build_and_response_mfa_token(user, auth) do
635 with {:ok, token} <- MFA.Token.create(user, auth) do
636 MFAView.render("mfa_response.json", %{token: token, user: user})
637 end
638 end
639
640 @spec validate_scopes(App.t(), map() | list()) ::
641 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
642 defp validate_scopes(%App{} = app, params) when is_map(params) do
643 requested_scopes = Scopes.fetch_scopes(params, app.scopes)
644 validate_scopes(app, requested_scopes)
645 end
646
647 defp validate_scopes(%App{} = app, requested_scopes) when is_list(requested_scopes) do
648 Scopes.validate(requested_scopes, app.scopes)
649 end
650
651 def default_redirect_uri(%App{} = app) do
652 app.redirect_uris
653 |> String.split()
654 |> Enum.at(0)
655 end
656
657 defp render_invalid_credentials_error(conn) do
658 render_error(conn, :bad_request, "Invalid credentials")
659 end
660 end