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