OAuthScopesPlug: disallowed nil token (unless with :fallback option). WIP: controller tests modification: OAuth scopes usage.

This commit is contained in:
Ivan Tashkinov 2019-12-15 22:32:42 +03:00
parent 8efacfed67
commit 7973cbdb9f
14 changed files with 638 additions and 912 deletions

View File

@ -18,16 +18,13 @@ def call(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
token = assigns[:token] token = assigns[:token]
scopes = transform_scopes(scopes, options) scopes = transform_scopes(scopes, options)
matched_scopes = token && filter_descendants(scopes, token.scopes) matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
cond do cond do
is_nil(token) -> token && op == :| && Enum.any?(matched_scopes) ->
maybe_perform_instance_privacy_check(conn, options)
op == :| && Enum.any?(matched_scopes) ->
conn conn
op == :& && matched_scopes == scopes -> token && op == :& && matched_scopes == scopes ->
conn conn
options[:fallback] == :proceed_unauthenticated -> options[:fallback] == :proceed_unauthenticated ->

View File

@ -1855,9 +1855,9 @@ def admin_api_update(user, params) do
]) ])
with {:ok, updated_user} <- update_and_set_cache(changeset) do with {:ok, updated_user} <- update_and_set_cache(changeset) do
if user.is_admin && !updated_user.is_admin do if user.is_admin != updated_user.is_admin do
# Tokens & authorizations containing any admin scopes must be revoked (revoking all). # Admin status change results in change of accessible OAuth scopes, and instead of changing
# This is an extra safety measure (tokens' admin scopes won't be accepted for non-admins). # already issued tokens we revoke them, requiring user to sign in again
global_sign_out(user) global_sign_out(user)
end end

View File

@ -52,7 +52,7 @@ def list_from(conn, %{"instance_address" => address}) do
@doc """ @doc """
Lists the packs available on the instance as JSON. Lists the packs available on the instance as JSON.
The information is public and does not require authentification. The format is The information is public and does not require authentication. The format is
a map of "pack directory name" to pack.json contents. a map of "pack directory name" to pack.json contents.
""" """
def list_packs(conn, _params) do def list_packs(conn, _params) do

View File

@ -22,7 +22,14 @@ defmodule Pleroma.Web.PleromaAPI.PleromaAPIController do
plug( plug(
OAuthScopesPlug, OAuthScopesPlug,
%{scopes: ["read:statuses"]} when action in [:conversation, :conversation_statuses] %{scopes: ["read:statuses"]}
when action in [:conversation, :conversation_statuses, :emoji_reactions_by]
)
plug(
OAuthScopesPlug,
%{scopes: ["write:statuses"]}
when action in [:react_with_emoji, :unreact_with_emoji]
) )
plug( plug(

View File

@ -22,7 +22,14 @@ defmodule Pleroma.Web.TwitterAPI.UtilController do
plug( plug(
OAuthScopesPlug, OAuthScopesPlug,
%{scopes: ["follow", "write:follows"]} %{scopes: ["follow", "write:follows"]}
when action in [:do_remote_follow, :follow_import] when action == :follow_import
)
# Note: follower can submit the form (with password auth) not being signed in (having no token)
plug(
OAuthScopesPlug,
%{fallback: :proceed_unauthenticated, scopes: ["follow", "write:follows"]}
when action == :do_remote_follow
) )
plug(OAuthScopesPlug, %{scopes: ["follow", "write:blocks"]} when action == :blocks_import) plug(OAuthScopesPlug, %{scopes: ["follow", "write:blocks"]} when action == :blocks_import)
@ -112,6 +119,28 @@ defp is_status?(acct) do
end end
end end
def do_remote_follow(%{assigns: %{user: user}} = conn, %{"user" => %{"id" => id}})
when not is_nil(user) do
with {:fetch_user, %User{} = followee} <- {:fetch_user, User.get_cached_by_id(id)},
{:ok, _follower, _followee, _activity} <- CommonAPI.follow(user, followee) do
conn
|> render("followed.html", %{error: false})
else
# Was already following user
{:error, "Could not follow user:" <> _rest} ->
render(conn, "followed.html", %{error: "Error following account"})
{:fetch_user, error} ->
Logger.debug("Remote follow failed with error #{inspect(error)}")
render(conn, "followed.html", %{error: "Could not find user"})
e ->
Logger.debug("Remote follow failed with error #{inspect(e)}")
render(conn, "followed.html", %{error: "Something went wrong."})
end
end
# Note: "id" is the id of followee user, disregard incorrect placing under "authorization"
def do_remote_follow(conn, %{ def do_remote_follow(conn, %{
"authorization" => %{"name" => username, "password" => password, "id" => id} "authorization" => %{"name" => username, "password" => password, "id" => id}
}) do }) do
@ -145,24 +174,12 @@ def do_remote_follow(conn, %{
end end
end end
def do_remote_follow(%{assigns: %{user: user}} = conn, %{"user" => %{"id" => id}}) do def do_remote_follow(%{assigns: %{user: nil}} = conn, _) do
with {:fetch_user, %User{} = followee} <- {:fetch_user, User.get_cached_by_id(id)}, render(conn, "followed.html", %{error: "Insufficient permissions: follow | write:follows."})
{:ok, _follower, _followee, _activity} <- CommonAPI.follow(user, followee) do
conn
|> render("followed.html", %{error: false})
else
# Was already following user
{:error, "Could not follow user:" <> _rest} ->
render(conn, "followed.html", %{error: "Error following account"})
{:fetch_user, error} ->
Logger.debug("Remote follow failed with error #{inspect(error)}")
render(conn, "followed.html", %{error: "Could not find user"})
e ->
Logger.debug("Remote follow failed with error #{inspect(e)}")
render(conn, "followed.html", %{error: "Something went wrong."})
end end
def do_remote_follow(conn, _) do
render(conn, "followed.html", %{error: "Something went wrong."})
end end
def notifications_read(%{assigns: %{user: user}} = conn, %{"id" => notification_id}) do def notifications_read(%{assigns: %{user: user}} = conn, %{"id" => notification_id}) do
@ -345,7 +362,9 @@ def change_email(%{assigns: %{user: user}} = conn, params) do
end end
def delete_account(%{assigns: %{user: user}} = conn, params) do def delete_account(%{assigns: %{user: user}} = conn, params) do
case CommonAPI.Utils.confirm_current_password(user, params["password"]) do password = params["password"] || ""
case CommonAPI.Utils.confirm_current_password(user, password) do
{:ok, user} -> {:ok, user} ->
User.delete(user) User.delete(user)
json(conn, %{status: "success"}) json(conn, %{status: "success"})

View File

@ -98,7 +98,7 @@ test "it creates a notification for user if the user blocks the activity author"
assert Notification.create_notification(activity, user) assert Notification.create_notification(activity, user)
end end
test "it creates a notificatin for the user if the user mutes the activity author" do test "it creates a notification for the user if the user mutes the activity author" do
muter = insert(:user) muter = insert(:user)
muted = insert(:user) muted = insert(:user)
{:ok, _} = User.mute(muter, muted) {:ok, _} = User.mute(muter, muted)

View File

@ -16,34 +16,6 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do
:ok :ok
end end
describe "when `assigns[:token]` is nil, " do
test "with :skip_instance_privacy_check option, proceeds with no op", %{conn: conn} do
conn =
conn
|> assign(:user, insert(:user))
|> OAuthScopesPlug.call(%{scopes: ["read"], skip_instance_privacy_check: true})
refute conn.halted
assert conn.assigns[:user]
refute called(EnsurePublicOrAuthenticatedPlug.call(conn, :_))
end
test "without :skip_instance_privacy_check option, calls EnsurePublicOrAuthenticatedPlug", %{
conn: conn
} do
conn =
conn
|> assign(:user, insert(:user))
|> OAuthScopesPlug.call(%{scopes: ["read"]})
refute conn.halted
assert conn.assigns[:user]
assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_))
end
end
test "if `token.scopes` fulfills specified 'any of' conditions, " <> test "if `token.scopes` fulfills specified 'any of' conditions, " <>
"proceeds with no op", "proceeds with no op",
%{conn: conn} do %{conn: conn} do
@ -75,64 +47,56 @@ test "if `token.scopes` fulfills specified 'all of' conditions, " <>
end end
describe "with `fallback: :proceed_unauthenticated` option, " do describe "with `fallback: :proceed_unauthenticated` option, " do
test "if `token.scopes` doesn't fulfill specified 'any of' conditions, " <> test "if `token.scopes` doesn't fulfill specified conditions, " <>
"clears `assigns[:user]` and calls EnsurePublicOrAuthenticatedPlug", "clears :user and :token assigns and calls EnsurePublicOrAuthenticatedPlug",
%{conn: conn} do %{conn: conn} do
token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user) user = insert(:user)
token1 = insert(:oauth_token, scopes: ["read", "write"], user: user)
conn = for token <- [token1, nil], op <- [:|, :&] do
ret_conn =
conn conn
|> assign(:user, token.user) |> assign(:user, user)
|> assign(:token, token)
|> OAuthScopesPlug.call(%{scopes: ["follow"], fallback: :proceed_unauthenticated})
refute conn.halted
refute conn.assigns[:user]
assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_))
end
test "if `token.scopes` doesn't fulfill specified 'all of' conditions, " <>
"clears `assigns[:user] and calls EnsurePublicOrAuthenticatedPlug",
%{conn: conn} do
token = insert(:oauth_token, scopes: ["read", "write"]) |> Repo.preload(:user)
conn =
conn
|> assign(:user, token.user)
|> assign(:token, token) |> assign(:token, token)
|> OAuthScopesPlug.call(%{ |> OAuthScopesPlug.call(%{
scopes: ["read", "follow"], scopes: ["follow"],
op: :&, op: op,
fallback: :proceed_unauthenticated fallback: :proceed_unauthenticated
}) })
refute conn.halted refute ret_conn.halted
refute conn.assigns[:user] refute ret_conn.assigns[:user]
refute ret_conn.assigns[:token]
assert called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) assert called(EnsurePublicOrAuthenticatedPlug.call(ret_conn, :_))
end
end end
test "with :skip_instance_privacy_check option, " <> test "with :skip_instance_privacy_check option, " <>
"if `token.scopes` doesn't fulfill specified conditions, " <> "if `token.scopes` doesn't fulfill specified conditions, " <>
"clears `assigns[:user]` and does not call EnsurePublicOrAuthenticatedPlug", "clears :user and :token assigns and does NOT call EnsurePublicOrAuthenticatedPlug",
%{conn: conn} do %{conn: conn} do
token = insert(:oauth_token, scopes: ["read:statuses", "write"]) |> Repo.preload(:user) user = insert(:user)
token1 = insert(:oauth_token, scopes: ["read:statuses", "write"], user: user)
conn = for token <- [token1, nil], op <- [:|, :&] do
ret_conn =
conn conn
|> assign(:user, token.user) |> assign(:user, user)
|> assign(:token, token) |> assign(:token, token)
|> OAuthScopesPlug.call(%{ |> OAuthScopesPlug.call(%{
scopes: ["read"], scopes: ["read"],
op: op,
fallback: :proceed_unauthenticated, fallback: :proceed_unauthenticated,
skip_instance_privacy_check: true skip_instance_privacy_check: true
}) })
refute conn.halted refute ret_conn.halted
refute conn.assigns[:user] refute ret_conn.assigns[:user]
refute ret_conn.assigns[:token]
refute called(EnsurePublicOrAuthenticatedPlug.call(conn, :_)) refute called(EnsurePublicOrAuthenticatedPlug.call(ret_conn, :_))
end
end end
end end
@ -140,25 +104,27 @@ test "with :skip_instance_privacy_check option, " <>
test "if `token.scopes` does not fulfill specified 'any of' conditions, " <> test "if `token.scopes` does not fulfill specified 'any of' conditions, " <>
"returns 403 and halts", "returns 403 and halts",
%{conn: conn} do %{conn: conn} do
token = insert(:oauth_token, scopes: ["read", "write"]) for token <- [insert(:oauth_token, scopes: ["read", "write"]), nil] do
any_of_scopes = ["follow"] any_of_scopes = ["follow", "push"]
conn = ret_conn =
conn conn
|> assign(:token, token) |> assign(:token, token)
|> OAuthScopesPlug.call(%{scopes: any_of_scopes}) |> OAuthScopesPlug.call(%{scopes: any_of_scopes})
assert conn.halted assert ret_conn.halted
assert 403 == conn.status assert 403 == ret_conn.status
expected_error = "Insufficient permissions: #{Enum.join(any_of_scopes, ", ")}." expected_error = "Insufficient permissions: #{Enum.join(any_of_scopes, " | ")}."
assert Jason.encode!(%{error: expected_error}) == conn.resp_body assert Jason.encode!(%{error: expected_error}) == ret_conn.resp_body
end
end end
test "if `token.scopes` does not fulfill specified 'all of' conditions, " <> test "if `token.scopes` does not fulfill specified 'all of' conditions, " <>
"returns 403 and halts", "returns 403 and halts",
%{conn: conn} do %{conn: conn} do
token = insert(:oauth_token, scopes: ["read", "write"]) for token <- [insert(:oauth_token, scopes: ["read", "write"]), nil] do
token_scopes = (token && token.scopes) || []
all_of_scopes = ["write", "follow"] all_of_scopes = ["write", "follow"]
conn = conn =
@ -170,11 +136,12 @@ test "if `token.scopes` does not fulfill specified 'all of' conditions, " <>
assert 403 == conn.status assert 403 == conn.status
expected_error = expected_error =
"Insufficient permissions: #{Enum.join(all_of_scopes -- token.scopes, ", ")}." "Insufficient permissions: #{Enum.join(all_of_scopes -- token_scopes, " & ")}."
assert Jason.encode!(%{error: expected_error}) == conn.resp_body assert Jason.encode!(%{error: expected_error}) == conn.resp_body
end end
end end
end
describe "with hierarchical scopes, " do describe "with hierarchical scopes, " do
test "if `token.scopes` fulfills specified 'any of' conditions, " <> test "if `token.scopes` fulfills specified 'any of' conditions, " <>

