Merge remote-tracking branch 'remotes/origin/develop' into 1427-oauth-admin-scopes
authorIvan Tashkinov <ivantashkinov@gmail.com>
Thu, 5 Dec 2019 21:26:31 +0000 (00:26 +0300)
committerIvan Tashkinov <ivantashkinov@gmail.com>
Thu, 5 Dec 2019 21:26:31 +0000 (00:26 +0300)
12 files changed:
CHANGELOG.md
config/config.exs
config/description.exs
lib/mix/tasks/pleroma/user.ex
lib/pleroma/config.ex
lib/pleroma/plugs/user_is_admin_plug.ex
lib/pleroma/user.ex
lib/pleroma/web/admin_api/admin_api_controller.ex
lib/pleroma/web/oauth/oauth_controller.ex
lib/pleroma/web/oauth/scopes.ex
lib/pleroma/web/pleroma_api/controllers/emoji_api_controller.ex
test/web/admin_api/admin_api_controller_test.exs

index a06ea211eb9dcf6b401c799c5357d3b8d04a1093..007c6f114294ddaaac45f8b1372b47f73f85b070 100644 (file)
@@ -45,6 +45,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
 - Mix task to list all users (`mix pleroma.user list`)
 - Support for `X-Forwarded-For` and similar HTTP headers which used by reverse proxies to pass a real user IP address to the backend. Must not be enabled unless your instance is behind at least one reverse proxy (such as Nginx, Apache HTTPD or Varnish Cache).
 - MRF: New module which handles incoming posts based on their age. By default, all incoming posts that are older than 2 days will be unlisted and not shown to their followers.
+- OAuth: admin scopes support (relevant setting: `[:auth, :enforce_oauth_admin_scope_usage]`).
 <details>
   <summary>API Changes</summary>
 
index b60ffef7dc9c7ad8a3690caf0fd7896d48b75613..a8534da5417ca042eefb815985bfa5cfd1c320c9 100644 (file)
@@ -562,7 +562,10 @@ config :ueberauth,
        base_path: "/oauth",
        providers: ueberauth_providers
 
-config :pleroma, :auth, oauth_consumer_strategies: oauth_consumer_strategies
+config :pleroma,
+       :auth,
+       enforce_oauth_admin_scope_usage: false,
+       oauth_consumer_strategies: oauth_consumer_strategies
 
 config :pleroma, Pleroma.Emails.Mailer, adapter: Swoosh.Adapters.Sendmail, enabled: false
 
