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