View File

@ -28,6 +28,26 @@ defmodule Pleroma.Web.ConnCase do
# The default endpoint for testing # The default endpoint for testing
@endpoint Pleroma.Web.Endpoint @endpoint Pleroma.Web.Endpoint
# Sets up OAuth access with specified scopes
defp oauth_access(scopes, opts \\ %{}) do
user =
Map.get_lazy(opts, :user, fn ->
Pleroma.Factory.insert(:user)
end)
token =
Map.get_lazy(opts, :oauth_token, fn ->
Pleroma.Factory.insert(:oauth_token, user: user, scopes: scopes)
end)
conn =
build_conn()
|> assign(:user, user)
|> assign(:token, token)
%{user: user, token: token, conn: conn}
end
end end
end end

View File

@ -296,7 +296,7 @@ def oauth_app_factory do
%Pleroma.Web.OAuth.App{ %Pleroma.Web.OAuth.App{
client_name: "Some client", client_name: "Some client",
redirect_uris: "https://example.com/callback", redirect_uris: "https://example.com/callback",
scopes: ["read", "write", "follow", "push"], scopes: ["read", "write", "follow", "push", "admin"],
website: "https://example.com", website: "https://example.com",
client_id: Ecto.UUID.generate(), client_id: Ecto.UUID.generate(),
client_secret: "aaa;/&bbb" client_secret: "aaa;/&bbb"
@ -310,19 +310,37 @@ def instance_factory do
} }
end end
def oauth_token_factory do def oauth_token_factory(attrs \\ %{}) do
oauth_app = insert(:oauth_app) scopes = Map.get(attrs, :scopes, ["read"])
oauth_app = Map.get_lazy(attrs, :app, fn -> insert(:oauth_app, scopes: scopes) end)
user = Map.get_lazy(attrs, :user, fn -> build(:user) end)
valid_until =
Map.get(attrs, :valid_until, NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10))
%Pleroma.Web.OAuth.Token{ %Pleroma.Web.OAuth.Token{
token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(), token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(),
scopes: ["read"],
refresh_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(), refresh_token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(),
user: build(:user), scopes: scopes,
app_id: oauth_app.id, user: user,
valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 10) app: oauth_app,
valid_until: valid_until
} }
end end
def oauth_admin_token_factory(attrs \\ %{}) do
user = Map.get_lazy(attrs, :user, fn -> build(:user, is_admin: true) end)
scopes =
attrs
|> Map.get(:scopes, ["admin"])
|> Kernel.++(["admin"])
|> Enum.uniq()
attrs = Map.merge(attrs, %{user: user, scopes: scopes})
oauth_token_factory(attrs)
end
def oauth_authorization_factory do def oauth_authorization_factory do
%Pleroma.Web.OAuth.Authorization{ %Pleroma.Web.OAuth.Authorization{
token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false), token: :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false),

File diff suppressed because it is too large Load Diff

View File

