[#468] Defined OAuth restrictions for all applicable routes.
[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.Web.OAuth.{Authorization, Token, App}
9 alias Pleroma.{Repo, User}
10 alias Comeonin.Pbkdf2
11
12 import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2]
13
14 plug(:fetch_session)
15 plug(:fetch_flash)
16
17 action_fallback(Pleroma.Web.OAuth.FallbackController)
18
19 def authorize(conn, params) do
20 params_scopes = oauth_scopes(params, nil)
21
22 scopes =
23 if params_scopes do
24 params_scopes
25 else
26 app = Repo.get_by(App, client_id: params["client_id"])
27 app && app.scopes
28 end
29
30 render(conn, "show.html", %{
31 response_type: params["response_type"],
32 client_id: params["client_id"],
33 scopes: scopes || [],
34 redirect_uri: params["redirect_uri"],
35 state: params["state"]
36 })
37 end
38
39 def create_authorization(conn, %{
40 "authorization" =>
41 %{
42 "name" => name,
43 "password" => password,
44 "client_id" => client_id,
45 "redirect_uri" => redirect_uri
46 } = auth_params
47 }) do
48 with %User{} = user <- User.get_by_nickname_or_email(name),
49 true <- Pbkdf2.checkpw(password, user.password_hash),
50 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
51 %App{} = app <- Repo.get_by(App, client_id: client_id),
52 true <- redirect_uri in String.split(app.redirect_uris),
53 scopes <- oauth_scopes(auth_params, []),
54 [] <- scopes -- app.scopes,
55 true <- Enum.any?(scopes),
56 {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do
57 # Special case: Local MastodonFE.
58 redirect_uri =
59 if redirect_uri == "." do
60 mastodon_api_url(conn, :login)
61 else
62 redirect_uri
63 end
64
65 cond do
66 redirect_uri == "urn:ietf:wg:oauth:2.0:oob" ->
67 render(conn, "results.html", %{
68 auth: auth
69 })
70
71 true ->
72 connector = if String.contains?(redirect_uri, "?"), do: "&", else: "?"
73 url = "#{redirect_uri}#{connector}"
74 url_params = %{:code => auth.token}
75
76 url_params =
77 if auth_params["state"] do
78 Map.put(url_params, :state, auth_params["state"])
79 else
80 url_params
81 end
82
83 url = "#{url}#{Plug.Conn.Query.encode(url_params)}"
84
85 redirect(conn, external: url)
86 end
87 else
88 res ->
89 msg =
90 if res == {:auth_active, false},
91 do: "Account confirmation pending",
92 else: "Invalid Username/Password/Permissions"
93
94 app = Repo.get_by(App, client_id: client_id)
95 available_scopes = (app && app.scopes) || oauth_scopes(auth_params, [])
96 scope_param = Enum.join(available_scopes, " ")
97
98 conn
99 |> put_flash(:error, msg)
100 |> put_status(:unauthorized)
101 |> authorize(Map.merge(auth_params, %{"scope" => scope_param}))
102 end
103 end
104
105 def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do
106 with %App{} = app <- get_app_from_request(conn, params),
107 fixed_token = fix_padding(params["code"]),
108 %Authorization{} = auth <-
109 Repo.get_by(Authorization, token: fixed_token, app_id: app.id),
110 {:ok, token} <- Token.exchange_token(app, auth),
111 {:ok, inserted_at} <- DateTime.from_naive(token.inserted_at, "Etc/UTC") do
112 response = %{
113 token_type: "Bearer",
114 access_token: token.token,
115 refresh_token: token.refresh_token,
116 created_at: DateTime.to_unix(inserted_at),
117 expires_in: 60 * 10,
118 scope: Enum.join(token.scopes)
119 }
120
121 json(conn, response)
122 else
123 _error ->
124 put_status(conn, 400)
125 |> json(%{error: "Invalid credentials"})
126 end
127 end
128
129 def token_exchange(
130 conn,
131 %{"grant_type" => "password", "username" => name, "password" => password} = params
132 ) do
133 with %App{} = app <- get_app_from_request(conn, params),
134 %User{} = user <- User.get_by_nickname_or_email(name),
135 true <- Pbkdf2.checkpw(password, user.password_hash),
136 {:auth_active, true} <- {:auth_active, User.auth_active?(user)},
137 scopes <- oauth_scopes(params, app.scopes),
138 [] <- scopes -- app.scopes,
139 true <- Enum.any?(scopes),
140 {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
141 {:ok, token} <- Token.exchange_token(app, auth) do
142 response = %{
143 token_type: "Bearer",
144 access_token: token.token,
145 refresh_token: token.refresh_token,
146 expires_in: 60 * 10,
147 scope: Enum.join(token.scopes, " ")
148 }
149
150 json(conn, response)
151 else
152 {:auth_active, false} ->
153 conn
154 |> put_status(:forbidden)
155 |> json(%{error: "Account confirmation pending"})
156
157 _error ->
158 put_status(conn, 400)
159 |> json(%{error: "Invalid credentials"})
160 end
161 end
162
163 def token_exchange(
164 conn,
165 %{"grant_type" => "password", "name" => name, "password" => _password} = params
166 ) do
167 params =
168 params
169 |> Map.delete("name")
170 |> Map.put("username", name)
171
172 token_exchange(conn, params)
173 end
174
175 def token_revoke(conn, %{"token" => token} = params) do
176 with %App{} = app <- get_app_from_request(conn, params),
177 %Token{} = token <- Repo.get_by(Token, token: token, app_id: app.id),
178 {:ok, %Token{}} <- Repo.delete(token) do
179 json(conn, %{})
180 else
181 _error ->
182 # RFC 7009: invalid tokens [in the request] do not cause an error response
183 json(conn, %{})
184 end
185 end
186
187 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
188 # decoding it. Investigate sometime.
189 defp fix_padding(token) do
190 token
191 |> URI.decode()
192 |> Base.url_decode64!(padding: false)
193 |> Base.url_encode64()
194 end
195
196 defp get_app_from_request(conn, params) do
197 # Per RFC 6749, HTTP Basic is preferred to body params
198 {client_id, client_secret} =
199 with ["Basic " <> encoded] <- get_req_header(conn, "authorization"),
200 {:ok, decoded} <- Base.decode64(encoded),
201 [id, secret] <-
202 String.split(decoded, ":")
203 |> Enum.map(fn s -> URI.decode_www_form(s) end) do
204 {id, secret}
205 else
206 _ -> {params["client_id"], params["client_secret"]}
207 end
208
209 if client_id && client_secret do
210 Repo.get_by(
211 App,
212 client_id: client_id,
213 client_secret: client_secret
214 )
215 else
216 nil
217 end
218 end
219 end