index 70e963399c8de149ccba0ef97f294b02d4b45ac3..45e4b43f16c3b34022aa1a517d5e9a0309d7cb9c 100644 (file)
@@ -2094,6 +2094,15 @@ config :pleroma, :config_description, [
     type: :group,
     description: "Authentication / authorization settings",
     children: [
+      %{
+        key: :enforce_oauth_admin_scope_usage,
+        type: :boolean,
+        description:
+          "OAuth admin scope requirement toggle. " <>
+            "If `true`, admin actions explicitly demand admin OAuth scope(s) presence in OAuth token " <>
+            "(client app must support admin scopes). If `false` and token doesn't have admin scope(s)," <>
+            "`is_admin` user flag grants access to admin-specific actions."
+      },
       %{
         key: :auth_template,
         type: :string,
index bc8eacda82aa3ac23774605db4d52d3f98cdcc1c..eff5191f5397d98f3b99ec6f58749c1368549d73 100644 (file)
@@ -8,7 +8,6 @@ defmodule Mix.Tasks.Pleroma.User do
   alias Ecto.Changeset
   alias Pleroma.User
   alias Pleroma.UserInviteToken
-  alias Pleroma.Web.OAuth
 
   @shortdoc "Manages Pleroma users"
   @moduledoc File.read!("docs/administration/CLI_tasks/user.md")
@@ -354,8 +353,7 @@ defmodule Mix.Tasks.Pleroma.User do
     start_pleroma()
 
     with %User{local: true} = user <- User.get_cached_by_nickname(nickname) do
-      OAuth.Token.delete_user_tokens(user)
-      OAuth.Authorization.delete_user_authorizations(user)
+      User.global_sign_out(user)
 
       shell_info("#{nickname} signed out from all apps.")
     else
@@ -393,10 +391,7 @@ defmodule Mix.Tasks.Pleroma.User do
   end
 
   defp set_admin(user, value) do
-    {:ok, user} =
-      user
-      |> Changeset.change(%{is_admin: value})
-      |> User.update_and_set_cache()
+    {:ok, user} = User.admin_api_update(user, %{is_admin: value})
 
     shell_info("Admin status of #{user.nickname}: #{user.is_admin}")
     user
index fcc0397101368e26d3eb22c5734160eaa017a205..cadab2f1567523ba5c20069f3de2a7efa3af9862 100644 (file)
@@ -65,4 +65,11 @@ defmodule Pleroma.Config do
   def oauth_consumer_strategies, do: get([:auth, :oauth_consumer_strategies], [])
 
   def oauth_consumer_enabled?, do: oauth_consumer_strategies() != []
+
+  def enforce_oauth_admin_scope_usage?, do: !!get([:auth, :enforce_oauth_admin_scope_usage])
+
+  def oauth_admin_scopes(scope) do
+    ["admin:#{scope}"] ++
+      if enforce_oauth_admin_scope_usage?(), do: [], else: [scope]
+  end
 end
index ee808f31f2f53988ff7bbfdeba61977171ad48e3..8814556f1c6b9a42735cc81e4316a1b15f9d502d 100644 (file)
@@ -5,19 +5,39 @@
 defmodule Pleroma.Plugs.UserIsAdminPlug do
   import Pleroma.Web.TranslationHelpers
   import Plug.Conn
+
   alias Pleroma.User
+  alias Pleroma.Web.OAuth
 
   def init(options) do
     options
   end
 
-  def call(%{assigns: %{user: %User{is_admin: true}}} = conn, _) do
-    conn
+  def call(%Plug.Conn{assigns: %{token: %OAuth.Token{scopes: oauth_scopes} = _token}} = conn, _) do
+    if OAuth.Scopes.contains_admin_scopes?(oauth_scopes) do
+      # Note: checking for _any_ admin scope presence, not necessarily fitting requested action.
+      #   Thus, controller must explicitly invoke OAuthScopesPlug to verify scope requirements.
+      conn
+    else
+      fail(conn)
+    end
+  end
+
+  unless Pleroma.Config.enforce_oauth_admin_scope_usage?() do
+    # To do: once AdminFE makes use of "admin" scope, disable the following func definition
+    #   (fail on no admin scope(s) in token even if `is_admin` is true)
+    def call(%Plug.Conn{assigns: %{user: %User{is_admin: true}}} = conn, _) do
+      conn
+    end
   end
 
   def call(conn, _) do
+    fail(conn)
+  end
+
+  defp fail(conn) do
     conn
-    |> render_error(:forbidden, "User is not admin.")
-    |> halt
+    |> render_error(:forbidden, "User is not an admin or OAuth admin scope is not granted.")
+    |> halt()
   end
 end
index 120cb2641252589cfdc36169451833a67d668252..7b8222ce170db28c093617640c9da6226ba2363f 100644 (file)
@@ -1727,13 +1727,27 @@ defmodule Pleroma.User do
   end
 
   def admin_api_update(user, params) do
-    user
-    |> cast(params, [
-      :is_moderator,
-      :is_admin,
-      :show_role
-    ])
-    |> update_and_set_cache()
+    changeset =
+      cast(user, params, [
+        :is_moderator,
+        :is_admin,
+        :show_role
+      ])
+
+    with {:ok, updated_user} <- update_and_set_cache(changeset) do
+      if user.is_admin && !updated_user.is_admin do
+        # Tokens & authorizations containing any admin scopes must be revoked (revoking all)
+        global_sign_out(user)
+      end
+
+      {:ok, updated_user}
+    end
+  end
+
+  @doc "Signs user out of all applications"
+  def global_sign_out(user) do
+    OAuth.Authorization.delete_user_authorizations(user)
+    OAuth.Token.delete_user_tokens(user)
   end
 
   def mascot_update(user, url) do
index 24fdc3c821920759735e7372d2bfe8a877f0c7d5..34d14710764ecbfa3602e6426215ab9dba75e012 100644 (file)
@@ -30,13 +30,13 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["read:accounts"]}
+    %{scopes: Pleroma.Config.oauth_admin_scopes("read:accounts")}
     when action in [:list_users, :user_show, :right_get, :invites]
   )
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["write:accounts"]}
+    %{scopes: Pleroma.Config.oauth_admin_scopes("write:accounts")}
     when action in [
            :get_invite_token,
            :revoke_invite,
@@ -58,35 +58,37 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["read:reports"]} when action in [:list_reports, :report_show]
+    %{scopes: Pleroma.Config.oauth_admin_scopes("read:reports")}
+    when action in [:list_reports, :report_show]
   )
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["write:reports"]}
+    %{scopes: Pleroma.Config.oauth_admin_scopes("write:reports")}
     when action in [:report_update_state, :report_respond]
   )
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["read:statuses"]} when action == :list_user_statuses
+    %{scopes: Pleroma.Config.oauth_admin_scopes("read:statuses")}
+    when action == :list_user_statuses
   )
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["write:statuses"]}
+    %{scopes: Pleroma.Config.oauth_admin_scopes("write:statuses")}
     when action in [:status_update, :status_delete]
   )
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["read"]}
+    %{scopes: Pleroma.Config.oauth_admin_scopes("read")}
     when action in [:config_show, :migrate_to_db, :migrate_from_db, :list_log]
   )
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["write"]}
+    %{scopes: Pleroma.Config.oauth_admin_scopes("write")}
     when action in [:relay_follow, :relay_unfollow, :config_update]
   )
 
