do not allow non-admins to register tokens with admin scopes
[akkoma] / lib / pleroma / web / o_auth / scopes.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.OAuth.Scopes do
6 @moduledoc """
7 Functions for dealing with scopes.
8 """
9
10 alias Pleroma.Web.Plugs.OAuthScopesPlug
11
12 @doc """
13 Fetch scopes from request params.
14
15 Note: `scopes` is used by Mastodon — supporting it but sticking to
16 OAuth's standard `scope` wherever we control it
17 """
18 @spec fetch_scopes(map() | struct(), list()) :: list()
19
20 def fetch_scopes(params, default) do
21 parse_scopes(params["scope"] || params["scopes"] || params[:scopes], default)
22 end
23
24 def parse_scopes(scopes, _default) when is_list(scopes) do
25 Enum.filter(scopes, &(&1 not in [nil, ""]))
26 end
27
28 def parse_scopes(scopes, default) when is_binary(scopes) do
29 scopes
30 |> to_list
31 |> parse_scopes(default)
32 end
33
34 def parse_scopes(_, default) do
35 default
36 end
37
38 @doc """
39 Convert scopes string to list
40 """
41 @spec to_list(binary()) :: [binary()]
42 def to_list(nil), do: []
43
44 def to_list(str) do
45 str
46 |> String.trim()
47 |> String.split(~r/[\s,]+/)
48 end
49
50 @doc """
51 Convert scopes list to string
52 """
53 @spec to_string(list()) :: binary()
54 def to_string(scopes), do: Enum.join(scopes, " ")
55
56 @doc """
57 Validates scopes.
58 """
59 @spec validate(list() | nil, list(), Pleroma.User.t()) ::
60 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes, :user_is_not_an_admin}
61 def validate(blank_scopes, _app_scopes, _user) when blank_scopes in [nil, []],
62 do: {:error, :missing_scopes}
63
64 def validate(scopes, app_scopes, %Pleroma.User{is_admin: is_admin}) do
65 if !is_admin && contains_admin_scopes?(scopes) do
66 {:error, :user_is_not_an_admin}
67 else
68 validate_scopes_are_supported(scopes, app_scopes)
69 end
70 end
71
72 defp validate_scopes_are_supported(scopes, app_scopes) do
73 case OAuthScopesPlug.filter_descendants(scopes, app_scopes) do
74 ^scopes -> {:ok, scopes}
75 _ -> {:error, :unsupported_scopes}
76 end
77 end
78
79 def contains_admin_scopes?(scopes) do
80 scopes
81 |> OAuthScopesPlug.filter_descendants(["admin"])
82 |> Enum.any?()
83 end
84 end