[#923] OAuth consumer params handling refactoring.
[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
17 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
18
19 if Pleroma.Config.oauth_consumer_enabled?(), do: plug(Ueberauth)
20
21 plug(:fetch_session)
22 plug(:fetch_flash)
23
24 action_fallback(Pleroma.Web.OAuth.FallbackController)
25
26 def authorize(%{assigns: %{token: %Token{} = token}} = conn, params) do
27 if ControllerHelper.truthy_param?(params["force_login"]) do
28 do_authorize(conn, params)
29 else
30 redirect_uri =
31 if is_binary(params["redirect_uri"]) do
32 params["redirect_uri"]
33 else
34 app = Repo.preload(token, :app).app
35
36 app.redirect_uris
37 |> String.split()
38 |> Enum.at(0)
39 end
40
41 redirect(conn, external: redirect_uri(conn, redirect_uri))
42 end
43 end
44
45 def authorize(conn, params), do: do_authorize(conn, params)
46
47 defp do_authorize(conn, %{"authorization" => auth_attrs}) do
48 app = Repo.get_by(App, client_id: auth_attrs["client_id"])
49 available_scopes = (app && app.scopes) || []
50 scopes = oauth_scopes(auth_attrs, nil) || available_scopes
51
52 render(conn, Authenticator.auth_template(), %{
53 response_type: auth_attrs["response_type"],
54 client_id: auth_attrs["client_id"],
55 available_scopes: available_scopes,
56 scopes: scopes,
57 redirect_uri: auth_attrs["redirect_uri"],
58 state: auth_attrs["state"],
59 params: auth_attrs
60 })
61 end
62
63 defp do_authorize(conn, auth_attrs), do: do_authorize(conn, %{"authorization" => auth_attrs})
64
65 def create_authorization(
66 conn,
67 %{"authorization" => _} = params,
68 opts \\ []
69 ) do
70 with {:ok, auth} <- do_create_authorization(conn, params, opts[:user]) do
71 after_create_authorization(conn, auth, params)
72 else
73 error ->
74 handle_create_authorization_error(conn, error, params)
75 end
76 end
77
78 def after_create_authorization(conn, auth, %{
79 "authorization" => %{"redirect_uri" => redirect_uri} = auth_attrs
80 }) do
81 redirect_uri = redirect_uri(conn, redirect_uri)
82
83 if redirect_uri == "urn:ietf:wg:oauth:2.0:oob" do
84 render(conn, "results.html", %{
85 auth: auth
86 })
87 else
88 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
89 url = "#{redirect_uri}#{connector}"
90 url_params = %{:code => auth.token}
91
92 url_params =
93 if auth_attrs["state"] do
94 Map.put(url_params, :state, auth_attrs["state"])
95 else
96 url_params
97 end
98
99 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
100
101 redirect(conn, external: url)
102 end
103 end
104
105 defp handle_create_authorization_error(
106 conn,
107 {scopes_issue, _},
108 %{"authorization" => _} = params
109 )
110 when scopes_issue in [:unsupported_scopes, :missing_scopes] do
111 # Per https://github.com/tootsuite/mastodon/blob/
112 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L39
113 conn
114 |> put_flash(:error, "This action is outside the authorized scopes")
115 |> put_status(:unauthorized)
116 |> authorize(params)
117 end
118
119 defp handle_create_authorization_error(
120 conn,
121 {:auth_active, false},
122 %{"authorization" => _} = params
123 ) do
124 # Per https://github.com/tootsuite/mastodon/blob/
125 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
126 conn
127 |> put_flash(:error, "Your login is missing a confirmed e-mail address")
128 |> put_status(:forbidden)
129 |> authorize(params)
130 end
131
132 defp handle_create_authorization_error(conn, error, %{"authorization" => _}) do
133 Authenticator.handle_error(conn, error)
134 end
135
136 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
137 with %App{} = app <- get_app_from_request(conn, params),
138 fixed_token = fix_padding(params["code"]),
139 %Authorization{} = auth <-
140 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
141 %User{} = user <- User.get_by_id(auth.user_id),
142 {:ok, token} <- Token.exchange_token(app, auth),
143 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
144 response = %{
145 token_type: "Bearer",
146 access_token: token.token,
147 refresh_token: token.refresh_token,
148 created_at: DateTime.to_unix(inserted_at),
149 expires_in: 60 * 10,
150 scope: Enum.join(token.scopes, " "),
151 me: user.ap_id
152 }
153
154 json(conn, response)
155 else
156 _error ->
157 put_status(conn, 400)
158 |> json(%{error: "Invalid credentials"})
159 end
160 end
161
162 def token_exchange(
163 conn,
164 %{"grant_type" => "password"} = params
165 ) do
166 with {_, {:ok, %User{} = user}} <- {:get_user, Authenticator.get_user(conn)},
167 %App{} = app <- get_app_from_request(conn, params),
168 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
169 {:user_active, true} <- {:user_active, !user.info.deactivated},
170 scopes <- oauth_scopes(params, app.scopes),
171 [] <- scopes -- app.scopes,
172 true <- Enum.any?(scopes),
173 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
174 {:ok, token} <- Token.exchange_token(app, auth) do
175 response = %{
176 token_type: "Bearer",
177 access_token: token.token,
178 refresh_token: token.refresh_token,
179 expires_in: 60 * 10,
180 scope: Enum.join(token.scopes, " "),
181 me: user.ap_id
182 }
183
184 json(conn, response)
185 else
186 {:auth_active, false} ->
187 # Per https://github.com/tootsuite/mastodon/blob/
188 # 51e154f5e87968d6bb115e053689767ab33e80cd/app/controllers/api/base_controller.rb#L76
189 conn
190 |> put_status(:forbidden)
191 |> json(%{error: "Your login is missing a confirmed e-mail address"})
192
193 {:user_active, false} ->
194 conn
195 |> put_status(:forbidden)
196 |> json(%{error: "Your account is currently disabled"})
197
198 _error ->
199 put_status(conn, 400)
200 |> json(%{error: "Invalid credentials"})
201 end
202 end
203
204 def token_exchange(
205 conn,
206 %{"grant_type" => "password", "name" => name, "password" => _password} = params
207 ) do
208 params =
209 params
210 |> Map.delete("name")
211 |> Map.put("username", name)
212
213 token_exchange(conn, params)
214 end
215
216 def token_revoke(conn, %{"token" => token} = params) do
217 with %App{} = app <- get_app_from_request(conn, params),
218 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
219 {:ok, %Token{}} <- Repo.delete(token) do
220 json(conn, %{})
221 else
222 _error ->
223 # RFC 7009: invalid tokens [in the request] do not cause an error response
224 json(conn, %{})
225 end
226 end
227
228 @doc "Prepares OAuth request to provider for Ueberauth"
229 def prepare_request(conn, %{"provider" => provider, "authorization" => auth_attrs}) do
230 scope =
231 oauth_scopes(auth_attrs, [])
232 |> Enum.join(" ")
233
234 state =
235 auth_attrs
236 |> Map.delete("scopes")
237 |> Map.put("scope", scope)
238 |> Poison.encode!()
239
240 params =
241 auth_attrs
242 |> Map.drop(~w(scope scopes client_id redirect_uri))
243 |> Map.put("state", state)
244
245 # Handing the request to Ueberauth
246 redirect(conn, to: o_auth_path(conn, :request, provider, params))
247 end
248
249 def request(conn, params) do
250 message =
251 if params["provider"] do
252 "Unsupported OAuth provider: #{params["provider"]}."
253 else
254 "Bad OAuth request."
255 end
256
257 conn
258 |> put_flash(:error, message)
259 |> redirect(to: "/")
260 end
261
262 def callback(%{assigns: %{ueberauth_failure: failure}} = conn, params) do
263 params = callback_params(params)
264 messages = for e <- Map.get(failure, :errors, []), do: e.message
265 message = Enum.join(messages, "; ")
266
267 conn
268 |> put_flash(:error, "Failed to authenticate: #{message}.")
269 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
270 end
271
272 def callback(conn, params) do
273 params = callback_params(params)
274
275 with {:ok, registration} <- Authenticator.get_registration(conn) do
276 user = Repo.preload(registration, :user).user
277 auth_attrs = Map.take(params, ~w(client_id redirect_uri scope scopes state))
278
279 if user do
280 create_authorization(
281 conn,
282 %{"authorization" => auth_attrs},
283 user: user
284 )
285 else
286 registration_params =
287 Map.merge(auth_attrs, %{
288 "nickname" => Registration.nickname(registration),
289 "email" => Registration.email(registration)
290 })
291
292 conn
293 |> put_session(:registration_id, registration.id)
294 |> registration_details(%{"authorization" => registration_params})
295 end
296 else
297 _ ->
298 conn
299 |> put_flash(:error, "Failed to set up user account.")
300 |> redirect(external: redirect_uri(conn, params["redirect_uri"]))
301 end
302 end
303
304 defp callback_params(%{"state" => state} = params) do
305 Map.merge(params, Poison.decode!(state))
306 end
307
308 def registration_details(conn, %{"authorization" => auth_attrs}) do
309 render(conn, "register.html", %{
310 client_id: auth_attrs["client_id"],
311 redirect_uri: auth_attrs["redirect_uri"],
312 state: auth_attrs["state"],
313 scopes: oauth_scopes(auth_attrs, []),
314 nickname: auth_attrs["nickname"],
315 email: auth_attrs["email"]
316 })
317 end
318
319 def register(conn, %{"authorization" => _, "op" => "connect"} = params) do
320 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
321 %Registration{} = registration <- Repo.get(Registration, registration_id),
322 {_, {:ok, auth}} <-
323 {:create_authorization, do_create_authorization(conn, params)},
324 %User{} = user <- Repo.preload(auth, :user).user,
325 {:ok, _updated_registration} <- Registration.bind_to_user(registration, user) do
326 conn
327 |> put_session_registration_id(nil)
328 |> after_create_authorization(auth, params)
329 else
330 {:create_authorization, error} ->
331 {:register, handle_create_authorization_error(conn, error, params)}
332
333 _ ->
334 {:register, :generic_error}
335 end
336 end
337
338 def register(conn, %{"authorization" => _, "op" => "register"} = params) do
339 with registration_id when not is_nil(registration_id) <- get_session_registration_id(conn),
340 %Registration{} = registration <- Repo.get(Registration, registration_id),
341 {:ok, user} <- Authenticator.create_from_registration(conn, registration) do
342 conn
343 |> put_session_registration_id(nil)
344 |> create_authorization(
345 params,
346 user: user
347 )
348 else
349 {:error, changeset} ->
350 message =
351 Enum.map(changeset.errors, fn {field, {error, _}} ->
352 "#{field} #{error}"
353 end)
354 |> Enum.join("; ")
355
356 message =
357 String.replace(
358 message,
359 "ap_id has already been taken",
360 "nickname has already been taken"
361 )
362
363 conn
364 |> put_status(:forbidden)
365 |> put_flash(:error, "Error: #{message}.")
366 |> registration_details(params)
367
368 _ ->
369 {:register, :generic_error}
370 end
371 end
372
373 defp do_create_authorization(
374 conn,
375 %{
376 "authorization" =>
377 %{
378 "client_id" => client_id,
379 "redirect_uri" => redirect_uri
380 } = auth_attrs
381 },
382 user \\ nil
383 ) do
384 with {_, {:ok, %User{} = user}} <-
385 {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
386 %App{} = app <- Repo.get_by(App, client_id: client_id),
387 true <- redirect_uri in String.split(app.redirect_uris),
388 scopes <- oauth_scopes(auth_attrs, []),
389 {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes},
390 # Note: `scope` param is intentionally not optional in this context
391 {:missing_scopes, false} <- {:missing_scopes, scopes == []},
392 {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
393 Authorization.create_authorization(app, user, scopes)
394 end
395 end
396
397 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
398 # decoding it. Investigate sometime.
399 defp fix_padding(token) do
400 token
401 |> URI.decode()
402 |> Base.url_decode64!(padding: false)
403 |> Base.url_encode64(padding: false)
404 end
405
406 defp get_app_from_request(conn, params) do
407 # Per RFC 6749, HTTP Basic is preferred to body params
408 {client_id, client_secret} =
409 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
410 {:ok, decoded} <- Base.decode64(encoded),
411 [id, secret] <-
412 String.split(decoded, ":")
413 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
414 {id, secret}
415 else
416 _ -> {params["client_id"], params["client_secret"]}
417 end
418
419 if client_id && client_secret do
420 Repo.get_by(
421 App,
422 client_id: client_id,
423 client_secret: client_secret
424 )
425 else
426 nil
427 end
428 end
429
430 # Special case: Local MastodonFE
431 defp redirect_uri(conn, "."), do: mastodon_api_url(conn, :login)
432
433 defp redirect_uri(_conn, redirect_uri), do: redirect_uri
434
435 defp get_session_registration_id(conn), do: get_session(conn, :registration_id)
436
437 defp put_session_registration_id(conn, registration_id),
438 do: put_session(conn, :registration_id, registration_id)
439 end