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