Merge branch 'feature/federator-behaviours' 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.Registration
9 alias Pleroma.Repo
10 alias Pleroma.User
11 alias Pleroma.Web.Auth.Authenticator
12 alias Pleroma.Web.ControllerHelper
13 alias Pleroma.Web.OAuth.App
14 alias Pleroma.Web.OAuth.Authorization
15 alias Pleroma.Web.OAuth.Token
16 alias Pleroma.Web.OAuth.Token.Strategy.RefreshToken
17 alias Pleroma.Web.OAuth.Token.Strategy.Revoke, as: RevokeToken
18 alias Pleroma.Web.OAuth.Scopes
19
20 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
21
22 @expires_in Pleroma.Config.get([:oauth2, :token_expires_in], 600)
23
24 plug(:fetch_session)
25 plug(:fetch_flash)
26
27 action_fallback(Pleroma.Web.OAuth.FallbackController)
28
29 # Note: this definition is only called from error-handling methods with `conn.params` as 2nd arg
30 def authorize(conn, %{"authorization" => _} = params) do
31 {auth_attrs, params} = Map.pop(params, "authorization")
32 authorize(conn, Map.merge(params, auth_attrs))
33 end
34
35 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
36 if ControllerHelper.truthy_param?(params["force_login"]) do
37 do_authorize(conn, params)
38 else
39 redirect_uri =
40 if is_binary(params["redirect_uri"]) do
41 params["redirect_uri"]
42 else
43 app = Repo.preload(token, :app).app
44
45 app.redirect_uris
46 |> String.split()
47 |> Enum.at(0)
48 end
49
50 redirect(conn, external: redirect_uri(conn, redirect_uri))
51 end
52 end
53
54 def authorize(conn, params), do: do_authorize(conn, params)
55
56 defp do_authorize(conn, params) do
57 app = Repo.get_by(App, client_id: params["client_id"])
58 available_scopes = (app && app.scopes) || []
59 scopes = Scopes.fetch_scopes(params, available_scopes)
60
61 # Note: `params` might differ from `conn.params`; use `@params` not `@conn.params` in template
62 render(conn, Authenticator.auth_template(), %{
63 response_type: params["response_type"],
64 client_id: params["client_id"],
65 available_scopes: available_scopes,
66 scopes: scopes,
67 redirect_uri: params["redirect_uri"],
68 state: params["state"],
69 params: params
70 })
71 end
72
73 def create_authorization(
74 conn,
75 %{"authorization" => _} = params,
76 opts \\ []
77 ) do
78 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
79 after_create_authorization(conn, auth, params)
80 else
81 error ->
82 handle_create_authorization_error(conn, error, params)
83 end
84 end
85
86 def after_create_authorization(conn, auth, %{
87 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
88 }) do
89 redirect_uri = redirect_uri(conn, redirect_uri)
90
91 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
92 render(conn, "results.html", %{
93 auth: auth
94 })
95 else
96 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
97 url = "#{redirect_uri}#{connector}"
98 url_params = %{:code => auth.token}
99
100 url_params =
101 if auth_attrs["state"] do
102 Map.put(url_params, :state, auth_attrs["state"])
103 else
104 url_params
105 end
106
107 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
108
109 redirect(conn, external: url)
110 end
111 end
112
113 defp handle_create_authorization_error(
114 conn,
115 {:error, scopes_issue},
116 %{"authorization" => _} = params
117 )
118 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
119 # Per https://github.com/tootsuite/mastodon/blob/
120 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
121 conn
122 |> put_flash(:error, "This action is outside the authorized scopes")
123 |> put_status(:unauthorized)
124 |> authorize(params)
125 end
126
127 defp handle_create_authorization_error(
128 conn,
129 {:auth_active, false},
130 %{"authorization" => _} = params
131 ) do
132 # Per https://github.com/tootsuite/mastodon/blob/
133 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
134 conn
135 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
136 |> put_status(:forbidden)
137 |> authorize(params)
138 end
139
140 defp handle_create_authorization_error(conn, error, %{"authorization" => _}) do
141 Authenticator.handle_error(conn, error)
142 end
143
144 @doc "Renew access_token with refresh_token"
145 def token_exchange(
146 conn,
147 %{"grant_type" => "refresh_token", "refresh_token" => token} = params
148 ) do
149 with %App{} = app <- get_app_from_request(conn, params),
150 {:ok, %{user: user} = token} <- Token.get_by_refresh_token(app, token),
151 {:ok, token} <- RefreshToken.grant(token) do
152 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
153
154 json(conn, response_token(user, token, response_attrs))
155 else
156 _error ->
157 put_status(conn, 400)
158 |> json(%{error: "Invalid credentials"})
159 end
160 end
161
162 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
163 with %App{} = app <- get_app_from_request(conn, params),
164 fixed_token = Token.Utils.fix_padding(params["code"]),
165 {:ok, auth} <- Authorization.get_by_token(app, fixed_token),
166 %User{} = user <- User.get_cached_by_id(auth.user_id),
167 {:ok, token} <- Token.exchange_token(app, auth) do
168 response_attrs = %{created_at: Token.Utils.format_created_at(token)}
169
170 json(conn, response_token(user, token, response_attrs))
171 else
172 _error ->
173 put_status(conn, 400)
174 |> json(%{error: "Invalid credentials"})
175 end
176 end
177
178 def token_exchange(
179 conn,
180 %{"grant_type" => "password"} = params
181 ) do
182 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
183 %App{} = app <- get_app_from_request(conn, params),
184 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
185 {:user_active, true} <- {:user_active, !user.info.deactivated},
186 {:ok, scopes} <- validate_scopes(app, params),
187 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
188 {:ok, token} <- Token.exchange_token(app, auth) do
189 json(conn, response_token(user, token))
190 else
191 {:auth_active, false} ->
192 # Per https://github.com/tootsuite/mastodon/blob/
193 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
194 conn
195 |> put_status(:forbidden)
196 |> json(%{error: "Your login is missing a confirmed e-mail address"})
197
198 {:user_active, false} ->
199 conn
200 |> put_status(:forbidden)
201 |> json(%{error: "Your account is currently disabled"})
202
203 _error ->
204 put_status(conn, 400)
205 |> json(%{error: "Invalid credentials"})
206 end
207 end
208
209 def token_exchange(
210 conn,
211 %{"grant_type" => "password", "name" => name, "password" => _password} = params
212 ) do
213 params =
214 params
215 |> Map.delete("name")
216 |> Map.put("username", name)
217
218 token_exchange(conn, params)
219 end
220
221 def token_exchange(conn, %{"grant_type" => "client_credentials"} = params) do
222 with %App{} = app <- get_app_from_request(conn, params),
223 {:ok, auth} <- Authorization.create_authorization(app, %User{}),
224 {:ok, token} <- Token.exchange_token(app, auth),
225 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
226 response = %{
227 token_type: "Bearer",
228 access_token: token.token,
229 refresh_token: token.refresh_token,
230 created_at: DateTime.to_unix(inserted_at),
231 expires_in: 60 * 10,
232 scope: Enum.join(token.scopes, " ")
233 }
234
235 json(conn, response)
236 else
237 _error ->
238 put_status(conn, 400)
239 |> json(%{error: "Invalid credentials"})
240 end
241 end
242
243 # Bad request
244 def token_exchange(conn, params), do: bad_request(conn, params)
245
246 def token_revoke(conn, %{"token" => _token} = params) do
247 with %App{} = app <- get_app_from_request(conn, params),
248 {:ok, _token} <- RevokeToken.revoke(app, params) do
249 json(conn, %{})
250 else
251 _error ->
252 # RFC 7009: invalid tokens [in the request] do not cause an error response
253 json(conn, %{})
254 end
255 end
256
257 def token_revoke(conn, params), do: bad_request(conn, params)
258
259 # Response for bad request
260 defp bad_request(conn, _) do
261 conn
262 |> put_status(500)
263 |> json(%{error: "Bad request"})
264 end
265
266 @doc "Prepares OAuth request to provider for Ueberauth"
267 def prepare_request(conn, %{"provider" => provider, "authorization" => auth_attrs}) do
268 scope =
269 auth_attrs
270 |> Scopes.fetch_scopes([])
271 |> Scopes.to_string()
272
273 state =
274 auth_attrs
275 |> Map.delete("scopes")
276 |> Map.put("scope", scope)
277 |> Poison.encode!()
278
279 params =
280 auth_attrs
281 |> Map.drop(~w(scope scopes client_id redirect_uri))
282 |> Map.put("state", state)
283
284 # Handing the request to Ueberauth
285 redirect(conn, to: o_auth_path(conn, :request, provider, params))
286 end
287
288 def request(conn, params) do
289 message =
290 if params["provider"] do
291 "Unsupported OAuth provider: #{params["provider"]}."
292 else
293 "Bad OAuth request."
294 end
295
296 conn
297 |> put_flash(:error, message)
298 |> redirect(to: "/")
299 end
300
301 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
302 params = callback_params(params)
303 messages = for e <- Map.get(failure, :errors, []), do: e.message
304 message = Enum.join(messages, "; ")
305
306 conn
307 |> put_flash(:error, "Failed to authenticate: #{message}.")
308 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
309 end
310
311 def callback(conn, params) do
312 params = callback_params(params)
313
314 with {:ok, registration} <- Authenticator.get_registration(conn) do
315 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
316
317 case Repo.get_assoc(registration, :user) do
318 {:ok, user} ->
319 create_authorization(conn, %{"authorization" => auth_attrs}, user: user)
320
321 _ ->
322 registration_params =
323 Map.merge(auth_attrs, %{
324 "nickname" => Registration.nickname(registration),
325 "email" => Registration.email(registration)
326 })
327
328 conn
329 |> put_session(:registration_id, registration.id)
330 |> registration_details(%{"authorization" => registration_params})
331 end
332 else
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, Poison.decode!(state))
342 end
343
344 def registration_details(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(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(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 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 defp get_app_from_request(conn, params) do
431 conn
432 |> fetch_client_credentials(params)
433 |> fetch_client
434 end
435
436 defp fetch_client({id, secret}) when is_binary(id) and is_binary(secret) do
437 Repo.get_by(App, client_id: id, client_secret: secret)
438 end
439
440 defp fetch_client({_id, _secret}), do: nil
441
442 defp fetch_client_credentials(conn, params) do
443 # Per RFC 6749, HTTP Basic is preferred to body params
444 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
445 {:ok, decoded} <- Base.decode64(encoded),
446 [id, secret] <-
447 Enum.map(
448 String.split(decoded, ":"),
449 fn s -> URI.decode_www_form(s) end
450 ) do
451 {id, secret}
452 else
453 _ -> {params["client_id"], params["client_secret"]}
454 end
455 end
456
457 # Special case: Local MastodonFE
458 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
459
460 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
461
462 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
463
464 defp put_session_registration_id(conn, registration_id),
465 do: put_session(conn, :registration_id, registration_id)
466
467 defp response_token(%User{} = user, token, opts \\ %{}) do
468 %{
469 token_type: "Bearer",
470 access_token: token.token,
471 refresh_token: token.refresh_token,
472 expires_in: @expires_in,
473 scope: Enum.join(token.scopes, " "),
474 me: user.ap_id
475 }
476 |> Map.merge(opts)
477 end
478
479 @spec validate_scopes(App.t(), map()) ::
480 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
481 defp validate_scopes(app, params) do
482 params
483 |> Scopes.fetch_scopes(app.scopes)
484 |> Scopes.validates(app.scopes)
485 end
486 end