[#1260] Rate-limiting for create authentication and related requests.
[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 {:ok, scopes} <- validate_scopes(app, params),
207 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
208 {:ok, token} <- Token.exchange_token(app, auth) do
209 json(conn, Token.Response.build(user, token))
210 else
211 {:auth_active, false} ->
212 # Per https://github.com/tootsuite/mastodon/blob/
213 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
214 render_error(conn, :forbidden, "Your login is missing a confirmed e-mail address")
215
216 {:user_active, false} ->
217 render_error(conn, :forbidden, "Your account is currently disabled")
218
219 _error ->
220 render_invalid_credentials_error(conn)
221 end
222 end
223
224 def token_exchange(
225 %Plug.Conn{} = conn,
226 %{"grant_type" => "password", "name" => name, "password" => _password} = params
227 ) do
228 params =
229 params
230 |> Map.delete("name")
231 |> Map.put("username", name)
232
233 token_exchange(conn, params)
234 end
235
236 def token_exchange(%Plug.Conn{} = conn, %{"grant_type" => "client_credentials"} = _params) do
237 with {:ok, app} <- Token.Utils.fetch_app(conn),
238 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
239 {:ok, token} <- Token.exchange_token(app, auth) do
240 json(conn, Token.Response.build_for_client_credentials(token))
241 else
242 _error -> render_invalid_credentials_error(conn)
243 end
244 end
245
246 # Bad request
247 def token_exchange(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
248
249 def token_revoke(%Plug.Conn{} = conn, %{"token" => _token} = params) do
250 with {:ok, app} <- Token.Utils.fetch_app(conn),
251 {:ok, _token} <- RevokeToken.revoke(app, params) do
252 json(conn, %{})
253 else
254 _error ->
255 # RFC 7009: invalid tokens [in the request] do not cause an error response
256 json(conn, %{})
257 end
258 end
259
260 def token_revoke(%Plug.Conn{} = conn, params), do: bad_request(conn, params)
261
262 # Response for bad request
263 defp bad_request(%Plug.Conn{} = conn, _) do
264 render_error(conn, :internal_server_error, "Bad request")
265 end
266
267 @doc "Prepares OAuth request to provider for Ueberauth"
268 def prepare_request(%Plug.Conn{} = conn, %{
269 "provider" => provider,
270 "authorization" => auth_attrs
271 }) do
272 scope =
273 auth_attrs
274 |> Scopes.fetch_scopes([])
275 |> Scopes.to_string()
276
277 state =
278 auth_attrs
279 |> Map.delete("scopes")
280 |> Map.put("scope", scope)
281 |> Jason.encode!()
282
283 params =
284 auth_attrs
285 |> Map.drop(~w(scope scopes client_id redirect_uri))
286 |> Map.put("state", state)
287
288 # Handing the request to Ueberauth
289 redirect(conn, to: o_auth_path(conn, :request, provider, params))
290 end
291
292 def request(%Plug.Conn{} = conn, params) do
293 message =
294 if params["provider"] do
295 dgettext("errors", "Unsupported OAuth provider: %{provider}.",
296 provider: params["provider"]
297 )
298 else
299 dgettext("errors", "Bad OAuth request.")
300 end
301
302 conn
303 |> put_flash(:error, message)
304 |> redirect(to: "/")
305 end
306
307 def callback(%Plug.Conn{assigns: %{ueberauth_failure: failure}} = conn, params) do
308 params = callback_params(params)
309 messages = for e <- Map.get(failure, :errors, []), do: e.message
310 message = Enum.join(messages, "; ")
311
312 conn
313 |> put_flash(
314 :error,
315 dgettext("errors", "Failed to authenticate: %{message}.", message: message)
316 )
317 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
318 end
319
320 def callback(%Plug.Conn{} = conn, params) do
321 params = callback_params(params)
322
323 with {:ok, registration} <- Authenticator.get_registration(conn) do
324 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
325
326 case Repo.get_assoc(registration, :user) do
327 {:ok, user} ->
328 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
329
330 _ ->
331 registration_params =
332 Map.merge(auth_attrs, %{
333 "nickname" => Registration.nickname(registration),
334 "email" => Registration.email(registration)
335 })
336
337 conn
338 |> put_session_registration_id(registration.id)
339 |> registration_details(%{"authorization" => registration_params})
340 end
341 else
342 error ->
343 Logger.debug(inspect(["OAUTH_ERROR", error, conn.assigns]))
344
345 conn
346 |> put_flash(:error, dgettext("errors", "Failed to set up user account."))
347 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
348 end
349 end
350
351 defp callback_params(%{"state" => state} = params) do
352 Map.merge(params, Jason.decode!(state))
353 end
354
355 def registration_details(%Plug.Conn{} = conn, %{"authorization" => auth_attrs}) do
356 render(conn, "register.html", %{
357 client_id: auth_attrs["client_id"],
358 redirect_uri: auth_attrs["redirect_uri"],
359 state: auth_attrs["state"],
360 scopes: Scopes.fetch_scopes(auth_attrs, []),
361 nickname: auth_attrs["nickname"],
362 email: auth_attrs["email"]
363 })
364 end
365
366 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "connect"} = params) do
367 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
368 %Registration{} = registration <- Repo.get(Registration, registration_id),
369 {_, {:ok, auth}} <- {:create_authorization, do_create_authorization(conn, params)},
370 %User{} = user <- Repo.preload(auth, :user).user,
371 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
372 conn
373 |> put_session_registration_id(nil)
374 |> after_create_authorization(auth, params)
375 else
376 {:create_authorization, error} ->
377 {:register, handle_create_authorization_error(conn, error, params)}
378
379 _ ->
380 {:register, :generic_error}
381 end
382 end
383
384 def register(%Plug.Conn{} = conn, %{"authorization" => _, "op" => "register"} = params) do
385 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
386 %Registration{} = registration <- Repo.get(Registration, registration_id),
387 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
388 conn
389 |> put_session_registration_id(nil)
390 |> create_authorization(
391 params,
392 user: user
393 )
394 else
395 {:error, changeset} ->
396 message =
397 Enum.map(changeset.errors, fn {field, {error, _}} ->
398 "#{field} #{error}"
399 end)
400 |> Enum.join("; ")
401
402 message =
403 String.replace(
404 message,
405 "ap_id has already been taken",
406 "nickname has already been taken"
407 )
408
409 conn
410 |> put_status(:forbidden)
411 |> put_flash(:error, "Error: #{message}.")
412 |> registration_details(params)
413
414 _ ->
415 {:register, :generic_error}
416 end
417 end
418
419 defp do_create_authorization(
420 %Plug.Conn{} = conn,
421 %{
422 "authorization" =>
423 %{
424 "client_id" => client_id,
425 "redirect_uri" => redirect_uri
426 } = auth_attrs
427 },
428 user \\ nil
429 ) do
430 with {_, {:ok, %User{} = user}} <-
431 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
432 %App{} = app <- Repo.get_by(App, client_id: client_id),
433 true <- redirect_uri in String.split(app.redirect_uris),
434 {:ok, scopes} <- validate_scopes(app, auth_attrs),
435 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
436 Authorization.create_authorization(app, user, scopes)
437 end
438 end
439
440 # Special case: Local MastodonFE
441 defp redirect_uri(%Plug.Conn{} = conn, "."), do: mastodon_api_url(conn, :login)
442
443 defp redirect_uri(%Plug.Conn{}, redirect_uri), do: redirect_uri
444
445 defp get_session_registration_id(%Plug.Conn{} = conn), do: get_session(conn, :registration_id)
446
447 defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
448 do: put_session(conn, :registration_id, registration_id)
449
450 @spec validate_scopes(App.t(), map()) ::
451 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
452 defp validate_scopes(app, params) do
453 params
454 |> Scopes.fetch_scopes(app.scopes)
455 |> Scopes.validates(app.scopes)
456 end
457
458 def default_redirect_uri(%App{} = app) do
459 app.redirect_uris
460 |> String.split()
461 |> Enum.at(0)
462 end
463
464 defp render_invalid_credentials_error(conn) do
465 render_error(conn, :bad_request, "Invalid credentials")
466 end
467 end