From 4ad843fb9df838f36c014ddfb76d7107ba2b5c7b Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Sat, 9 Feb 2019 17:09:08 +0300 Subject: [PATCH 01/12] [#468] Prototype of OAuth2 scopes support. TwitterAPI scope restrictions. --- lib/pleroma/plugs/oauth_scopes_plug.ex | 29 ++++++ lib/pleroma/web/oauth.ex | 11 +++ lib/pleroma/web/oauth/authorization.ex | 6 +- lib/pleroma/web/oauth/oauth_controller.ex | 12 +-- lib/pleroma/web/oauth/token.ex | 8 +- lib/pleroma/web/router.ex | 98 ++++++++++++------- .../web/templates/o_auth/o_auth/show.html.eex | 4 +- ...208131753_add_scope_to_o_auth_entities.exs | 11 +++ ...8_data_migration_populate_o_auth_scope.exs | 29 ++++++ 9 files changed, 159 insertions(+), 49 deletions(-) create mode 100644 lib/pleroma/plugs/oauth_scopes_plug.ex create mode 100644 lib/pleroma/web/oauth.ex create mode 100644 priv/repo/migrations/20190208131753_add_scope_to_o_auth_entities.exs create mode 100644 priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scope.exs diff --git a/lib/pleroma/plugs/oauth_scopes_plug.ex b/lib/pleroma/plugs/oauth_scopes_plug.ex new file mode 100644 index 000000000..a16adb004 --- /dev/null +++ b/lib/pleroma/plugs/oauth_scopes_plug.ex @@ -0,0 +1,29 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Plugs.OAuthScopesPlug do + import Plug.Conn + alias Pleroma.Web.OAuth + + @behaviour Plug + + def init(%{required_scopes: _} = options), do: options + + def call(%Plug.Conn{assigns: assigns} = conn, %{required_scopes: required_scopes}) do + token = assigns[:token] + granted_scopes = token && OAuth.parse_scopes(token.scope) + + if is_nil(token) || required_scopes -- granted_scopes == [] do + conn + else + missing_scopes = required_scopes -- granted_scopes + error_message = "Insufficient permissions: #{Enum.join(missing_scopes, ", ")}." + + conn + |> put_resp_content_type("application/json") + |> send_resp(403, Jason.encode!(%{error: error_message})) + |> halt() + end + end +end diff --git a/lib/pleroma/web/oauth.ex b/lib/pleroma/web/oauth.ex new file mode 100644 index 000000000..44b83433e --- /dev/null +++ b/lib/pleroma/web/oauth.ex @@ -0,0 +1,11 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.OAuth do + def parse_scopes(scopes) do + scopes + |> to_string() + |> String.split([" ", ","]) + end +end diff --git a/lib/pleroma/web/oauth/authorization.ex b/lib/pleroma/web/oauth/authorization.ex index f8c65602d..0fbaa902b 100644 --- a/lib/pleroma/web/oauth/authorization.ex +++ b/lib/pleroma/web/oauth/authorization.ex @@ -6,12 +6,14 @@ defmodule Pleroma.Web.OAuth.Authorization do use Ecto.Schema alias Pleroma.{User, Repo} + alias Pleroma.Web.OAuth alias Pleroma.Web.OAuth.{Authorization, App} import Ecto.{Changeset, Query} schema "oauth_authorizations" do field(:token, :string) + field(:scope, :string) field(:valid_until, :naive_datetime) field(:used, :boolean, default: false) belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId) @@ -20,7 +22,8 @@ defmodule Pleroma.Web.OAuth.Authorization do timestamps() end - def create_authorization(%App{} = app, %User{} = user) do + def create_authorization(%App{} = app, %User{} = user, scope \\ nil) do + scopes = OAuth.parse_scopes(scope || app.scopes) token = :crypto.strong_rand_bytes(32) |> Base.url_encode64() authorization = %Authorization{ @@ -28,6 +31,7 @@ defmodule Pleroma.Web.OAuth.Authorization do used: false, user_id: user.id, app_id: app.id, + scope: Enum.join(scopes, " "), valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10) } diff --git a/lib/pleroma/web/oauth/oauth_controller.ex b/lib/pleroma/web/oauth/oauth_controller.ex index 8ec963c79..15345d4ba 100644 --- a/lib/pleroma/web/oauth/oauth_controller.ex +++ b/lib/pleroma/web/oauth/oauth_controller.ex @@ -38,7 +38,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, %App{} = app <- Repo.get_by(App, client_id: client_id), true <- redirect_uri in String.split(app.redirect_uris), - {:ok, auth} <- Authorization.create_authorization(app, user) do + {:ok, auth} <- Authorization.create_authorization(app, user, params["scope"]) do # Special case: Local MastodonFE. redirect_uri = if redirect_uri == "." do @@ -81,8 +81,6 @@ defmodule Pleroma.Web.OAuth.OAuthController do end end - # TODO - # - proper scope handling def token_exchange(conn, %{"grant_type" => "authorization_code"} = params) do with %App{} = app <- get_app_from_request(conn, params), fixed_token = fix_padding(params["code"]), @@ -96,7 +94,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do refresh_token: token.refresh_token, created_at: DateTime.to_unix(inserted_at), expires_in: 60 * 10, - scope: "read write follow" + scope: token.scope } json(conn, response) @@ -107,8 +105,6 @@ defmodule Pleroma.Web.OAuth.OAuthController do end end - # TODO - # - investigate a way to verify the user wants to grant read/write/follow once scope handling is done def token_exchange( conn, %{"grant_type" => "password", "username" => name, "password" => password} = params @@ -117,14 +113,14 @@ defmodule Pleroma.Web.OAuth.OAuthController do %User{} = user <- User.get_by_nickname_or_email(name), true <- Pbkdf2.checkpw(password, user.password_hash), {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, - {:ok, auth} <- Authorization.create_authorization(app, user), + {:ok, auth} <- Authorization.create_authorization(app, user, params["scope"]), {:ok, token} <- Token.exchange_token(app, auth) do response = %{ token_type: "Bearer", access_token: token.token, refresh_token: token.refresh_token, expires_in: 60 * 10, - scope: "read write follow" + scope: token.scope } json(conn, response) diff --git a/lib/pleroma/web/oauth/token.ex b/lib/pleroma/web/oauth/token.ex index 4e01b123b..61f43ed5a 100644 --- a/lib/pleroma/web/oauth/token.ex +++ b/lib/pleroma/web/oauth/token.ex @@ -8,11 +8,13 @@ defmodule Pleroma.Web.OAuth.Token do import Ecto.Query alias Pleroma.{User, Repo} + alias Pleroma.Web.OAuth alias Pleroma.Web.OAuth.{Token, App, Authorization} schema "oauth_tokens" do field(:token, :string) field(:refresh_token, :string) + field(:scope, :string) field(:valid_until, :naive_datetime) belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId) belongs_to(:app, App) @@ -23,17 +25,19 @@ defmodule Pleroma.Web.OAuth.Token do def exchange_token(app, auth) do with {:ok, auth} <- Authorization.use_token(auth), true <- auth.app_id == app.id do - create_token(app, Repo.get(User, auth.user_id)) + create_token(app, Repo.get(User, auth.user_id), auth.scope) end end - def create_token(%App{} = app, %User{} = user) do + def create_token(%App{} = app, %User{} = user, scope \\ nil) do + scopes = OAuth.parse_scopes(scope || app.scopes) token = :crypto.strong_rand_bytes(32) |> Base.url_encode64() refresh_token = :crypto.strong_rand_bytes(32) |> Base.url_encode64() token = %Token{ token: token, refresh_token: refresh_token, + scope: Enum.join(scopes, " "), user_id: user.id, app_id: app.id, valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10) diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 7f606ac40..1316d7f98 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -74,6 +74,18 @@ defmodule Pleroma.Web.Router do plug(Pleroma.Plugs.EnsureUserKeyPlug) end + pipeline :oauth_read do + plug(Pleroma.Plugs.OAuthScopesPlug, %{required_scopes: ["read"]}) + end + + pipeline :oauth_write do + plug(Pleroma.Plugs.OAuthScopesPlug, %{required_scopes: ["write"]}) + end + + pipeline :oauth_follow do + plug(Pleroma.Plugs.OAuthScopesPlug, %{required_scopes: ["follow"]}) + end + pipeline :well_known do plug(:accepts, ["json", "jrd+json", "xml", "xrd+xml"]) end @@ -338,55 +350,67 @@ defmodule Pleroma.Web.Router do get("/account/verify_credentials", TwitterAPI.Controller, :verify_credentials) post("/account/verify_credentials", TwitterAPI.Controller, :verify_credentials) - post("/account/update_profile", TwitterAPI.Controller, :update_profile) - post("/account/update_profile_banner", TwitterAPI.Controller, :update_banner) - post("/qvitter/update_background_image", TwitterAPI.Controller, :update_background) + scope [] do + pipe_through(:oauth_read) - get("/statuses/home_timeline", TwitterAPI.Controller, :friends_timeline) - get("/statuses/friends_timeline", TwitterAPI.Controller, :friends_timeline) - get("/statuses/mentions", TwitterAPI.Controller, :mentions_timeline) - get("/statuses/mentions_timeline", TwitterAPI.Controller, :mentions_timeline) - get("/statuses/dm_timeline", TwitterAPI.Controller, :dm_timeline) - get("/qvitter/statuses/notifications", TwitterAPI.Controller, :notifications) + get("/statuses/home_timeline", TwitterAPI.Controller, :friends_timeline) + get("/statuses/friends_timeline", TwitterAPI.Controller, :friends_timeline) + get("/statuses/mentions", TwitterAPI.Controller, :mentions_timeline) + get("/statuses/mentions_timeline", TwitterAPI.Controller, :mentions_timeline) + get("/statuses/dm_timeline", TwitterAPI.Controller, :dm_timeline) + get("/qvitter/statuses/notifications", TwitterAPI.Controller, :notifications) - # XXX: this is really a pleroma API, but we want to keep the pleroma namespace clean - # for now. - post("/qvitter/statuses/notifications/read", TwitterAPI.Controller, :notifications_read) + get("/pleroma/friend_requests", TwitterAPI.Controller, :friend_requests) - post("/statuses/update", TwitterAPI.Controller, :status_update) - post("/statuses/retweet/:id", TwitterAPI.Controller, :retweet) - post("/statuses/unretweet/:id", TwitterAPI.Controller, :unretweet) - post("/statuses/destroy/:id", TwitterAPI.Controller, :delete_post) + get("/friends/ids", TwitterAPI.Controller, :friends_ids) + get("/friendships/no_retweets/ids", TwitterAPI.Controller, :empty_array) - post("/statuses/pin/:id", TwitterAPI.Controller, :pin) - post("/statuses/unpin/:id", TwitterAPI.Controller, :unpin) + get("/mutes/users/ids", TwitterAPI.Controller, :empty_array) + get("/qvitter/mutes", TwitterAPI.Controller, :raw_empty_array) - get("/pleroma/friend_requests", TwitterAPI.Controller, :friend_requests) - post("/pleroma/friendships/approve", TwitterAPI.Controller, :approve_friend_request) - post("/pleroma/friendships/deny", TwitterAPI.Controller, :deny_friend_request) + get("/externalprofile/show", TwitterAPI.Controller, :external_profile) - post("/friendships/create", TwitterAPI.Controller, :follow) - post("/friendships/destroy", TwitterAPI.Controller, :unfollow) - post("/blocks/create", TwitterAPI.Controller, :block) - post("/blocks/destroy", TwitterAPI.Controller, :unblock) + post("/qvitter/statuses/notifications/read", TwitterAPI.Controller, :notifications_read) + end - post("/statusnet/media/upload", TwitterAPI.Controller, :upload) - post("/media/upload", TwitterAPI.Controller, :upload_json) - post("/media/metadata/create", TwitterAPI.Controller, :update_media) + scope [] do + pipe_through(:oauth_write) - post("/favorites/create/:id", TwitterAPI.Controller, :favorite) - post("/favorites/create", TwitterAPI.Controller, :favorite) - post("/favorites/destroy/:id", TwitterAPI.Controller, :unfavorite) + post("/account/update_profile", TwitterAPI.Controller, :update_profile) + post("/account/update_profile_banner", TwitterAPI.Controller, :update_banner) + post("/qvitter/update_background_image", TwitterAPI.Controller, :update_background) - post("/qvitter/update_avatar", TwitterAPI.Controller, :update_avatar) + post("/statuses/update", TwitterAPI.Controller, :status_update) + post("/statuses/retweet/:id", TwitterAPI.Controller, :retweet) + post("/statuses/unretweet/:id", TwitterAPI.Controller, :unretweet) + post("/statuses/destroy/:id", TwitterAPI.Controller, :delete_post) - get("/friends/ids", TwitterAPI.Controller, :friends_ids) - get("/friendships/no_retweets/ids", TwitterAPI.Controller, :empty_array) + post("/statuses/pin/:id", TwitterAPI.Controller, :pin) + post("/statuses/unpin/:id", TwitterAPI.Controller, :unpin) - get("/mutes/users/ids", TwitterAPI.Controller, :empty_array) - get("/qvitter/mutes", TwitterAPI.Controller, :raw_empty_array) + post("/statusnet/media/upload", TwitterAPI.Controller, :upload) + post("/media/upload", TwitterAPI.Controller, :upload_json) + post("/media/metadata/create", TwitterAPI.Controller, :update_media) - get("/externalprofile/show", TwitterAPI.Controller, :external_profile) + post("/favorites/create/:id", TwitterAPI.Controller, :favorite) + post("/favorites/create", TwitterAPI.Controller, :favorite) + post("/favorites/destroy/:id", TwitterAPI.Controller, :unfavorite) + + post("/qvitter/update_avatar", TwitterAPI.Controller, :update_avatar) + end + + scope [] do + pipe_through(:oauth_follow) + + post("/pleroma/friendships/approve", TwitterAPI.Controller, :approve_friend_request) + post("/pleroma/friendships/deny", TwitterAPI.Controller, :deny_friend_request) + + post("/friendships/create", TwitterAPI.Controller, :follow) + post("/friendships/destroy", TwitterAPI.Controller, :unfollow) + + post("/blocks/create", TwitterAPI.Controller, :block) + post("/blocks/destroy", TwitterAPI.Controller, :unblock) + end end pipeline :ap_relay do diff --git a/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex b/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex index de2241ec9..e1c0af975 100644 --- a/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex +++ b/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex @@ -8,10 +8,12 @@ <%= label f, :password, "Password" %> <%= password_input f, :password %>
+<%= label f, :scope, "Scopes" %> +<%= text_input f, :scope, value: @scope %> +
<%= hidden_input f, :client_id, value: @client_id %> <%= hidden_input f, :response_type, value: @response_type %> <%= hidden_input f, :redirect_uri, value: @redirect_uri %> -<%= hidden_input f, :scope, value: @scope %> <%= hidden_input f, :state, value: @state%> <%= submit "Authorize" %> <% end %> diff --git a/priv/repo/migrations/20190208131753_add_scope_to_o_auth_entities.exs b/priv/repo/migrations/20190208131753_add_scope_to_o_auth_entities.exs new file mode 100644 index 000000000..809e9ab22 --- /dev/null +++ b/priv/repo/migrations/20190208131753_add_scope_to_o_auth_entities.exs @@ -0,0 +1,11 @@ +defmodule Pleroma.Repo.Migrations.AddScopeToOAuthEntities do + use Ecto.Migration + + def change do + for t <- [:oauth_authorizations, :oauth_tokens] do + alter table(t) do + add :scope, :string + end + end + end +end diff --git a/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scope.exs b/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scope.exs new file mode 100644 index 000000000..722cd6cf9 --- /dev/null +++ b/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scope.exs @@ -0,0 +1,29 @@ +defmodule Pleroma.Repo.Migrations.DataMigrationPopulateOAuthScope do + use Ecto.Migration + + require Ecto.Query + + alias Ecto.Query + alias Pleroma.Repo + alias Pleroma.Web.OAuth + alias Pleroma.Web.OAuth.{App, Authorization, Token} + + def up do + for app <- Repo.all(Query.from(app in App)) do + scopes = OAuth.parse_scopes(app.scopes) + scope = Enum.join(scopes, " ") + + Repo.update_all( + Query.from(auth in Authorization, where: auth.app_id == ^app.id), + set: [scope: scope] + ) + + Repo.update_all( + Query.from(token in Token, where: token.app_id == ^app.id), + set: [scope: scope] + ) + end + end + + def down, do: :noop +end From a337bd114c3cbbb8e8270ec56a012e82f84df808 Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Sat, 9 Feb 2019 17:32:33 +0300 Subject: [PATCH 02/12] [#468] MastodonAPI scope restrictions. Removed obsolete "POST /web/login" route. --- lib/pleroma/web/router.ex | 155 ++++++++++++++++++++++---------------- 1 file changed, 91 insertions(+), 64 deletions(-) diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 1316d7f98..4ece311d3 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -154,10 +154,20 @@ defmodule Pleroma.Web.Router do scope "/api/pleroma", Pleroma.Web.TwitterAPI do pipe_through(:authenticated_api) - post("/blocks_import", UtilController, :blocks_import) - post("/follow_import", UtilController, :follow_import) - post("/change_password", UtilController, :change_password) - post("/delete_account", UtilController, :delete_account) + + scope [] do + pipe_through(:oauth_write) + + post("/change_password", UtilController, :change_password) + post("/delete_account", UtilController, :delete_account) + end + + scope [] do + pipe_through(:oauth_follow) + + post("/blocks_import", UtilController, :blocks_import) + post("/follow_import", UtilController, :follow_import) + end end scope "/oauth", Pleroma.Web.OAuth do @@ -170,86 +180,104 @@ defmodule Pleroma.Web.Router do scope "/api/v1", Pleroma.Web.MastodonAPI do pipe_through(:authenticated_api) - patch("/accounts/update_credentials", MastodonAPIController, :update_credentials) get("/accounts/verify_credentials", MastodonAPIController, :verify_credentials) - get("/accounts/relationships", MastodonAPIController, :relationships) - get("/accounts/search", MastodonAPIController, :account_search) - post("/accounts/:id/follow", MastodonAPIController, :follow) - post("/accounts/:id/unfollow", MastodonAPIController, :unfollow) - post("/accounts/:id/block", MastodonAPIController, :block) - post("/accounts/:id/unblock", MastodonAPIController, :unblock) - post("/accounts/:id/mute", MastodonAPIController, :relationship_noop) - post("/accounts/:id/unmute", MastodonAPIController, :relationship_noop) - get("/accounts/:id/lists", MastodonAPIController, :account_lists) - get("/follow_requests", MastodonAPIController, :follow_requests) - post("/follow_requests/:id/authorize", MastodonAPIController, :authorize_follow_request) - post("/follow_requests/:id/reject", MastodonAPIController, :reject_follow_request) + scope [] do + pipe_through(:oauth_read) - post("/follows", MastodonAPIController, :follow) + get("/accounts/relationships", MastodonAPIController, :relationships) + get("/accounts/search", MastodonAPIController, :account_search) - get("/blocks", MastodonAPIController, :blocks) + get("/accounts/:id/lists", MastodonAPIController, :account_lists) - get("/mutes", MastodonAPIController, :empty_array) + get("/follow_requests", MastodonAPIController, :follow_requests) + get("/blocks", MastodonAPIController, :blocks) + get("/mutes", MastodonAPIController, :empty_array) - get("/timelines/home", MastodonAPIController, :home_timeline) + get("/timelines/home", MastodonAPIController, :home_timeline) + get("/timelines/direct", MastodonAPIController, :dm_timeline) - get("/timelines/direct", MastodonAPIController, :dm_timeline) + get("/favourites", MastodonAPIController, :favourites) + get("/bookmarks", MastodonAPIController, :bookmarks) - get("/favourites", MastodonAPIController, :favourites) - get("/bookmarks", MastodonAPIController, :bookmarks) + post("/notifications/clear", MastodonAPIController, :clear_notifications) + post("/notifications/dismiss", MastodonAPIController, :dismiss_notification) + get("/notifications", MastodonAPIController, :notifications) + get("/notifications/:id", MastodonAPIController, :get_notification) - post("/statuses", MastodonAPIController, :post_status) - delete("/statuses/:id", MastodonAPIController, :delete_status) + get("/lists", MastodonAPIController, :get_lists) + get("/lists/:id", MastodonAPIController, :get_list) + get("/lists/:id/accounts", MastodonAPIController, :list_accounts) - post("/statuses/:id/reblog", MastodonAPIController, :reblog_status) - post("/statuses/:id/unreblog", MastodonAPIController, :unreblog_status) - post("/statuses/:id/favourite", MastodonAPIController, :fav_status) - post("/statuses/:id/unfavourite", MastodonAPIController, :unfav_status) - post("/statuses/:id/pin", MastodonAPIController, :pin_status) - post("/statuses/:id/unpin", MastodonAPIController, :unpin_status) - post("/statuses/:id/bookmark", MastodonAPIController, :bookmark_status) - post("/statuses/:id/unbookmark", MastodonAPIController, :unbookmark_status) + get("/domain_blocks", MastodonAPIController, :domain_blocks) - post("/notifications/clear", MastodonAPIController, :clear_notifications) - post("/notifications/dismiss", MastodonAPIController, :dismiss_notification) - get("/notifications", MastodonAPIController, :notifications) - get("/notifications/:id", MastodonAPIController, :get_notification) + get("/filters", MastodonAPIController, :get_filters) - post("/media", MastodonAPIController, :upload) - put("/media/:id", MastodonAPIController, :update_media) + get("/suggestions", MastodonAPIController, :suggestions) - get("/lists", MastodonAPIController, :get_lists) - get("/lists/:id", MastodonAPIController, :get_list) - delete("/lists/:id", MastodonAPIController, :delete_list) - post("/lists", MastodonAPIController, :create_list) - put("/lists/:id", MastodonAPIController, :rename_list) - get("/lists/:id/accounts", MastodonAPIController, :list_accounts) - post("/lists/:id/accounts", MastodonAPIController, :add_to_list) - delete("/lists/:id/accounts", MastodonAPIController, :remove_from_list) + get("/endorsements", MastodonAPIController, :empty_array) + end - get("/domain_blocks", MastodonAPIController, :domain_blocks) - post("/domain_blocks", MastodonAPIController, :block_domain) - delete("/domain_blocks", MastodonAPIController, :unblock_domain) + scope [] do + pipe_through(:oauth_write) - get("/filters", MastodonAPIController, :get_filters) - post("/filters", MastodonAPIController, :create_filter) - get("/filters/:id", MastodonAPIController, :get_filter) - put("/filters/:id", MastodonAPIController, :update_filter) - delete("/filters/:id", MastodonAPIController, :delete_filter) + patch("/accounts/update_credentials", MastodonAPIController, :update_credentials) - post("/push/subscription", MastodonAPIController, :create_push_subscription) - get("/push/subscription", MastodonAPIController, :get_push_subscription) - put("/push/subscription", MastodonAPIController, :update_push_subscription) - delete("/push/subscription", MastodonAPIController, :delete_push_subscription) + post("/statuses", MastodonAPIController, :post_status) + delete("/statuses/:id", MastodonAPIController, :delete_status) - get("/suggestions", MastodonAPIController, :suggestions) + post("/statuses/:id/reblog", MastodonAPIController, :reblog_status) + post("/statuses/:id/unreblog", MastodonAPIController, :unreblog_status) + post("/statuses/:id/favourite", MastodonAPIController, :fav_status) + post("/statuses/:id/unfavourite", MastodonAPIController, :unfav_status) + post("/statuses/:id/pin", MastodonAPIController, :pin_status) + post("/statuses/:id/unpin", MastodonAPIController, :unpin_status) + post("/statuses/:id/bookmark", MastodonAPIController, :bookmark_status) + post("/statuses/:id/unbookmark", MastodonAPIController, :unbookmark_status) - get("/endorsements", MastodonAPIController, :empty_array) + post("/media", MastodonAPIController, :upload) + put("/media/:id", MastodonAPIController, :update_media) + + delete("/lists/:id", MastodonAPIController, :delete_list) + post("/lists", MastodonAPIController, :create_list) + put("/lists/:id", MastodonAPIController, :rename_list) + + post("/lists/:id/accounts", MastodonAPIController, :add_to_list) + delete("/lists/:id/accounts", MastodonAPIController, :remove_from_list) + + post("/filters", MastodonAPIController, :create_filter) + get("/filters/:id", MastodonAPIController, :get_filter) + put("/filters/:id", MastodonAPIController, :update_filter) + delete("/filters/:id", MastodonAPIController, :delete_filter) + end + + scope [] do + pipe_through(:oauth_follow) + + post("/follows", MastodonAPIController, :follow) + post("/accounts/:id/follow", MastodonAPIController, :follow) + + post("/accounts/:id/unfollow", MastodonAPIController, :unfollow) + post("/accounts/:id/block", MastodonAPIController, :block) + post("/accounts/:id/unblock", MastodonAPIController, :unblock) + post("/accounts/:id/mute", MastodonAPIController, :relationship_noop) + post("/accounts/:id/unmute", MastodonAPIController, :relationship_noop) + + post("/follow_requests/:id/authorize", MastodonAPIController, :authorize_follow_request) + post("/follow_requests/:id/reject", MastodonAPIController, :reject_follow_request) + + post("/domain_blocks", MastodonAPIController, :block_domain) + delete("/domain_blocks", MastodonAPIController, :unblock_domain) + + post("/push/subscription", MastodonAPIController, :create_push_subscription) + get("/push/subscription", MastodonAPIController, :get_push_subscription) + put("/push/subscription", MastodonAPIController, :update_push_subscription) + delete("/push/subscription", MastodonAPIController, :delete_push_subscription) + end end scope "/api/web", Pleroma.Web.MastodonAPI do - pipe_through(:authenticated_api) + pipe_through([:authenticated_api, :oauth_write]) put("/settings", MastodonAPIController, :put_settings) end @@ -510,7 +538,6 @@ defmodule Pleroma.Web.Router do pipe_through(:mastodon_html) get("/web/login", MastodonAPIController, :login) - post("/web/login", MastodonAPIController, :login_post) get("/web/*path", MastodonAPIController, :index) delete("/auth/sign_out", MastodonAPIController, :logout) end From 063baca5e4f3a100c0d45dffb14e4968599ef43b Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Thu, 14 Feb 2019 00:29:29 +0300 Subject: [PATCH 03/12] [#468] User UI for OAuth permissions restriction. Standardized storage format for `scopes` fields, updated usages. --- lib/pleroma/plugs/oauth_scopes_plug.ex | 3 +-- .../mastodon_api/mastodon_api_controller.ex | 12 ++++++++++-- lib/pleroma/web/oauth.ex | 19 ++++++++++++++++--- lib/pleroma/web/oauth/app.ex | 2 +- lib/pleroma/web/oauth/authorization.ex | 9 ++++----- lib/pleroma/web/oauth/oauth_controller.ex | 18 +++++++++++++----- lib/pleroma/web/oauth/token.ex | 11 +++++------ lib/pleroma/web/templates/layout/app.html.eex | 4 ++++ .../web/templates/o_auth/o_auth/show.html.eex | 12 ++++++++++-- mix.lock | 6 +++--- ...8131753_add_scopes_to_o_auth_entities.exs} | 4 ++-- ...data_migration_populate_o_auth_scopes.exs} | 7 +++---- ...03_change_apps_scopes_to_varchar_array.exs | 17 +++++++++++++++++ test/integration/mastodon_websocket_test.exs | 2 +- test/support/factory.ex | 2 +- test/web/oauth/authorization_test.exs | 6 +++--- test/web/oauth/oauth_controller_test.exs | 1 + test/web/oauth/token_test.exs | 6 +++--- 18 files changed, 98 insertions(+), 43 deletions(-) rename priv/repo/migrations/{20190208131753_add_scope_to_o_auth_entities.exs => 20190208131753_add_scopes_to_o_auth_entities.exs} (53%) rename priv/repo/migrations/{20190209123318_data_migration_populate_o_auth_scope.exs => 20190209123318_data_migration_populate_o_auth_scopes.exs} (85%) create mode 100644 priv/repo/migrations/20190213185503_change_apps_scopes_to_varchar_array.exs diff --git a/lib/pleroma/plugs/oauth_scopes_plug.ex b/lib/pleroma/plugs/oauth_scopes_plug.ex index a16adb004..a81e29830 100644 --- a/lib/pleroma/plugs/oauth_scopes_plug.ex +++ b/lib/pleroma/plugs/oauth_scopes_plug.ex @@ -4,7 +4,6 @@ defmodule Pleroma.Plugs.OAuthScopesPlug do import Plug.Conn - alias Pleroma.Web.OAuth @behaviour Plug @@ -12,7 +11,7 @@ defmodule Pleroma.Plugs.OAuthScopesPlug do def call(%Plug.Conn{assigns: assigns} = conn, %{required_scopes: required_scopes}) do token = assigns[:token] - granted_scopes = token && OAuth.parse_scopes(token.scope) + granted_scopes = token && token.scopes if is_nil(token) || required_scopes -- granted_scopes == [] do conn diff --git a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex index dbe7c2554..59f472e91 100644 --- a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex +++ b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex @@ -19,6 +19,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.Utils alias Pleroma.Web.CommonAPI + alias Pleroma.Web.OAuth alias Pleroma.Web.OAuth.{Authorization, Token, App} alias Pleroma.Web.MediaProxy @@ -31,7 +32,10 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do action_fallback(:errors) def create_app(conn, params) do - with cs <- App.register_changeset(%App{}, params), + scopes = OAuth.parse_scopes(params["scope"] || params["scopes"]) + app_attrs = params |> Map.drop(["scope", "scopes"]) |> Map.put("scopes", scopes) + + with cs <- App.register_changeset(%App{}, app_attrs), false <- cs.changes[:client_name] == @local_mastodon_name, {:ok, app} <- Repo.insert(cs) do res = %{ @@ -1162,7 +1166,11 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do {:ok, app} else _e -> - cs = App.register_changeset(%App{}, Map.put(find_attrs, :scopes, "read,write,follow")) + cs = + App.register_changeset( + %App{}, + Map.put(find_attrs, :scopes, ["read", "write", "follow"]) + ) Repo.insert(cs) end diff --git a/lib/pleroma/web/oauth.ex b/lib/pleroma/web/oauth.ex index 44b83433e..761b80fde 100644 --- a/lib/pleroma/web/oauth.ex +++ b/lib/pleroma/web/oauth.ex @@ -3,9 +3,22 @@ # SPDX-License-Identifier: AGPL-3.0-only defmodule Pleroma.Web.OAuth do - def parse_scopes(scopes) do + def parse_scopes(nil) do + nil + end + + def parse_scopes(scopes) when is_list(scopes) do scopes - |> to_string() - |> String.split([" ", ","]) + end + + def parse_scopes(scopes) do + scopes = + scopes + |> to_string() + |> String.trim() + + if scopes == "", + do: [], + else: String.split(scopes, [" ", ","]) end end diff --git a/lib/pleroma/web/oauth/app.ex b/lib/pleroma/web/oauth/app.ex index 967ac04b5..c04626a73 100644 --- a/lib/pleroma/web/oauth/app.ex +++ b/lib/pleroma/web/oauth/app.ex @@ -9,7 +9,7 @@ defmodule Pleroma.Web.OAuth.App do schema "apps" do field(:client_name, :string) field(:redirect_uris, :string) - field(:scopes, :string) + field(:scopes, {:array, :string}, default: []) field(:website, :string) field(:client_id, :string) field(:client_secret, :string) diff --git a/lib/pleroma/web/oauth/authorization.ex b/lib/pleroma/web/oauth/authorization.ex index 0fbaa902b..c5b7ec9a5 100644 --- a/lib/pleroma/web/oauth/authorization.ex +++ b/lib/pleroma/web/oauth/authorization.ex @@ -6,14 +6,13 @@ defmodule Pleroma.Web.OAuth.Authorization do use Ecto.Schema alias Pleroma.{User, Repo} - alias Pleroma.Web.OAuth alias Pleroma.Web.OAuth.{Authorization, App} import Ecto.{Changeset, Query} schema "oauth_authorizations" do field(:token, :string) - field(:scope, :string) + field(:scopes, {:array, :string}, default: []) field(:valid_until, :naive_datetime) field(:used, :boolean, default: false) belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId) @@ -22,8 +21,8 @@ defmodule Pleroma.Web.OAuth.Authorization do timestamps() end - def create_authorization(%App{} = app, %User{} = user, scope \\ nil) do - scopes = OAuth.parse_scopes(scope || app.scopes) + def create_authorization(%App{} = app, %User{} = user, scopes \\ nil) do + scopes = scopes || app.scopes token = :crypto.strong_rand_bytes(32) |> Base.url_encode64() authorization = %Authorization{ @@ -31,7 +30,7 @@ defmodule Pleroma.Web.OAuth.Authorization do used: false, user_id: user.id, app_id: app.id, - scope: Enum.join(scopes, " "), + scopes: scopes, valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10) } diff --git a/lib/pleroma/web/oauth/oauth_controller.ex b/lib/pleroma/web/oauth/oauth_controller.ex index 15345d4ba..f00d5293d 100644 --- a/lib/pleroma/web/oauth/oauth_controller.ex +++ b/lib/pleroma/web/oauth/oauth_controller.ex @@ -5,6 +5,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do use Pleroma.Web, :controller + alias Pleroma.Web.OAuth alias Pleroma.Web.OAuth.{Authorization, Token, App} alias Pleroma.{Repo, User} alias Comeonin.Pbkdf2 @@ -18,7 +19,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do render(conn, "show.html", %{ response_type: params["response_type"], client_id: params["client_id"], - scope: params["scope"], + scopes: scopes(params) || [], redirect_uri: params["redirect_uri"], state: params["state"] }) @@ -38,7 +39,10 @@ defmodule Pleroma.Web.OAuth.OAuthController do {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, %App{} = app <- Repo.get_by(App, client_id: client_id), true <- redirect_uri in String.split(app.redirect_uris), - {:ok, auth} <- Authorization.create_authorization(app, user, params["scope"]) do + scopes <- scopes(params) || app.scopes, + [] <- scopes -- app.scopes, + true <- Enum.any?(scopes), + {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do # Special case: Local MastodonFE. redirect_uri = if redirect_uri == "." do @@ -94,7 +98,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do refresh_token: token.refresh_token, created_at: DateTime.to_unix(inserted_at), expires_in: 60 * 10, - scope: token.scope + scope: Enum.join(token.scopes) } json(conn, response) @@ -113,14 +117,15 @@ defmodule Pleroma.Web.OAuth.OAuthController do %User{} = user <- User.get_by_nickname_or_email(name), true <- Pbkdf2.checkpw(password, user.password_hash), {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, - {:ok, auth} <- Authorization.create_authorization(app, user, params["scope"]), + scopes <- scopes(params) || app.scopes, + {:ok, auth} <- Authorization.create_authorization(app, user, scopes), {:ok, token} <- Token.exchange_token(app, auth) do response = %{ token_type: "Bearer", access_token: token.token, refresh_token: token.refresh_token, expires_in: 60 * 10, - scope: token.scope + scope: Enum.join(token.scopes, " ") } json(conn, response) @@ -192,4 +197,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do nil end end + + defp scopes(params), + do: OAuth.parse_scopes(params["scopes"] || params["scope"]) end diff --git a/lib/pleroma/web/oauth/token.ex b/lib/pleroma/web/oauth/token.ex index 61f43ed5a..1fae5ed3a 100644 --- a/lib/pleroma/web/oauth/token.ex +++ b/lib/pleroma/web/oauth/token.ex @@ -8,13 +8,12 @@ defmodule Pleroma.Web.OAuth.Token do import Ecto.Query alias Pleroma.{User, Repo} - alias Pleroma.Web.OAuth alias Pleroma.Web.OAuth.{Token, App, Authorization} schema "oauth_tokens" do field(:token, :string) field(:refresh_token, :string) - field(:scope, :string) + field(:scopes, {:array, :string}, default: []) field(:valid_until, :naive_datetime) belongs_to(:user, Pleroma.User, type: Pleroma.FlakeId) belongs_to(:app, App) @@ -25,19 +24,19 @@ defmodule Pleroma.Web.OAuth.Token do def exchange_token(app, auth) do with {:ok, auth} <- Authorization.use_token(auth), true <- auth.app_id == app.id do - create_token(app, Repo.get(User, auth.user_id), auth.scope) + create_token(app, Repo.get(User, auth.user_id), auth.scopes) end end - def create_token(%App{} = app, %User{} = user, scope \\ nil) do - scopes = OAuth.parse_scopes(scope || app.scopes) + def create_token(%App{} = app, %User{} = user, scopes \\ nil) do + scopes = scopes || app.scopes token = :crypto.strong_rand_bytes(32) |> Base.url_encode64() refresh_token = :crypto.strong_rand_bytes(32) |> Base.url_encode64() token = %Token{ token: token, refresh_token: refresh_token, - scope: Enum.join(scopes, " "), + scopes: scopes, user_id: user.id, app_id: app.id, valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10) diff --git a/lib/pleroma/web/templates/layout/app.html.eex b/lib/pleroma/web/templates/layout/app.html.eex index 8dd3284d6..f944cbc26 100644 --- a/lib/pleroma/web/templates/layout/app.html.eex +++ b/lib/pleroma/web/templates/layout/app.html.eex @@ -54,6 +54,10 @@ border-bottom: 2px solid #4b8ed8; } + input[type="checkbox"] { + width: auto; + } + button { box-sizing: border-box; width: 100%; diff --git a/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex b/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex index e1c0af975..1ecb5b444 100644 --- a/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex +++ b/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex @@ -5,12 +5,20 @@ <%= label f, :name, "Name or email" %> <%= text_input f, :name %>
+
<%= label f, :password, "Password" %> <%= password_input f, :password %>
-<%= label f, :scope, "Scopes" %> -<%= text_input f, :scope, value: @scope %>
+ +<%= label f, :scope, "Permissions" %> +
+<%= for scope <- @scopes do %> + <%= checkbox f, :"scopes_#{scope}", hidden_input: false, value: scope, checked_value: scope, name: "authorization[scopes][]" %> + <%= label f, :"scopes_#{scope}", String.capitalize(scope) %> +
+<% end %> + <%= hidden_input f, :client_id, value: @client_id %> <%= hidden_input f, :response_type, value: @response_type %> <%= hidden_input f, :redirect_uri, value: @redirect_uri %> diff --git a/mix.lock b/mix.lock index 31725a477..02748f541 100644 --- a/mix.lock +++ b/mix.lock @@ -20,8 +20,8 @@ "ex_aws_s3": {:hex, :ex_aws_s3, "2.0.1", "9e09366e77f25d3d88c5393824e613344631be8db0d1839faca49686e99b6704", [:mix], [{:ex_aws, "~> 2.0", [hex: :ex_aws, repo: "hexpm", optional: false]}, {:sweet_xml, ">= 0.0.0", [hex: :sweet_xml, repo: "hexpm", optional: true]}], "hexpm"}, "ex_doc": {:hex, :ex_doc, "0.19.1", "519bb9c19526ca51d326c060cb1778d4a9056b190086a8c6c115828eaccea6cf", [:mix], [{:earmark, "~> 1.1", [hex: :earmark, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.7", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm"}, "ex_machina": {:hex, :ex_machina, "2.2.0", "fec496331e04fc2db2a1a24fe317c12c0c4a50d2beb8ebb3531ed1f0d84be0ed", [:mix], [{:ecto, "~> 2.1", [hex: :ecto, repo: "hexpm", optional: true]}], "hexpm"}, - "floki": {:hex, :floki, "0.20.4", "be42ac911fece24b4c72f3b5846774b6e61b83fe685c2fc9d62093277fb3bc86", [:mix], [{:html_entities, "~> 0.4.0", [hex: :html_entities, repo: "hexpm", optional: false]}, {:mochiweb, "~> 2.15", [hex: :mochiweb, repo: "hexpm", optional: false]}], "hexpm"}, "ex_syslogger": {:git, "https://github.com/slashmili/ex_syslogger.git", "f3963399047af17e038897c69e20d552e6899e1d", [tag: "1.4.0"]}, + "floki": {:hex, :floki, "0.20.4", "be42ac911fece24b4c72f3b5846774b6e61b83fe685c2fc9d62093277fb3bc86", [:mix], [{:html_entities, "~> 0.4.0", [hex: :html_entities, repo: "hexpm", optional: false]}, {:mochiweb, "~> 2.15", [hex: :mochiweb, repo: "hexpm", optional: false]}], "hexpm"}, "gen_smtp": {:hex, :gen_smtp, "0.13.0", "11f08504c4bdd831dc520b8f84a1dce5ce624474a797394e7aafd3c29f5dcd25", [:rebar3], [], "hexpm"}, "gettext": {:hex, :gettext, "0.15.0", "40a2b8ce33a80ced7727e36768499fc9286881c43ebafccae6bab731e2b2b8ce", [:mix], [], "hexpm"}, "hackney": {:hex, :hackney, "1.14.3", "b5f6f5dcc4f1fba340762738759209e21914516df6be440d85772542d4a5e412", [:rebar3], [{:certifi, "2.4.2", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "6.0.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "1.0.1", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "1.1.4", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}], "hexpm"}, @@ -45,9 +45,9 @@ "pbkdf2_elixir": {:hex, :pbkdf2_elixir, "0.12.3", "6706a148809a29c306062862c803406e88f048277f6e85b68faf73291e820b84", [:mix], [], "hexpm"}, "phoenix": {:git, "https://github.com/phoenixframework/phoenix.git", "ea22dc50b574178a300ecd19253443960407df93", [branch: "v1.4"]}, "phoenix_ecto": {:hex, :phoenix_ecto, "3.3.0", "702f6e164512853d29f9d20763493f2b3bcfcb44f118af2bc37bb95d0801b480", [:mix], [{:ecto, "~> 2.1", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.9", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"}, - "phoenix_html": {:hex, :phoenix_html, "2.11.2", "86ebd768258ba60a27f5578bec83095bdb93485d646fc4111db8844c316602d6", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"}, + "phoenix_html": {:hex, :phoenix_html, "2.13.1", "fa8f034b5328e2dfa0e4131b5569379003f34bc1fafdaa84985b0b9d2f12e68b", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"}, "phoenix_pubsub": {:hex, :phoenix_pubsub, "1.1.1", "6668d787e602981f24f17a5fbb69cc98f8ab085114ebfac6cc36e10a90c8e93c", [:mix], [], "hexpm"}, - "plug": {:hex, :plug, "1.7.1", "8516d565fb84a6a8b2ca722e74e2cd25ca0fc9d64f364ec9dbec09d33eb78ccd", [:mix], [{:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}], "hexpm"}, + "plug": {:hex, :plug, "1.7.2", "d7b7db7fbd755e8283b6c0a50be71ec0a3d67d9213d74422d9372effc8e87fd1", [:mix], [{:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}], "hexpm"}, "plug_cowboy": {:hex, :plug_cowboy, "1.0.0", "2e2a7d3409746d335f451218b8bb0858301c3de6d668c3052716c909936eb57a", [:mix], [{:cowboy, "~> 1.0", [hex: :cowboy, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"}, "plug_crypto": {:hex, :plug_crypto, "1.0.0", "18e49317d3fa343f24620ed22795ec29d4a5e602d52d1513ccea0b07d8ea7d4d", [:mix], [], "hexpm"}, "poison": {:hex, :poison, "3.1.0", "d9eb636610e096f86f25d9a46f35a9facac35609a7591b3be3326e99a0484665", [:mix], [], "hexpm"}, diff --git a/priv/repo/migrations/20190208131753_add_scope_to_o_auth_entities.exs b/priv/repo/migrations/20190208131753_add_scopes_to_o_auth_entities.exs similarity index 53% rename from priv/repo/migrations/20190208131753_add_scope_to_o_auth_entities.exs rename to priv/repo/migrations/20190208131753_add_scopes_to_o_auth_entities.exs index 809e9ab22..4efbebc4d 100644 --- a/priv/repo/migrations/20190208131753_add_scope_to_o_auth_entities.exs +++ b/priv/repo/migrations/20190208131753_add_scopes_to_o_auth_entities.exs @@ -1,10 +1,10 @@ -defmodule Pleroma.Repo.Migrations.AddScopeToOAuthEntities do +defmodule Pleroma.Repo.Migrations.AddScopeSToOAuthEntities do use Ecto.Migration def change do for t <- [:oauth_authorizations, :oauth_tokens] do alter table(t) do - add :scope, :string + add :scopes, {:array, :string}, default: [], null: false end end end diff --git a/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scope.exs b/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scopes.exs similarity index 85% rename from priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scope.exs rename to priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scopes.exs index 722cd6cf9..30b10f56f 100644 --- a/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scope.exs +++ b/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scopes.exs @@ -1,4 +1,4 @@ -defmodule Pleroma.Repo.Migrations.DataMigrationPopulateOAuthScope do +defmodule Pleroma.Repo.Migrations.DataMigrationPopulateOAuthScopes do use Ecto.Migration require Ecto.Query @@ -11,16 +11,15 @@ defmodule Pleroma.Repo.Migrations.DataMigrationPopulateOAuthScope do def up do for app <- Repo.all(Query.from(app in App)) do scopes = OAuth.parse_scopes(app.scopes) - scope = Enum.join(scopes, " ") Repo.update_all( Query.from(auth in Authorization, where: auth.app_id == ^app.id), - set: [scope: scope] + set: [scopes: scopes] ) Repo.update_all( Query.from(token in Token, where: token.app_id == ^app.id), - set: [scope: scope] + set: [scopes: scopes] ) end end diff --git a/priv/repo/migrations/20190213185503_change_apps_scopes_to_varchar_array.exs b/priv/repo/migrations/20190213185503_change_apps_scopes_to_varchar_array.exs new file mode 100644 index 000000000..72decd401 --- /dev/null +++ b/priv/repo/migrations/20190213185503_change_apps_scopes_to_varchar_array.exs @@ -0,0 +1,17 @@ +defmodule Pleroma.Repo.Migrations.ChangeAppsScopesToVarcharArray do + use Ecto.Migration + + @alter_apps_scopes "ALTER TABLE apps ALTER COLUMN scopes" + + def up do + execute "#{@alter_apps_scopes} TYPE varchar(255)[] USING string_to_array(scopes, ',')::varchar(255)[];" + execute "#{@alter_apps_scopes} SET DEFAULT ARRAY[]::character varying[];" + execute "#{@alter_apps_scopes} SET NOT NULL;" + end + + def down do + execute "#{@alter_apps_scopes} DROP NOT NULL;" + execute "#{@alter_apps_scopes} DROP DEFAULT;" + execute "#{@alter_apps_scopes} TYPE varchar(255) USING array_to_string(scopes, ',')::varchar(255);" + end +end diff --git a/test/integration/mastodon_websocket_test.exs b/test/integration/mastodon_websocket_test.exs index 2e385f5ad..0c513b6e7 100644 --- a/test/integration/mastodon_websocket_test.exs +++ b/test/integration/mastodon_websocket_test.exs @@ -80,7 +80,7 @@ defmodule Pleroma.Integration.MastodonWebsocketTest do Pleroma.Repo.insert( OAuth.App.register_changeset(%OAuth.App{}, %{ client_name: "client", - scopes: "scope", + scopes: ["scope"], redirect_uris: "url" }) ) diff --git a/test/support/factory.ex b/test/support/factory.ex index 0c21093ce..eaa6f0ce2 100644 --- a/test/support/factory.ex +++ b/test/support/factory.ex @@ -214,7 +214,7 @@ defmodule Pleroma.Factory do %Pleroma.Web.OAuth.App{ client_name: "Some client", redirect_uris: "https://example.com/callback", - scopes: "read", + scopes: ["read"], website: "https://example.com", client_id: "aaabbb==", client_secret: "aaa;/&bbb" diff --git a/test/web/oauth/authorization_test.exs b/test/web/oauth/authorization_test.exs index 3b1ddada8..68db1ceb0 100644 --- a/test/web/oauth/authorization_test.exs +++ b/test/web/oauth/authorization_test.exs @@ -12,7 +12,7 @@ defmodule Pleroma.Web.OAuth.AuthorizationTest do Repo.insert( App.register_changeset(%App{}, %{ client_name: "client", - scopes: "scope", + scopes: ["scope"], redirect_uris: "url" }) ) @@ -32,7 +32,7 @@ defmodule Pleroma.Web.OAuth.AuthorizationTest do Repo.insert( App.register_changeset(%App{}, %{ client_name: "client", - scopes: "scope", + scopes: ["scope"], redirect_uris: "url" }) ) @@ -65,7 +65,7 @@ defmodule Pleroma.Web.OAuth.AuthorizationTest do Repo.insert( App.register_changeset(%App{}, %{ client_name: "client", - scopes: "scope", + scopes: ["scope"], redirect_uris: "url" }) ) diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs index e0d3cb55f..74d512c7f 100644 --- a/test/web/oauth/oauth_controller_test.exs +++ b/test/web/oauth/oauth_controller_test.exs @@ -21,6 +21,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do "password" => "test", "client_id" => app.client_id, "redirect_uri" => app.redirect_uris, + "scope" => Enum.join(app.scopes, " "), "state" => "statepassed" } }) diff --git a/test/web/oauth/token_test.exs b/test/web/oauth/token_test.exs index 9a241d61a..63a7eb3ae 100644 --- a/test/web/oauth/token_test.exs +++ b/test/web/oauth/token_test.exs @@ -14,7 +14,7 @@ defmodule Pleroma.Web.OAuth.TokenTest do Repo.insert( App.register_changeset(%App{}, %{ client_name: "client", - scopes: "scope", + scopes: ["scope"], redirect_uris: "url" }) ) @@ -39,7 +39,7 @@ defmodule Pleroma.Web.OAuth.TokenTest do Repo.insert( App.register_changeset(%App{}, %{ client_name: "client1", - scopes: "scope", + scopes: ["scope"], redirect_uris: "url" }) ) @@ -48,7 +48,7 @@ defmodule Pleroma.Web.OAuth.TokenTest do Repo.insert( App.register_changeset(%App{}, %{ client_name: "client2", - scopes: "scope", + scopes: ["scope"], redirect_uris: "url" }) ) From 949e35e26deaf6dc7c2e552b1b8db63de8a87445 Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Thu, 14 Feb 2019 14:28:26 +0300 Subject: [PATCH 04/12] [#468] OAuth scopes-related data migration simplification. --- ..._data_migration_populate_o_auth_scopes.exs | 28 ------------------- ..._data_migration_populate_o_auth_scopes.exs | 11 ++++++++ 2 files changed, 11 insertions(+), 28 deletions(-) delete mode 100644 priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scopes.exs create mode 100644 priv/repo/migrations/20190213185600_data_migration_populate_o_auth_scopes.exs diff --git a/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scopes.exs b/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scopes.exs deleted file mode 100644 index 30b10f56f..000000000 --- a/priv/repo/migrations/20190209123318_data_migration_populate_o_auth_scopes.exs +++ /dev/null @@ -1,28 +0,0 @@ -defmodule Pleroma.Repo.Migrations.DataMigrationPopulateOAuthScopes do - use Ecto.Migration - - require Ecto.Query - - alias Ecto.Query - alias Pleroma.Repo - alias Pleroma.Web.OAuth - alias Pleroma.Web.OAuth.{App, Authorization, Token} - - def up do - for app <- Repo.all(Query.from(app in App)) do - scopes = OAuth.parse_scopes(app.scopes) - - Repo.update_all( - Query.from(auth in Authorization, where: auth.app_id == ^app.id), - set: [scopes: scopes] - ) - - Repo.update_all( - Query.from(token in Token, where: token.app_id == ^app.id), - set: [scopes: scopes] - ) - end - end - - def down, do: :noop -end diff --git a/priv/repo/migrations/20190213185600_data_migration_populate_o_auth_scopes.exs b/priv/repo/migrations/20190213185600_data_migration_populate_o_auth_scopes.exs new file mode 100644 index 000000000..7afbcbd76 --- /dev/null +++ b/priv/repo/migrations/20190213185600_data_migration_populate_o_auth_scopes.exs @@ -0,0 +1,11 @@ +defmodule Pleroma.Repo.Migrations.DataMigrationPopulateOAuthScopes do + use Ecto.Migration + + def up do + for t <- [:oauth_authorizations, :oauth_tokens] do + execute "UPDATE #{t} SET scopes = apps.scopes FROM apps WHERE #{t}.app_id = apps.id;" + end + end + + def down, do: :noop +end From 027adbc9e5c60cd43b8857eb7a3124e6df1310c2 Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Thu, 14 Feb 2019 17:03:19 +0300 Subject: [PATCH 05/12] [#468] Refactored OAuth scopes parsing / defaults handling. --- lib/pleroma/web/controller_helper.ex | 4 ++++ .../mastodon_api/mastodon_api_controller.ex | 11 ++++++--- lib/pleroma/web/oauth.ex | 23 +++++++++---------- lib/pleroma/web/oauth/oauth_controller.ex | 12 ++++------ 4 files changed, 28 insertions(+), 22 deletions(-) diff --git a/lib/pleroma/web/controller_helper.ex b/lib/pleroma/web/controller_helper.ex index 14e3d19fd..a32195b49 100644 --- a/lib/pleroma/web/controller_helper.ex +++ b/lib/pleroma/web/controller_helper.ex @@ -5,6 +5,10 @@ defmodule Pleroma.Web.ControllerHelper do use Pleroma.Web, :controller + def oauth_scopes(params, default) do + Pleroma.Web.OAuth.parse_scopes(params["scopes"] || params["scope"], default) + end + def json_response(conn, status, json) do conn |> put_status(status) diff --git a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex index 59f472e91..a1e9472b2 100644 --- a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex +++ b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex @@ -19,11 +19,12 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.Utils alias Pleroma.Web.CommonAPI - alias Pleroma.Web.OAuth alias Pleroma.Web.OAuth.{Authorization, Token, App} alias Pleroma.Web.MediaProxy + import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2] import Ecto.Query + require Logger @httpoison Application.get_env(:pleroma, :httpoison) @@ -32,8 +33,12 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do action_fallback(:errors) def create_app(conn, params) do - scopes = OAuth.parse_scopes(params["scope"] || params["scopes"]) - app_attrs = params |> Map.drop(["scope", "scopes"]) |> Map.put("scopes", scopes) + scopes = oauth_scopes(params, []) + + app_attrs = + params + |> Map.drop(["scope", "scopes"]) + |> Map.put("scopes", scopes) with cs <- App.register_changeset(%App{}, app_attrs), false <- cs.changes[:client_name] == @local_mastodon_name, diff --git a/lib/pleroma/web/oauth.ex b/lib/pleroma/web/oauth.ex index 761b80fde..8c78d1100 100644 --- a/lib/pleroma/web/oauth.ex +++ b/lib/pleroma/web/oauth.ex @@ -3,22 +3,21 @@ # SPDX-License-Identifier: AGPL-3.0-only defmodule Pleroma.Web.OAuth do - def parse_scopes(nil) do - nil + def parse_scopes(scopes, default) when is_list(scopes) do + scopes = Enum.filter(scopes, &(&1 not in [nil, ""])) + + if Enum.any?(scopes), + do: scopes, + else: default end - def parse_scopes(scopes) when is_list(scopes) do + def parse_scopes(scopes, default) when is_binary(scopes) do scopes + |> String.split(~r/[\s,]+/) + |> parse_scopes(default) end - def parse_scopes(scopes) do - scopes = - scopes - |> to_string() - |> String.trim() - - if scopes == "", - do: [], - else: String.split(scopes, [" ", ","]) + def parse_scopes(_, default) do + default end end diff --git a/lib/pleroma/web/oauth/oauth_controller.ex b/lib/pleroma/web/oauth/oauth_controller.ex index f00d5293d..3e905c7c7 100644 --- a/lib/pleroma/web/oauth/oauth_controller.ex +++ b/lib/pleroma/web/oauth/oauth_controller.ex @@ -5,11 +5,12 @@ defmodule Pleroma.Web.OAuth.OAuthController do use Pleroma.Web, :controller - alias Pleroma.Web.OAuth alias Pleroma.Web.OAuth.{Authorization, Token, App} alias Pleroma.{Repo, User} alias Comeonin.Pbkdf2 + import Pleroma.Web.ControllerHelper, only: [oauth_scopes: 2] + plug(:fetch_session) plug(:fetch_flash) @@ -19,7 +20,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do render(conn, "show.html", %{ response_type: params["response_type"], client_id: params["client_id"], - scopes: scopes(params) || [], + scopes: oauth_scopes(params, []), redirect_uri: params["redirect_uri"], state: params["state"] }) @@ -39,7 +40,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, %App{} = app <- Repo.get_by(App, client_id: client_id), true <- redirect_uri in String.split(app.redirect_uris), - scopes <- scopes(params) || app.scopes, + scopes <- oauth_scopes(params, app.scopes), [] <- scopes -- app.scopes, true <- Enum.any?(scopes), {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do @@ -117,7 +118,7 @@ defmodule Pleroma.Web.OAuth.OAuthController do %User{} = user <- User.get_by_nickname_or_email(name), true <- Pbkdf2.checkpw(password, user.password_hash), {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, - scopes <- scopes(params) || app.scopes, + scopes <- oauth_scopes(params, app.scopes), {:ok, auth} <- Authorization.create_authorization(app, user, scopes), {:ok, token} <- Token.exchange_token(app, auth) do response = %{ @@ -197,7 +198,4 @@ defmodule Pleroma.Web.OAuth.OAuthController do nil end end - - defp scopes(params), - do: OAuth.parse_scopes(params["scopes"] || params["scope"]) end From 2a4a4f3342bb3d2bbbd2354e858278d2e17f8654 Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Fri, 15 Feb 2019 19:54:37 +0300 Subject: [PATCH 06/12] [#468] Defined OAuth restrictions for all applicable routes. Improved missing "scopes" param handling. Allowed "any of" / "all of" mode specification in OAuthScopesPlug. Fixed auth UI / behavior when user selects no permissions at /oauth/authorize. --- lib/pleroma/plugs/oauth_scopes_plug.ex | 37 ++++-- lib/pleroma/web/controller_helper.ex | 2 +- .../mastodon_api/mastodon_api_controller.ex | 2 +- lib/pleroma/web/oauth.ex | 9 +- lib/pleroma/web/oauth/oauth_controller.ex | 42 ++++-- lib/pleroma/web/router.ex | 124 ++++++++++++------ .../web/templates/o_auth/o_auth/show.html.eex | 2 +- 7 files changed, 142 insertions(+), 76 deletions(-) diff --git a/lib/pleroma/plugs/oauth_scopes_plug.ex b/lib/pleroma/plugs/oauth_scopes_plug.ex index a81e29830..f2bfa2b1a 100644 --- a/lib/pleroma/plugs/oauth_scopes_plug.ex +++ b/lib/pleroma/plugs/oauth_scopes_plug.ex @@ -7,22 +7,35 @@ defmodule Pleroma.Plugs.OAuthScopesPlug do @behaviour Plug - def init(%{required_scopes: _} = options), do: options + def init(%{scopes: _} = options), do: options - def call(%Plug.Conn{assigns: assigns} = conn, %{required_scopes: required_scopes}) do + def call(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do + op = options[:op] || :| token = assigns[:token] - granted_scopes = token && token.scopes - if is_nil(token) || required_scopes -- granted_scopes == [] do - conn - else - missing_scopes = required_scopes -- granted_scopes - error_message = "Insufficient permissions: #{Enum.join(missing_scopes, ", ")}." + cond do + is_nil(token) -> + conn - conn - |> put_resp_content_type("application/json") - |> send_resp(403, Jason.encode!(%{error: error_message})) - |> halt() + op == :| && scopes -- token.scopes != scopes -> + conn + + op == :& && scopes -- token.scopes == [] -> + conn + + options[:fallback] == :proceed_unauthenticated -> + conn + |> assign(:user, nil) + |> assign(:token, nil) + + true -> + missing_scopes = scopes -- token.scopes + error_message = "Insufficient permissions: #{Enum.join(missing_scopes, " #{op} ")}." + + conn + |> put_resp_content_type("application/json") + |> send_resp(403, Jason.encode!(%{error: error_message})) + |> halt() end end end diff --git a/lib/pleroma/web/controller_helper.ex b/lib/pleroma/web/controller_helper.ex index a32195b49..8f36329ee 100644 --- a/lib/pleroma/web/controller_helper.ex +++ b/lib/pleroma/web/controller_helper.ex @@ -6,7 +6,7 @@ defmodule Pleroma.Web.ControllerHelper do use Pleroma.Web, :controller def oauth_scopes(params, default) do - Pleroma.Web.OAuth.parse_scopes(params["scopes"] || params["scope"], default) + Pleroma.Web.OAuth.parse_scopes(params["scope"] || params["scopes"], default) end def json_response(conn, status, json) do diff --git a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex index a1e9472b2..0e77ec907 100644 --- a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex +++ b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex @@ -33,7 +33,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do action_fallback(:errors) def create_app(conn, params) do - scopes = oauth_scopes(params, []) + scopes = oauth_scopes(params, ["read"]) app_attrs = params diff --git a/lib/pleroma/web/oauth.ex b/lib/pleroma/web/oauth.ex index 8c78d1100..d2835a0ba 100644 --- a/lib/pleroma/web/oauth.ex +++ b/lib/pleroma/web/oauth.ex @@ -3,16 +3,13 @@ # SPDX-License-Identifier: AGPL-3.0-only defmodule Pleroma.Web.OAuth do - def parse_scopes(scopes, default) when is_list(scopes) do - scopes = Enum.filter(scopes, &(&1 not in [nil, ""])) - - if Enum.any?(scopes), - do: scopes, - else: default + def parse_scopes(scopes, _default) when is_list(scopes) do + Enum.filter(scopes, &(&1 not in [nil, ""])) end def parse_scopes(scopes, default) when is_binary(scopes) do scopes + |> String.trim() |> String.split(~r/[\s,]+/) |> parse_scopes(default) end diff --git a/lib/pleroma/web/oauth/oauth_controller.ex b/lib/pleroma/web/oauth/oauth_controller.ex index 3e905c7c7..d8d3ea5b4 100644 --- a/lib/pleroma/web/oauth/oauth_controller.ex +++ b/lib/pleroma/web/oauth/oauth_controller.ex @@ -17,10 +17,20 @@ defmodule Pleroma.Web.OAuth.OAuthController do action_fallback(Pleroma.Web.OAuth.FallbackController) def authorize(conn, params) do + params_scopes = oauth_scopes(params, nil) + + scopes = + if params_scopes do + params_scopes + else + app = Repo.get_by(App, client_id: params["client_id"]) + app && app.scopes + end + render(conn, "show.html", %{ response_type: params["response_type"], client_id: params["client_id"], - scopes: oauth_scopes(params, []), + scopes: scopes || [], redirect_uri: params["redirect_uri"], state: params["state"] }) @@ -33,14 +43,14 @@ defmodule Pleroma.Web.OAuth.OAuthController do "password" => password, "client_id" => client_id, "redirect_uri" => redirect_uri - } = params + } = auth_params }) do with %User{} = user <- User.get_by_nickname_or_email(name), true <- Pbkdf2.checkpw(password, user.password_hash), {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, %App{} = app <- Repo.get_by(App, client_id: client_id), true <- redirect_uri in String.split(app.redirect_uris), - scopes <- oauth_scopes(params, app.scopes), + scopes <- oauth_scopes(auth_params, []), [] <- scopes -- app.scopes, true <- Enum.any?(scopes), {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do @@ -64,8 +74,8 @@ defmodule Pleroma.Web.OAuth.OAuthController do url_params = %{:code => auth.token} url_params = - if params["state"] do - Map.put(url_params, :state, params["state"]) + if auth_params["state"] do + Map.put(url_params, :state, auth_params["state"]) else url_params end @@ -75,14 +85,20 @@ defmodule Pleroma.Web.OAuth.OAuthController do redirect(conn, external: url) end else - {:auth_active, false} -> - conn - |> put_flash(:error, "Account confirmation pending") - |> put_status(:forbidden) - |> authorize(params) + res -> + msg = + if res == {:auth_active, false}, + do: "Account confirmation pending", + else: "Invalid Username/Password/Permissions" - error -> - error + app = Repo.get_by(App, client_id: client_id) + available_scopes = (app && app.scopes) || oauth_scopes(auth_params, []) + scope_param = Enum.join(available_scopes, " ") + + conn + |> put_flash(:error, msg) + |> put_status(:unauthorized) + |> authorize(Map.merge(auth_params, %{"scope" => scope_param})) end end @@ -119,6 +135,8 @@ defmodule Pleroma.Web.OAuth.OAuthController do true <- Pbkdf2.checkpw(password, user.password_hash), {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, scopes <- oauth_scopes(params, app.scopes), + [] <- scopes -- app.scopes, + true <- Enum.any?(scopes), {:ok, auth} <- Authorization.create_authorization(app, user, scopes), {:ok, token} <- Token.exchange_token(app, auth) do response = %{ diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 4ece311d3..6f17de1ca 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -74,16 +74,23 @@ defmodule Pleroma.Web.Router do plug(Pleroma.Plugs.EnsureUserKeyPlug) end + pipeline :oauth_read_or_unauthenticated do + plug(Pleroma.Plugs.OAuthScopesPlug, %{ + scopes: ["read"], + fallback: :proceed_unauthenticated + }) + end + pipeline :oauth_read do - plug(Pleroma.Plugs.OAuthScopesPlug, %{required_scopes: ["read"]}) + plug(Pleroma.Plugs.OAuthScopesPlug, %{scopes: ["read"]}) end pipeline :oauth_write do - plug(Pleroma.Plugs.OAuthScopesPlug, %{required_scopes: ["write"]}) + plug(Pleroma.Plugs.OAuthScopesPlug, %{scopes: ["write"]}) end pipeline :oauth_follow do - plug(Pleroma.Plugs.OAuthScopesPlug, %{required_scopes: ["follow"]}) + plug(Pleroma.Plugs.OAuthScopesPlug, %{scopes: ["follow"]}) end pipeline :well_known do @@ -113,6 +120,7 @@ defmodule Pleroma.Web.Router do scope "/api/pleroma", Pleroma.Web.TwitterAPI do pipe_through(:pleroma_api) + get("/password_reset/:token", UtilController, :show_password_reset) post("/password_reset", UtilController, :password_reset) get("/emoji", UtilController, :emoji) @@ -125,7 +133,8 @@ defmodule Pleroma.Web.Router do end scope "/api/pleroma/admin", Pleroma.Web.AdminAPI do - pipe_through(:admin_api) + pipe_through([:admin_api, :oauth_write]) + delete("/user", AdminAPIController, :user_delete) post("/user", AdminAPIController, :user_create) put("/users/tag", AdminAPIController, :tag_users) @@ -147,9 +156,14 @@ defmodule Pleroma.Web.Router do scope "/", Pleroma.Web.TwitterAPI do pipe_through(:pleroma_html) - get("/ostatus_subscribe", UtilController, :remote_follow) - post("/ostatus_subscribe", UtilController, :do_remote_follow) + post("/main/ostatus", UtilController, :remote_subscribe) + get("/ostatus_subscribe", UtilController, :remote_follow) + + scope [] do + pipe_through(:oauth_follow) + post("/ostatus_subscribe", UtilController, :do_remote_follow) + end end scope "/api/pleroma", Pleroma.Web.TwitterAPI do @@ -180,11 +194,11 @@ defmodule Pleroma.Web.Router do scope "/api/v1", Pleroma.Web.MastodonAPI do pipe_through(:authenticated_api) - get("/accounts/verify_credentials", MastodonAPIController, :verify_credentials) - scope [] do pipe_through(:oauth_read) + get("/accounts/verify_credentials", MastodonAPIController, :verify_credentials) + get("/accounts/relationships", MastodonAPIController, :relationships) get("/accounts/search", MastodonAPIController, :account_search) @@ -284,33 +298,40 @@ defmodule Pleroma.Web.Router do scope "/api/v1", Pleroma.Web.MastodonAPI do pipe_through(:api) + get("/instance", MastodonAPIController, :masto_instance) get("/instance/peers", MastodonAPIController, :peers) post("/apps", MastodonAPIController, :create_app) get("/custom_emojis", MastodonAPIController, :custom_emojis) - get("/timelines/public", MastodonAPIController, :public_timeline) - get("/timelines/tag/:tag", MastodonAPIController, :hashtag_timeline) - get("/timelines/list/:list_id", MastodonAPIController, :list_timeline) - - get("/statuses/:id", MastodonAPIController, :get_status) - get("/statuses/:id/context", MastodonAPIController, :get_context) get("/statuses/:id/card", MastodonAPIController, :status_card) + get("/statuses/:id/favourited_by", MastodonAPIController, :favourited_by) get("/statuses/:id/reblogged_by", MastodonAPIController, :reblogged_by) - get("/accounts/:id/statuses", MastodonAPIController, :user_statuses) - get("/accounts/:id/followers", MastodonAPIController, :followers) - get("/accounts/:id/following", MastodonAPIController, :following) - get("/accounts/:id", MastodonAPIController, :user) - get("/trends", MastodonAPIController, :empty_array) - get("/search", MastodonAPIController, :search) + scope [] do + pipe_through(:oauth_read_or_unauthenticated) + + get("/timelines/public", MastodonAPIController, :public_timeline) + get("/timelines/tag/:tag", MastodonAPIController, :hashtag_timeline) + get("/timelines/list/:list_id", MastodonAPIController, :list_timeline) + + get("/statuses/:id", MastodonAPIController, :get_status) + get("/statuses/:id/context", MastodonAPIController, :get_context) + + get("/accounts/:id/statuses", MastodonAPIController, :user_statuses) + get("/accounts/:id/followers", MastodonAPIController, :followers) + get("/accounts/:id/following", MastodonAPIController, :following) + get("/accounts/:id", MastodonAPIController, :user) + + get("/search", MastodonAPIController, :search) + end end scope "/api/v2", Pleroma.Web.MastodonAPI do - pipe_through(:api) + pipe_through([:api, :oauth_read_or_unauthenticated]) get("/search", MastodonAPIController, :search2) end @@ -327,19 +348,11 @@ defmodule Pleroma.Web.Router do scope "/api", Pleroma.Web do pipe_through(:api) - get("/statuses/user_timeline", TwitterAPI.Controller, :user_timeline) - get("/qvitter/statuses/user_timeline", TwitterAPI.Controller, :user_timeline) - get("/users/show", TwitterAPI.Controller, :show_user) - - get("/statuses/followers", TwitterAPI.Controller, :followers) - get("/statuses/friends", TwitterAPI.Controller, :friends) - get("/statuses/blocks", TwitterAPI.Controller, :blocks) - get("/statuses/show/:id", TwitterAPI.Controller, :fetch_status) - get("/statusnet/conversation/:id", TwitterAPI.Controller, :fetch_conversation) - post("/account/register", TwitterAPI.Controller, :register) post("/account/password_reset", TwitterAPI.Controller, :password_reset) + post("/account/resend_confirmation_email", TwitterAPI.Controller, :resend_confirmation_email) + get( "/account/confirm_email/:user_id/:token", TwitterAPI.Controller, @@ -347,14 +360,26 @@ defmodule Pleroma.Web.Router do as: :confirm_email ) - post("/account/resend_confirmation_email", TwitterAPI.Controller, :resend_confirmation_email) + scope [] do + pipe_through(:oauth_read_or_unauthenticated) - get("/search", TwitterAPI.Controller, :search) - get("/statusnet/tags/timeline/:tag", TwitterAPI.Controller, :public_and_external_timeline) + get("/statuses/user_timeline", TwitterAPI.Controller, :user_timeline) + get("/qvitter/statuses/user_timeline", TwitterAPI.Controller, :user_timeline) + get("/users/show", TwitterAPI.Controller, :show_user) + + get("/statuses/followers", TwitterAPI.Controller, :followers) + get("/statuses/friends", TwitterAPI.Controller, :friends) + get("/statuses/blocks", TwitterAPI.Controller, :blocks) + get("/statuses/show/:id", TwitterAPI.Controller, :fetch_status) + get("/statusnet/conversation/:id", TwitterAPI.Controller, :fetch_conversation) + + get("/search", TwitterAPI.Controller, :search) + get("/statusnet/tags/timeline/:tag", TwitterAPI.Controller, :public_and_external_timeline) + end end scope "/api", Pleroma.Web do - pipe_through(:api) + pipe_through([:api, :oauth_read_or_unauthenticated]) get("/statuses/public_timeline", TwitterAPI.Controller, :public_timeline) @@ -368,19 +393,19 @@ defmodule Pleroma.Web.Router do end scope "/api", Pleroma.Web, as: :twitter_api_search do - pipe_through(:api) + pipe_through([:api, :oauth_read_or_unauthenticated]) get("/pleroma/search_user", TwitterAPI.Controller, :search_user) end scope "/api", Pleroma.Web, as: :authenticated_twitter_api do pipe_through(:authenticated_api) - get("/account/verify_credentials", TwitterAPI.Controller, :verify_credentials) - post("/account/verify_credentials", TwitterAPI.Controller, :verify_credentials) - scope [] do pipe_through(:oauth_read) + get("/account/verify_credentials", TwitterAPI.Controller, :verify_credentials) + post("/account/verify_credentials", TwitterAPI.Controller, :verify_credentials) + get("/statuses/home_timeline", TwitterAPI.Controller, :friends_timeline) get("/statuses/friends_timeline", TwitterAPI.Controller, :friends_timeline) get("/statuses/mentions", TwitterAPI.Controller, :mentions_timeline) @@ -506,9 +531,16 @@ defmodule Pleroma.Web.Router do scope "/", Pleroma.Web.ActivityPub do pipe_through([:activitypub_client]) - get("/api/ap/whoami", ActivityPubController, :whoami) - get("/users/:nickname/inbox", ActivityPubController, :read_inbox) - post("/users/:nickname/outbox", ActivityPubController, :update_outbox) + scope [] do + pipe_through(:oauth_read) + get("/api/ap/whoami", ActivityPubController, :whoami) + get("/users/:nickname/inbox", ActivityPubController, :read_inbox) + end + + scope [] do + pipe_through(:oauth_write) + post("/users/:nickname/outbox", ActivityPubController, :update_outbox) + end end scope "/relay", Pleroma.Web.ActivityPub do @@ -518,6 +550,7 @@ defmodule Pleroma.Web.Router do scope "/", Pleroma.Web.ActivityPub do pipe_through(:activitypub) + post("/users/:nickname/inbox", ActivityPubController, :inbox) post("/inbox", ActivityPubController, :inbox) end @@ -538,8 +571,12 @@ defmodule Pleroma.Web.Router do pipe_through(:mastodon_html) get("/web/login", MastodonAPIController, :login) - get("/web/*path", MastodonAPIController, :index) delete("/auth/sign_out", MastodonAPIController, :logout) + + scope [] do + pipe_through(:oauth_read) + get("/web/*path", MastodonAPIController, :index) + end end pipeline :remote_media do @@ -547,6 +584,7 @@ defmodule Pleroma.Web.Router do scope "/proxy/", Pleroma.Web.MediaProxy do pipe_through(:remote_media) + get("/:sig/:url", MediaProxyController, :remote) get("/:sig/:url/:filename", MediaProxyController, :remote) end diff --git a/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex b/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex index 1ecb5b444..41b58aca0 100644 --- a/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex +++ b/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex @@ -14,7 +14,7 @@ <%= label f, :scope, "Permissions" %>
<%= for scope <- @scopes do %> - <%= checkbox f, :"scopes_#{scope}", hidden_input: false, value: scope, checked_value: scope, name: "authorization[scopes][]" %> + <%= checkbox f, :"scopes_#{scope}", value: scope, checked_value: scope, unchecked_value: "", name: "authorization[scopes][]" %> <%= label f, :"scopes_#{scope}", String.capitalize(scope) %>
<% end %> From dcf24a3233bb50689d26f9d7833f98158730ce35 Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Sun, 17 Feb 2019 13:49:14 +0300 Subject: [PATCH 07/12] [#468] Refactored OAuth scopes' defaults & missing selection handling. --- lib/pleroma/web/controller_helper.ex | 1 + .../mastodon_api/mastodon_api_controller.ex | 2 +- lib/pleroma/web/oauth/oauth_controller.ex | 46 +++++++++---------- .../web/templates/o_auth/o_auth/show.html.eex | 7 +-- test/support/factory.ex | 2 +- 5 files changed, 28 insertions(+), 30 deletions(-) diff --git a/lib/pleroma/web/controller_helper.ex b/lib/pleroma/web/controller_helper.ex index 8f36329ee..5915ea40e 100644 --- a/lib/pleroma/web/controller_helper.ex +++ b/lib/pleroma/web/controller_helper.ex @@ -6,6 +6,7 @@ defmodule Pleroma.Web.ControllerHelper do use Pleroma.Web, :controller def oauth_scopes(params, default) do + # Note: `scopes` is used by Mastodon — supporting it but sticking to OAuth's standard `scope` wherever we control it Pleroma.Web.OAuth.parse_scopes(params["scope"] || params["scopes"], default) end diff --git a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex index 0e77ec907..5d51e913d 100644 --- a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex +++ b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex @@ -1156,7 +1156,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do response_type: "code", client_id: app.client_id, redirect_uri: ".", - scope: app.scopes + scope: Enum.join(app.scopes, " ") ) conn diff --git a/lib/pleroma/web/oauth/oauth_controller.ex b/lib/pleroma/web/oauth/oauth_controller.ex index d8d3ea5b4..fe2c958c9 100644 --- a/lib/pleroma/web/oauth/oauth_controller.ex +++ b/lib/pleroma/web/oauth/oauth_controller.ex @@ -17,20 +17,15 @@ defmodule Pleroma.Web.OAuth.OAuthController do action_fallback(Pleroma.Web.OAuth.FallbackController) def authorize(conn, params) do - params_scopes = oauth_scopes(params, nil) - - scopes = - if params_scopes do - params_scopes - else - app = Repo.get_by(App, client_id: params["client_id"]) - app && app.scopes - end + app = Repo.get_by(App, client_id: params["client_id"]) + available_scopes = (app && app.scopes) || [] + scopes = oauth_scopes(params, nil) || available_scopes render(conn, "show.html", %{ response_type: params["response_type"], client_id: params["client_id"], - scopes: scopes || [], + available_scopes: available_scopes, + scopes: scopes, redirect_uri: params["redirect_uri"], state: params["state"] }) @@ -47,12 +42,13 @@ defmodule Pleroma.Web.OAuth.OAuthController do }) do with %User{} = user <- User.get_by_nickname_or_email(name), true <- Pbkdf2.checkpw(password, user.password_hash), - {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, %App{} = app <- Repo.get_by(App, client_id: client_id), true <- redirect_uri in String.split(app.redirect_uris), scopes <- oauth_scopes(auth_params, []), - [] <- scopes -- app.scopes, - true <- Enum.any?(scopes), + {:unsupported_scopes, []} <- {:unsupported_scopes, scopes -- app.scopes}, + # Note: `scope` param is intentionally not optional in this context + {:missing_scopes, false} <- {:missing_scopes, scopes == []}, + {:auth_active, true} <- {:auth_active, User.auth_active?(user)}, {:ok, auth} <- Authorization.create_authorization(app, user, scopes) do # Special case: Local MastodonFE. redirect_uri = @@ -85,20 +81,20 @@ defmodule Pleroma.Web.OAuth.OAuthController do redirect(conn, external: url) end else - res -> - msg = - if res == {:auth_active, false}, - do: "Account confirmation pending", - else: "Invalid Username/Password/Permissions" - - app = Repo.get_by(App, client_id: client_id) - available_scopes = (app && app.scopes) || oauth_scopes(auth_params, []) - scope_param = Enum.join(available_scopes, " ") - + {scopes_issue, _} when scopes_issue in [:unsupported_scopes, :missing_scopes] -> conn - |> put_flash(:error, msg) + |> put_flash(:error, "Permissions not specified.") |> put_status(:unauthorized) - |> authorize(Map.merge(auth_params, %{"scope" => scope_param})) + |> authorize(auth_params) + + {:auth_active, false} -> + conn + |> put_flash(:error, "Account confirmation pending.") + |> put_status(:forbidden) + |> authorize(auth_params) + + error -> + error end end diff --git a/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex b/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex index 41b58aca0..6e88efe11 100644 --- a/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex +++ b/lib/pleroma/web/templates/o_auth/o_auth/show.html.eex @@ -13,9 +13,10 @@ <%= label f, :scope, "Permissions" %>
-<%= for scope <- @scopes do %> - <%= checkbox f, :"scopes_#{scope}", value: scope, checked_value: scope, unchecked_value: "", name: "authorization[scopes][]" %> - <%= label f, :"scopes_#{scope}", String.capitalize(scope) %> +<%= for scope <- @available_scopes do %> + <%# Note: using hidden input with `unchecked_value` in order to distinguish user's empty selection from `scope` param being omitted %> + <%= checkbox f, :"scope_#{scope}", value: scope in @scopes && scope, checked_value: scope, unchecked_value: "", name: "authorization[scope][]" %> + <%= label f, :"scope_#{scope}", String.capitalize(scope) %>
<% end %> diff --git a/test/support/factory.ex b/test/support/factory.ex index eaa6f0ce2..fa5d60bfc 100644 --- a/test/support/factory.ex +++ b/test/support/factory.ex @@ -214,7 +214,7 @@ defmodule Pleroma.Factory do %Pleroma.Web.OAuth.App{ client_name: "Some client", redirect_uris: "https://example.com/callback", - scopes: ["read"], + scopes: ["read", "write", "follow"], website: "https://example.com", client_id: "aaabbb==", client_secret: "aaa;/&bbb" From d3fe2c8ec6116fbc3058f7a795ef59564bddfb08 Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Sun, 17 Feb 2019 14:07:35 +0300 Subject: [PATCH 08/12] [#468] Formatting fix. --- lib/pleroma/web/router.ex | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index e09164a77..81e83579e 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -240,16 +240,16 @@ defmodule Pleroma.Web.Router do post("/statuses", MastodonAPIController, :post_status) delete("/statuses/:id", MastodonAPIController, :delete_status) - post("/statuses/:id/reblog", MastodonAPIController, :reblog_status) - post("/statuses/:id/unreblog", MastodonAPIController, :unreblog_status) - post("/statuses/:id/favourite", MastodonAPIController, :fav_status) - post("/statuses/:id/unfavourite", MastodonAPIController, :unfav_status) - post("/statuses/:id/pin", MastodonAPIController, :pin_status) - post("/statuses/:id/unpin", MastodonAPIController, :unpin_status) - post("/statuses/:id/bookmark", MastodonAPIController, :bookmark_status) - post("/statuses/:id/unbookmark", MastodonAPIController, :unbookmark_status) - post("/statuses/:id/mute", MastodonAPIController, :mute_conversation) - post("/statuses/:id/unmute", MastodonAPIController, :unmute_conversation) + post("/statuses/:id/reblog", MastodonAPIController, :reblog_status) + post("/statuses/:id/unreblog", MastodonAPIController, :unreblog_status) + post("/statuses/:id/favourite", MastodonAPIController, :fav_status) + post("/statuses/:id/unfavourite", MastodonAPIController, :unfav_status) + post("/statuses/:id/pin", MastodonAPIController, :pin_status) + post("/statuses/:id/unpin", MastodonAPIController, :unpin_status) + post("/statuses/:id/bookmark", MastodonAPIController, :bookmark_status) + post("/statuses/:id/unbookmark", MastodonAPIController, :unbookmark_status) + post("/statuses/:id/mute", MastodonAPIController, :mute_conversation) + post("/statuses/:id/unmute", MastodonAPIController, :unmute_conversation) post("/media", MastodonAPIController, :upload) put("/media/:id", MastodonAPIController, :update_media) From 04ee877a20a849db53a307a1736e635229129b7a Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Tue, 19 Feb 2019 22:28:21 +0300 Subject: [PATCH 09/12] [#468] Added OAuth scopes-specific tests. --- .../mastodon_api_controller_test.exs | 18 ++++ test/web/oauth/authorization_test.exs | 50 ++++------ test/web/oauth/oauth_controller_test.exs | 96 ++++++++++++++++--- test/web/oauth/token_test.exs | 8 +- .../twitter_api_controller_test.exs | 18 ++++ test/web/twitter_api/util_controller_test.exs | 19 ++++ 6 files changed, 162 insertions(+), 47 deletions(-) diff --git a/test/web/mastodon_api/mastodon_api_controller_test.exs b/test/web/mastodon_api/mastodon_api_controller_test.exs index e43bc4508..8dcbde48b 100644 --- a/test/web/mastodon_api/mastodon_api_controller_test.exs +++ b/test/web/mastodon_api/mastodon_api_controller_test.exs @@ -1536,6 +1536,24 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do assert user_response = json_response(conn, 200) assert user_response["header"] != User.banner_url(user) end + + test "requires 'write' permission", %{conn: conn} do + token1 = insert(:oauth_token, scopes: ["read"]) + token2 = insert(:oauth_token, scopes: ["write", "follow"]) + + for token <- [token1, token2] do + conn = + conn + |> put_req_header("authorization", "Bearer #{token.token}") + |> patch("/api/v1/accounts/update_credentials", %{}) + + if token == token1 do + assert %{"error" => "Insufficient permissions: write."} == json_response(conn, 403) + else + assert json_response(conn, 200) + end + end + end end test "get instance information", %{conn: conn} do diff --git a/test/web/oauth/authorization_test.exs b/test/web/oauth/authorization_test.exs index b1a51e30e..306db2e62 100644 --- a/test/web/oauth/authorization_test.exs +++ b/test/web/oauth/authorization_test.exs @@ -8,36 +8,37 @@ defmodule Pleroma.Web.OAuth.AuthorizationTest do alias Pleroma.Web.OAuth.App import Pleroma.Factory - test "create an authorization token for a valid app" do + setup do {:ok, app} = Repo.insert( App.register_changeset(%App{}, %{ client_name: "client", - scopes: ["scope"], + scopes: ["read", "write"], redirect_uris: "url" }) ) - user = insert(:user) - - {:ok, auth} = Authorization.create_authorization(app, user) - - assert auth.user_id == user.id - assert auth.app_id == app.id - assert String.length(auth.token) > 10 - assert auth.used == false + %{app: app} end - test "use up a token" do - {:ok, app} = - Repo.insert( - App.register_changeset(%App{}, %{ - client_name: "client", - scopes: ["scope"], - redirect_uris: "url" - }) - ) + test "create an authorization token for a valid app", %{app: app} do + user = insert(:user) + {:ok, auth1} = Authorization.create_authorization(app, user) + assert auth1.scopes == app.scopes + + {:ok, auth2} = Authorization.create_authorization(app, user, ["read"]) + assert auth2.scopes == ["read"] + + for auth <- [auth1, auth2] do + assert auth.user_id == user.id + assert auth.app_id == app.id + assert String.length(auth.token) > 10 + assert auth.used == false + end + end + + test "use up a token", %{app: app} do user = insert(:user) {:ok, auth} = Authorization.create_authorization(app, user) @@ -61,16 +62,7 @@ defmodule Pleroma.Web.OAuth.AuthorizationTest do assert {:error, "token expired"} == Authorization.use_token(expired_auth) end - test "delete authorizations" do - {:ok, app} = - Repo.insert( - App.register_changeset(%App{}, %{ - client_name: "client", - scopes: ["scope"], - redirect_uris: "url" - }) - ) - + test "delete authorizations", %{app: app} do user = insert(:user) {:ok, auth} = Authorization.create_authorization(app, user) diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs index ca1c04319..53d83e6e8 100644 --- a/test/web/oauth/oauth_controller_test.exs +++ b/test/web/oauth/oauth_controller_test.exs @@ -12,7 +12,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do test "redirects with oauth authorization" do user = insert(:user) - app = insert(:oauth_app) + app = insert(:oauth_app, scopes: ["read", "write", "follow"]) conn = build_conn() @@ -22,7 +22,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do "password" => "test", "client_id" => app.client_id, "redirect_uri" => app.redirect_uris, - "scope" => Enum.join(app.scopes, " "), + "scope" => "read write", "state" => "statepassed" } }) @@ -33,10 +33,12 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do query = URI.parse(target).query |> URI.query_decoder() |> Map.new() assert %{"state" => "statepassed", "code" => code} = query - assert Repo.get_by(Authorization, token: code) + auth = Repo.get_by(Authorization, token: code) + assert auth + assert auth.scopes == ["read", "write"] end - test "correctly handles wrong credentials", %{conn: conn} do + test "returns 401 for wrong credentials", %{conn: conn} do user = insert(:user) app = insert(:oauth_app) @@ -48,7 +50,8 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do "password" => "wrong", "client_id" => app.client_id, "redirect_uri" => app.redirect_uris, - "state" => "statepassed" + "state" => "statepassed", + "scope" => Enum.join(app.scopes, " ") } }) |> html_response(:unauthorized) @@ -58,14 +61,66 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do assert result =~ app.redirect_uris # Error message - assert result =~ "Invalid" + assert result =~ "Invalid Username/Password" + end + + test "returns 401 for missing scopes", %{conn: conn} do + user = insert(:user) + app = insert(:oauth_app) + + result = + conn + |> post("/oauth/authorize", %{ + "authorization" => %{ + "name" => user.nickname, + "password" => "test", + "client_id" => app.client_id, + "redirect_uri" => app.redirect_uris, + "state" => "statepassed", + "scope" => "" + } + }) + |> html_response(:unauthorized) + + # Keep the details + assert result =~ app.client_id + assert result =~ app.redirect_uris + + # Error message + assert result =~ "Permissions not specified" + end + + test "returns 401 for scopes beyond app scopes", %{conn: conn} do + user = insert(:user) + app = insert(:oauth_app, scopes: ["read", "write"]) + + result = + conn + |> post("/oauth/authorize", %{ + "authorization" => %{ + "name" => user.nickname, + "password" => "test", + "client_id" => app.client_id, + "redirect_uri" => app.redirect_uris, + "state" => "statepassed", + "scope" => "read write follow" + } + }) + |> html_response(:unauthorized) + + # Keep the details + assert result =~ app.client_id + assert result =~ app.redirect_uris + + # Error message + assert result =~ "Permissions not specified" end test "issues a token for an all-body request" do user = insert(:user) - app = insert(:oauth_app) + app = insert(:oauth_app, scopes: ["read", "write"]) - {:ok, auth} = Authorization.create_authorization(app, user) + {:ok, auth} = Authorization.create_authorization(app, user, ["write"]) conn = build_conn() @@ -78,15 +133,19 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do }) assert %{"access_token" => token} = json_response(conn, 200) - assert Repo.get_by(Token, token: token) + + token = Repo.get_by(Token, token: token) + assert token + assert token.scopes == auth.scopes end - test "issues a token for `password` grant_type with valid credentials" do + test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do password = "testpassword" user = insert(:user, password_hash: Comeonin.Pbkdf2.hashpwsalt(password)) - app = insert(:oauth_app) + app = insert(:oauth_app, scopes: ["read", "write"]) + # Note: "scope" param is intentionally omitted conn = build_conn() |> post("/oauth/token", %{ @@ -98,14 +157,18 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do }) assert %{"access_token" => token} = json_response(conn, 200) - assert Repo.get_by(Token, token: token) + + token = Repo.get_by(Token, token: token) + assert token + assert token.scopes == app.scopes end test "issues a token for request with HTTP basic auth client credentials" do user = insert(:user) - app = insert(:oauth_app) + app = insert(:oauth_app, scopes: ["scope1", "scope2"]) - {:ok, auth} = Authorization.create_authorization(app, user) + {:ok, auth} = Authorization.create_authorization(app, user, ["scope2"]) + assert auth.scopes == ["scope2"] app_encoded = (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret)) @@ -121,7 +184,10 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do }) assert %{"access_token" => token} = json_response(conn, 200) - assert Repo.get_by(Token, token: token) + + token = Repo.get_by(Token, token: token) + assert token + assert token.scopes == ["scope2"] end test "rejects token exchange with invalid client credentials" do diff --git a/test/web/oauth/token_test.exs b/test/web/oauth/token_test.exs index a708e4991..62444a0fa 100644 --- a/test/web/oauth/token_test.exs +++ b/test/web/oauth/token_test.exs @@ -11,24 +11,26 @@ defmodule Pleroma.Web.OAuth.TokenTest do import Pleroma.Factory - test "exchanges a auth token for an access token" do + test "exchanges a auth token for an access token, preserving `scopes`" do {:ok, app} = Repo.insert( App.register_changeset(%App{}, %{ client_name: "client", - scopes: ["scope"], + scopes: ["read", "write"], redirect_uris: "url" }) ) user = insert(:user) - {:ok, auth} = Authorization.create_authorization(app, user) + {:ok, auth} = Authorization.create_authorization(app, user, ["read"]) + assert auth.scopes == ["read"] {:ok, token} = Token.exchange_token(app, auth) assert token.app_id == app.id assert token.user_id == user.id + assert token.scopes == auth.scopes assert String.length(token.token) > 10 assert String.length(token.refresh_token) > 10 diff --git a/test/web/twitter_api/twitter_api_controller_test.exs b/test/web/twitter_api/twitter_api_controller_test.exs index 1571ab68e..27b1e878c 100644 --- a/test/web/twitter_api/twitter_api_controller_test.exs +++ b/test/web/twitter_api/twitter_api_controller_test.exs @@ -1690,6 +1690,24 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do assert [relationship] = json_response(conn, 200) assert other_user.id == relationship["id"] end + + test "requires 'read' permission", %{conn: conn} do + token1 = insert(:oauth_token, scopes: ["write"]) + token2 = insert(:oauth_token, scopes: ["read"]) + + for token <- [token1, token2] do + conn = + conn + |> put_req_header("authorization", "Bearer #{token.token}") + |> get("/api/pleroma/friend_requests") + + if token == token1 do + assert %{"error" => "Insufficient permissions: read."} == json_response(conn, 403) + else + assert json_response(conn, 200) + end + end + end end describe "POST /api/pleroma/friendships/approve" do diff --git a/test/web/twitter_api/util_controller_test.exs b/test/web/twitter_api/util_controller_test.exs index 007d7d8e6..fc762ab18 100644 --- a/test/web/twitter_api/util_controller_test.exs +++ b/test/web/twitter_api/util_controller_test.exs @@ -16,6 +16,25 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do assert response == "job started" end + + test "requires 'follow' permission", %{conn: conn} do + token1 = insert(:oauth_token, scopes: ["read", "write"]) + token2 = insert(:oauth_token, scopes: ["follow"]) + another_user = insert(:user) + + for token <- [token1, token2] do + conn = + conn + |> put_req_header("authorization", "Bearer #{token.token}") + |> post("/api/pleroma/follow_import", %{"list" => "#{another_user.ap_id}"}) + + if token == token1 do + assert %{"error" => "Insufficient permissions: follow."} == json_response(conn, 403) + else + assert json_response(conn, 200) + end + end + end end describe "POST /api/pleroma/blocks_import" do From 337367d764dda8947eb0369f31da641c045dd3b0 Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Wed, 20 Feb 2019 12:27:28 +0300 Subject: [PATCH 10/12] [#468] More OAuth scopes-specific tests. --- test/plugs/oauth_scopes_plug_test.exs | 122 ++++++++++++++++++ .../twitter_api_controller_test.exs | 16 +++ 2 files changed, 138 insertions(+) create mode 100644 test/plugs/oauth_scopes_plug_test.exs diff --git a/test/plugs/oauth_scopes_plug_test.exs b/test/plugs/oauth_scopes_plug_test.exs new file mode 100644 index 000000000..f328026df --- /dev/null +++ b/test/plugs/oauth_scopes_plug_test.exs @@ -0,0 +1,122 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2018 Pleroma Authors +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Plugs.OAuthScopesPlugTest do + use Pleroma.Web.ConnCase, async: true + + alias Pleroma.Plugs.OAuthScopesPlug + alias Pleroma.Repo + + import Pleroma.Factory + + test "proceeds with no op if `assigns[:token]` is nil", %{conn: conn} do + conn = + conn + |> assign(:user, insert(:user)) + |> OAuthScopesPlug.call(%{scopes: ["read"]}) + + refute conn.halted + assert conn.assigns[:user] + end + + test "proceeds with no op if `token.scopes` fulfill specified 'any of' conditions", %{ + conn: conn + } do + token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user) + + conn = + conn + |> assign(:user, token.user) + |> assign(:token, token) + |> OAuthScopesPlug.call(%{scopes: ["read"]}) + + refute conn.halted + assert conn.assigns[:user] + end + + test "proceeds with no op if `token.scopes` fulfill specified 'all of' conditions", %{ + conn: conn + } do + token = insert(:oauth_token, scopes: ["scope1", "scope2", "scope3"]) |> Repo.preload(:user) + + conn = + conn + |> assign(:user, token.user) + |> assign(:token, token) + |> OAuthScopesPlug.call(%{scopes: ["scope2", "scope3"], op: :&}) + + refute conn.halted + assert conn.assigns[:user] + end + + test "proceeds with cleared `assigns[:user]` if `token.scopes` doesn't fulfill specified 'any of' conditions " <> + "and `fallback: :proceed_unauthenticated` option is specified", + %{conn: conn} do + token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user) + + conn = + conn + |> assign(:user, token.user) + |> assign(:token, token) + |> OAuthScopesPlug.call(%{scopes: ["follow"], fallback: :proceed_unauthenticated}) + + refute conn.halted + refute conn.assigns[:user] + end + + test "proceeds with cleared `assigns[:user]` if `token.scopes` doesn't fulfill specified 'all of' conditions " <> + "and `fallback: :proceed_unauthenticated` option is specified", + %{conn: conn} do + token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user) + + conn = + conn + |> assign(:user, token.user) + |> assign(:token, token) + |> OAuthScopesPlug.call(%{ + scopes: ["read", "follow"], + op: :&, + fallback: :proceed_unauthenticated + }) + + refute conn.halted + refute conn.assigns[:user] + end + + test "returns 403 and halts in case of no :fallback option and `token.scopes` not fulfilling specified 'any of' conditions", + %{conn: conn} do + token = insert(:oauth_token, scopes: ["read", "write"]) + any_of_scopes = ["follow"] + + conn = + conn + |> assign(:token, token) + |> OAuthScopesPlug.call(%{scopes: any_of_scopes}) + + assert conn.halted + assert 403 == conn.status + + expected_error = "Insufficient permissions: #{Enum.join(any_of_scopes, ", ")}." + assert Jason.encode!(%{error: expected_error}) == conn.resp_body + end + + test "returns 403 and halts in case of no :fallback option and `token.scopes` not fulfilling specified 'all of' conditions", + %{conn: conn} do + token = insert(:oauth_token, scopes: ["read", "write"]) + all_of_scopes = ["write", "follow"] + + conn = + conn + |> assign(:token, token) + |> OAuthScopesPlug.call(%{scopes: all_of_scopes, op: :&}) + + assert conn.halted + assert 403 == conn.status + + expected_error = + "Insufficient permissions: #{Enum.join(all_of_scopes -- token.scopes, ", ")}." + + assert Jason.encode!(%{error: expected_error}) == conn.resp_body + end +end diff --git a/test/web/twitter_api/twitter_api_controller_test.exs b/test/web/twitter_api/twitter_api_controller_test.exs index 27b1e878c..05a832967 100644 --- a/test/web/twitter_api/twitter_api_controller_test.exs +++ b/test/web/twitter_api/twitter_api_controller_test.exs @@ -14,6 +14,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do alias Pleroma.Notification alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.OAuth.Token + alias Pleroma.Web.TwitterAPI.Controller alias Pleroma.Web.TwitterAPI.UserView alias Pleroma.Web.TwitterAPI.NotificationView alias Pleroma.Web.CommonAPI @@ -22,6 +23,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do alias Ecto.Changeset import Pleroma.Factory + import Mock @banner "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7" @@ -187,6 +189,20 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do |> get("/api/statuses/public_timeline.json") |> json_response(200) end + + test_with_mock "treats user as unauthenticated if `assigns[:token]` is present but lacks `read` permission", + Controller, + [:passthrough], + [] do + token = insert(:oauth_token, scopes: ["write"]) + + build_conn() + |> put_req_header("authorization", "Bearer #{token.token}") + |> get("/api/statuses/public_timeline.json") + |> json_response(200) + + assert called(Controller.public_timeline(%{assigns: %{user: nil}}, :_)) + end end describe "GET /statuses/public_and_external_timeline.json" do From 3ad91ec3c165a1db853390c75f09c8618d08deae Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Wed, 20 Feb 2019 14:05:02 +0300 Subject: [PATCH 11/12] [#468] Adjusted scope restriction for MastodonAPIController#index. --- lib/pleroma/web/router.ex | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 3692e13e3..421fb075a 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -582,7 +582,7 @@ defmodule Pleroma.Web.Router do delete("/auth/sign_out", MastodonAPIController, :logout) scope [] do - pipe_through(:oauth_read) + pipe_through(:oauth_read_or_unauthenticated) get("/web/*path", MastodonAPIController, :index) end end From b574d97c2ee5ea926342b6ef00d9c22c1cc7ebdd Mon Sep 17 00:00:00 2001 From: Ivan Tashkinov Date: Wed, 20 Feb 2019 17:27:41 +0300 Subject: [PATCH 12/12] [#468] Added support for `push` OAuth scope (Mastodon 2.4+). --- .../web/mastodon_api/mastodon_api_controller.ex | 12 +++++++++++- lib/pleroma/web/router.ex | 8 ++++++++ test/support/factory.ex | 2 +- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex index d484351e9..17b95eb44 100644 --- a/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex +++ b/lib/pleroma/web/mastodon_api/mastodon_api_controller.ex @@ -1273,15 +1273,25 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do defp get_or_make_app() do find_attrs = %{client_name: @local_mastodon_name, redirect_uris: "."} + scopes = ["read", "write", "follow", "push"] with %App{} = app <- Repo.get_by(App, find_attrs) do + {:ok, app} = + if app.scopes == scopes do + {:ok, app} + else + app + |> Ecto.Changeset.change(%{scopes: scopes}) + |> Repo.update() + end + {:ok, app} else _e -> cs = App.register_changeset( %App{}, - Map.put(find_attrs, :scopes, ["read", "write", "follow"]) + Map.put(find_attrs, :scopes, scopes) ) Repo.insert(cs) diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 562e24ad9..559d3aa0c 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -93,6 +93,10 @@ defmodule Pleroma.Web.Router do plug(Pleroma.Plugs.OAuthScopesPlug, %{scopes: ["follow"]}) end + pipeline :oauth_push do + plug(Pleroma.Plugs.OAuthScopesPlug, %{scopes: ["push"]}) + end + pipeline :well_known do plug(:accepts, ["json", "jrd+json", "xml", "xrd+xml"]) end @@ -290,6 +294,10 @@ defmodule Pleroma.Web.Router do post("/domain_blocks", MastodonAPIController, :block_domain) delete("/domain_blocks", MastodonAPIController, :unblock_domain) + end + + scope [] do + pipe_through(:oauth_push) post("/push/subscription", MastodonAPIController, :create_push_subscription) get("/push/subscription", MastodonAPIController, :get_push_subscription) diff --git a/test/support/factory.ex b/test/support/factory.ex index 0c59b3ce8..d1956d1cd 100644 --- a/test/support/factory.ex +++ b/test/support/factory.ex @@ -214,7 +214,7 @@ defmodule Pleroma.Factory do %Pleroma.Web.OAuth.App{ client_name: "Some client", redirect_uris: "https://example.com/callback", - scopes: ["read", "write", "follow"], + scopes: ["read", "write", "follow", "push"], website: "https://example.com", client_id: "aaabbb==", client_secret: "aaa;/&bbb"