Fix oauth2 (for real) (#179)
[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 maybe_remove_token(%Plug.Conn{assigns: %{token: %{app: id}}} = conn, %App{id: id}) do
75 conn
76 end
77
78 defp maybe_remove_token(conn, _app) do
79 conn
80 |> assign(:token, nil)
81 end
82
83 defp do_authorize(%Plug.Conn{} = conn, params) do
84 app = Repo.get_by(App, client_id: params["client_id"])
85 conn = maybe_remove_token(conn, app)
86 available_scopes = (app && app.scopes) || []
87 scopes = Scopes.fetch_scopes(params, available_scopes)
88
89 # if we already have a token for this specific setup, we can use that
90 with false <- Params.truthy_param?(params["force_login"]),
91 %App{} <- app,
92 %{assigns: %{user: %Pleroma.User{} = user}} <- conn,
93 {:ok, %Token{} = token} <- Token.get_preexisting_by_app_and_user(app, user),
94 true <- scopes == token.scopes do
95 token = Repo.preload(token, :app)
96
97 conn
98 |> assign(:token, token)
99 |> handle_existing_authorization(params)
100 else
101 _ ->
102 user =
103 with %{assigns: %{user: %User{} = user}} <- conn do
104 user
105 else
106 _ -> nil
107 end
108
109 scopes =
110 if scopes == [] do
111 available_scopes
112 else
113 scopes
114 end
115
116 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
117 render(conn, Authenticator.auth_template(), %{
118 user: user,
119 app: app && Map.delete(app, :client_secret),
120 response_type: params["response_type"],
121 client_id: params["client_id"],
122 available_scopes: available_scopes,
123 scopes: scopes,
124 redirect_uri: params["redirect_uri"],
125 state: params["state"],
126 params: params,
127 view_module: OAuthView
128 })
129 end
130 end
131
132 defp handle_existing_authorization(
133 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
134 %{"redirect_uri" => @oob_token_redirect_uri}
135 ) do
136 render(conn, "oob_token_exists.html", %{token: token})
137 end
138
139 defp handle_existing_authorization(
140 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
141 %{} = params
142 ) do
143 app = Repo.preload(token, :app).app
144
145 redirect_uri =
146 if is_binary(params["redirect_uri"]) do
147 params["redirect_uri"]
148 else
149 default_redirect_uri(app)
150 end
151
152 if redirect_uri in String.split(app.redirect_uris) do
153 redirect_uri = redirect_uri(conn, redirect_uri)
154 url_params = %{access_token: token.token}
155 url_params = Maps.put_if_present(url_params, :state, params["state"])
156 url = UriHelper.modify_uri_params(redirect_uri, url_params)
157 redirect(conn, external: url)
158 else
159 conn
160 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
161 |> redirect(external: redirect_uri(conn, redirect_uri))
162 end
163 end
164
165 def create_authorization(_, _, opts \\ [])
166
167 def create_authorization(%Plug.Conn{assigns: %{user: %User{} = user}} = conn, params, []) do
168 create_authorization(conn, params, user: user)
169 end
170
171 def create_authorization(%Plug.Conn{} = conn, %{"authorization" => _} = params, opts) do
172 with {:ok, auth, user} <- do_create_authorization(conn, params, opts[:user]),
173 {:mfa_required, _, _, false} <- {:mfa_required, user, auth, MFA.require?(user)} do
174 after_create_authorization(conn, 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.exchange_token(app, auth) 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 |> json(OAuthView.render("token.json", view_params))
347 end
348
349 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:mfa_required, user, auth, _}) do
350 conn
351 |> put_status(:forbidden)
352 |> json(build_and_response_mfa_token(user, auth))
353 end
354
355 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :deactivated}) do
356 render_error(
357 conn,
358 :forbidden,
359 "Your account is currently disabled",
360 %{},
361 "account_is_disabled"
362 )
363 end
364
365 defp handle_token_exchange_error(
366 %Plug.Conn{} = conn,
367 {:account_status, :password_reset_pending}
368 ) do
369 render_error(
370 conn,
371 :forbidden,
372 "Password reset is required",
373 %{},
374 "password_reset_required"
375 )
376 end
377
378 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :confirmation_pending}) do
379 render_error(
380 conn,
381 :forbidden,
382 "Your login is missing a confirmed e-mail address",
383 %{},
384 "missing_confirmed_email"
385 )
386 end
387
388 defp handle_token_exchange_error(%Plug.Conn{} = conn, {:account_status, :approval_pending}) do
389 render_error(
390 conn,
391 :forbidden,
392 "Your account is awaiting approval.",
393 %{},
394 "awaiting_approval"
395 )
396 end
397
398 defp handle_token_exchange_error(%Plug.Conn{} = conn, _error) do
399 render_invalid_credentials_error(conn)
400 end
401
402 def token_revoke(%Plug.Conn{} = conn, %{"token" => token}) do
403 with {:ok, %Token{} = oauth_token} <- Token.get_by_token(token),
404 {:ok, _oauth_token} <- RevokeToken.revoke(oauth_token) do
405 json(conn, %{})
406 else
407 _error ->
408 # RFC 7009: invalid tokens [in the request] do not cause an error response
409 json(conn, %{})
410 end
411 end
412
413 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
414
415 # Response for bad request
416 defp bad_request(%Plug.Conn{} = conn, _) do
417 render_error(conn, :internal_server_error, "Bad request")
418 end
419
420 @doc "Prepares OAuth request to provider for Ueberauth"
421 def prepare_request(%Plug.Conn{} = conn, %{
422 "provider" => provider,
423 "authorization" => auth_attrs
424 }) do
425 scope =
426 auth_attrs
427 |> Scopes.fetch_scopes([])
428 |> Scopes.to_string()
429
430 state =
431 auth_attrs
432 |> Map.delete("scopes")
433 |> Map.put("scope", scope)
434 |> Jason.encode!()
435
436 params =
437 auth_attrs
438 |> Map.drop(~w(scope scopes client_id redirect_uri))
439 |> Map.put("state", state)
440
441 # Handing the request to Ueberauth
442 redirect(conn, to: Routes.o_auth_path(conn, :request, provider, params))
443 end
444
445 def request(%Plug.Conn{} = conn, params) do
446 message =
447 if params["provider"] do
448 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
449 provider: params["provider"]
450 )
451 else
452 dgettext("errors", "Bad OAuth request.")
453 end
454
455 conn
456 |> put_flash(:error, message)
457 |> redirect(to: "/")
458 end
459
460 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
461 params = callback_params(params)
462 messages = for e <- Map.get(failure, :errors, []), do: e.message
463 message = Enum.join(messages, "; ")
464
465 conn
466 |> put_flash(
467 :error,
468 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
469 )
470 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
471 end
472
473 def callback(%Plug.Conn{} = conn, params) do
474 params = callback_params(params)
475
476 with {:ok, registration} <- Authenticator.get_registration(conn) do
477 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
478
479 case Repo.get_assoc(registration, :user) do
480 {:ok, user} ->
481 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
482
483 _ ->
484 registration_params =
485 Map.merge(auth_attrs, %{
486 "nickname" => Registration.nickname(registration),
487 "email" => Registration.email(registration)
488 })
489
490 conn
491 |> put_session_registration_id(registration.id)
492 |> registration_details(%{"authorization" => registration_params})
493 end
494 else
495 error ->
496 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
497
498 conn
499 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
500 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
501 end
502 end
503
504 defp callback_params(%{"state" => state} = params) do
505 Map.merge(params, Jason.decode!(state))
506 end
507
508 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
509 render(conn, "register.html", %{
510 client_id: auth_attrs["client_id"],
511 redirect_uri: auth_attrs["redirect_uri"],
512 state: auth_attrs["state"],
513 scopes: Scopes.fetch_scopes(auth_attrs, []),
514 nickname: auth_attrs["nickname"],
515 email: auth_attrs["email"]
516 })
517 end
518
519 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
520 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
521 %Registration{} = registration <- Repo.get(Registration, registration_id),
522 {_, {:ok, auth, _user}} <-
523 {:create_authorization, do_create_authorization(conn, params)},
524 %User{} = user <- Repo.preload(auth, :user).user,
525 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
526 conn
527 |> put_session_registration_id(nil)
528 |> after_create_authorization(auth, params)
529 else
530 {:create_authorization, error} ->
531 {:register, handle_create_authorization_error(conn, error, params)}
532
533 _ ->
534 {:register, :generic_error}
535 end
536 end
537
538 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
539 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
540 %Registration{} = registration <- Repo.get(Registration, registration_id),
541 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
542 conn
543 |> put_session_registration_id(nil)
544 |> create_authorization(
545 params,
546 user: user
547 )
548 else
549 {:error, changeset} ->
550 message =
551 Enum.map(changeset.errors, fn {field, {error, _}} ->
552 "#{field} #{error}"
553 end)
554 |> Enum.join("; ")
555
556 message =
557 String.replace(
558 message,
559 "ap_id has already been taken",
560 "nickname has already been taken"
561 )
562
563 conn
564 |> put_status(:forbidden)
565 |> put_flash(:error, "Error: #{message}.")
566 |> registration_details(params)
567
568 _ ->
569 {:register, :generic_error}
570 end
571 end
572
573 defp do_create_authorization(conn, auth_attrs, user \\ nil)
574
575 defp do_create_authorization(
576 %Plug.Conn{} = conn,
577 %{
578 "authorization" =>
579 %{
580 "client_id" => client_id,
581 "redirect_uri" => redirect_uri
582 } = auth_attrs
583 },
584 user
585 ) do
586 with {_, {:ok, %User{} = user}} <-
587 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
588 %App{} = app <- Repo.get_by(App, client_id: client_id),
589 true <- redirect_uri in String.split(app.redirect_uris),
590 requested_scopes <- Scopes.fetch_scopes(auth_attrs, app.scopes),
591 {:ok, auth} <- do_create_authorization(user, app, requested_scopes) do
592 {:ok, auth, user}
593 end
594 end
595
596 defp do_create_authorization(%User{} = user, %App{} = app, requested_scopes)
597 when is_list(requested_scopes) do
598 with {:account_status, :active} <- {:account_status, User.account_status(user)},
599 {:ok, scopes} <- validate_scopes(app, requested_scopes),
600 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
601 {:ok, auth}
602 end
603 end
604
605 # Note: intended to be a private function but opened for AccountController that logs in on signup
606 @doc "If checks pass, creates authorization and token for given user, app and requested scopes."
607 def login(%User{} = user, %App{} = app, requested_scopes) when is_list(requested_scopes) do
608 with {:ok, auth} <- do_create_authorization(user, app, requested_scopes),
609 {:mfa_required, _, _, false} <- {:mfa_required, user, auth, MFA.require?(user)},
610 {:ok, token} <- Token.exchange_token(app, auth) do
611 {:ok, token}
612 end
613 end
614
615 # Special case: Local MastodonFE
616 defp redirect_uri(%Plug.Conn{} = conn, "."), do: Routes.auth_url(conn, :login)
617
618 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
619
620 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
621
622 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
623 do: put_session(conn, :registration_id, registration_id)
624
625 defp build_and_response_mfa_token(user, auth) do
626 with {:ok, token} <- MFA.Token.create(user, auth) do
627 MFAView.render("mfa_response.json", %{token: token, user: user})
628 end
629 end
630
631 @spec validate_scopes(App.t(), map() | list()) ::
632 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
633 defp validate_scopes(%App{} = app, params) when is_map(params) do
634 requested_scopes = Scopes.fetch_scopes(params, app.scopes)
635 validate_scopes(app, requested_scopes)
636 end
637
638 defp validate_scopes(%App{} = app, requested_scopes) when is_list(requested_scopes) do
639 Scopes.validate(requested_scopes, app.scopes)
640 end
641
642 def default_redirect_uri(%App{} = app) do
643 app.redirect_uris
644 |> String.split()
645 |> Enum.at(0)
646 end
647
648 defp render_invalid_credentials_error(conn) do
649 render_error(conn, :bad_request, "Invalid credentials")
650 end
651 end