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