[#1427] Fixes / improvements of admin scopes support. Added tests.
[akkoma] / lib / pleroma / plugs / oauth_scopes_plug.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.Plugs.OAuthScopesPlug do
6 import Plug.Conn
7 import Pleroma.Web.Gettext
8
9 alias Pleroma.Config
10 alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
11
12 @behaviour Plug
13
14 def init(%{scopes: _} = options), do: options
15
16 def call(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
17 op = options[:op] || :|
18 token = assigns[:token]
19
20 scopes =
21 if options[:admin] do
22 Config.oauth_admin_scopes(scopes)
23 else
24 scopes
25 end
26
27 matched_scopes = token && filter_descendants(scopes, token.scopes)
28
29 cond do
30 is_nil(token) ->
31 maybe_perform_instance_privacy_check(conn, options)
32
33 op == :| && Enum.any?(matched_scopes) ->
34 conn
35
36 op == :& && matched_scopes == scopes ->
37 conn
38
39 options[:fallback] == :proceed_unauthenticated ->
40 conn
41 |> assign(:user, nil)
42 |> assign(:token, nil)
43 |> maybe_perform_instance_privacy_check(options)
44
45 true ->
46 missing_scopes = scopes -- matched_scopes
47 permissions = Enum.join(missing_scopes, " #{op} ")
48
49 error_message =
50 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
51
52 conn
53 |> put_resp_content_type("application/json")
54 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
55 |> halt()
56 end
57 end
58
59 @doc "Filters descendants of supported scopes"
60 def filter_descendants(scopes, supported_scopes) do
61 Enum.filter(
62 scopes,
63 fn scope ->
64 Enum.find(
65 supported_scopes,
66 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
67 )
68 end
69 )
70 end
71
72 defp maybe_perform_instance_privacy_check(%Plug.Conn{} = conn, options) do
73 if options[:skip_instance_privacy_check] do
74 conn
75 else
76 EnsurePublicOrAuthenticatedPlug.call(conn, [])
77 end
78 end
79 end