@ -23,24 +23,14 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
clear_config([:instance, :allow_relay]) clear_config([:instance, :allow_relay])
describe "posting statuses" do describe "posting statuses" do
setup do setup do: oauth_access(["write:statuses"])
user = insert(:user)
conn =
build_conn()
|> assign(:user, user)
[conn: conn]
end
test "posting a status does not increment reblog_count when relaying", %{conn: conn} do test "posting a status does not increment reblog_count when relaying", %{conn: conn} do
Pleroma.Config.put([:instance, :federating], true) Pleroma.Config.put([:instance, :federating], true)
Pleroma.Config.get([:instance, :allow_relay], true) Pleroma.Config.get([:instance, :allow_relay], true)
user = insert(:user)
response = response =
conn conn
|> assign(:user, user)
|> post("api/v1/statuses", %{ |> post("api/v1/statuses", %{
"content_type" => "text/plain", "content_type" => "text/plain",
"source" => "Pleroma FE", "source" => "Pleroma FE",
@ -54,7 +44,6 @@ test "posting a status does not increment reblog_count when relaying", %{conn: c
response = response =
conn conn
|> assign(:user, user)
|> get("api/v1/statuses/#{response["id"]}", %{}) |> get("api/v1/statuses/#{response["id"]}", %{})
|> json_response(200) |> json_response(200)
@ -132,9 +121,7 @@ test "posting a status", %{conn: conn} do
NaiveDateTime.to_iso8601(expiration.scheduled_at) NaiveDateTime.to_iso8601(expiration.scheduled_at)
end end
test "posting an undefined status with an attachment", %{conn: conn} do test "posting an undefined status with an attachment", %{user: user, conn: conn} do
user = insert(:user)
file = %Plug.Upload{ file = %Plug.Upload{
content_type: "image/jpg", content_type: "image/jpg",
path: Path.absname("test/fixtures/image.jpg"), path: Path.absname("test/fixtures/image.jpg"),
@ -144,17 +131,14 @@ test "posting an undefined status with an attachment", %{conn: conn} do
{:ok, upload} = ActivityPub.upload(file, actor: user.ap_id) {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"media_ids" => [to_string(upload.id)] "media_ids" => [to_string(upload.id)]
}) })
assert json_response(conn, 200) assert json_response(conn, 200)
end end
test "replying to a status", %{conn: conn} do test "replying to a status", %{user: user, conn: conn} do
user = insert(:user)
{:ok, replied_to} = CommonAPI.post(user, %{"status" => "cofe"}) {:ok, replied_to} = CommonAPI.post(user, %{"status" => "cofe"})
conn = conn =
@ -169,8 +153,10 @@ test "replying to a status", %{conn: conn} do
assert Activity.get_in_reply_to_activity(activity).id == replied_to.id assert Activity.get_in_reply_to_activity(activity).id == replied_to.id
end end
test "replying to a direct message with visibility other than direct", %{conn: conn} do test "replying to a direct message with visibility other than direct", %{
user = insert(:user) user: user,
conn: conn
} do
{:ok, replied_to} = CommonAPI.post(user, %{"status" => "suya..", "visibility" => "direct"}) {:ok, replied_to} = CommonAPI.post(user, %{"status" => "suya..", "visibility" => "direct"})
Enum.each(["public", "private", "unlisted"], fn visibility -> Enum.each(["public", "private", "unlisted"], fn visibility ->
@ -187,18 +173,14 @@ test "replying to a direct message with visibility other than direct", %{conn: c
end end
test "posting a status with an invalid in_reply_to_id", %{conn: conn} do test "posting a status with an invalid in_reply_to_id", %{conn: conn} do
conn = conn = post(conn, "/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => ""})
conn
|> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => ""})
assert %{"content" => "xD", "id" => id} = json_response(conn, 200) assert %{"content" => "xD", "id" => id} = json_response(conn, 200)
assert Activity.get_by_id(id) assert Activity.get_by_id(id)
end end
test "posting a sensitive status", %{conn: conn} do test "posting a sensitive status", %{conn: conn} do
conn = conn = post(conn, "/api/v1/statuses", %{"status" => "cofe", "sensitive" => true})
conn
|> post("/api/v1/statuses", %{"status" => "cofe", "sensitive" => true})
assert %{"content" => "cofe", "id" => id, "sensitive" => true} = json_response(conn, 200) assert %{"content" => "cofe", "id" => id, "sensitive" => true} = json_response(conn, 200)
assert Activity.get_by_id(id) assert Activity.get_by_id(id)
@ -206,8 +188,7 @@ test "posting a sensitive status", %{conn: conn} do
test "posting a fake status", %{conn: conn} do test "posting a fake status", %{conn: conn} do
real_conn = real_conn =
conn post(conn, "/api/v1/statuses", %{
|> post("/api/v1/statuses", %{
"status" => "status" =>
"\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it" "\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it"
}) })
@ -226,8 +207,7 @@ test "posting a fake status", %{conn: conn} do
|> Kernel.put_in(["pleroma", "conversation_id"], nil) |> Kernel.put_in(["pleroma", "conversation_id"], nil)
fake_conn = fake_conn =
conn post(conn, "/api/v1/statuses", %{
|> post("/api/v1/statuses", %{
"status" => "status" =>
"\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it", "\"Tenshi Eating a Corndog\" is a much discussed concept on /jp/. The significance of it is disputed, so I will focus on one core concept: the symbolism behind it",
"preview" => true "preview" => true
@ -254,8 +234,7 @@ test "posting a status with OGP link preview", %{conn: conn} do
Config.put([:rich_media, :enabled], true) Config.put([:rich_media, :enabled], true)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> post("/api/v1/statuses", %{
"status" => "https://example.com/ogp" "status" => "https://example.com/ogp"
}) })
@ -267,9 +246,7 @@ test "posting a direct status", %{conn: conn} do
user2 = insert(:user) user2 = insert(:user)
content = "direct cofe @#{user2.nickname}" content = "direct cofe @#{user2.nickname}"
conn = conn = post(conn, "api/v1/statuses", %{"status" => content, "visibility" => "direct"})
conn
|> post("api/v1/statuses", %{"status" => content, "visibility" => "direct"})
assert %{"id" => id} = response = json_response(conn, 200) assert %{"id" => id} = response = json_response(conn, 200)
assert response["visibility"] == "direct" assert response["visibility"] == "direct"
@ -282,14 +259,13 @@ test "posting a direct status", %{conn: conn} do
end end
describe "posting scheduled statuses" do describe "posting scheduled statuses" do
setup do: oauth_access(["write:statuses"])
test "creates a scheduled activity", %{conn: conn} do test "creates a scheduled activity", %{conn: conn} do
user = insert(:user)
scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "scheduled", "status" => "scheduled",
"scheduled_at" => scheduled_at "scheduled_at" => scheduled_at
}) })
@ -299,8 +275,7 @@ test "creates a scheduled activity", %{conn: conn} do
assert [] == Repo.all(Activity) assert [] == Repo.all(Activity)
end end
test "creates a scheduled activity with a media attachment", %{conn: conn} do test "creates a scheduled activity with a media attachment", %{user: user, conn: conn} do
user = insert(:user)
scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond) scheduled_at = NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(120), :millisecond)
file = %Plug.Upload{ file = %Plug.Upload{
@ -312,9 +287,7 @@ test "creates a scheduled activity with a media attachment", %{conn: conn} do
{:ok, upload} = ActivityPub.upload(file, actor: user.ap_id) {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"media_ids" => [to_string(upload.id)], "media_ids" => [to_string(upload.id)],
"status" => "scheduled", "status" => "scheduled",
"scheduled_at" => scheduled_at "scheduled_at" => scheduled_at
@ -326,15 +299,11 @@ test "creates a scheduled activity with a media attachment", %{conn: conn} do
test "skips the scheduling and creates the activity if scheduled_at is earlier than 5 minutes from now", test "skips the scheduling and creates the activity if scheduled_at is earlier than 5 minutes from now",
%{conn: conn} do %{conn: conn} do
user = insert(:user)
scheduled_at = scheduled_at =
NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(5) - 1, :millisecond) NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(5) - 1, :millisecond)
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "not scheduled", "status" => "not scheduled",
"scheduled_at" => scheduled_at "scheduled_at" => scheduled_at
}) })
@ -343,9 +312,7 @@ test "skips the scheduling and creates the activity if scheduled_at is earlier t
assert [] == Repo.all(ScheduledActivity) assert [] == Repo.all(ScheduledActivity)
end end
test "returns error when daily user limit is exceeded", %{conn: conn} do test "returns error when daily user limit is exceeded", %{user: user, conn: conn} do
user = insert(:user)
today = today =
NaiveDateTime.utc_now() NaiveDateTime.utc_now()
|> NaiveDateTime.add(:timer.minutes(6), :millisecond) |> NaiveDateTime.add(:timer.minutes(6), :millisecond)
@ -355,17 +322,12 @@ test "returns error when daily user limit is exceeded", %{conn: conn} do
{:ok, _} = ScheduledActivity.create(user, attrs) {:ok, _} = ScheduledActivity.create(user, attrs)
{:ok, _} = ScheduledActivity.create(user, attrs) {:ok, _} = ScheduledActivity.create(user, attrs)
conn = conn = post(conn, "/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => today})
conn
|> assign(:user, user)
|> post("/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => today})
assert %{"error" => "daily limit exceeded"} == json_response(conn, 422) assert %{"error" => "daily limit exceeded"} == json_response(conn, 422)
end end
test "returns error when total user limit is exceeded", %{conn: conn} do test "returns error when total user limit is exceeded", %{user: user, conn: conn} do
user = insert(:user)
today = today =
NaiveDateTime.utc_now() NaiveDateTime.utc_now()
|> NaiveDateTime.add(:timer.minutes(6), :millisecond) |> NaiveDateTime.add(:timer.minutes(6), :millisecond)
@ -382,23 +344,20 @@ test "returns error when total user limit is exceeded", %{conn: conn} do
{:ok, _} = ScheduledActivity.create(user, %{params: %{}, scheduled_at: tomorrow}) {:ok, _} = ScheduledActivity.create(user, %{params: %{}, scheduled_at: tomorrow})
conn = conn =
conn post(conn, "/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => tomorrow})
|> assign(:user, user)
|> post("/api/v1/statuses", %{"status" => "scheduled", "scheduled_at" => tomorrow})
assert %{"error" => "total limit exceeded"} == json_response(conn, 422) assert %{"error" => "total limit exceeded"} == json_response(conn, 422)
end end
end end
describe "posting polls" do describe "posting polls" do
setup do: oauth_access(["write:statuses"])
test "posting a poll", %{conn: conn} do test "posting a poll", %{conn: conn} do
user = insert(:user)
time = NaiveDateTime.utc_now() time = NaiveDateTime.utc_now()
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "Who is the #bestgrill?", "status" => "Who is the #bestgrill?",
"poll" => %{"options" => ["Rei", "Asuka", "Misato"], "expires_in" => 420} "poll" => %{"options" => ["Rei", "Asuka", "Misato"], "expires_in" => 420}
}) })
@ -414,13 +373,10 @@ test "posting a poll", %{conn: conn} do
end end
test "option limit is enforced", %{conn: conn} do test "option limit is enforced", %{conn: conn} do
user = insert(:user)
limit = Config.get([:instance, :poll_limits, :max_options]) limit = Config.get([:instance, :poll_limits, :max_options])
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "desu~", "status" => "desu~",
"poll" => %{"options" => Enum.map(0..limit, fn _ -> "desu" end), "expires_in" => 1} "poll" => %{"options" => Enum.map(0..limit, fn _ -> "desu" end), "expires_in" => 1}
}) })
@ -430,13 +386,10 @@ test "option limit is enforced", %{conn: conn} do
end end
test "option character limit is enforced", %{conn: conn} do test "option character limit is enforced", %{conn: conn} do
user = insert(:user)
limit = Config.get([:instance, :poll_limits, :max_option_chars]) limit = Config.get([:instance, :poll_limits, :max_option_chars])
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "...", "status" => "...",
"poll" => %{ "poll" => %{
"options" => [Enum.reduce(0..limit, "", fn _, acc -> acc <> "." end)], "options" => [Enum.reduce(0..limit, "", fn _, acc -> acc <> "." end)],
@ -449,13 +402,10 @@ test "option character limit is enforced", %{conn: conn} do
end end
test "minimal date limit is enforced", %{conn: conn} do test "minimal date limit is enforced", %{conn: conn} do
user = insert(:user)
limit = Config.get([:instance, :poll_limits, :min_expiration]) limit = Config.get([:instance, :poll_limits, :min_expiration])
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "imagine arbitrary limits", "status" => "imagine arbitrary limits",
"poll" => %{ "poll" => %{
"options" => ["this post was made by pleroma gang"], "options" => ["this post was made by pleroma gang"],
@ -468,13 +418,10 @@ test "minimal date limit is enforced", %{conn: conn} do
end end
test "maximum date limit is enforced", %{conn: conn} do test "maximum date limit is enforced", %{conn: conn} do
user = insert(:user)
limit = Config.get([:instance, :poll_limits, :max_expiration]) limit = Config.get([:instance, :poll_limits, :max_expiration])
conn = conn =
conn post(conn, "/api/v1/statuses", %{
|> assign(:user, user)
|> post("/api/v1/statuses", %{
"status" => "imagine arbitrary limits", "status" => "imagine arbitrary limits",
"poll" => %{ "poll" => %{
"options" => ["this post was made by pleroma gang"], "options" => ["this post was made by pleroma gang"],
@ -487,19 +434,18 @@ test "maximum date limit is enforced", %{conn: conn} do
end end
end end
test "get a status", %{conn: conn} do test "get a status" do
%{conn: conn} = oauth_access(["read:statuses"])
activity = insert(:note_activity) activity = insert(:note_activity)
conn = conn = get(conn, "/api/v1/statuses/#{activity.id}")
conn
|> get("/api/v1/statuses/#{activity.id}")
assert %{"id" => id} = json_response(conn, 200) assert %{"id" => id} = json_response(conn, 200)
assert id == to_string(activity.id) assert id == to_string(activity.id)
end end
test "get a direct status", %{conn: conn} do test "get a direct status" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:statuses"])
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
@ -516,7 +462,8 @@ test "get a direct status", %{conn: conn} do
assert res["pleroma"]["direct_conversation_id"] == participation.id assert res["pleroma"]["direct_conversation_id"] == participation.id
end end
test "get statuses by IDs", %{conn: conn} do test "get statuses by IDs" do
%{conn: conn} = oauth_access(["read:statuses"])
%{id: id1} = insert(:note_activity) %{id: id1} = insert(:note_activity)
%{id: id2} = insert(:note_activity) %{id: id2} = insert(:note_activity)
@ -527,9 +474,9 @@ test "get statuses by IDs", %{conn: conn} do
end end
describe "deleting a status" do describe "deleting a status" do
test "when you created it", %{conn: conn} do test "when you created it" do
activity = insert(:note_activity) %{user: author, conn: conn} = oauth_access(["write:statuses"])
author = User.get_cached_by_ap_id(activity.data["actor"]) activity = insert(:note_activity, user: author)
conn = conn =
conn conn
@ -541,14 +488,11 @@ test "when you created it", %{conn: conn} do
refute Activity.get_by_id(activity.id) refute Activity.get_by_id(activity.id)
end end
test "when you didn't create it", %{conn: conn} do test "when you didn't create it" do
%{conn: conn} = oauth_access(["write:statuses"])
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
conn = conn = delete(conn, "/api/v1/statuses/#{activity.id}")
conn
|> assign(:user, user)
|> delete("/api/v1/statuses/#{activity.id}")
assert %{"error" => _} = json_response(conn, 403) assert %{"error" => _} = json_response(conn, 403)
@ -564,6 +508,7 @@ test "when you're an admin or moderator", %{conn: conn} do
res_conn = res_conn =
conn conn
|> assign(:user, admin) |> assign(:user, admin)
|> assign(:token, insert(:oauth_token, user: admin, scopes: ["write:statuses"]))
|> delete("/api/v1/statuses/#{activity1.id}") |> delete("/api/v1/statuses/#{activity1.id}")
assert %{} = json_response(res_conn, 200) assert %{} = json_response(res_conn, 200)
@ -571,6 +516,7 @@ test "when you're an admin or moderator", %{conn: conn} do
res_conn = res_conn =
conn conn
|> assign(:user, moderator) |> assign(:user, moderator)
|> assign(:token, insert(:oauth_token, user: moderator, scopes: ["write:statuses"]))
|> delete("/api/v1/statuses/#{activity2.id}") |> delete("/api/v1/statuses/#{activity2.id}")
assert %{} = json_response(res_conn, 200) assert %{} = json_response(res_conn, 200)
@ -581,14 +527,12 @@ test "when you're an admin or moderator", %{conn: conn} do
end end
describe "reblogging" do describe "reblogging" do
setup do: oauth_access(["write:statuses"])
test "reblogs and returns the reblogged status", %{conn: conn} do test "reblogs and returns the reblogged status", %{conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/reblog")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/reblog")
assert %{ assert %{
"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}, "reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1},
@ -600,12 +544,8 @@ test "reblogs and returns the reblogged status", %{conn: conn} do
test "reblogs privately and returns the reblogged status", %{conn: conn} do test "reblogs privately and returns the reblogged status", %{conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/reblog", %{"visibility" => "private"})
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/reblog", %{"visibility" => "private"})
assert %{ assert %{
"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}, "reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1},
@ -616,7 +556,7 @@ test "reblogs privately and returns the reblogged status", %{conn: conn} do
assert to_string(activity.id) == id assert to_string(activity.id) == id
end end
test "reblogged status for another user", %{conn: conn} do test "reblogged status for another user" do
activity = insert(:note_activity) activity = insert(:note_activity)
user1 = insert(:user) user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
@ -627,8 +567,9 @@ test "reblogged status for another user", %{conn: conn} do
{:ok, _, _object} = CommonAPI.repeat(activity.id, user2) {:ok, _, _object} = CommonAPI.repeat(activity.id, user2)
conn_res = conn_res =
conn build_conn()
|> assign(:user, user3) |> assign(:user, user3)
|> assign(:token, insert(:oauth_token, user: user3, scopes: ["read:statuses"]))
|> get("/api/v1/statuses/#{reblog_activity1.id}") |> get("/api/v1/statuses/#{reblog_activity1.id}")
assert %{ assert %{
@ -639,8 +580,9 @@ test "reblogged status for another user", %{conn: conn} do
} = json_response(conn_res, 200) } = json_response(conn_res, 200)
conn_res = conn_res =
conn build_conn()
|> assign(:user, user2) |> assign(:user, user2)
|> assign(:token, insert(:oauth_token, user: user2, scopes: ["read:statuses"]))
|> get("/api/v1/statuses/#{reblog_activity1.id}") |> get("/api/v1/statuses/#{reblog_activity1.id}")
assert %{ assert %{
@ -654,28 +596,21 @@ test "reblogged status for another user", %{conn: conn} do
end end
test "returns 400 error when activity is not exist", %{conn: conn} do test "returns 400 error when activity is not exist", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/statuses/foo/reblog")
conn =
conn
|> assign(:user, user)
|> post("/api/v1/statuses/foo/reblog")
assert json_response(conn, 400) == %{"error" => "Could not repeat"} assert json_response(conn, 400) == %{"error" => "Could not repeat"}
end end
end end
describe "unreblogging" do describe "unreblogging" do
test "unreblogs and returns the unreblogged status", %{conn: conn} do setup do: oauth_access(["write:statuses"])
test "unreblogs and returns the unreblogged status", %{user: user, conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
{:ok, _, _} = CommonAPI.repeat(activity.id, user) {:ok, _, _} = CommonAPI.repeat(activity.id, user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/unreblog")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/unreblog")
assert %{"id" => id, "reblogged" => false, "reblogs_count" => 0} = json_response(conn, 200) assert %{"id" => id, "reblogged" => false, "reblogs_count" => 0} = json_response(conn, 200)
@ -683,26 +618,19 @@ test "unreblogs and returns the unreblogged status", %{conn: conn} do
end end
test "returns 400 error when activity is not exist", %{conn: conn} do test "returns 400 error when activity is not exist", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/statuses/foo/unreblog")
conn =
conn
|> assign(:user, user)
|> post("/api/v1/statuses/foo/unreblog")
assert json_response(conn, 400) == %{"error" => "Could not unrepeat"} assert json_response(conn, 400) == %{"error" => "Could not unrepeat"}
end end
end end
describe "favoriting" do describe "favoriting" do
setup do: oauth_access(["write:favourites"])
test "favs a status and returns it", %{conn: conn} do test "favs a status and returns it", %{conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/favourite")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/favourite")
assert %{"id" => id, "favourites_count" => 1, "favourited" => true} = assert %{"id" => id, "favourites_count" => 1, "favourited" => true} =
json_response(conn, 200) json_response(conn, 200)
@ -711,28 +639,21 @@ test "favs a status and returns it", %{conn: conn} do
end end
test "returns 400 error for a wrong id", %{conn: conn} do test "returns 400 error for a wrong id", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/statuses/1/favourite")
conn =
conn
|> assign(:user, user)
|> post("/api/v1/statuses/1/favourite")
assert json_response(conn, 400) == %{"error" => "Could not favorite"} assert json_response(conn, 400) == %{"error" => "Could not favorite"}
end end
end end
describe "unfavoriting" do describe "unfavoriting" do
test "unfavorites a status and returns it", %{conn: conn} do setup do: oauth_access(["write:favourites"])
test "unfavorites a status and returns it", %{user: user, conn: conn} do
activity = insert(:note_activity) activity = insert(:note_activity)
user = insert(:user)
{:ok, _, _} = CommonAPI.favorite(activity.id, user) {:ok, _, _} = CommonAPI.favorite(activity.id, user)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/unfavourite")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/unfavourite")
assert %{"id" => id, "favourites_count" => 0, "favourited" => false} = assert %{"id" => id, "favourites_count" => 0, "favourited" => false} =
json_response(conn, 200) json_response(conn, 200)
@ -741,23 +662,19 @@ test "unfavorites a status and returns it", %{conn: conn} do
end end
test "returns 400 error for a wrong id", %{conn: conn} do test "returns 400 error for a wrong id", %{conn: conn} do
user = insert(:user) conn = post(conn, "/api/v1/statuses/1/unfavourite")
conn =
conn
|> assign(:user, user)
|> post("/api/v1/statuses/1/unfavourite")
assert json_response(conn, 400) == %{"error" => "Could not unfavorite"} assert json_response(conn, 400) == %{"error" => "Could not unfavorite"}
end end
end end
describe "pinned statuses" do describe "pinned statuses" do
setup do setup do: oauth_access(["write:accounts"])
user = insert(:user)
setup %{user: user} do
{:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"}) {:ok, activity} = CommonAPI.post(user, %{"status" => "HI!!!"})
[user: user, activity: activity] %{activity: activity}
end end
clear_config([:instance, :max_pinned_statuses]) do clear_config([:instance, :max_pinned_statuses]) do
@ -769,13 +686,11 @@ test "pin status", %{conn: conn, user: user, activity: activity} do
assert %{"id" => ^id_str, "pinned" => true} = assert %{"id" => ^id_str, "pinned" => true} =
conn conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/pin") |> post("/api/v1/statuses/#{activity.id}/pin")
|> json_response(200) |> json_response(200)
assert [%{"id" => ^id_str, "pinned" => true}] = assert [%{"id" => ^id_str, "pinned" => true}] =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
|> json_response(200) |> json_response(200)
end end
@ -783,19 +698,16 @@ test "pin status", %{conn: conn, user: user, activity: activity} do
test "/pin: returns 400 error when activity is not public", %{conn: conn, user: user} do test "/pin: returns 400 error when activity is not public", %{conn: conn, user: user} do
{:ok, dm} = CommonAPI.post(user, %{"status" => "test", "visibility" => "direct"}) {:ok, dm} = CommonAPI.post(user, %{"status" => "test", "visibility" => "direct"})
conn = conn = post(conn, "/api/v1/statuses/#{dm.id}/pin")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{dm.id}/pin")
assert json_response(conn, 400) == %{"error" => "Could not pin"} assert json_response(conn, 400) == %{"error" => "Could not pin"}
end end
test "unpin status", %{conn: conn, user: user, activity: activity} do test "unpin status", %{conn: conn, user: user, activity: activity} do
{:ok, _} = CommonAPI.pin(activity.id, user) {:ok, _} = CommonAPI.pin(activity.id, user)
user = refresh_record(user)
id_str = to_string(activity.id) id_str = to_string(activity.id)
user = refresh_record(user)
assert %{"id" => ^id_str, "pinned" => false} = assert %{"id" => ^id_str, "pinned" => false} =
conn conn
@ -805,16 +717,12 @@ test "unpin status", %{conn: conn, user: user, activity: activity} do
assert [] = assert [] =
conn conn
|> assign(:user, user)
|> get("/api/v1/accounts/#{user.id}/statuses?pinned=true") |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")
|> json_response(200) |> json_response(200)
end end
test "/unpin: returns 400 error when activity is not exist", %{conn: conn, user: user} do test "/unpin: returns 400 error when activity is not exist", %{conn: conn} do
conn = conn = post(conn, "/api/v1/statuses/1/unpin")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/1/unpin")
assert json_response(conn, 400) == %{"error" => "Could not unpin"} assert json_response(conn, 400) == %{"error" => "Could not unpin"}
end end
@ -826,7 +734,6 @@ test "max pinned statuses", %{conn: conn, user: user, activity: activity_one} do
assert %{"id" => ^id_str_one, "pinned" => true} = assert %{"id" => ^id_str_one, "pinned" => true} =
conn conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{id_str_one}/pin") |> post("/api/v1/statuses/#{id_str_one}/pin")
|> json_response(200) |> json_response(200)
@ -844,8 +751,7 @@ test "max pinned statuses", %{conn: conn, user: user, activity: activity_one} do
setup do setup do
Config.put([:rich_media, :enabled], true) Config.put([:rich_media, :enabled], true)
user = insert(:user) oauth_access(["read:statuses"])
%{user: user}
end end
test "returns rich-media card", %{conn: conn, user: user} do test "returns rich-media card", %{conn: conn, user: user} do
@ -887,7 +793,6 @@ test "returns rich-media card", %{conn: conn, user: user} do
response_two = response_two =
conn conn
|> assign(:user, user)
|> get("/api/v1/statuses/#{activity.id}/card") |> get("/api/v1/statuses/#{activity.id}/card")
|> json_response(200) |> json_response(200)
@ -925,72 +830,55 @@ test "replaces missing description with an empty string", %{conn: conn, user: us
end end
test "bookmarks" do test "bookmarks" do
user = insert(:user) %{conn: conn} = oauth_access(["write:bookmarks", "read:bookmarks"])
for_user = insert(:user) author = insert(:user)
{:ok, activity1} = {:ok, activity1} =
CommonAPI.post(user, %{ CommonAPI.post(author, %{
"status" => "heweoo?" "status" => "heweoo?"
}) })
{:ok, activity2} = {:ok, activity2} =
CommonAPI.post(user, %{ CommonAPI.post(author, %{
"status" => "heweoo!" "status" => "heweoo!"
}) })
response1 = response1 = post(conn, "/api/v1/statuses/#{activity1.id}/bookmark")
build_conn()
|> assign(:user, for_user)
|> post("/api/v1/statuses/#{activity1.id}/bookmark")
assert json_response(response1, 200)["bookmarked"] == true assert json_response(response1, 200)["bookmarked"] == true
response2 = response2 = post(conn, "/api/v1/statuses/#{activity2.id}/bookmark")
build_conn()
|> assign(:user, for_user)
|> post("/api/v1/statuses/#{activity2.id}/bookmark")
assert json_response(response2, 200)["bookmarked"] == true assert json_response(response2, 200)["bookmarked"] == true
bookmarks = bookmarks = get(conn, "/api/v1/bookmarks")
build_conn()
|> assign(:user, for_user)
|> get("/api/v1/bookmarks")
assert [json_response(response2, 200), json_response(response1, 200)] == assert [json_response(response2, 200), json_response(response1, 200)] ==
json_response(bookmarks, 200) json_response(bookmarks, 200)
response1 = response1 = post(conn, "/api/v1/statuses/#{activity1.id}/unbookmark")
build_conn()
|> assign(:user, for_user)
|> post("/api/v1/statuses/#{activity1.id}/unbookmark")
assert json_response(response1, 200)["bookmarked"] == false assert json_response(response1, 200)["bookmarked"] == false
bookmarks = bookmarks = get(conn, "/api/v1/bookmarks")
build_conn()
|> assign(:user, for_user)
|> get("/api/v1/bookmarks")
assert [json_response(response2, 200)] == json_response(bookmarks, 200) assert [json_response(response2, 200)] == json_response(bookmarks, 200)
end end
describe "conversation muting" do describe "conversation muting" do
setup do: oauth_access(["write:mutes"])
setup do setup do
post_user = insert(:user) post_user = insert(:user)
user = insert(:user)
{:ok, activity} = CommonAPI.post(post_user, %{"status" => "HIE"}) {:ok, activity} = CommonAPI.post(post_user, %{"status" => "HIE"})
%{activity: activity}
[user: user, activity: activity]
end end
test "mute conversation", %{conn: conn, user: user, activity: activity} do test "mute conversation", %{conn: conn, activity: activity} do
id_str = to_string(activity.id) id_str = to_string(activity.id)
assert %{"id" => ^id_str, "muted" => true} = assert %{"id" => ^id_str, "muted" => true} =
conn conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/mute") |> post("/api/v1/statuses/#{activity.id}/mute")
|> json_response(200) |> json_response(200)
end end
@ -998,10 +886,7 @@ test "mute conversation", %{conn: conn, user: user, activity: activity} do
test "cannot mute already muted conversation", %{conn: conn, user: user, activity: activity} do test "cannot mute already muted conversation", %{conn: conn, user: user, activity: activity} do
{:ok, _} = CommonAPI.add_mute(user, activity) {:ok, _} = CommonAPI.add_mute(user, activity)
conn = conn = post(conn, "/api/v1/statuses/#{activity.id}/mute")
conn
|> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/mute")
assert json_response(conn, 400) == %{"error" => "conversation is already muted"} assert json_response(conn, 400) == %{"error" => "conversation is already muted"}
end end
@ -1010,11 +895,10 @@ test "unmute conversation", %{conn: conn, user: user, activity: activity} do
{:ok, _} = CommonAPI.add_mute(user, activity) {:ok, _} = CommonAPI.add_mute(user, activity)
id_str = to_string(activity.id) id_str = to_string(activity.id)
user = refresh_record(user)
assert %{"id" => ^id_str, "muted" => false} = assert %{"id" => ^id_str, "muted" => false} =
conn conn
|> assign(:user, user) # |> assign(:user, user)
|> post("/api/v1/statuses/#{activity.id}/unmute") |> post("/api/v1/statuses/#{activity.id}/unmute")
|> json_response(200) |> json_response(200)
end end
@ -1031,6 +915,7 @@ test "Repeated posts that are replies incorrectly have in_reply_to_id null", %{c
conn1 = conn1 =
conn conn
|> assign(:user, user2) |> assign(:user, user2)
|> assign(:token, insert(:oauth_token, user: user2, scopes: ["write:statuses"]))
|> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => replied_to.id}) |> post("/api/v1/statuses", %{"status" => "xD", "in_reply_to_id" => replied_to.id})
assert %{"content" => "xD", "id" => id} = json_response(conn1, 200) assert %{"content" => "xD", "id" => id} = json_response(conn1, 200)
@ -1044,6 +929,7 @@ test "Repeated posts that are replies incorrectly have in_reply_to_id null", %{c
conn2 = conn2 =
conn conn
|> assign(:user, user3) |> assign(:user, user3)
|> assign(:token, insert(:oauth_token, user: user3, scopes: ["write:statuses"]))
|> post("/api/v1/statuses/#{activity.id}/reblog") |> post("/api/v1/statuses/#{activity.id}/reblog")
assert %{"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}} = assert %{"reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}} =
@ -1055,6 +941,7 @@ test "Repeated posts that are replies incorrectly have in_reply_to_id null", %{c
conn3 = conn3 =
conn conn
|> assign(:user, user3) |> assign(:user, user3)
|> assign(:token, insert(:oauth_token, user: user3, scopes: ["read:statuses"]))
|> get("api/v1/timelines/home") |> get("api/v1/timelines/home")
[reblogged_activity] = json_response(conn3, 200) [reblogged_activity] = json_response(conn3, 200)
@ -1066,15 +953,12 @@ test "Repeated posts that are replies incorrectly have in_reply_to_id null", %{c
end end
describe "GET /api/v1/statuses/:id/favourited_by" do describe "GET /api/v1/statuses/:id/favourited_by" do
setup do setup do: oauth_access(["read:accounts"])
user = insert(:user)
setup %{user: user} do
{:ok, activity} = CommonAPI.post(user, %{"status" => "test"}) {:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
conn = %{activity: activity}
build_conn()
|> assign(:user, user)
[conn: conn, activity: activity, user: user]
end end
test "returns users who have favorited the status", %{conn: conn, activity: activity} do test "returns users who have favorited the status", %{conn: conn, activity: activity} do
@ -1114,20 +998,18 @@ test "does not return users who have favorited the status but are blocked", %{
response = response =
conn conn
|> assign(:user, user)
|> get("/api/v1/statuses/#{activity.id}/favourited_by") |> get("/api/v1/statuses/#{activity.id}/favourited_by")
|> json_response(:ok) |> json_response(:ok)
assert Enum.empty?(response) assert Enum.empty?(response)
end end
test "does not fail on an unauthenticated request", %{conn: conn, activity: activity} do test "does not fail on an unauthenticated request", %{activity: activity} do
other_user = insert(:user) other_user = insert(:user)
{:ok, _, _} = CommonAPI.favorite(activity.id, other_user) {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
response = response =
conn build_conn()
|> assign(:user, nil)
|> get("/api/v1/statuses/#{activity.id}/favourited_by") |> get("/api/v1/statuses/#{activity.id}/favourited_by")
|> json_response(:ok) |> json_response(:ok)
@ -1135,7 +1017,7 @@ test "does not fail on an unauthenticated request", %{conn: conn, activity: acti
assert id == other_user.id assert id == other_user.id
end end
test "requires authentification for private posts", %{conn: conn, user: user} do test "requires authentication for private posts", %{user: user} do
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
@ -1146,15 +1028,25 @@ test "requires authentification for private posts", %{conn: conn, user: user} do
{:ok, _, _} = CommonAPI.favorite(activity.id, other_user) {:ok, _, _} = CommonAPI.favorite(activity.id, other_user)
favourited_by_url = "/api/v1/statuses/#{activity.id}/favourited_by"
build_conn()
|> get(favourited_by_url)
|> json_response(404)
conn =
build_conn()
|> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
conn conn
|> assign(:user, nil) |> assign(:token, nil)
|> get("/api/v1/statuses/#{activity.id}/favourited_by") |> get(favourited_by_url)
|> json_response(404) |> json_response(404)
response = response =
build_conn() conn
|> assign(:user, other_user) |> get(favourited_by_url)
|> get("/api/v1/statuses/#{activity.id}/favourited_by")
|> json_response(200) |> json_response(200)
[%{"id" => id}] = response [%{"id" => id}] = response
@ -1163,15 +1055,12 @@ test "requires authentification for private posts", %{conn: conn, user: user} do
end end
describe "GET /api/v1/statuses/:id/reblogged_by" do describe "GET /api/v1/statuses/:id/reblogged_by" do
setup do setup do: oauth_access(["read:accounts"])
user = insert(:user)
setup %{user: user} do
{:ok, activity} = CommonAPI.post(user, %{"status" => "test"}) {:ok, activity} = CommonAPI.post(user, %{"status" => "test"})
conn = %{activity: activity}
build_conn()
|> assign(:user, user)
[conn: conn, activity: activity, user: user]
end end
test "returns users who have reblogged the status", %{conn: conn, activity: activity} do test "returns users who have reblogged the status", %{conn: conn, activity: activity} do
@ -1211,7 +1100,6 @@ test "does not return users who have reblogged the status but are blocked", %{
response = response =
conn conn
|> assign(:user, user)
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(:ok) |> json_response(:ok)
@ -1219,7 +1107,7 @@ test "does not return users who have reblogged the status but are blocked", %{
end end
test "does not return users who have reblogged the status privately", %{ test "does not return users who have reblogged the status privately", %{
conn: %{assigns: %{user: user}} = conn, conn: conn,
activity: activity activity: activity
} do } do
other_user = insert(:user) other_user = insert(:user)
@ -1228,20 +1116,18 @@ test "does not return users who have reblogged the status privately", %{
response = response =
conn conn
|> assign(:user, user)
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(:ok) |> json_response(:ok)
assert Enum.empty?(response) assert Enum.empty?(response)
end end
test "does not fail on an unauthenticated request", %{conn: conn, activity: activity} do test "does not fail on an unauthenticated request", %{activity: activity} do
other_user = insert(:user) other_user = insert(:user)
{:ok, _, _} = CommonAPI.repeat(activity.id, other_user) {:ok, _, _} = CommonAPI.repeat(activity.id, other_user)
response = response =
conn build_conn()
|> assign(:user, nil)
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(:ok) |> json_response(:ok)
@ -1249,7 +1135,7 @@ test "does not fail on an unauthenticated request", %{conn: conn, activity: acti
assert id == other_user.id assert id == other_user.id
end end
test "requires authentification for private posts", %{conn: conn, user: user} do test "requires authentication for private posts", %{user: user} do
other_user = insert(:user) other_user = insert(:user)
{:ok, activity} = {:ok, activity} =
@ -1258,14 +1144,14 @@ test "requires authentification for private posts", %{conn: conn, user: user} do
"visibility" => "direct" "visibility" => "direct"
}) })
conn build_conn()
|> assign(:user, nil)
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(404) |> json_response(404)
response = response =
build_conn() build_conn()
|> assign(:user, other_user) |> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["read:accounts"]))
|> get("/api/v1/statuses/#{activity.id}/reblogged_by") |> get("/api/v1/statuses/#{activity.id}/reblogged_by")
|> json_response(200) |> json_response(200)
@ -1284,7 +1170,6 @@ test "context" do
response = response =
build_conn() build_conn()
|> assign(:user, nil)
|> get("/api/v1/statuses/#{id3}/context") |> get("/api/v1/statuses/#{id3}/context")
|> json_response(:ok) |> json_response(:ok)
@ -1294,8 +1179,8 @@ test "context" do
} = response } = response
end end
test "returns the favorites of a user", %{conn: conn} do test "returns the favorites of a user" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["read:favourites"])
other_user = insert(:user) other_user = insert(:user)
{:ok, _} = CommonAPI.post(other_user, %{"status" => "bla"}) {:ok, _} = CommonAPI.post(other_user, %{"status" => "bla"})
@ -1303,10 +1188,7 @@ test "returns the favorites of a user", %{conn: conn} do
{:ok, _, _} = CommonAPI.favorite(activity.id, user) {:ok, _, _} = CommonAPI.favorite(activity.id, user)
first_conn = first_conn = get(conn, "/api/v1/favourites")
conn
|> assign(:user, user)
|> get("/api/v1/favourites")
assert [status] = json_response(first_conn, 200) assert [status] = json_response(first_conn, 200)
assert status["id"] == to_string(activity.id) assert status["id"] == to_string(activity.id)
@ -1325,18 +1207,12 @@ test "returns the favorites of a user", %{conn: conn} do
last_like = status["id"] last_like = status["id"]
second_conn = second_conn = get(conn, "/api/v1/favourites?since_id=#{last_like}")
conn
|> assign(:user, user)
|> get("/api/v1/favourites?since_id=#{last_like}")
assert [second_status] = json_response(second_conn, 200) assert [second_status] = json_response(second_conn, 200)
assert second_status["id"] == to_string(second_activity.id) assert second_status["id"] == to_string(second_activity.id)
third_conn = third_conn = get(conn, "/api/v1/favourites?limit=0")
conn
|> assign(:user, user)
|> get("/api/v1/favourites?limit=0")
assert [] = json_response(third_conn, 200) assert [] = json_response(third_conn, 200)
end end

View File

@ -450,7 +450,7 @@ test "properly handles internal calls with `authorization`-wrapped params", %{
test "renders authentication page if user is already authenticated but `force_login` is tru-ish", test "renders authentication page if user is already authenticated but `force_login` is tru-ish",
%{app: app, conn: conn} do %{app: app, conn: conn} do
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn
@ -474,7 +474,7 @@ test "renders authentication page if user is already authenticated but user requ
app: app, app: app,
conn: conn conn: conn
} do } do
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn
@ -497,7 +497,7 @@ test "with existing authentication and non-OOB `redirect_uri`, redirects to app
app: app, app: app,
conn: conn conn: conn
} do } do
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn
@ -523,7 +523,7 @@ test "with existing authentication and unlisted non-OOB `redirect_uri`, redirect
conn: conn conn: conn
} do } do
unlisted_redirect_uri = "http://cross-site-request.com" unlisted_redirect_uri = "http://cross-site-request.com"
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn
@ -547,7 +547,7 @@ test "with existing authentication and OOB `redirect_uri`, redirects to app with
app: app, app: app,
conn: conn conn: conn
} do } do
token = insert(:oauth_token, app_id: app.id) token = insert(:oauth_token, app: app)
conn = conn =
conn conn

View File

@ -23,6 +23,7 @@ test "POST /api/v1/pleroma/statuses/:id/react_with_emoji", %{conn: conn} do
result = result =
conn conn
|> assign(:user, other_user) |> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
|> post("/api/v1/pleroma/statuses/#{activity.id}/react_with_emoji", %{"emoji" => ""}) |> post("/api/v1/pleroma/statuses/#{activity.id}/react_with_emoji", %{"emoji" => ""})
assert %{"id" => id} = json_response(result, 200) assert %{"id" => id} = json_response(result, 200)
@ -39,6 +40,7 @@ test "POST /api/v1/pleroma/statuses/:id/unreact_with_emoji", %{conn: conn} do
result = result =
conn conn
|> assign(:user, other_user) |> assign(:user, other_user)
|> assign(:token, insert(:oauth_token, user: other_user, scopes: ["write:statuses"]))
|> post("/api/v1/pleroma/statuses/#{activity.id}/unreact_with_emoji", %{"emoji" => ""}) |> post("/api/v1/pleroma/statuses/#{activity.id}/unreact_with_emoji", %{"emoji" => ""})
assert %{"id" => id} = json_response(result, 200) assert %{"id" => id} = json_response(result, 200)
@ -55,6 +57,11 @@ test "GET /api/v1/pleroma/statuses/:id/emoji_reactions_by", %{conn: conn} do
{:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"}) {:ok, activity} = CommonAPI.post(user, %{"status" => "#cofe"})
conn =
conn
|> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["read:statuses"]))
result = result =
conn conn
|> get("/api/v1/pleroma/statuses/#{activity.id}/emoji_reactions_by") |> get("/api/v1/pleroma/statuses/#{activity.id}/emoji_reactions_by")
@ -73,9 +80,9 @@ test "GET /api/v1/pleroma/statuses/:id/emoji_reactions_by", %{conn: conn} do
assert represented_user["id"] == other_user.id assert represented_user["id"] == other_user.id
end end
test "/api/v1/pleroma/conversations/:id", %{conn: conn} do test "/api/v1/pleroma/conversations/:id" do
user = insert(:user) user = insert(:user)
other_user = insert(:user) %{user: other_user, conn: conn} = oauth_access(["read:statuses"])
{:ok, _activity} = {:ok, _activity} =
CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}!", "visibility" => "direct"}) CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}!", "visibility" => "direct"})
@ -84,16 +91,15 @@ test "/api/v1/pleroma/conversations/:id", %{conn: conn} do
result = result =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/pleroma/conversations/#{participation.id}") |> get("/api/v1/pleroma/conversations/#{participation.id}")
|> json_response(200) |> json_response(200)
assert result["id"] == participation.id |> to_string() assert result["id"] == participation.id |> to_string()
end end
test "/api/v1/pleroma/conversations/:id/statuses", %{conn: conn} do test "/api/v1/pleroma/conversations/:id/statuses" do
user = insert(:user) user = insert(:user)
other_user = insert(:user) %{user: other_user, conn: conn} = oauth_access(["read:statuses"])
third_user = insert(:user) third_user = insert(:user)
{:ok, _activity} = {:ok, _activity} =
@ -113,7 +119,6 @@ test "/api/v1/pleroma/conversations/:id/statuses", %{conn: conn} do
result = result =
conn conn
|> assign(:user, other_user)
|> get("/api/v1/pleroma/conversations/#{participation.id}/statuses") |> get("/api/v1/pleroma/conversations/#{participation.id}/statuses")
|> json_response(200) |> json_response(200)
@ -124,8 +129,8 @@ test "/api/v1/pleroma/conversations/:id/statuses", %{conn: conn} do
assert [%{"id" => ^id_one}, %{"id" => ^id_two}] = result assert [%{"id" => ^id_one}, %{"id" => ^id_two}] = result
end end
test "PATCH /api/v1/pleroma/conversations/:id", %{conn: conn} do test "PATCH /api/v1/pleroma/conversations/:id" do
user = insert(:user) %{user: user, conn: conn} = oauth_access(["write:conversations"])
other_user = insert(:user) other_user = insert(:user)
{:ok, _activity} = CommonAPI.post(user, %{"status" => "Hi", "visibility" => "direct"}) {:ok, _activity} = CommonAPI.post(user, %{"status" => "Hi", "visibility" => "direct"})
@ -140,7 +145,6 @@ test "PATCH /api/v1/pleroma/conversations/:id", %{conn: conn} do
result = result =
conn conn
|> assign(:user, user)
|> patch("/api/v1/pleroma/conversations/#{participation.id}", %{ |> patch("/api/v1/pleroma/conversations/#{participation.id}", %{
"recipients" => [user.id, other_user.id] "recipients" => [user.id, other_user.id]
}) })
@ -155,9 +159,9 @@ test "PATCH /api/v1/pleroma/conversations/:id", %{conn: conn} do
assert other_user in participation.recipients assert other_user in participation.recipients
end end
test "POST /api/v1/pleroma/conversations/read", %{conn: conn} do test "POST /api/v1/pleroma/conversations/read" do
user = insert(:user) user = insert(:user)
other_user = insert(:user) %{user: other_user, conn: conn} = oauth_access(["write:notifications"])
{:ok, _activity} = {:ok, _activity} =
CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}", "visibility" => "direct"}) CommonAPI.post(user, %{"status" => "Hi @#{other_user.nickname}", "visibility" => "direct"})
@ -172,7 +176,6 @@ test "POST /api/v1/pleroma/conversations/read", %{conn: conn} do
[%{"unread" => false}, %{"unread" => false}] = [%{"unread" => false}, %{"unread" => false}] =
conn conn
|> assign(:user, other_user)
|> post("/api/v1/pleroma/conversations/read", %{}) |> post("/api/v1/pleroma/conversations/read", %{})
|> json_response(200) |> json_response(200)
@ -183,8 +186,9 @@ test "POST /api/v1/pleroma/conversations/read", %{conn: conn} do
end end
describe "POST /api/v1/pleroma/notifications/read" do describe "POST /api/v1/pleroma/notifications/read" do
test "it marks a single notification as read", %{conn: conn} do setup do: oauth_access(["write:notifications"])
user1 = insert(:user)
test "it marks a single notification as read", %{user: user1, conn: conn} do
user2 = insert(:user) user2 = insert(:user)
{:ok, activity1} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"}) {:ok, activity1} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
{:ok, activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"}) {:ok, activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
@ -193,7 +197,6 @@ test "it marks a single notification as read", %{conn: conn} do
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/v1/pleroma/notifications/read", %{"id" => "#{notification1.id}"}) |> post("/api/v1/pleroma/notifications/read", %{"id" => "#{notification1.id}"})
|> json_response(:ok) |> json_response(:ok)
@ -202,8 +205,7 @@ test "it marks a single notification as read", %{conn: conn} do
refute Repo.get(Notification, notification2.id).seen refute Repo.get(Notification, notification2.id).seen
end end
test "it marks multiple notifications as read", %{conn: conn} do test "it marks multiple notifications as read", %{user: user1, conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
{:ok, _activity1} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"}) {:ok, _activity1} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
{:ok, _activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"}) {:ok, _activity2} = CommonAPI.post(user2, %{"status" => "hi @#{user1.nickname}"})
@ -213,7 +215,6 @@ test "it marks multiple notifications as read", %{conn: conn} do
[response1, response2] = [response1, response2] =
conn conn
|> assign(:user, user1)
|> post("/api/v1/pleroma/notifications/read", %{"max_id" => "#{notification2.id}"}) |> post("/api/v1/pleroma/notifications/read", %{"max_id" => "#{notification2.id}"})
|> json_response(:ok) |> json_response(:ok)
@ -225,11 +226,8 @@ test "it marks multiple notifications as read", %{conn: conn} do
end end
test "it returns error when notification not found", %{conn: conn} do test "it returns error when notification not found", %{conn: conn} do
user1 = insert(:user)
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/v1/pleroma/notifications/read", %{"id" => "22222222222222"}) |> post("/api/v1/pleroma/notifications/read", %{"id" => "22222222222222"})
|> json_response(:bad_request) |> json_response(:bad_request)

View File

@ -6,10 +6,10 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
use Pleroma.Web.ConnCase use Pleroma.Web.ConnCase
use Oban.Testing, repo: Pleroma.Repo use Oban.Testing, repo: Pleroma.Repo
alias Pleroma.Repo
alias Pleroma.Tests.ObanHelpers alias Pleroma.Tests.ObanHelpers
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.CommonAPI alias Pleroma.Web.CommonAPI
import ExUnit.CaptureLog import ExUnit.CaptureLog
import Pleroma.Factory import Pleroma.Factory
import Mock import Mock
@ -24,21 +24,20 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do
clear_config([:user, :deny_follow_blocked]) clear_config([:user, :deny_follow_blocked])
describe "POST /api/pleroma/follow_import" do describe "POST /api/pleroma/follow_import" do
setup do: oauth_access(["follow"])
test "it returns HTTP 200", %{conn: conn} do test "it returns HTTP 200", %{conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/follow_import", %{"list" => "#{user2.ap_id}"}) |> post("/api/pleroma/follow_import", %{"list" => "#{user2.ap_id}"})
|> json_response(:ok) |> json_response(:ok)
assert response == "job started" assert response == "job started"
end end
test "it imports follow lists from file", %{conn: conn} do test "it imports follow lists from file", %{user: user1, conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
with_mocks([ with_mocks([
@ -49,7 +48,6 @@ test "it imports follow lists from file", %{conn: conn} do
]) do ]) do
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/follow_import", %{"list" => %Plug.Upload{path: "follow_list.txt"}}) |> post("/api/pleroma/follow_import", %{"list" => %Plug.Upload{path: "follow_list.txt"}})
|> json_response(:ok) |> json_response(:ok)
@ -67,12 +65,10 @@ test "it imports follow lists from file", %{conn: conn} do
end end
test "it imports new-style mastodon follow lists", %{conn: conn} do test "it imports new-style mastodon follow lists", %{conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/follow_import", %{ |> post("/api/pleroma/follow_import", %{
"list" => "Account address,Show boosts\n#{user2.ap_id},true" "list" => "Account address,Show boosts\n#{user2.ap_id},true"
}) })
@ -81,7 +77,7 @@ test "it imports new-style mastodon follow lists", %{conn: conn} do
assert response == "job started" assert response == "job started"
end end
test "requires 'follow' or 'write:follows' permissions", %{conn: conn} do test "requires 'follow' or 'write:follows' permissions" do
token1 = insert(:oauth_token, scopes: ["read", "write"]) token1 = insert(:oauth_token, scopes: ["read", "write"])
token2 = insert(:oauth_token, scopes: ["follow"]) token2 = insert(:oauth_token, scopes: ["follow"])
token3 = insert(:oauth_token, scopes: ["something"]) token3 = insert(:oauth_token, scopes: ["something"])
@ -89,7 +85,7 @@ test "requires 'follow' or 'write:follows' permissions", %{conn: conn} do
for token <- [token1, token2, token3] do for token <- [token1, token2, token3] do
conn = conn =
conn build_conn()
|> put_req_header("authorization", "Bearer #{token.token}") |> put_req_header("authorization", "Bearer #{token.token}")
|> post("/api/pleroma/follow_import", %{"list" => "#{another_user.ap_id}"}) |> post("/api/pleroma/follow_import", %{"list" => "#{another_user.ap_id}"})
@ -104,21 +100,21 @@ test "requires 'follow' or 'write:follows' permissions", %{conn: conn} do
end end
describe "POST /api/pleroma/blocks_import" do describe "POST /api/pleroma/blocks_import" do
# Note: "follow" or "write:blocks" permission is required
setup do: oauth_access(["write:blocks"])
test "it returns HTTP 200", %{conn: conn} do test "it returns HTTP 200", %{conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/blocks_import", %{"list" => "#{user2.ap_id}"}) |> post("/api/pleroma/blocks_import", %{"list" => "#{user2.ap_id}"})
|> json_response(:ok) |> json_response(:ok)
assert response == "job started" assert response == "job started"
end end
test "it imports blocks users from file", %{conn: conn} do test "it imports blocks users from file", %{user: user1, conn: conn} do
user1 = insert(:user)
user2 = insert(:user) user2 = insert(:user)
user3 = insert(:user) user3 = insert(:user)
@ -127,7 +123,6 @@ test "it imports blocks users from file", %{conn: conn} do
]) do ]) do
response = response =
conn conn
|> assign(:user, user1)
|> post("/api/pleroma/blocks_import", %{"list" => %Plug.Upload{path: "blocks_list.txt"}}) |> post("/api/pleroma/blocks_import", %{"list" => %Plug.Upload{path: "blocks_list.txt"}})
|> json_response(:ok) |> json_response(:ok)
@ -146,18 +141,17 @@ test "it imports blocks users from file", %{conn: conn} do
end end
describe "PUT /api/pleroma/notification_settings" do describe "PUT /api/pleroma/notification_settings" do
test "it updates notification settings", %{conn: conn} do setup do: oauth_access(["write:accounts"])
user = insert(:user)
test "it updates notification settings", %{user: user, conn: conn} do
conn conn
|> assign(:user, user)
|> put("/api/pleroma/notification_settings", %{ |> put("/api/pleroma/notification_settings", %{
"followers" => false, "followers" => false,
"bar" => 1 "bar" => 1
}) })
|> json_response(:ok) |> json_response(:ok)
user = Repo.get(User, user.id) user = refresh_record(user)
assert %Pleroma.User.NotificationSetting{ assert %Pleroma.User.NotificationSetting{
followers: false, followers: false,
@ -168,11 +162,8 @@ test "it updates notification settings", %{conn: conn} do
} == user.notification_settings } == user.notification_settings
end end
test "it update notificatin privacy option", %{conn: conn} do test "it updates notification privacy option", %{user: user, conn: conn} do
user = insert(:user)
conn conn
|> assign(:user, user)
|> put("/api/pleroma/notification_settings", %{"privacy_option" => "1"}) |> put("/api/pleroma/notification_settings", %{"privacy_option" => "1"})
|> json_response(:ok) |> json_response(:ok)
@ -375,13 +366,13 @@ test "show follow page with error when user cannot fecth by `acct` link", %{conn
end end
describe "POST /ostatus_subscribe - do_remote_follow/2 with assigned user" do describe "POST /ostatus_subscribe - do_remote_follow/2 with assigned user" do
test "follows user", %{conn: conn} do setup do: oauth_access(["follow"])
user = insert(:user)
test "follows user", %{user: user, conn: conn} do
user2 = insert(:user) user2 = insert(:user)
response = response =
conn conn
|> assign(:user, user)
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200) |> response(200)
@ -389,55 +380,63 @@ test "follows user", %{conn: conn} do
assert user2.follower_address in User.following(user) assert user2.follower_address in User.following(user)
end end
test "returns error when user is deactivated", %{conn: conn} do test "returns error when user is deactivated" do
user = insert(:user, deactivated: true) user = insert(:user, deactivated: true)
user2 = insert(:user) user2 = insert(:user)
response = response =
conn build_conn()
|> assign(:user, user) |> assign(:user, user)
|> assign(:token, insert(:oauth_token, user: user, scopes: ["follow"]))
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200) |> response(200)
assert response =~ "Error following account" assert response =~ "Error following account"
end end
test "returns error when user is blocked", %{conn: conn} do test "returns error when user is blocked", %{user: user, conn: conn} do
Pleroma.Config.put([:user, :deny_follow_blocked], true) Pleroma.Config.put([:user, :deny_follow_blocked], true)
user = insert(:user)
user2 = insert(:user) user2 = insert(:user)
{:ok, _user_block} = Pleroma.User.block(user2, user) {:ok, _user_block} = Pleroma.User.block(user2, user)
response = response =
conn conn
|> assign(:user, user)
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200) |> response(200)
assert response =~ "Error following account" assert response =~ "Error following account"
end end
test "returns error when followee not found", %{conn: conn} do test "returns error on insufficient permissions", %{user: user, conn: conn} do
user = insert(:user) user2 = insert(:user)
for token <- [nil, insert(:oauth_token, user: user, scopes: ["read"])] do
response =
conn
|> assign(:token, token)
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200)
assert response =~ "Error following account"
end
end
test "returns error when followee not found", %{conn: conn} do
response = response =
conn conn
|> assign(:user, user)
|> post("/ostatus_subscribe", %{"user" => %{"id" => "jimm"}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => "jimm"}})
|> response(200) |> response(200)
assert response =~ "Error following account" assert response =~ "Error following account"
end end
test "returns success result when user already in followers", %{conn: conn} do test "returns success result when user already in followers", %{user: user, conn: conn} do
user = insert(:user)
user2 = insert(:user) user2 = insert(:user)
{:ok, _, _, _} = CommonAPI.follow(user, user2) {:ok, _, _, _} = CommonAPI.follow(user, user2)
response = response =
conn conn
|> assign(:user, refresh_record(user))
|> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}}) |> post("/ostatus_subscribe", %{"user" => %{"id" => user2.id}})
|> response(200) |> response(200)
@ -574,12 +573,11 @@ test "returns 503 when healthcheck enabled and health is false", %{conn: conn}
end end
describe "POST /api/pleroma/disable_account" do describe "POST /api/pleroma/disable_account" do
test "it returns HTTP 200", %{conn: conn} do setup do: oauth_access(["write:accounts"])
user = insert(:user)
test "with valid permissions and password, it disables the account", %{conn: conn, user: user} do
response = response =
conn conn
|> assign(:user, user)
|> post("/api/pleroma/disable_account", %{"password" => "test"}) |> post("/api/pleroma/disable_account", %{"password" => "test"})
|> json_response(:ok) |> json_response(:ok)
@ -591,12 +589,11 @@ test "it returns HTTP 200", %{conn: conn} do
assert user.deactivated == true assert user.deactivated == true
end end
test "it returns returns when password invalid", %{conn: conn} do test "with valid permissions and invalid password, it returns an error", %{conn: conn} do
user = insert(:user) user = insert(:user)
response = response =
conn conn
|> assign(:user, user)
|> post("/api/pleroma/disable_account", %{"password" => "test1"}) |> post("/api/pleroma/disable_account", %{"password" => "test1"})
|> json_response(:ok) |> json_response(:ok)
@ -666,7 +663,7 @@ test "it redirect to webfinger url", %{conn: conn} do
"https://social.heldscal.la/main/ostatussub?profile=#{user.ap_id}" "https://social.heldscal.la/main/ostatussub?profile=#{user.ap_id}"
end end
test "it renders form with error when use not found", %{conn: conn} do test "it renders form with error when user not found", %{conn: conn} do
user2 = insert(:user, ap_id: "shp@social.heldscal.la") user2 = insert(:user, ap_id: "shp@social.heldscal.la")
response = response =
@ -691,29 +688,21 @@ test "it returns new captcha", %{conn: conn} do
end end
end end
defp with_credentials(conn, username, password) do
header_content = "Basic " <> Base.encode64("#{username}:#{password}")
put_req_header(conn, "authorization", header_content)
end
defp valid_user(_context) do
user = insert(:user)
[user: user]
end
describe "POST /api/pleroma/change_email" do describe "POST /api/pleroma/change_email" do
setup [:valid_user] setup do: oauth_access(["write:accounts"])
test "without credentials", %{conn: conn} do test "without permissions", %{conn: conn} do
conn = post(conn, "/api/pleroma/change_email")
assert json_response(conn, 403) == %{"error" => "Invalid credentials."}
end
test "with credentials and invalid password", %{conn: conn, user: current_user} do
conn = conn =
conn conn
|> with_credentials(current_user.nickname, "test") |> assign(:token, nil)
|> post("/api/pleroma/change_email", %{ |> post("/api/pleroma/change_email")
assert json_response(conn, 403) == %{"error" => "Insufficient permissions: write:accounts."}
end
test "with proper permissions and invalid password", %{conn: conn} do
conn =
post(conn, "/api/pleroma/change_email", %{
"password" => "hi", "password" => "hi",
"email" => "test@test.com" "email" => "test@test.com"
}) })
@ -721,14 +710,11 @@ test "with credentials and invalid password", %{conn: conn, user: current_user}
assert json_response(conn, 200) == %{"error" => "Invalid password."} assert json_response(conn, 200) == %{"error" => "Invalid password."}
end end
test "with credentials, valid password and invalid email", %{ test "with proper permissions, valid password and invalid email", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test", "password" => "test",
"email" => "foobar" "email" => "foobar"
}) })
@ -736,28 +722,22 @@ test "with credentials, valid password and invalid email", %{
assert json_response(conn, 200) == %{"error" => "Email has invalid format."} assert json_response(conn, 200) == %{"error" => "Email has invalid format."}
end end
test "with credentials, valid password and no email", %{ test "with proper permissions, valid password and no email", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test" "password" => "test"
}) })
assert json_response(conn, 200) == %{"error" => "Email can't be blank."} assert json_response(conn, 200) == %{"error" => "Email can't be blank."}
end end
test "with credentials, valid password and blank email", %{ test "with proper permissions, valid password and blank email", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test", "password" => "test",
"email" => "" "email" => ""
}) })
@ -765,16 +745,13 @@ test "with credentials, valid password and blank email", %{
assert json_response(conn, 200) == %{"error" => "Email can't be blank."} assert json_response(conn, 200) == %{"error" => "Email can't be blank."}
end end
test "with credentials, valid password and non unique email", %{ test "with proper permissions, valid password and non unique email", %{
conn: conn, conn: conn
user: current_user
} do } do
user = insert(:user) user = insert(:user)
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test", "password" => "test",
"email" => user.email "email" => user.email
}) })
@ -782,14 +759,11 @@ test "with credentials, valid password and non unique email", %{
assert json_response(conn, 200) == %{"error" => "Email has already been taken."} assert json_response(conn, 200) == %{"error" => "Email has already been taken."}
end end
test "with credentials, valid password and valid email", %{ test "with proper permissions, valid password and valid email", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_email", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_email", %{
"password" => "test", "password" => "test",
"email" => "cofe@foobar.com" "email" => "cofe@foobar.com"
}) })
@ -799,18 +773,20 @@ test "with credentials, valid password and valid email", %{
end end
describe "POST /api/pleroma/change_password" do describe "POST /api/pleroma/change_password" do
setup [:valid_user] setup do: oauth_access(["write:accounts"])
test "without credentials", %{conn: conn} do test "without permissions", %{conn: conn} do
conn = post(conn, "/api/pleroma/change_password")
assert json_response(conn, 403) == %{"error" => "Invalid credentials."}
end
test "with credentials and invalid password", %{conn: conn, user: current_user} do
conn = conn =
conn conn
|> with_credentials(current_user.nickname, "test") |> assign(:token, nil)
|> post("/api/pleroma/change_password", %{ |> post("/api/pleroma/change_password")
assert json_response(conn, 403) == %{"error" => "Insufficient permissions: write:accounts."}
end
test "with proper permissions and invalid password", %{conn: conn} do
conn =
post(conn, "/api/pleroma/change_password", %{
"password" => "hi", "password" => "hi",
"new_password" => "newpass", "new_password" => "newpass",
"new_password_confirmation" => "newpass" "new_password_confirmation" => "newpass"
@ -819,14 +795,12 @@ test "with credentials and invalid password", %{conn: conn, user: current_user}
assert json_response(conn, 200) == %{"error" => "Invalid password."} assert json_response(conn, 200) == %{"error" => "Invalid password."}
end end
test "with credentials, valid password and new password and confirmation not matching", %{ test "with proper permissions, valid password and new password and confirmation not matching",
conn: conn, %{
user: current_user conn: conn
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_password", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_password", %{
"password" => "test", "password" => "test",
"new_password" => "newpass", "new_password" => "newpass",
"new_password_confirmation" => "notnewpass" "new_password_confirmation" => "notnewpass"
@ -837,14 +811,11 @@ test "with credentials, valid password and new password and confirmation not mat
} }
end end
test "with credentials, valid password and invalid new password", %{ test "with proper permissions, valid password and invalid new password", %{
conn: conn, conn: conn
user: current_user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_password", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_password", %{
"password" => "test", "password" => "test",
"new_password" => "", "new_password" => "",
"new_password_confirmation" => "" "new_password_confirmation" => ""
@ -855,51 +826,48 @@ test "with credentials, valid password and invalid new password", %{
} }
end end
test "with credentials, valid password and matching new password and confirmation", %{ test "with proper permissions, valid password and matching new password and confirmation", %{
conn: conn, conn: conn,
user: current_user user: user
} do } do
conn = conn =
conn post(conn, "/api/pleroma/change_password", %{
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/change_password", %{
"password" => "test", "password" => "test",
"new_password" => "newpass", "new_password" => "newpass",
"new_password_confirmation" => "newpass" "new_password_confirmation" => "newpass"
}) })
assert json_response(conn, 200) == %{"status" => "success"} assert json_response(conn, 200) == %{"status" => "success"}
fetched_user = User.get_cached_by_id(current_user.id) fetched_user = User.get_cached_by_id(user.id)
assert Comeonin.Pbkdf2.checkpw("newpass", fetched_user.password_hash) == true assert Comeonin.Pbkdf2.checkpw("newpass", fetched_user.password_hash) == true
end end
end end
describe "POST /api/pleroma/delete_account" do describe "POST /api/pleroma/delete_account" do
setup [:valid_user] setup do: oauth_access(["write:accounts"])
test "without credentials", %{conn: conn} do test "without permissions", %{conn: conn} do
conn = post(conn, "/api/pleroma/delete_account")
assert json_response(conn, 403) == %{"error" => "Invalid credentials."}
end
test "with credentials and invalid password", %{conn: conn, user: current_user} do
conn = conn =
conn conn
|> with_credentials(current_user.nickname, "test") |> assign(:token, nil)
|> post("/api/pleroma/delete_account", %{"password" => "hi"}) |> post("/api/pleroma/delete_account")
assert json_response(conn, 200) == %{"error" => "Invalid password."} assert json_response(conn, 403) ==
%{"error" => "Insufficient permissions: write:accounts."}
end end
test "with credentials and valid password", %{conn: conn, user: current_user} do test "with proper permissions and wrong or missing password", %{conn: conn} do
conn = for params <- [%{"password" => "hi"}, %{}] do
conn ret_conn = post(conn, "/api/pleroma/delete_account", params)
|> with_credentials(current_user.nickname, "test")
|> post("/api/pleroma/delete_account", %{"password" => "test"}) assert json_response(ret_conn, 200) == %{"error" => "Invalid password."}
end
end
test "with proper permissions and valid password", %{conn: conn} do
conn = post(conn, "/api/pleroma/delete_account", %{"password" => "test"})
assert json_response(conn, 200) == %{"status" => "success"} assert json_response(conn, 200) == %{"status" => "success"}
# Wait a second for the started task to end
:timer.sleep(1000)
end end
end end
end end