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