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