index 2aee8cab2bab4c384f205c04a96c499764514e97..87acdec97c98e16e1e882413cfba3f7933d3ef65 100644 (file)
@@ -222,7 +222,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
          {:user_active, true} <- {:user_active, !user.deactivated},
          {:password_reset_pending, false} <-
            {:password_reset_pending, user.password_reset_pending},
-         {:ok, scopes} <- validate_scopes(app, params),
+         {:ok, scopes} <- validate_scopes(app, params, user),
          {:ok, auth} <- Authorization.create_authorization(app, user, scopes),
          {:ok, token} <- Token.exchange_token(app, auth) do
       json(conn, Token.Response.build(user, token))
@@ -471,7 +471,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do
            {:get_user, (user && {:ok, user}) || Authenticator.get_user(conn)},
          %App{} = app <- Repo.get_by(App, client_id: client_id),
          true <- redirect_uri in String.split(app.redirect_uris),
-         {:ok, scopes} <- validate_scopes(app, auth_attrs),
+         {:ok, scopes} <- validate_scopes(app, auth_attrs, user),
          {:auth_active, true} <- {:auth_active, User.auth_active?(user)} do
       Authorization.create_authorization(app, user, scopes)
     end
@@ -487,12 +487,12 @@ defmodule Pleroma.Web.OAuth.OAuthController do
   defp put_session_registration_id(%Plug.Conn{} = conn, registration_id),
     do: put_session(conn, :registration_id, registration_id)
 
-  @spec validate_scopes(App.t(), map()) ::
+  @spec validate_scopes(App.t(), map(), User.t()) ::
           {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
-  defp validate_scopes(app, params) do
+  defp validate_scopes(%App{} = app, params, %User{} = user) do
     params
     |> Scopes.fetch_scopes(app.scopes)
-    |> Scopes.validate(app.scopes)
+    |> Scopes.validate(app.scopes, user)
   end
 
   def default_redirect_uri(%App{} = app) do
index 48bd1440749340649309da78f20a7f36603a43bf..5e04652c2ae554667fff4376039e654be723ecb4 100644 (file)
@@ -7,6 +7,9 @@ defmodule Pleroma.Web.OAuth.Scopes do
   Functions for dealing with scopes.
   """
 
+  alias Pleroma.Plugs.OAuthScopesPlug
+  alias Pleroma.User
+
   @doc """
   Fetch scopes from request params.
 
@@ -53,15 +56,36 @@ defmodule Pleroma.Web.OAuth.Scopes do
   @doc """
   Validates scopes.
   """
-  @spec validate(list() | nil, list()) ::
+  @spec validate(list() | nil, list(), User.t()) ::
           {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
-  def validate([], _app_scopes), do: {:error, :missing_scopes}
-  def validate(nil, _app_scopes), do: {:error, :missing_scopes}
+  def validate(blank_scopes, _app_scopes, _user) when blank_scopes in [nil, []],
+    do: {:error, :missing_scopes}
 
-  def validate(scopes, app_scopes) do
-    case Pleroma.Plugs.OAuthScopesPlug.filter_descendants(scopes, app_scopes) do
+  def validate(scopes, app_scopes, %User{} = user) do
+    with {:ok, _} <- ensure_scopes_support(scopes, app_scopes),
+         {:ok, scopes} <- authorize_admin_scopes(scopes, app_scopes, user) do
+      {:ok, scopes}
+    end
+  end
+
+  defp ensure_scopes_support(scopes, app_scopes) do
+    case OAuthScopesPlug.filter_descendants(scopes, app_scopes) do
       ^scopes -> {:ok, scopes}
       _ -> {:error, :unsupported_scopes}
     end
   end
+
+  defp authorize_admin_scopes(scopes, app_scopes, %User{} = user) do
+    if user.is_admin || !contains_admin_scopes?(scopes) || !contains_admin_scopes?(app_scopes) do
+      {:ok, scopes}
+    else
+      {:error, :unsupported_scopes}
+    end
+  end
+
+  def contains_admin_scopes?(scopes) do
+    scopes
+    |> OAuthScopesPlug.filter_descendants(["admin"])
+    |> Enum.any?()
+  end
 end
index a474d41d480b1734e1c092b1e5d508e94a94bdc9..6f286032eafb510a40ce6bb0da5e04079de17505 100644 (file)
@@ -7,7 +7,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIController do
 
   plug(
     OAuthScopesPlug,
-    %{scopes: ["write"]}
+    %{scopes: Pleroma.Config.oauth_admin_scopes("write")}
     when action in [
            :create,
            :delete,
index 32577afeebef7ef1419de2be08d1c03435637180..d0131fd903ea6f19371786ed75630f91c67d5fdf 100644 (file)
@@ -1559,7 +1559,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do
         |> assign(:user, user)
         |> get("/api/pleroma/admin/reports")
 
-      assert json_response(conn, :forbidden) == %{"error" => "User is not admin."}
+      assert json_response(conn, :forbidden) ==
+               %{"error" => "User is not an admin or OAuth admin scope is not granted."}
     end
 
     test "returns 403 when requested by anonymous" do