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