Merge branch 'chore/fast_sanitize_bump' into 'develop'
[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 = transform_scopes(scopes, options)
21 matched_scopes = token && filter_descendants(scopes, token.scopes)
22
23 cond do
24 is_nil(token) ->
25 maybe_perform_instance_privacy_check(conn, options)
26
27 op == :| && Enum.any?(matched_scopes) ->
28 conn
29
30 op == :& && matched_scopes == scopes ->
31 conn
32
33 options[:fallback] == :proceed_unauthenticated ->
34 conn
35 |> assign(:user, nil)
36 |> assign(:token, nil)
37 |> maybe_perform_instance_privacy_check(options)
38
39 true ->
40 missing_scopes = scopes -- matched_scopes
41 permissions = Enum.join(missing_scopes, " #{op} ")
42
43 error_message =
44 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
45
46 conn
47 |> put_resp_content_type("application/json")
48 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
49 |> halt()
50 end
51 end
52
53 @doc "Filters descendants of supported scopes"
54 def filter_descendants(scopes, supported_scopes) do
55 Enum.filter(
56 scopes,
57 fn scope ->
58 Enum.find(
59 supported_scopes,
60 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
61 )
62 end
63 )
64 end
65
66 @doc "Transforms scopes by applying supported options (e.g. :admin)"
67 def transform_scopes(scopes, options) do
68 if options[:admin] do
69 Config.oauth_admin_scopes(scopes)
70 else
71 scopes
72 end
73 end
74
75 defp maybe_perform_instance_privacy_check(%Plug.Conn{} = conn, options) do
76 if options[:skip_instance_privacy_check] do
77 conn
78 else
79 EnsurePublicOrAuthenticatedPlug.call(conn, [])
80 end
81 end
82 end