Merge remote-tracking branch 'remotes/upstream/develop' into 1234-mastodon-2-4-3...
[akkoma] / lib / pleroma / web / oauth / oauth_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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.Registration
10 alias Pleroma.Repo
11 alias Pleroma.User
12 alias Pleroma.Web.Auth.Authenticator
13 alias Pleroma.Web.ControllerHelper
14 alias Pleroma.Web.OAuth.App
15 alias Pleroma.Web.OAuth.Authorization
16 alias Pleroma.Web.OAuth.Token
17 alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
18 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
19 alias Pleroma.Web.OAuth.Scopes
20
21 require Logger
22
23 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
24
25 plug(:fetch_session)
26 plug(:fetch_flash)
27
28 action_fallback(Pleroma.Web.OAuth.FallbackController)
29
30 @oob_token_redirect_uri "urn:ietf:wg:oauth:2.0:oob"
31
32 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
33 def authorize(%Plug.Conn{} = conn, %{"authorization" => _} = params) do
34 {auth_attrs, params} = Map.pop(params, "authorization")
35 authorize(conn, Map.merge(params, auth_attrs))
36 end
37
38 def authorize(%Plug.Conn{assigns: %{token: %Token{}}} = conn, params) do
39 if ControllerHelper.truthy_param?(params["force_login"]) do
40 do_authorize(conn, params)
41 else
42 handle_existing_authorization(conn, params)
43 end
44 end
45
46 def authorize(%Plug.Conn{} = conn, params), do: do_authorize(conn, params)
47
48 defp do_authorize(%Plug.Conn{} = conn, params) do
49 app = Repo.get_by(App, client_id: params["client_id"])
50 available_scopes = (app && app.scopes) || []
51 scopes = Scopes.fetch_scopes(params, available_scopes)
52
53 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
54 render(conn, Authenticator.auth_template(), %{
55 response_type: params["response_type"],
56 client_id: params["client_id"],
57 available_scopes: available_scopes,
58 scopes: scopes,
59 redirect_uri: params["redirect_uri"],
60 state: params["state"],
61 params: params
62 })
63 end
64
65 defp handle_existing_authorization(
66 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
67 %{"redirect_uri" => @oob_token_redirect_uri}
68 ) do
69 render(conn, "oob_token_exists.html", %{token: token})
70 end
71
72 defp handle_existing_authorization(
73 %Plug.Conn{assigns: %{token: %Token{} = token}} = conn,
74 %{} = params
75 ) do
76 app = Repo.preload(token, :app).app
77
78 redirect_uri =
79 if is_binary(params["redirect_uri"]) do
80 params["redirect_uri"]
81 else
82 default_redirect_uri(app)
83 end
84
85 if redirect_uri in String.split(app.redirect_uris) do
86 redirect_uri = redirect_uri(conn, redirect_uri)
87 url_params = %{access_token: token.token}
88 url_params = UriHelper.append_param_if_present(url_params, :state, params["state"])
89 url = UriHelper.append_uri_params(redirect_uri, url_params)
90 redirect(conn, external: url)
91 else
92 conn
93 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
94 |> redirect(external: redirect_uri(conn, redirect_uri))
95 end
96 end
97
98 def create_authorization(
99 %Plug.Conn{} = conn,
100 %{"authorization" => _} = params,
101 opts \\ []
102 ) do
103 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
104 after_create_authorization(conn, auth, params)
105 else
106 error ->
107 handle_create_authorization_error(conn, error, params)
108 end
109 end
110
111 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
112 "authorization" => %{"redirect_uri" => @oob_token_redirect_uri}
113 }) do
114 render(conn, "oob_authorization_created.html", %{auth: auth})
115 end
116
117 def after_create_authorization(%Plug.Conn{} = conn, %Authorization{} = auth, %{
118 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
119 }) do
120 app = Repo.preload(auth, :app).app
121
122 # An extra safety measure before we redirect (also done in `do_create_authorization/2`)
123 if redirect_uri in String.split(app.redirect_uris) do
124 redirect_uri = redirect_uri(conn, redirect_uri)
125 url_params = %{code: auth.token}
126 url_params = UriHelper.append_param_if_present(url_params, :state, auth_attrs["state"])
127 url = UriHelper.append_uri_params(redirect_uri, url_params)
128 redirect(conn, external: url)
129 else
130 conn
131 |> put_flash(:error, dgettext("errors", "Unlisted redirect_uri."))
132 |> redirect(external: redirect_uri(conn, redirect_uri))
133 end
134 end
135
136 defp handle_create_authorization_error(
137 %Plug.Conn{} = conn,
138 {:error, scopes_issue},
139 %{"authorization" => _} = params
140 )
141 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
142 # Per https://github.com/tootsuite/mastodon/blob/
143 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
144 conn
145 |> put_flash(:error, dgettext("errors", "This action is outside the authorized scopes"))
146 |> put_status(:unauthorized)
147 |> authorize(params)
148 end
149
150 defp handle_create_authorization_error(
151 %Plug.Conn{} = conn,
152 {:auth_active, false},
153 %{"authorization" => _} = params
154 ) do
155 # Per https://github.com/tootsuite/mastodon/blob/
156 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
157 conn
158 |> put_flash(:error, dgettext("errors", "Your login is missing a confirmed e-mail address"))
159 |> put_status(:forbidden)
160 |> authorize(params)
161 end
162
163 defp handle_create_authorization_error(%Plug.Conn{} = conn, error, %{"authorization" => _}) do
164 Authenticator.handle_error(conn, error)
165 end
166
167 @doc "Renew access_token with refresh_token"
168 def token_exchange(
169 %Plug.Conn{} = conn,
170 %{"grant_type" => "refresh_token", "refresh_token" => token} = _params
171 ) do
172 with {:ok, app} <- Token.Utils.fetch_app(conn),
173 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
174 {:ok, token} <- RefreshToken.grant(token) do
175 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
176
177 json(conn, Token.Response.build(user, token, response_attrs))
178 else
179 _error -> render_invalid_credentials_error(conn)
180 end
181 end
182
183 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "authorization_code"} = params) do
184 with {:ok, app} <- Token.Utils.fetch_app(conn),
185 fixed_token = Token.Utils.fix_padding(params["code"]),
186 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
187 %User{} = user <- User.get_cached_by_id(auth.user_id),
188 {:ok, token} <- Token.exchange_token(app, auth) do
189 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
190
191 json(conn, Token.Response.build(user, token, response_attrs))
192 else
193 _error -> render_invalid_credentials_error(conn)
194 end
195 end
196
197 def token_exchange(
198 %Plug.Conn{} = conn,
199 %{"grant_type" => "password"} = params
200 ) do
201 with {:ok, %User{} = user} <- Authenticator.get_user(conn),
202 {:ok, app} <- Token.Utils.fetch_app(conn),
203 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
204 {:user_active, true} <- {:user_active, !user.info.deactivated},
205 {:password_reset_pending, false} <-
206 {:password_reset_pending, user.info.password_reset_pending},
207 {:ok, scopes} <- validate_scopes(app, params),
208 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
209 {:ok, token} <- Token.exchange_token(app, auth) do
210 json(conn, Token.Response.build(user, token))
211 else
212 {:auth_active, false} ->
213 # Per https://github.com/tootsuite/mastodon/blob/
214 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
215 render_error(
216 conn,
217 :forbidden,
218 "Your login is missing a confirmed e-mail address",
219 %{},
220 "missing_confirmed_email"
221 )
222
223 {:user_active, false} ->
224 render_error(
225 conn,
226 :forbidden,
227 "Your account is currently disabled",
228 %{},
229 "account_is_disabled"
230 )
231
232 {:password_reset_pending, true} ->
233 render_error(
234 conn,
235 :forbidden,
236 "Password reset is required",
237 %{},
238 "password_reset_required"
239 )
240
241 _error ->
242 render_invalid_credentials_error(conn)
243 end
244 end
245
246 def token_exchange(
247 %Plug.Conn{} = conn,
248 %{"grant_type" => "password", "name" => name, "password" => _password} = params
249 ) do
250 params =
251 params
252 |> Map.delete("name")
253 |> Map.put("username", name)
254
255 token_exchange(conn, params)
256 end
257
258 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "client_credentials"} = _params) do
259 with {:ok, app} <- Token.Utils.fetch_app(conn),
260 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
261 {:ok, token} <- Token.exchange_token(app, auth) do
262 json(conn, Token.Response.build_for_client_credentials(token))
263 else
264 _error -> render_invalid_credentials_error(conn)
265 end
266 end
267
268 # Bad request
269 def token_exchange(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
270
271 def token_revoke(%Plug.Conn{} = conn, %{"token" => _token} = params) do
272 with {:ok, app} <- Token.Utils.fetch_app(conn),
273 {:ok, _token} <- RevokeToken.revoke(app, params) do
274 json(conn, %{})
275 else
276 _error ->
277 # RFC 7009: invalid tokens [in the request] do not cause an error response
278 json(conn, %{})
279 end
280 end
281
282 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
283
284 # Response for bad request
285 defp bad_request(%Plug.Conn{} = conn, _) do
286 render_error(conn, :internal_server_error, "Bad request")
287 end
288
289 @doc "Prepares OAuth request to provider for Ueberauth"
290 def prepare_request(%Plug.Conn{} = conn, %{
291 "provider" => provider,
292 "authorization" => auth_attrs
293 }) do
294 scope =
295 auth_attrs
296 |> Scopes.fetch_scopes([])
297 |> Scopes.to_string()
298
299 state =
300 auth_attrs
301 |> Map.delete("scopes")
302 |> Map.put("scope", scope)
303 |> Jason.encode!()
304
305 params =
306 auth_attrs
307 |> Map.drop(~w(scope scopes client_id redirect_uri))
308 |> Map.put("state", state)
309
310 # Handing the request to Ueberauth
311 redirect(conn, to: o_auth_path(conn, :request, provider, params))
312 end
313
314 def request(%Plug.Conn{} = conn, params) do
315 message =
316 if params["provider"] do
317 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
318 provider: params["provider"]
319 )
320 else
321 dgettext("errors", "Bad OAuth request.")
322 end
323
324 conn
325 |> put_flash(:error, message)
326 |> redirect(to: "/")
327 end
328
329 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
330 params = callback_params(params)
331 messages = for e <- Map.get(failure, :errors, []), do: e.message
332 message = Enum.join(messages, "; ")
333
334 conn
335 |> put_flash(
336 :error,
337 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
338 )
339 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
340 end
341
342 def callback(%Plug.Conn{} = conn, params) do
343 params = callback_params(params)
344
345 with {:ok, registration} <- Authenticator.get_registration(conn) do
346 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
347
348 case Repo.get_assoc(registration, :user) do
349 {:ok, user} ->
350 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
351
352 _ ->
353 registration_params =
354 Map.merge(auth_attrs, %{
355 "nickname" => Registration.nickname(registration),
356 "email" => Registration.email(registration)
357 })
358
359 conn
360 |> put_session_registration_id(registration.id)
361 |> registration_details(%{"authorization" => registration_params})
362 end
363 else
364 error ->
365 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
366
367 conn
368 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
369 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
370 end
371 end
372
373 defp callback_params(%{"state" => state} = params) do
374 Map.merge(params, Jason.decode!(state))
375 end
376
377 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
378 render(conn, "register.html", %{
379 client_id: auth_attrs["client_id"],
380 redirect_uri: auth_attrs["redirect_uri"],
381 state: auth_attrs["state"],
382 scopes: Scopes.fetch_scopes(auth_attrs, []),
383 nickname: auth_attrs["nickname"],
384 email: auth_attrs["email"]
385 })
386 end
387
388 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
389 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
390 %Registration{} = registration <- Repo.get(Registration, registration_id),
391 {_, {:ok, auth}} <- {:create_authorization, do_create_authorization(conn, params)},
392 %User{} = user <- Repo.preload(auth, :user).user,
393 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
394 conn
395 |> put_session_registration_id(nil)
396 |> after_create_authorization(auth, params)
397 else
398 {:create_authorization, error} ->
399 {:register, handle_create_authorization_error(conn, error, params)}
400
401 _ ->
402 {:register, :generic_error}
403 end
404 end
405
406 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
407 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
408 %Registration{} = registration <- Repo.get(Registration, registration_id),
409 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
410 conn
411 |> put_session_registration_id(nil)
412 |> create_authorization(
413 params,
414 user: user
415 )
416 else
417 {:error, changeset} ->
418 message =
419 Enum.map(changeset.errors, fn {field, {error, _}} ->
420 "#{field} #{error}"
421 end)
422 |> Enum.join("; ")
423
424 message =
425 String.replace(
426 message,
427 "ap_id has already been taken",
428 "nickname has already been taken"
429 )
430
431 conn
432 |> put_status(:forbidden)
433 |> put_flash(:error, "Error: #{message}.")
434 |> registration_details(params)
435
436 _ ->
437 {:register, :generic_error}
438 end
439 end
440
441 defp do_create_authorization(
442 %Plug.Conn{} = conn,
443 %{
444 "authorization" =>
445 %{
446 "client_id" => client_id,
447 "redirect_uri" => redirect_uri
448 } = auth_attrs
449 },
450 user \\ nil
451 ) do
452 with {_, {:ok, %User{} = user}} <-
453 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
454 %App{} = app <- Repo.get_by(App, client_id: client_id),
455 true <- redirect_uri in String.split(app.redirect_uris),
456 {:ok, scopes} <- validate_scopes(app, auth_attrs),
457 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
458 Authorization.create_authorization(app, user, scopes)
459 end
460 end
461
462 # Special case: Local MastodonFE
463 defp redirect_uri(%Plug.Conn{} = conn, "."), do: auth_url(conn, :login)
464
465 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
466
467 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
468
469 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
470 do: put_session(conn, :registration_id, registration_id)
471
472 @spec validate_scopes(App.t(), map()) ::
473 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
474 defp validate_scopes(app, params) do
475 params
476 |> Scopes.fetch_scopes(app.scopes)
477 |> Scopes.validate(app.scopes)
478 end
479
480 def default_redirect_uri(%App{} = app) do
481 app.redirect_uris
482 |> String.split()
483 |> Enum.at(0)
484 end
485
486 defp render_invalid_credentials_error(conn) do
487 render_error(conn, :bad_request, "Invalid credentials")
488 end
489 end