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