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