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