diff options
Diffstat (limited to 'test')
104 files changed, 1967 insertions, 994 deletions
| diff --git a/test/activity/ir/topics_test.exs b/test/activity/ir/topics_test.exs index e75f83586..44aec1e19 100644 --- a/test/activity/ir/topics_test.exs +++ b/test/activity/ir/topics_test.exs @@ -59,8 +59,8 @@ defmodule Pleroma.Activity.Ir.TopicsTest do    describe "public visibility create events" do      setup do        activity = %Activity{ -        object: %Object{data: %{"type" => "Create", "attachment" => []}}, -        data: %{"to" => [Pleroma.Constants.as_public()]} +        object: %Object{data: %{"attachment" => []}}, +        data: %{"type" => "Create", "to" => [Pleroma.Constants.as_public()]}        }        {:ok, activity: activity} @@ -98,8 +98,8 @@ defmodule Pleroma.Activity.Ir.TopicsTest do    describe "public visibility create events with attachments" do      setup do        activity = %Activity{ -        object: %Object{data: %{"type" => "Create", "attachment" => ["foo"]}}, -        data: %{"to" => [Pleroma.Constants.as_public()]} +        object: %Object{data: %{"attachment" => ["foo"]}}, +        data: %{"type" => "Create", "to" => [Pleroma.Constants.as_public()]}        }        {:ok, activity: activity} diff --git a/test/activity_expiration_test.exs b/test/activity_expiration_test.exs index 4cda5e985..e899d4509 100644 --- a/test/activity_expiration_test.exs +++ b/test/activity_expiration_test.exs @@ -7,7 +7,7 @@ defmodule Pleroma.ActivityExpirationTest do    alias Pleroma.ActivityExpiration    import Pleroma.Factory -  clear_config([ActivityExpiration, :enabled]) +  setup do: clear_config([ActivityExpiration, :enabled])    test "finds activities due to be deleted only" do      activity = insert(:note_activity) diff --git a/test/activity_test.exs b/test/activity_test.exs index 46b55beaa..0c19f481b 100644 --- a/test/activity_test.exs +++ b/test/activity_test.exs @@ -138,7 +138,7 @@ defmodule Pleroma.ActivityTest do        }      end -    clear_config([:instance, :limit_to_local_content]) +    setup do: clear_config([:instance, :limit_to_local_content])      test "finds utf8 text in statuses", %{        japanese_activity: japanese_activity, diff --git a/test/captcha_test.exs b/test/captcha_test.exs index 5e29b48b0..ac1d846e8 100644 --- a/test/captcha_test.exs +++ b/test/captcha_test.exs @@ -12,8 +12,7 @@ defmodule Pleroma.CaptchaTest do    alias Pleroma.Captcha.Native    @ets_options [:ordered_set, :private, :named_table, {:read_concurrency, true}] - -  clear_config([Pleroma.Captcha, :enabled]) +  setup do: clear_config([Pleroma.Captcha, :enabled])    describe "Kocaptcha" do      setup do diff --git a/test/config/holder_test.exs b/test/config/holder_test.exs index 2368d4856..15d48b5c7 100644 --- a/test/config/holder_test.exs +++ b/test/config/holder_test.exs @@ -7,8 +7,8 @@ defmodule Pleroma.Config.HolderTest do    alias Pleroma.Config.Holder -  test "config/0" do -    config = Holder.config() +  test "default_config/0" do +    config = Holder.default_config()      assert config[:pleroma][Pleroma.Uploaders.Local][:uploads] == "test/uploads"      assert config[:tesla][:adapter] == Tesla.Mock @@ -20,15 +20,15 @@ defmodule Pleroma.Config.HolderTest do      refute config[:phoenix][:serve_endpoints]    end -  test "config/1" do -    pleroma_config = Holder.config(:pleroma) +  test "default_config/1" do +    pleroma_config = Holder.default_config(:pleroma)      assert pleroma_config[Pleroma.Uploaders.Local][:uploads] == "test/uploads" -    tesla_config = Holder.config(:tesla) +    tesla_config = Holder.default_config(:tesla)      assert tesla_config[:adapter] == Tesla.Mock    end -  test "config/2" do -    assert Holder.config(:pleroma, Pleroma.Uploaders.Local) == [uploads: "test/uploads"] -    assert Holder.config(:tesla, :adapter) == Tesla.Mock +  test "default_config/2" do +    assert Holder.default_config(:pleroma, Pleroma.Uploaders.Local) == [uploads: "test/uploads"] +    assert Holder.default_config(:tesla, :adapter) == Tesla.Mock    end  end diff --git a/test/config/loader_test.exs b/test/config/loader_test.exs index 4c93e5d4d..607572f4e 100644 --- a/test/config/loader_test.exs +++ b/test/config/loader_test.exs @@ -7,28 +7,13 @@ defmodule Pleroma.Config.LoaderTest do    alias Pleroma.Config.Loader -  test "load/1" do -    config = Loader.load("test/fixtures/config/temp.secret.exs") +  test "read/1" do +    config = Loader.read("test/fixtures/config/temp.secret.exs")      assert config[:pleroma][:first_setting][:key] == "value"      assert config[:pleroma][:first_setting][:key2] == [Pleroma.Repo]      assert config[:quack][:level] == :info    end -  test "load_and_merge/0" do -    config = Loader.load_and_merge() - -    refute config[:pleroma][Pleroma.Repo] -    refute config[:pleroma][Pleroma.Web.Endpoint] -    refute config[:pleroma][:env] -    refute config[:pleroma][:configurable_from_database] -    refute config[:pleroma][:database] -    refute config[:phoenix][:serve_endpoints] - -    assert config[:pleroma][:ecto_repos] == [Pleroma.Repo] -    assert config[:pleroma][Pleroma.Uploaders.Local][:uploads] == "test/uploads" -    assert config[:tesla][:adapter] == Tesla.Mock -  end -    test "filter_group/2" do      assert Loader.filter_group(:pleroma,               pleroma: [ diff --git a/test/config/transfer_task_test.exs b/test/config/transfer_task_test.exs index ce31d1e87..0265a6156 100644 --- a/test/config/transfer_task_test.exs +++ b/test/config/transfer_task_test.exs @@ -10,9 +10,7 @@ defmodule Pleroma.Config.TransferTaskTest do    alias Pleroma.Config.TransferTask    alias Pleroma.ConfigDB -  clear_config(:configurable_from_database) do -    Pleroma.Config.put(:configurable_from_database, true) -  end +  setup do: clear_config(:configurable_from_database, true)    test "transfer config values from db to env" do      refute Application.get_env(:pleroma, :test_key) @@ -70,7 +68,7 @@ defmodule Pleroma.Config.TransferTaskTest do      assert Application.get_env(:quack, :level) == :info      assert Application.get_env(:quack, :meta) == [:none] -    default = Pleroma.Config.Holder.config(:quack, :webhook_url) +    default = Pleroma.Config.Holder.default_config(:quack, :webhook_url)      assert Application.get_env(:quack, :webhook_url) == default      on_exit(fn -> diff --git a/test/conversation_test.exs b/test/conversation_test.exs index dc0027d04..056a0e920 100644 --- a/test/conversation_test.exs +++ b/test/conversation_test.exs @@ -11,9 +11,7 @@ defmodule Pleroma.ConversationTest do    import Pleroma.Factory -  clear_config_all([:instance, :federating]) do -    Pleroma.Config.put([:instance, :federating], true) -  end +  setup_all do: clear_config([:instance, :federating], true)    test "it goes through old direct conversations" do      user = insert(:user) diff --git a/test/earmark_renderer_test.exs b/test/earmark_renderer_test.exs new file mode 100644 index 000000000..220d97d16 --- /dev/null +++ b/test/earmark_renderer_test.exs @@ -0,0 +1,79 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2020 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only +defmodule Pleroma.EarmarkRendererTest do +  use ExUnit.Case + +  test "Paragraph" do +    code = ~s[Hello\n\nWorld!] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == "<p>Hello</p><p>World!</p>" +  end + +  test "raw HTML" do +    code = ~s[<a href="http://example.org/">OwO</a><!-- what's this?-->] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == "<p>#{code}</p>" +  end + +  test "rulers" do +    code = ~s[before\n\n-----\n\nafter] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == "<p>before</p><hr /><p>after</p>" +  end + +  test "headings" do +    code = ~s[# h1\n## h2\n### h3\n] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == ~s[<h1>h1</h1><h2>h2</h2><h3>h3</h3>] +  end + +  test "blockquote" do +    code = ~s[> whoms't are you quoting?] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == "<blockquote><p>whoms’t are you quoting?</p></blockquote>" +  end + +  test "code" do +    code = ~s[`mix`] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == ~s[<p><code class="inline">mix</code></p>] + +    code = ~s[``mix``] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == ~s[<p><code class="inline">mix</code></p>] + +    code = ~s[```\nputs "Hello World"\n```] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == ~s[<pre><code class="">puts "Hello World"</code></pre>] +  end + +  test "lists" do +    code = ~s[- one\n- two\n- three\n- four] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == "<ul><li>one</li><li>two</li><li>three</li><li>four</li></ul>" + +    code = ~s[1. one\n2. two\n3. three\n4. four\n] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == "<ol><li>one</li><li>two</li><li>three</li><li>four</li></ol>" +  end + +  test "delegated renderers" do +    code = ~s[a<br/>b] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == "<p>#{code}</p>" + +    code = ~s[*aaaa~*] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == ~s[<p><em>aaaa~</em></p>] + +    code = ~s[**aaaa~**] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == ~s[<p><strong>aaaa~</strong></p>] + +    # strikethrought +    code = ~s[<del>aaaa~</del>] +    result = Earmark.as_html!(code, %Earmark.Options{renderer: Pleroma.EarmarkRenderer}) +    assert result == ~s[<p><del>aaaa~</del></p>] +  end +end diff --git a/test/emails/mailer_test.exs b/test/emails/mailer_test.exs index f30aa6a72..e6e34cba8 100644 --- a/test/emails/mailer_test.exs +++ b/test/emails/mailer_test.exs @@ -14,8 +14,7 @@ defmodule Pleroma.Emails.MailerTest do      subject: "Pleroma test email",      to: [{"Test User", "user1@example.com"}]    } - -  clear_config([Pleroma.Emails.Mailer, :enabled]) +  setup do: clear_config([Pleroma.Emails.Mailer, :enabled])    test "not send email when mailer is disabled" do      Pleroma.Config.put([Pleroma.Emails.Mailer, :enabled], false) diff --git a/test/fixtures/relay/accept-follow.json b/test/fixtures/relay/accept-follow.json new file mode 100644 index 000000000..1b166f2da --- /dev/null +++ b/test/fixtures/relay/accept-follow.json @@ -0,0 +1,15 @@ +{ +  "@context": "https://www.w3.org/ns/activitystreams", +  "actor": "https://relay.mastodon.host/actor", +  "id": "https://relay.mastodon.host/activities/ec477b69-db26-4019-923e-cf809de516ab", +  "object": { +    "actor": "{{ap_id}}", +    "id": "{{activity_id}}", +    "object": "https://relay.mastodon.host/actor", +    "type": "Follow" +  }, +  "to": [ +    "{{ap_id}}" +  ], +  "type": "Accept" +}
\ No newline at end of file diff --git a/test/fixtures/relay/relay.json b/test/fixtures/relay/relay.json new file mode 100644 index 000000000..77ae7f06c --- /dev/null +++ b/test/fixtures/relay/relay.json @@ -0,0 +1,20 @@ +{ +  "@context": "https://www.w3.org/ns/activitystreams", +  "endpoints": { +    "sharedInbox": "https://relay.mastodon.host/inbox" +  }, +  "followers": "https://relay.mastodon.host/followers", +  "following": "https://relay.mastodon.host/following", +  "inbox": "https://relay.mastodon.host/inbox", +  "name": "ActivityRelay", +  "type": "Application", +  "id": "https://relay.mastodon.host/actor", +  "publicKey": { +    "id": "https://relay.mastodon.host/actor#main-key", +    "owner": "https://relay.mastodon.host/actor", +    "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAuNYHNYETdsZFsdcTTEQo\nlsTP9yz4ZjOGrQ1EjoBA7NkjBUxxUAPxZbBjWPT9F+L3IbCX1IwI2OrBM/KwDlug\nV41xnjNmxSCUNpxX5IMZtFaAz9/hWu6xkRTs9Bh6XWZxi+db905aOqszb9Mo3H2g\nQJiAYemXwTh2kBO7XlBDbsMhO11Tu8FxcWTMdR54vlGv4RoiVh8dJRa06yyiTs+m\njbj/OJwR06mHHwlKYTVT/587NUb+e9QtCK6t/dqpyZ1o7vKSK5PSldZVjwHt292E\nXVxFOQVXi7JazTwpdPww79ECSe8ThCykOYCNkm3RjsKuLuokp7Vzq1hXIoeBJ7z2\ndU8vbgg/JyazsOsTxkVs2nd2i9/QW2SH+sX9X3357+XLSCh/A8p8fv/GeoN7UCXe\n4DWHFJZDlItNFfymiPbQH+omuju8qrfW9ngk1gFeI2mahXFQVu7x0qsaZYioCIrZ\nwq0zPnUGl9u0tLUXQz+ZkInRrEz+JepDVauy5/3QdzMLG420zCj/ygDrFzpBQIrc\n62Z6URueUBJox0UK71K+usxqOrepgw8haFGMvg3STFo34pNYjoK4oKO+h5qZEDFD\nb1n57t6JWUaBocZbJns9RGASq5gih+iMk2+zPLWp1x64yvuLsYVLPLBHxjCxS6lA\ndWcopZHi7R/OsRz+vTT7420CAwEAAQ==\n-----END PUBLIC KEY-----" +  }, +  "summary": "ActivityRelay bot", +  "preferredUsername": "relay", +  "url": "https://relay.mastodon.host/actor" +}
\ No newline at end of file diff --git a/test/http/request_builder_test.exs b/test/http/request_builder_test.exs index 11a9314ae..bf3a15ebe 100644 --- a/test/http/request_builder_test.exs +++ b/test/http/request_builder_test.exs @@ -8,8 +8,8 @@ defmodule Pleroma.HTTP.RequestBuilderTest do    alias Pleroma.HTTP.RequestBuilder    describe "headers/2" do -    clear_config([:http, :send_user_agent]) -    clear_config([:http, :user_agent]) +    setup do: clear_config([:http, :send_user_agent]) +    setup do: clear_config([:http, :user_agent])      test "don't send pleroma user agent" do        assert RequestBuilder.headers(%{}, []) == %{headers: []} diff --git a/test/notification_test.exs b/test/notification_test.exs index 56a581810..d87eca836 100644 --- a/test/notification_test.exs +++ b/test/notification_test.exs @@ -6,12 +6,14 @@ defmodule Pleroma.NotificationTest do    use Pleroma.DataCase    import Pleroma.Factory +  import Mock    alias Pleroma.Notification    alias Pleroma.Tests.ObanHelpers    alias Pleroma.User    alias Pleroma.Web.ActivityPub.Transmogrifier    alias Pleroma.Web.CommonAPI +  alias Pleroma.Web.Push    alias Pleroma.Web.Streamer    describe "create_notifications" do @@ -80,6 +82,80 @@ defmodule Pleroma.NotificationTest do      end    end +  describe "CommonApi.post/2 notification-related functionality" do +    test_with_mock "creates but does NOT send notification to blocker user", +                   Push, +                   [:passthrough], +                   [] do +      user = insert(:user) +      blocker = insert(:user) +      {:ok, _user_relationship} = User.block(blocker, user) + +      {:ok, _activity} = CommonAPI.post(user, %{"status" => "hey @#{blocker.nickname}!"}) + +      blocker_id = blocker.id +      assert [%Notification{user_id: ^blocker_id}] = Repo.all(Notification) +      refute called(Push.send(:_)) +    end + +    test_with_mock "creates but does NOT send notification to notification-muter user", +                   Push, +                   [:passthrough], +                   [] do +      user = insert(:user) +      muter = insert(:user) +      {:ok, _user_relationships} = User.mute(muter, user) + +      {:ok, _activity} = CommonAPI.post(user, %{"status" => "hey @#{muter.nickname}!"}) + +      muter_id = muter.id +      assert [%Notification{user_id: ^muter_id}] = Repo.all(Notification) +      refute called(Push.send(:_)) +    end + +    test_with_mock "creates but does NOT send notification to thread-muter user", +                   Push, +                   [:passthrough], +                   [] do +      user = insert(:user) +      thread_muter = insert(:user) + +      {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{thread_muter.nickname}!"}) + +      {:ok, _} = CommonAPI.add_mute(thread_muter, activity) + +      {:ok, _same_context_activity} = +        CommonAPI.post(user, %{ +          "status" => "hey-hey-hey @#{thread_muter.nickname}!", +          "in_reply_to_status_id" => activity.id +        }) + +      [pre_mute_notification, post_mute_notification] = +        Repo.all(from(n in Notification, where: n.user_id == ^thread_muter.id, order_by: n.id)) + +      pre_mute_notification_id = pre_mute_notification.id +      post_mute_notification_id = post_mute_notification.id + +      assert called( +               Push.send( +                 :meck.is(fn +                   %Notification{id: ^pre_mute_notification_id} -> true +                   _ -> false +                 end) +               ) +             ) + +      refute called( +               Push.send( +                 :meck.is(fn +                   %Notification{id: ^post_mute_notification_id} -> true +                   _ -> false +                 end) +               ) +             ) +    end +  end +    describe "create_notification" do      @tag needs_streamer: true      test "it creates a notification for user and send to the 'user' and the 'user:notification' stream" do @@ -382,7 +458,7 @@ defmodule Pleroma.NotificationTest do      end    end -  describe "notification target determination" do +  describe "notification target determination / get_notified_from_activity/2" do      test "it sends notifications to addressed users in new messages" do        user = insert(:user)        other_user = insert(:user) @@ -392,7 +468,9 @@ defmodule Pleroma.NotificationTest do            "status" => "hey @#{other_user.nickname}!"          }) -      assert other_user in Notification.get_notified_from_activity(activity) +      {enabled_receivers, _disabled_receivers} = Notification.get_notified_from_activity(activity) + +      assert other_user in enabled_receivers      end      test "it sends notifications to mentioned users in new messages" do @@ -420,7 +498,9 @@ defmodule Pleroma.NotificationTest do        {:ok, activity} = Transmogrifier.handle_incoming(create_activity) -      assert other_user in Notification.get_notified_from_activity(activity) +      {enabled_receivers, _disabled_receivers} = Notification.get_notified_from_activity(activity) + +      assert other_user in enabled_receivers      end      test "it does not send notifications to users who are only cc in new messages" do @@ -442,7 +522,9 @@ defmodule Pleroma.NotificationTest do        {:ok, activity} = Transmogrifier.handle_incoming(create_activity) -      assert other_user not in Notification.get_notified_from_activity(activity) +      {enabled_receivers, _disabled_receivers} = Notification.get_notified_from_activity(activity) + +      assert other_user not in enabled_receivers      end      test "it does not send notification to mentioned users in likes" do @@ -457,7 +539,10 @@ defmodule Pleroma.NotificationTest do        {:ok, activity_two, _} = CommonAPI.favorite(activity_one.id, third_user) -      assert other_user not in Notification.get_notified_from_activity(activity_two) +      {enabled_receivers, _disabled_receivers} = +        Notification.get_notified_from_activity(activity_two) + +      assert other_user not in enabled_receivers      end      test "it does not send notification to mentioned users in announces" do @@ -472,7 +557,57 @@ defmodule Pleroma.NotificationTest do        {:ok, activity_two, _} = CommonAPI.repeat(activity_one.id, third_user) -      assert other_user not in Notification.get_notified_from_activity(activity_two) +      {enabled_receivers, _disabled_receivers} = +        Notification.get_notified_from_activity(activity_two) + +      assert other_user not in enabled_receivers +    end + +    test "it returns blocking recipient in disabled recipients list" do +      user = insert(:user) +      other_user = insert(:user) +      {:ok, _user_relationship} = User.block(other_user, user) + +      {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"}) + +      {enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity) + +      assert [] == enabled_receivers +      assert [other_user] == disabled_receivers +    end + +    test "it returns notification-muting recipient in disabled recipients list" do +      user = insert(:user) +      other_user = insert(:user) +      {:ok, _user_relationships} = User.mute(other_user, user) + +      {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"}) + +      {enabled_receivers, disabled_receivers} = Notification.get_notified_from_activity(activity) + +      assert [] == enabled_receivers +      assert [other_user] == disabled_receivers +    end + +    test "it returns thread-muting recipient in disabled recipients list" do +      user = insert(:user) +      other_user = insert(:user) + +      {:ok, activity} = CommonAPI.post(user, %{"status" => "hey @#{other_user.nickname}!"}) + +      {:ok, _} = CommonAPI.add_mute(other_user, activity) + +      {:ok, same_context_activity} = +        CommonAPI.post(user, %{ +          "status" => "hey-hey-hey @#{other_user.nickname}!", +          "in_reply_to_status_id" => activity.id +        }) + +      {enabled_receivers, disabled_receivers} = +        Notification.get_notified_from_activity(same_context_activity) + +      assert [other_user] == disabled_receivers +      refute other_user in enabled_receivers      end    end @@ -667,17 +802,13 @@ defmodule Pleroma.NotificationTest do        Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)        ObanHelpers.perform_all() -      assert [] = Notification.for_user(follower) -        assert [                 %{                   activity: %{                     data: %{"type" => "Move", "actor" => ^old_ap_id, "target" => ^new_ap_id}                   }                 } -             ] = Notification.for_user(follower, %{with_move: true}) - -      assert [] = Notification.for_user(other_follower) +             ] = Notification.for_user(follower)        assert [                 %{ @@ -685,7 +816,7 @@ defmodule Pleroma.NotificationTest do                     data: %{"type" => "Move", "actor" => ^old_ap_id, "target" => ^new_ap_id}                   }                 } -             ] = Notification.for_user(other_follower, %{with_move: true}) +             ] = Notification.for_user(other_follower)      end    end @@ -720,7 +851,7 @@ defmodule Pleroma.NotificationTest do        assert Notification.for_user(user) == []      end -    test "it doesn't return notificatitons for blocked domain" do +    test "it doesn't return notifications for blocked domain" do        user = insert(:user)        blocked = insert(:user, ap_id: "http://some-domain.com")        {:ok, user} = User.block_domain(user, "some-domain.com") diff --git a/test/object/fetcher_test.exs b/test/object/fetcher_test.exs index 4775ee152..c06e91f12 100644 --- a/test/object/fetcher_test.exs +++ b/test/object/fetcher_test.exs @@ -28,8 +28,7 @@ defmodule Pleroma.Object.FetcherTest do    describe "max thread distance restriction" do      @ap_id "http://mastodon.example.org/@admin/99541947525187367" - -    clear_config([:instance, :federation_incoming_replies_max_depth]) +    setup do: clear_config([:instance, :federation_incoming_replies_max_depth])      test "it returns thread depth exceeded error if thread depth is exceeded" do        Pleroma.Config.put([:instance, :federation_incoming_replies_max_depth], 0) @@ -160,7 +159,7 @@ defmodule Pleroma.Object.FetcherTest do    end    describe "signed fetches" do -    clear_config([:activitypub, :sign_object_fetches]) +    setup do: clear_config([:activitypub, :sign_object_fetches])      test_with_mock "it signs fetches when configured to do so",                     Pleroma.Signature, diff --git a/test/object_test.exs b/test/object_test.exs index 85b2a3f6d..fe583decd 100644 --- a/test/object_test.exs +++ b/test/object_test.exs @@ -74,8 +74,8 @@ defmodule Pleroma.ObjectTest do    end    describe "delete attachments" do -    clear_config([Pleroma.Upload]) -    clear_config([:instance, :cleanup_attachments]) +    setup do: clear_config([Pleroma.Upload]) +    setup do: clear_config([:instance, :cleanup_attachments])      test "Disabled via config" do        Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) diff --git a/test/plugs/admin_secret_authentication_plug_test.exs b/test/plugs/admin_secret_authentication_plug_test.exs index 2e300ac0c..100016c62 100644 --- a/test/plugs/admin_secret_authentication_plug_test.exs +++ b/test/plugs/admin_secret_authentication_plug_test.exs @@ -23,7 +23,7 @@ defmodule Pleroma.Plugs.AdminSecretAuthenticationPlugTest do    end    describe "when secret set it assigns an admin user" do -    clear_config([:admin_token]) +    setup do: clear_config([:admin_token])      test "with `admin_token` query parameter", %{conn: conn} do        Pleroma.Config.put(:admin_token, "password123") diff --git a/test/plugs/cache_control_test.exs b/test/plugs/cache_control_test.exs index 005912ffb..6b567e81d 100644 --- a/test/plugs/cache_control_test.exs +++ b/test/plugs/cache_control_test.exs @@ -9,7 +9,7 @@ defmodule Pleroma.Web.CacheControlTest do    test "Verify Cache-Control header on static assets", %{conn: conn} do      conn = get(conn, "/index.html") -    assert Conn.get_resp_header(conn, "cache-control") == ["public max-age=86400 must-revalidate"] +    assert Conn.get_resp_header(conn, "cache-control") == ["public, no-cache"]    end    test "Verify Cache-Control header on the API", %{conn: conn} do diff --git a/test/plugs/ensure_authenticated_plug_test.exs b/test/plugs/ensure_authenticated_plug_test.exs index 18be5edd0..7f3559b83 100644 --- a/test/plugs/ensure_authenticated_plug_test.exs +++ b/test/plugs/ensure_authenticated_plug_test.exs @@ -8,24 +8,62 @@ defmodule Pleroma.Plugs.EnsureAuthenticatedPlugTest do    alias Pleroma.Plugs.EnsureAuthenticatedPlug    alias Pleroma.User -  test "it halts if no user is assigned", %{conn: conn} do -    conn = -      conn -      |> EnsureAuthenticatedPlug.call(%{}) +  describe "without :if_func / :unless_func options" do +    test "it halts if user is NOT assigned", %{conn: conn} do +      conn = EnsureAuthenticatedPlug.call(conn, %{}) -    assert conn.status == 403 -    assert conn.halted == true +      assert conn.status == 403 +      assert conn.halted == true +    end + +    test "it continues if a user is assigned", %{conn: conn} do +      conn = assign(conn, :user, %User{}) +      ret_conn = EnsureAuthenticatedPlug.call(conn, %{}) + +      assert ret_conn == conn +    end    end -  test "it continues if a user is assigned", %{conn: conn} do -    conn = -      conn -      |> assign(:user, %User{}) +  describe "with :if_func / :unless_func options" do +    setup do +      %{ +        true_fn: fn -> true end, +        false_fn: fn -> false end +      } +    end + +    test "it continues if a user is assigned", %{conn: conn, true_fn: true_fn, false_fn: false_fn} do +      conn = assign(conn, :user, %User{}) +      assert EnsureAuthenticatedPlug.call(conn, if_func: true_fn) == conn +      assert EnsureAuthenticatedPlug.call(conn, if_func: false_fn) == conn +      assert EnsureAuthenticatedPlug.call(conn, unless_func: true_fn) == conn +      assert EnsureAuthenticatedPlug.call(conn, unless_func: false_fn) == conn +    end + +    test "it continues if a user is NOT assigned but :if_func evaluates to `false`", +         %{conn: conn, false_fn: false_fn} do +      assert EnsureAuthenticatedPlug.call(conn, if_func: false_fn) == conn +    end + +    test "it continues if a user is NOT assigned but :unless_func evaluates to `true`", +         %{conn: conn, true_fn: true_fn} do +      assert EnsureAuthenticatedPlug.call(conn, unless_func: true_fn) == conn +    end + +    test "it halts if a user is NOT assigned and :if_func evaluates to `true`", +         %{conn: conn, true_fn: true_fn} do +      conn = EnsureAuthenticatedPlug.call(conn, if_func: true_fn) + +      assert conn.status == 403 +      assert conn.halted == true +    end -    ret_conn = -      conn -      |> EnsureAuthenticatedPlug.call(%{}) +    test "it halts if a user is NOT assigned and :unless_func evaluates to `false`", +         %{conn: conn, false_fn: false_fn} do +      conn = EnsureAuthenticatedPlug.call(conn, unless_func: false_fn) -    assert ret_conn == conn +      assert conn.status == 403 +      assert conn.halted == true +    end    end  end diff --git a/test/plugs/ensure_public_or_authenticated_plug_test.exs b/test/plugs/ensure_public_or_authenticated_plug_test.exs index 3fcb4d372..411252274 100644 --- a/test/plugs/ensure_public_or_authenticated_plug_test.exs +++ b/test/plugs/ensure_public_or_authenticated_plug_test.exs @@ -9,7 +9,7 @@ defmodule Pleroma.Plugs.EnsurePublicOrAuthenticatedPlugTest do    alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug    alias Pleroma.User -  clear_config([:instance, :public]) +  setup do: clear_config([:instance, :public])    test "it halts if not public and no user is assigned", %{conn: conn} do      Config.put([:instance, :public], false) diff --git a/test/plugs/http_security_plug_test.exs b/test/plugs/http_security_plug_test.exs index 944a9a139..84e4c274f 100644 --- a/test/plugs/http_security_plug_test.exs +++ b/test/plugs/http_security_plug_test.exs @@ -7,9 +7,9 @@ defmodule Pleroma.Web.Plugs.HTTPSecurityPlugTest do    alias Pleroma.Config    alias Plug.Conn -  clear_config([:http_securiy, :enabled]) -  clear_config([:http_security, :sts]) -  clear_config([:http_security, :referrer_policy]) +  setup do: clear_config([:http_securiy, :enabled]) +  setup do: clear_config([:http_security, :sts]) +  setup do: clear_config([:http_security, :referrer_policy])    describe "http security enabled" do      setup do diff --git a/test/plugs/instance_static_test.exs b/test/plugs/instance_static_test.exs index 8cd9b5712..b8f070d6a 100644 --- a/test/plugs/instance_static_test.exs +++ b/test/plugs/instance_static_test.exs @@ -12,9 +12,7 @@ defmodule Pleroma.Web.RuntimeStaticPlugTest do      on_exit(fn -> File.rm_rf(@dir) end)    end -  clear_config([:instance, :static_dir]) do -    Pleroma.Config.put([:instance, :static_dir], @dir) -  end +  setup do: clear_config([:instance, :static_dir], @dir)    test "overrides index" do      bundled_index = get(build_conn(), "/") diff --git a/test/plugs/oauth_plug_test.exs b/test/plugs/oauth_plug_test.exs index 8534a5c13..f74c068cd 100644 --- a/test/plugs/oauth_plug_test.exs +++ b/test/plugs/oauth_plug_test.exs @@ -38,7 +38,7 @@ defmodule Pleroma.Plugs.OAuthPlugTest do      assert conn.assigns[:user] == opts[:user]    end -  test "with valid token(downcase) in url parameters, it assings the user", opts do +  test "with valid token(downcase) in url parameters, it assigns the user", opts do      conn =        :get        |> build_conn("/?access_token=#{opts[:token]}") diff --git a/test/plugs/oauth_scopes_plug_test.exs b/test/plugs/oauth_scopes_plug_test.exs index 1b3aa85b6..e79ecf263 100644 --- a/test/plugs/oauth_scopes_plug_test.exs +++ b/test/plugs/oauth_scopes_plug_test.exs @@ -193,7 +193,7 @@ defmodule Pleroma.Plugs.OAuthScopesPlugTest do    end    describe "transform_scopes/2" do -    clear_config([:auth, :enforce_oauth_admin_scope_usage]) +    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage])      setup do        {:ok, %{f: &OAuthScopesPlug.transform_scopes/2}} diff --git a/test/plugs/rate_limiter_test.exs b/test/plugs/rate_limiter_test.exs index 8023271e4..0ce9f3a0a 100644 --- a/test/plugs/rate_limiter_test.exs +++ b/test/plugs/rate_limiter_test.exs @@ -3,8 +3,7 @@  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Plugs.RateLimiterTest do -  use ExUnit.Case, async: true -  use Plug.Test +  use Pleroma.Web.ConnCase    alias Pleroma.Config    alias Pleroma.Plugs.RateLimiter @@ -13,14 +12,12 @@ defmodule Pleroma.Plugs.RateLimiterTest do    import Pleroma.Tests.Helpers, only: [clear_config: 1, clear_config: 2]    # Note: each example must work with separate buckets in order to prevent concurrency issues - -  clear_config([Pleroma.Web.Endpoint, :http, :ip]) -  clear_config(:rate_limit) +  setup do: clear_config([Pleroma.Web.Endpoint, :http, :ip]) +  setup do: clear_config(:rate_limit)    describe "config" do      @limiter_name :test_init - -    clear_config([Pleroma.Plugs.RemoteIp, :enabled]) +    setup do: clear_config([Pleroma.Plugs.RemoteIp, :enabled])      test "config is required for plug to work" do        Config.put([:rate_limit, @limiter_name], {1, 1}) @@ -36,63 +33,44 @@ defmodule Pleroma.Plugs.RateLimiterTest do                 |> RateLimiter.init()                 |> RateLimiter.action_settings()      end +  end -    test "it is disabled for localhost" do -      Config.put([:rate_limit, @limiter_name], {1, 1}) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {127, 0, 0, 1}) -      Config.put([Pleroma.Plugs.RemoteIp, :enabled], false) - -      assert RateLimiter.disabled?() == true -    end +  test "it is disabled if it remote ip plug is enabled but no remote ip is found" do +    Config.put([Pleroma.Web.Endpoint, :http, :ip], {127, 0, 0, 1}) +    assert RateLimiter.disabled?(Plug.Conn.assign(build_conn(), :remote_ip_found, false)) +  end -    test "it is disabled for socket" do -      Config.put([:rate_limit, @limiter_name], {1, 1}) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {:local, "/path/to/pleroma.sock"}) -      Config.put([Pleroma.Plugs.RemoteIp, :enabled], false) +  test "it restricts based on config values" do +    limiter_name = :test_plug_opts +    scale = 80 +    limit = 5 -      assert RateLimiter.disabled?() == true -    end +    Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +    Config.put([:rate_limit, limiter_name], {scale, limit}) -    test "it is enabled for socket when remote ip is enabled" do -      Config.put([:rate_limit, @limiter_name], {1, 1}) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {:local, "/path/to/pleroma.sock"}) -      Config.put([Pleroma.Plugs.RemoteIp, :enabled], true) +    plug_opts = RateLimiter.init(name: limiter_name) +    conn = build_conn(:get, "/") -      assert RateLimiter.disabled?() == false +    for i <- 1..5 do +      conn = RateLimiter.call(conn, plug_opts) +      assert {^i, _} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts) +      Process.sleep(10)      end -    test "it restricts based on config values" do -      limiter_name = :test_plug_opts -      scale = 80 -      limit = 5 - -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) -      Config.put([:rate_limit, limiter_name], {scale, limit}) - -      plug_opts = RateLimiter.init(name: limiter_name) -      conn = conn(:get, "/") - -      for i <- 1..5 do -        conn = RateLimiter.call(conn, plug_opts) -        assert {^i, _} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts) -        Process.sleep(10) -      end - -      conn = RateLimiter.call(conn, plug_opts) -      assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests) -      assert conn.halted +    conn = RateLimiter.call(conn, plug_opts) +    assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests) +    assert conn.halted -      Process.sleep(50) +    Process.sleep(50) -      conn = conn(:get, "/") +    conn = build_conn(:get, "/") -      conn = RateLimiter.call(conn, plug_opts) -      assert {1, 4} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts) +    conn = RateLimiter.call(conn, plug_opts) +    assert {1, 4} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts) -      refute conn.status == Plug.Conn.Status.code(:too_many_requests) -      refute conn.resp_body -      refute conn.halted -    end +    refute conn.status == Plug.Conn.Status.code(:too_many_requests) +    refute conn.resp_body +    refute conn.halted    end    describe "options" do @@ -105,7 +83,7 @@ defmodule Pleroma.Plugs.RateLimiterTest do        base_bucket_name = "#{limiter_name}:group1"        plug_opts = RateLimiter.init(name: limiter_name, bucket_name: base_bucket_name) -      conn = conn(:get, "/") +      conn = build_conn(:get, "/")        RateLimiter.call(conn, plug_opts)        assert {1, 4} = RateLimiter.inspect_bucket(conn, base_bucket_name, plug_opts) @@ -119,9 +97,9 @@ defmodule Pleroma.Plugs.RateLimiterTest do        plug_opts = RateLimiter.init(name: limiter_name, params: ["id"]) -      conn = conn(:get, "/?id=1") +      conn = build_conn(:get, "/?id=1")        conn = Plug.Conn.fetch_query_params(conn) -      conn_2 = conn(:get, "/?id=2") +      conn_2 = build_conn(:get, "/?id=2")        RateLimiter.call(conn, plug_opts)        assert {1, 4} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts) @@ -140,9 +118,9 @@ defmodule Pleroma.Plugs.RateLimiterTest do        id = "100" -      conn = conn(:get, "/?id=#{id}") +      conn = build_conn(:get, "/?id=#{id}")        conn = Plug.Conn.fetch_query_params(conn) -      conn_2 = conn(:get, "/?id=#{101}") +      conn_2 = build_conn(:get, "/?id=#{101}")        RateLimiter.call(conn, plug_opts)        assert {1, 4} = RateLimiter.inspect_bucket(conn, base_bucket_name, plug_opts) @@ -158,8 +136,8 @@ defmodule Pleroma.Plugs.RateLimiterTest do        plug_opts = RateLimiter.init(name: limiter_name) -      conn = %{conn(:get, "/") | remote_ip: {127, 0, 0, 2}} -      conn_2 = %{conn(:get, "/") | remote_ip: {127, 0, 0, 3}} +      conn = %{build_conn(:get, "/") | remote_ip: {127, 0, 0, 2}} +      conn_2 = %{build_conn(:get, "/") | remote_ip: {127, 0, 0, 3}}        for i <- 1..5 do          conn = RateLimiter.call(conn, plug_opts) @@ -199,7 +177,7 @@ defmodule Pleroma.Plugs.RateLimiterTest do        plug_opts = RateLimiter.init(name: limiter_name)        user = insert(:user) -      conn = conn(:get, "/") |> assign(:user, user) +      conn = build_conn(:get, "/") |> assign(:user, user)        for i <- 1..5 do          conn = RateLimiter.call(conn, plug_opts) @@ -221,10 +199,10 @@ defmodule Pleroma.Plugs.RateLimiterTest do        plug_opts = RateLimiter.init(name: limiter_name)        user = insert(:user) -      conn = conn(:get, "/") |> assign(:user, user) +      conn = build_conn(:get, "/") |> assign(:user, user)        user_2 = insert(:user) -      conn_2 = conn(:get, "/") |> assign(:user, user_2) +      conn_2 = build_conn(:get, "/") |> assign(:user, user_2)        for i <- 1..5 do          conn = RateLimiter.call(conn, plug_opts) @@ -250,8 +228,8 @@ defmodule Pleroma.Plugs.RateLimiterTest do      opts = RateLimiter.init(name: limiter_name) -    conn = conn(:get, "/") -    conn_2 = conn(:get, "/") +    conn = build_conn(:get, "/") +    conn_2 = build_conn(:get, "/")      %Task{pid: pid1} =        task1 = diff --git a/test/plugs/remote_ip_test.exs b/test/plugs/remote_ip_test.exs index 9c3737b0b..752ab32e7 100644 --- a/test/plugs/remote_ip_test.exs +++ b/test/plugs/remote_ip_test.exs @@ -9,8 +9,7 @@ defmodule Pleroma.Plugs.RemoteIpTest do    alias Pleroma.Plugs.RemoteIp    import Pleroma.Tests.Helpers, only: [clear_config: 1, clear_config: 2] - -  clear_config(RemoteIp) +  setup do: clear_config(RemoteIp)    test "disabled" do      Pleroma.Config.put(RemoteIp, enabled: false) diff --git a/test/plugs/user_enabled_plug_test.exs b/test/plugs/user_enabled_plug_test.exs index 931513d83..b219d8abf 100644 --- a/test/plugs/user_enabled_plug_test.exs +++ b/test/plugs/user_enabled_plug_test.exs @@ -8,7 +8,7 @@ defmodule Pleroma.Plugs.UserEnabledPlugTest do    alias Pleroma.Plugs.UserEnabledPlug    import Pleroma.Factory -  clear_config([:instance, :account_activation_required]) +  setup do: clear_config([:instance, :account_activation_required])    test "doesn't do anything if the user isn't set", %{conn: conn} do      ret_conn = diff --git a/test/plugs/user_is_admin_plug_test.exs b/test/plugs/user_is_admin_plug_test.exs index 015d51018..fd6a50e53 100644 --- a/test/plugs/user_is_admin_plug_test.exs +++ b/test/plugs/user_is_admin_plug_test.exs @@ -9,9 +9,7 @@ defmodule Pleroma.Plugs.UserIsAdminPlugTest do    import Pleroma.Factory    describe "unless [:auth, :enforce_oauth_admin_scope_usage]," do -    clear_config([:auth, :enforce_oauth_admin_scope_usage]) do -      Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], false) -    end +    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)      test "accepts a user that is an admin" do        user = insert(:user, is_admin: true) @@ -42,9 +40,7 @@ defmodule Pleroma.Plugs.UserIsAdminPlugTest do    end    describe "with [:auth, :enforce_oauth_admin_scope_usage]," do -    clear_config([:auth, :enforce_oauth_admin_scope_usage]) do -      Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], true) -    end +    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], true)      setup do        admin_user = insert(:user, is_admin: true) diff --git a/test/repo_test.exs b/test/repo_test.exs index 75e85f974..daffc6542 100644 --- a/test/repo_test.exs +++ b/test/repo_test.exs @@ -67,7 +67,7 @@ defmodule Pleroma.RepoTest do        :ok      end -    clear_config([:i_am_aware_this_may_cause_data_loss, :disable_migration_check]) +    setup do: clear_config([:i_am_aware_this_may_cause_data_loss, :disable_migration_check])      test "raises if it detects unapplied migrations" do        assert_raise Pleroma.Repo.UnappliedMigrationsError, fn -> diff --git a/test/reverse_proxy_test.exs b/test/reverse_proxy_test.exs index 18d70862c..87c6aca4e 100644 --- a/test/reverse_proxy_test.exs +++ b/test/reverse_proxy_test.exs @@ -275,17 +275,6 @@ defmodule Pleroma.ReverseProxyTest do    end    describe "cache resp headers" do -    test "returns headers", %{conn: conn} do -      ClientMock -      |> expect(:request, fn :get, "/cache/" <> ttl, _, _, _ -> -        {:ok, 200, [{"cache-control", "public, max-age=" <> ttl}], %{}} -      end) -      |> expect(:stream_body, fn _ -> :done end) - -      conn = ReverseProxy.call(conn, "/cache/10") -      assert {"cache-control", "public, max-age=10"} in conn.resp_headers -    end -      test "add cache-control", %{conn: conn} do        ClientMock        |> expect(:request, fn :get, "/cache", _, _, _ -> @@ -294,7 +283,7 @@ defmodule Pleroma.ReverseProxyTest do        |> expect(:stream_body, fn _ -> :done end)        conn = ReverseProxy.call(conn, "/cache") -      assert {"cache-control", "public"} in conn.resp_headers +      assert {"cache-control", "public, max-age=1209600"} in conn.resp_headers      end    end diff --git a/test/scheduled_activity_test.exs b/test/scheduled_activity_test.exs index 4369e7e8a..7faa5660d 100644 --- a/test/scheduled_activity_test.exs +++ b/test/scheduled_activity_test.exs @@ -8,7 +8,7 @@ defmodule Pleroma.ScheduledActivityTest do    alias Pleroma.ScheduledActivity    import Pleroma.Factory -  clear_config([ScheduledActivity, :enabled]) +  setup do: clear_config([ScheduledActivity, :enabled])    setup context do      DataCase.ensure_local_uploader(context) diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index 0f2e81f9e..064874201 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -26,6 +26,8 @@ defmodule Pleroma.Web.ConnCase do        use Pleroma.Tests.Helpers        import Pleroma.Web.Router.Helpers +      alias Pleroma.Config +        # The default endpoint for testing        @endpoint Pleroma.Web.Endpoint @@ -48,6 +50,28 @@ defmodule Pleroma.Web.ConnCase do          %{user: user, token: token, conn: conn}        end + +      defp ensure_federating_or_authenticated(conn, url, user) do +        initial_setting = Config.get([:instance, :federating]) +        on_exit(fn -> Config.put([:instance, :federating], initial_setting) end) + +        Config.put([:instance, :federating], false) + +        conn +        |> get(url) +        |> response(403) + +        conn +        |> assign(:user, user) +        |> get(url) +        |> response(200) + +        Config.put([:instance, :federating], true) + +        conn +        |> get(url) +        |> response(200) +      end      end    end diff --git a/test/support/helpers.ex b/test/support/helpers.ex index 6bf4b019e..e68e9bfd2 100644 --- a/test/support/helpers.ex +++ b/test/support/helpers.ex @@ -17,35 +17,17 @@ defmodule Pleroma.Tests.Helpers do    defmacro clear_config(config_path, do: yield) do      quote do -      setup do -        initial_setting = Config.get(unquote(config_path)) -        unquote(yield) -        on_exit(fn -> Config.put(unquote(config_path), initial_setting) end) -        :ok -      end -    end -  end - -  @doc "Stores initial config value and restores it after *all* test examples are executed." -  defmacro clear_config_all(config_path) do -    quote do -      clear_config_all(unquote(config_path)) do -      end +      initial_setting = Config.get(unquote(config_path)) +      unquote(yield) +      on_exit(fn -> Config.put(unquote(config_path), initial_setting) end) +      :ok      end    end -  @doc """ -  Stores initial config value and restores it after *all* test examples are executed. -  Only use if *all* test examples should work with the same stubbed value -  (*no* examples set a different value). -  """ -  defmacro clear_config_all(config_path, do: yield) do +  defmacro clear_config(config_path, temp_setting) do      quote do -      setup_all do -        initial_setting = Config.get(unquote(config_path)) -        unquote(yield) -        on_exit(fn -> Config.put(unquote(config_path), initial_setting) end) -        :ok +      clear_config(unquote(config_path)) do +        Config.put(unquote(config_path), unquote(temp_setting))        end      end    end @@ -55,9 +37,7 @@ defmodule Pleroma.Tests.Helpers do        import Pleroma.Tests.Helpers,          only: [            clear_config: 1, -          clear_config: 2, -          clear_config_all: 1, -          clear_config_all: 2 +          clear_config: 2          ]        def to_datetime(naive_datetime) do diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex index 0079d8c44..79ab129fd 100644 --- a/test/support/http_request_mock.ex +++ b/test/support/http_request_mock.ex @@ -1292,6 +1292,10 @@ defmodule HttpRequestMock do      {:ok, %Tesla.Env{status: 404, body: ""}}    end +  def get("https://relay.mastodon.host/actor", _, _, _) do +    {:ok, %Tesla.Env{status: 200, body: File.read!("test/fixtures/relay/relay.json")}} +  end +    def get(url, query, body, headers) do      {:error,       "Mock response not implemented for GET #{inspect(url)}, #{query}, #{inspect(body)}, #{ @@ -1304,6 +1308,10 @@ defmodule HttpRequestMock do    def post(url, query \\ [], body \\ [], headers \\ []) +  def post("https://relay.mastodon.host/inbox", _, _, _) do +    {:ok, %Tesla.Env{status: 200, body: ""}} +  end +    def post("http://example.org/needs_refresh", _, _, _) do      {:ok,       %Tesla.Env{ diff --git a/test/tasks/config_test.exs b/test/tasks/config_test.exs index a6c0de351..3dee4f082 100644 --- a/test/tasks/config_test.exs +++ b/test/tasks/config_test.exs @@ -20,9 +20,7 @@ defmodule Mix.Tasks.Pleroma.ConfigTest do      :ok    end -  clear_config_all(:configurable_from_database) do -    Pleroma.Config.put(:configurable_from_database, true) -  end +  setup_all do: clear_config(:configurable_from_database, true)    test "error if file with custom settings doesn't exist" do      Mix.Tasks.Pleroma.Config.migrate_to_db("config/not_existance_config_file.exs") diff --git a/test/tasks/relay_test.exs b/test/tasks/relay_test.exs index 08855f245..d3d88467d 100644 --- a/test/tasks/relay_test.exs +++ b/test/tasks/relay_test.exs @@ -38,6 +38,9 @@ defmodule Mix.Tasks.Pleroma.RelayTest do        assert activity.data["type"] == "Follow"        assert activity.data["actor"] == local_user.ap_id        assert activity.data["object"] == target_user.ap_id + +      :ok = Mix.Tasks.Pleroma.Relay.run(["list"]) +      assert_receive {:mix_shell, :info, ["mastodon.example.org (no Accept received)"]}      end    end diff --git a/test/tasks/robots_txt_test.exs b/test/tasks/robots_txt_test.exs index e03c9c192..7040a0e4e 100644 --- a/test/tasks/robots_txt_test.exs +++ b/test/tasks/robots_txt_test.exs @@ -7,7 +7,7 @@ defmodule Mix.Tasks.Pleroma.RobotsTxtTest do    use Pleroma.Tests.Helpers    alias Mix.Tasks.Pleroma.RobotsTxt -  clear_config([:instance, :static_dir]) +  setup do: clear_config([:instance, :static_dir])    test "creates new dir" do      path = "test/fixtures/new_dir/" diff --git a/test/upload/filter/anonymize_filename_test.exs b/test/upload/filter/anonymize_filename_test.exs index 330158580..2d5c580f1 100644 --- a/test/upload/filter/anonymize_filename_test.exs +++ b/test/upload/filter/anonymize_filename_test.exs @@ -18,7 +18,7 @@ defmodule Pleroma.Upload.Filter.AnonymizeFilenameTest do      %{upload_file: upload_file}    end -  clear_config([Pleroma.Upload.Filter.AnonymizeFilename, :text]) +  setup do: clear_config([Pleroma.Upload.Filter.AnonymizeFilename, :text])    test "it replaces filename on pre-defined text", %{upload_file: upload_file} do      Config.put([Upload.Filter.AnonymizeFilename, :text], "custom-file.png") diff --git a/test/upload/filter/mogrify_test.exs b/test/upload/filter/mogrify_test.exs index 52483d80c..b6a463e8c 100644 --- a/test/upload/filter/mogrify_test.exs +++ b/test/upload/filter/mogrify_test.exs @@ -10,7 +10,7 @@ defmodule Pleroma.Upload.Filter.MogrifyTest do    alias Pleroma.Upload    alias Pleroma.Upload.Filter -  clear_config([Filter.Mogrify, :args]) +  setup do: clear_config([Filter.Mogrify, :args])    test "apply mogrify filter" do      Config.put([Filter.Mogrify, :args], [{"tint", "40"}]) diff --git a/test/upload/filter_test.exs b/test/upload/filter_test.exs index 2ffc5247b..352b66402 100644 --- a/test/upload/filter_test.exs +++ b/test/upload/filter_test.exs @@ -8,7 +8,7 @@ defmodule Pleroma.Upload.FilterTest do    alias Pleroma.Config    alias Pleroma.Upload.Filter -  clear_config([Pleroma.Upload.Filter.AnonymizeFilename, :text]) +  setup do: clear_config([Pleroma.Upload.Filter.AnonymizeFilename, :text])    test "applies filters" do      Config.put([Pleroma.Upload.Filter.AnonymizeFilename, :text], "custom-file.png") diff --git a/test/upload_test.exs b/test/upload_test.exs index 6ce42b630..060a940bb 100644 --- a/test/upload_test.exs +++ b/test/upload_test.exs @@ -250,9 +250,7 @@ defmodule Pleroma.UploadTest do    end    describe "Setting a custom base_url for uploaded media" do -    clear_config([Pleroma.Upload, :base_url]) do -      Pleroma.Config.put([Pleroma.Upload, :base_url], "https://cache.pleroma.social") -    end +    setup do: clear_config([Pleroma.Upload, :base_url], "https://cache.pleroma.social")      test "returns a media url with configured base_url" do        base_url = Pleroma.Config.get([Pleroma.Upload, :base_url]) diff --git a/test/uploaders/s3_test.exs b/test/uploaders/s3_test.exs index fdc7eff41..6950ccb25 100644 --- a/test/uploaders/s3_test.exs +++ b/test/uploaders/s3_test.exs @@ -11,12 +11,11 @@ defmodule Pleroma.Uploaders.S3Test do    import Mock    import ExUnit.CaptureLog -  clear_config([Pleroma.Uploaders.S3]) do -    Config.put([Pleroma.Uploaders.S3], -      bucket: "test_bucket", -      public_endpoint: "https://s3.amazonaws.com" -    ) -  end +  setup do: +          clear_config(Pleroma.Uploaders.S3, +            bucket: "test_bucket", +            public_endpoint: "https://s3.amazonaws.com" +          )    describe "get_file/1" do      test "it returns path to local folder for files" do diff --git a/test/user_search_test.exs b/test/user_search_test.exs index 406cc8fb2..cb847b516 100644 --- a/test/user_search_test.exs +++ b/test/user_search_test.exs @@ -15,7 +15,7 @@ defmodule Pleroma.UserSearchTest do    end    describe "User.search" do -    clear_config([:instance, :limit_to_local_content]) +    setup do: clear_config([:instance, :limit_to_local_content])      test "excluded invisible users from results" do        user = insert(:user, %{nickname: "john t1000"}) diff --git a/test/user_test.exs b/test/user_test.exs index 84d7f5727..8055ebd08 100644 --- a/test/user_test.exs +++ b/test/user_test.exs @@ -24,7 +24,7 @@ defmodule Pleroma.UserTest do      :ok    end -  clear_config([:instance, :account_activation_required]) +  setup do: clear_config([:instance, :account_activation_required])    describe "service actors" do      test "returns updated invisible actor" do @@ -86,7 +86,7 @@ defmodule Pleroma.UserTest do        {:ok, user: insert(:user)}      end -    test "outgoing_relations_ap_ids/1", %{user: user} do +    test "outgoing_relationships_ap_ids/1", %{user: user} do        rel_types = [:block, :mute, :notification_mute, :reblog_mute, :inverse_subscription]        ap_ids_by_rel = @@ -124,10 +124,10 @@ defmodule Pleroma.UserTest do        assert ap_ids_by_rel[:inverse_subscription] ==                 Enum.sort(Enum.map(User.subscriber_users(user), & &1.ap_id)) -      outgoing_relations_ap_ids = User.outgoing_relations_ap_ids(user, rel_types) +      outgoing_relationships_ap_ids = User.outgoing_relationships_ap_ids(user, rel_types)        assert ap_ids_by_rel == -               Enum.into(outgoing_relations_ap_ids, %{}, fn {k, v} -> {k, Enum.sort(v)} end) +               Enum.into(outgoing_relationships_ap_ids, %{}, fn {k, v} -> {k, Enum.sort(v)} end)      end    end @@ -297,7 +297,7 @@ defmodule Pleroma.UserTest do    end    describe "unfollow/2" do -    clear_config([:instance, :external_user_synchronization]) +    setup do: clear_config([:instance, :external_user_synchronization])      test "unfollow with syncronizes external user" do        Pleroma.Config.put([:instance, :external_user_synchronization], true) @@ -375,10 +375,9 @@ defmodule Pleroma.UserTest do        password_confirmation: "test",        email: "email@example.com"      } - -    clear_config([:instance, :autofollowed_nicknames]) -    clear_config([:instance, :welcome_message]) -    clear_config([:instance, :welcome_user_nickname]) +    setup do: clear_config([:instance, :autofollowed_nicknames]) +    setup do: clear_config([:instance, :welcome_message]) +    setup do: clear_config([:instance, :welcome_user_nickname])      test "it autofollows accounts that are set for it" do        user = insert(:user) @@ -412,7 +411,11 @@ defmodule Pleroma.UserTest do        assert activity.actor == welcome_user.ap_id      end -    test "it requires an email, name, nickname and password, bio is optional" do +    setup do: clear_config([:instance, :account_activation_required]) + +    test "it requires an email, name, nickname and password, bio is optional when account_activation_required is enabled" do +      Pleroma.Config.put([:instance, :account_activation_required], true) +        @full_user_data        |> Map.keys()        |> Enum.each(fn key -> @@ -423,6 +426,19 @@ defmodule Pleroma.UserTest do        end)      end +    test "it requires an name, nickname and password, bio and email are optional when account_activation_required is disabled" do +      Pleroma.Config.put([:instance, :account_activation_required], false) + +      @full_user_data +      |> Map.keys() +      |> Enum.each(fn key -> +        params = Map.delete(@full_user_data, key) +        changeset = User.register_changeset(%User{}, params) + +        assert if key in [:bio, :email], do: changeset.valid?, else: not changeset.valid? +      end) +    end +      test "it restricts certain nicknames" do        [restricted_name | _] = Pleroma.Config.get([User, :restricted_nicknames]) @@ -458,10 +474,7 @@ defmodule Pleroma.UserTest do        password_confirmation: "test",        email: "email@example.com"      } - -    clear_config([:instance, :account_activation_required]) do -      Pleroma.Config.put([:instance, :account_activation_required], true) -    end +    setup do: clear_config([:instance, :account_activation_required], true)      test "it creates unconfirmed user" do        changeset = User.register_changeset(%User{}, @full_user_data) @@ -604,9 +617,8 @@ defmodule Pleroma.UserTest do        ap_id: "http...",        avatar: %{some: "avatar"}      } - -    clear_config([:instance, :user_bio_length]) -    clear_config([:instance, :user_name_length]) +    setup do: clear_config([:instance, :user_bio_length]) +    setup do: clear_config([:instance, :user_name_length])      test "it confirms validity" do        cs = User.remote_user_creation(@valid_remote) @@ -1099,7 +1111,7 @@ defmodule Pleroma.UserTest do        [user: user]      end -    clear_config([:instance, :federating]) +    setup do: clear_config([:instance, :federating])      test ".delete_user_activities deletes all create activities", %{user: user} do        {:ok, activity} = CommonAPI.post(user, %{"status" => "2hu"}) @@ -1280,7 +1292,7 @@ defmodule Pleroma.UserTest do    end    describe "account_status/1" do -    clear_config([:instance, :account_activation_required]) +    setup do: clear_config([:instance, :account_activation_required])      test "return confirmation_pending for unconfirm user" do        Pleroma.Config.put([:instance, :account_activation_required], true) @@ -1648,7 +1660,7 @@ defmodule Pleroma.UserTest do    end    describe "following/followers synchronization" do -    clear_config([:instance, :external_user_synchronization]) +    setup do: clear_config([:instance, :external_user_synchronization])      test "updates the counters normally on following/getting a follow when disabled" do        Pleroma.Config.put([:instance, :external_user_synchronization], false) @@ -1753,7 +1765,7 @@ defmodule Pleroma.UserTest do        [local_user: local_user, remote_user: remote_user]      end -    clear_config([:instance, :limit_to_local_content]) +    setup do: clear_config([:instance, :limit_to_local_content])      test "allows getting remote users by id no matter what :limit_to_local_content is set to", %{        remote_user: remote_user diff --git a/test/web/activity_pub/activity_pub_controller_test.exs b/test/web/activity_pub/activity_pub_controller_test.exs index 9151034da..573853afa 100644 --- a/test/web/activity_pub/activity_pub_controller_test.exs +++ b/test/web/activity_pub/activity_pub_controller_test.exs @@ -8,6 +8,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do    import Pleroma.Factory    alias Pleroma.Activity +  alias Pleroma.Config    alias Pleroma.Delivery    alias Pleroma.Instances    alias Pleroma.Object @@ -25,12 +26,10 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      :ok    end -  clear_config_all([:instance, :federating], -    do: Pleroma.Config.put([:instance, :federating], true) -  ) +  setup do: clear_config([:instance, :federating], true)    describe "/relay" do -    clear_config([:instance, :allow_relay]) +    setup do: clear_config([:instance, :allow_relay])      test "with the relay active, it returns the relay user", %{conn: conn} do        res = @@ -42,12 +41,21 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end      test "with the relay disabled, it returns 404", %{conn: conn} do -      Pleroma.Config.put([:instance, :allow_relay], false) +      Config.put([:instance, :allow_relay], false)        conn        |> get(activity_pub_path(conn, :relay))        |> json_response(404) -      |> assert +    end + +    test "on non-federating instance, it returns 404", %{conn: conn} do +      Config.put([:instance, :federating], false) +      user = insert(:user) + +      conn +      |> assign(:user, user) +      |> get(activity_pub_path(conn, :relay)) +      |> json_response(404)      end    end @@ -60,6 +68,16 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert res["id"] =~ "/fetch"      end + +    test "on non-federating instance, it returns 404", %{conn: conn} do +      Config.put([:instance, :federating], false) +      user = insert(:user) + +      conn +      |> assign(:user, user) +      |> get(activity_pub_path(conn, :internal_fetch)) +      |> json_response(404) +    end    end    describe "/users/:nickname" do @@ -123,9 +141,34 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert json_response(conn, 404)      end + +    test "it returns error when user is not found", %{conn: conn} do +      response = +        conn +        |> put_req_header("accept", "application/json") +        |> get("/users/jimm") +        |> json_response(404) + +      assert response == "Not found" +    end + +    test "it requires authentication if instance is NOT federating", %{ +      conn: conn +    } do +      user = insert(:user) + +      conn = +        put_req_header( +          conn, +          "accept", +          "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"" +        ) + +      ensure_federating_or_authenticated(conn, "/users/#{user.nickname}.json", user) +    end    end -  describe "/object/:uuid" do +  describe "/objects/:uuid" do      test "it returns a json representation of the object with accept application/json", %{        conn: conn      } do @@ -236,6 +279,18 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert "Not found" == json_response(conn2, :not_found)      end + +    test "it requires authentication if instance is NOT federating", %{ +      conn: conn +    } do +      user = insert(:user) +      note = insert(:note) +      uuid = String.split(note.data["id"], "/") |> List.last() + +      conn = put_req_header(conn, "accept", "application/activity+json") + +      ensure_federating_or_authenticated(conn, "/objects/#{uuid}", user) +    end    end    describe "/activities/:uuid" do @@ -307,6 +362,18 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert "Not found" == json_response(conn2, :not_found)      end + +    test "it requires authentication if instance is NOT federating", %{ +      conn: conn +    } do +      user = insert(:user) +      activity = insert(:note_activity) +      uuid = String.split(activity.data["id"], "/") |> List.last() + +      conn = put_req_header(conn, "accept", "application/activity+json") + +      ensure_federating_or_authenticated(conn, "/activities/#{uuid}", user) +    end    end    describe "/inbox" do @@ -341,6 +408,72 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert "ok" == json_response(conn, 200)        assert Instances.reachable?(sender_url)      end + +    test "accept follow activity", %{conn: conn} do +      Pleroma.Config.put([:instance, :federating], true) +      relay = Relay.get_actor() + +      assert {:ok, %Activity{} = activity} = Relay.follow("https://relay.mastodon.host/actor") + +      followed_relay = Pleroma.User.get_by_ap_id("https://relay.mastodon.host/actor") +      relay = refresh_record(relay) + +      accept = +        File.read!("test/fixtures/relay/accept-follow.json") +        |> String.replace("{{ap_id}}", relay.ap_id) +        |> String.replace("{{activity_id}}", activity.data["id"]) + +      assert "ok" == +               conn +               |> assign(:valid_signature, true) +               |> put_req_header("content-type", "application/activity+json") +               |> post("/inbox", accept) +               |> json_response(200) + +      ObanHelpers.perform(all_enqueued(worker: ReceiverWorker)) + +      assert Pleroma.FollowingRelationship.following?( +               relay, +               followed_relay +             ) + +      Mix.shell(Mix.Shell.Process) + +      on_exit(fn -> +        Mix.shell(Mix.Shell.IO) +      end) + +      :ok = Mix.Tasks.Pleroma.Relay.run(["list"]) +      assert_receive {:mix_shell, :info, ["relay.mastodon.host"]} +    end + +    test "without valid signature, " <> +           "it only accepts Create activities and requires enabled federation", +         %{conn: conn} do +      data = File.read!("test/fixtures/mastodon-post-activity.json") |> Poison.decode!() +      non_create_data = File.read!("test/fixtures/mastodon-announce.json") |> Poison.decode!() + +      conn = put_req_header(conn, "content-type", "application/activity+json") + +      Config.put([:instance, :federating], false) + +      conn +      |> post("/inbox", data) +      |> json_response(403) + +      conn +      |> post("/inbox", non_create_data) +      |> json_response(403) + +      Config.put([:instance, :federating], true) + +      ret_conn = post(conn, "/inbox", data) +      assert "ok" == json_response(ret_conn, 200) + +      conn +      |> post("/inbox", non_create_data) +      |> json_response(400) +    end    end    describe "/users/:nickname/inbox" do @@ -479,22 +612,11 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      test "it rejects reads from other users", %{conn: conn} do        user = insert(:user) -      otheruser = insert(:user) - -      conn = -        conn -        |> assign(:user, otheruser) -        |> put_req_header("accept", "application/activity+json") -        |> get("/users/#{user.nickname}/inbox") - -      assert json_response(conn, 403) -    end - -    test "it doesn't crash without an authenticated user", %{conn: conn} do -      user = insert(:user) +      other_user = insert(:user)        conn =          conn +        |> assign(:user, other_user)          |> put_req_header("accept", "application/activity+json")          |> get("/users/#{user.nickname}/inbox") @@ -575,14 +697,30 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        refute recipient.follower_address in activity.data["cc"]        refute recipient.follower_address in activity.data["to"]      end + +    test "it requires authentication", %{conn: conn} do +      user = insert(:user) +      conn = put_req_header(conn, "accept", "application/activity+json") + +      ret_conn = get(conn, "/users/#{user.nickname}/inbox") +      assert json_response(ret_conn, 403) + +      ret_conn = +        conn +        |> assign(:user, user) +        |> get("/users/#{user.nickname}/inbox") + +      assert json_response(ret_conn, 200) +    end    end -  describe "/users/:nickname/outbox" do -    test "it will not bomb when there is no activity", %{conn: conn} do +  describe "GET /users/:nickname/outbox" do +    test "it returns 200 even if there're no activities", %{conn: conn} do        user = insert(:user)        conn =          conn +        |> assign(:user, user)          |> put_req_header("accept", "application/activity+json")          |> get("/users/#{user.nickname}/outbox") @@ -597,6 +735,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        conn =          conn +        |> assign(:user, user)          |> put_req_header("accept", "application/activity+json")          |> get("/users/#{user.nickname}/outbox?page=true") @@ -609,24 +748,38 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        conn =          conn +        |> assign(:user, user)          |> put_req_header("accept", "application/activity+json")          |> get("/users/#{user.nickname}/outbox?page=true")        assert response(conn, 200) =~ announce_activity.data["object"]      end -    test "it rejects posts from other users", %{conn: conn} do +    test "it requires authentication if instance is NOT federating", %{ +      conn: conn +    } do +      user = insert(:user) +      conn = put_req_header(conn, "accept", "application/activity+json") + +      ensure_federating_or_authenticated(conn, "/users/#{user.nickname}/outbox", user) +    end +  end + +  describe "POST /users/:nickname/outbox" do +    test "it rejects posts from other users / unauuthenticated users", %{conn: conn} do        data = File.read!("test/fixtures/activitypub-client-post-activity.json") |> Poison.decode!()        user = insert(:user) -      otheruser = insert(:user) +      other_user = insert(:user) +      conn = put_req_header(conn, "content-type", "application/activity+json") -      conn = -        conn -        |> assign(:user, otheruser) -        |> put_req_header("content-type", "application/activity+json") -        |> post("/users/#{user.nickname}/outbox", data) +      conn +      |> post("/users/#{user.nickname}/outbox", data) +      |> json_response(403) -      assert json_response(conn, 403) +      conn +      |> assign(:user, other_user) +      |> post("/users/#{user.nickname}/outbox", data) +      |> json_response(403)      end      test "it inserts an incoming create activity into the database", %{conn: conn} do @@ -741,24 +894,42 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        result =          conn -        |> assign(:relay, true)          |> get("/relay/followers")          |> json_response(200)        assert result["first"]["orderedItems"] == [user.ap_id]      end + +    test "on non-federating instance, it returns 404", %{conn: conn} do +      Config.put([:instance, :federating], false) +      user = insert(:user) + +      conn +      |> assign(:user, user) +      |> get("/relay/followers") +      |> json_response(404) +    end    end    describe "/relay/following" do      test "it returns relay following", %{conn: conn} do        result =          conn -        |> assign(:relay, true)          |> get("/relay/following")          |> json_response(200)        assert result["first"]["orderedItems"] == []      end + +    test "on non-federating instance, it returns 404", %{conn: conn} do +      Config.put([:instance, :federating], false) +      user = insert(:user) + +      conn +      |> assign(:user, user) +      |> get("/relay/following") +      |> json_response(404) +    end    end    describe "/users/:nickname/followers" do @@ -769,32 +940,36 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        result =          conn +        |> assign(:user, user_two)          |> get("/users/#{user_two.nickname}/followers")          |> json_response(200)        assert result["first"]["orderedItems"] == [user.ap_id]      end -    test "it returns returns a uri if the user has 'hide_followers' set", %{conn: conn} do +    test "it returns a uri if the user has 'hide_followers' set", %{conn: conn} do        user = insert(:user)        user_two = insert(:user, hide_followers: true)        User.follow(user, user_two)        result =          conn +        |> assign(:user, user)          |> get("/users/#{user_two.nickname}/followers")          |> json_response(200)        assert is_binary(result["first"])      end -    test "it returns a 403 error on pages, if the user has 'hide_followers' set and the request is not authenticated", +    test "it returns a 403 error on pages, if the user has 'hide_followers' set and the request is from another user",           %{conn: conn} do -      user = insert(:user, hide_followers: true) +      user = insert(:user) +      other_user = insert(:user, hide_followers: true)        result =          conn -        |> get("/users/#{user.nickname}/followers?page=1") +        |> assign(:user, user) +        |> get("/users/#{other_user.nickname}/followers?page=1")        assert result.status == 403        assert result.resp_body == "" @@ -826,6 +1001,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        result =          conn +        |> assign(:user, user)          |> get("/users/#{user.nickname}/followers")          |> json_response(200) @@ -835,12 +1011,21 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        result =          conn +        |> assign(:user, user)          |> get("/users/#{user.nickname}/followers?page=2")          |> json_response(200)        assert length(result["orderedItems"]) == 5        assert result["totalItems"] == 15      end + +    test "returns 403 if requester is not logged in", %{conn: conn} do +      user = insert(:user) + +      conn +      |> get("/users/#{user.nickname}/followers") +      |> json_response(403) +    end    end    describe "/users/:nickname/following" do @@ -851,6 +1036,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        result =          conn +        |> assign(:user, user)          |> get("/users/#{user.nickname}/following")          |> json_response(200) @@ -858,25 +1044,28 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end      test "it returns a uri if the user has 'hide_follows' set", %{conn: conn} do -      user = insert(:user, hide_follows: true) -      user_two = insert(:user) +      user = insert(:user) +      user_two = insert(:user, hide_follows: true)        User.follow(user, user_two)        result =          conn -        |> get("/users/#{user.nickname}/following") +        |> assign(:user, user) +        |> get("/users/#{user_two.nickname}/following")          |> json_response(200)        assert is_binary(result["first"])      end -    test "it returns a 403 error on pages, if the user has 'hide_follows' set and the request is not authenticated", +    test "it returns a 403 error on pages, if the user has 'hide_follows' set and the request is from another user",           %{conn: conn} do -      user = insert(:user, hide_follows: true) +      user = insert(:user) +      user_two = insert(:user, hide_follows: true)        result =          conn -        |> get("/users/#{user.nickname}/following?page=1") +        |> assign(:user, user) +        |> get("/users/#{user_two.nickname}/following?page=1")        assert result.status == 403        assert result.resp_body == "" @@ -909,6 +1098,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        result =          conn +        |> assign(:user, user)          |> get("/users/#{user.nickname}/following")          |> json_response(200) @@ -918,12 +1108,21 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        result =          conn +        |> assign(:user, user)          |> get("/users/#{user.nickname}/following?page=2")          |> json_response(200)        assert length(result["orderedItems"]) == 5        assert result["totalItems"] == 15      end + +    test "returns 403 if requester is not logged in", %{conn: conn} do +      user = insert(:user) + +      conn +      |> get("/users/#{user.nickname}/following") +      |> json_response(403) +    end    end    describe "delivery tracking" do @@ -1008,8 +1207,8 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end    end -  describe "Additionnal ActivityPub C2S endpoints" do -    test "/api/ap/whoami", %{conn: conn} do +  describe "Additional ActivityPub C2S endpoints" do +    test "GET /api/ap/whoami", %{conn: conn} do        user = insert(:user)        conn = @@ -1020,12 +1219,16 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        user = User.get_cached_by_id(user.id)        assert UserView.render("user.json", %{user: user}) == json_response(conn, 200) + +      conn +      |> get("/api/ap/whoami") +      |> json_response(403)      end -    clear_config([:media_proxy]) -    clear_config([Pleroma.Upload]) +    setup do: clear_config([:media_proxy]) +    setup do: clear_config([Pleroma.Upload]) -    test "uploadMedia", %{conn: conn} do +    test "POST /api/ap/upload_media", %{conn: conn} do        user = insert(:user)        desc = "Description of the image" @@ -1045,6 +1248,10 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert object["name"] == desc        assert object["type"] == "Document"        assert object["actor"] == user.ap_id + +      conn +      |> post("/api/ap/upload_media", %{"file" => image, "description" => desc}) +      |> json_response(403)      end    end  end diff --git a/test/web/activity_pub/activity_pub_test.exs b/test/web/activity_pub/activity_pub_test.exs index 3dd3dd04d..049b14498 100644 --- a/test/web/activity_pub/activity_pub_test.exs +++ b/test/web/activity_pub/activity_pub_test.exs @@ -27,7 +27,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do      :ok    end -  clear_config([:instance, :federating]) +  setup do: clear_config([:instance, :federating])    describe "streaming out participations" do      test "it streams them out" do @@ -1396,7 +1396,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do    end    describe "deletion" do -    clear_config([:instance, :rewrite_policy]) +    setup do: clear_config([:instance, :rewrite_policy])      test "it reverts deletion on error" do        note = insert(:note_activity) @@ -1425,6 +1425,12 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        assert Repo.get(Object, object.id).data["type"] == "Tombstone"      end +    test "it doesn't fail when an activity was already deleted" do +      {:ok, delete} = insert(:note_activity) |> Object.normalize() |> ActivityPub.delete() + +      assert {:ok, ^delete} = delete |> Object.normalize() |> ActivityPub.delete() +    end +      test "decrements user note count only for public activities" do        user = insert(:user, note_count: 10) @@ -1580,7 +1586,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do    end    describe "update" do -    clear_config([:instance, :max_pinned_statuses]) +    setup do: clear_config([:instance, :max_pinned_statuses])      test "it creates an update activity with the new user data" do        user = insert(:user) @@ -1955,11 +1961,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        activity = %Activity{activity | object: nil} -      assert [%Notification{activity: ^activity}] = -               Notification.for_user(follower, %{with_move: true}) +      assert [%Notification{activity: ^activity}] = Notification.for_user(follower) -      assert [%Notification{activity: ^activity}] = -               Notification.for_user(follower_move_opted_out, %{with_move: true}) +      assert [%Notification{activity: ^activity}] = Notification.for_user(follower_move_opted_out)      end      test "old user must be in the new user's `also_known_as` list" do diff --git a/test/web/activity_pub/mrf/hellthread_policy_test.exs b/test/web/activity_pub/mrf/hellthread_policy_test.exs index 916b95692..95ef0b168 100644 --- a/test/web/activity_pub/mrf/hellthread_policy_test.exs +++ b/test/web/activity_pub/mrf/hellthread_policy_test.exs @@ -26,7 +26,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicyTest do      [user: user, message: message]    end -  clear_config(:mrf_hellthread) +  setup do: clear_config(:mrf_hellthread)    describe "reject" do      test "rejects the message if the recipient count is above reject_threshold", %{ diff --git a/test/web/activity_pub/mrf/keyword_policy_test.exs b/test/web/activity_pub/mrf/keyword_policy_test.exs index 18242a889..fd1f7aec8 100644 --- a/test/web/activity_pub/mrf/keyword_policy_test.exs +++ b/test/web/activity_pub/mrf/keyword_policy_test.exs @@ -7,7 +7,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do    alias Pleroma.Web.ActivityPub.MRF.KeywordPolicy -  clear_config(:mrf_keyword) +  setup do: clear_config(:mrf_keyword)    setup do      Pleroma.Config.put([:mrf_keyword], %{reject: [], federated_timeline_removal: [], replace: []}) diff --git a/test/web/activity_pub/mrf/mention_policy_test.exs b/test/web/activity_pub/mrf/mention_policy_test.exs index 08f7be542..aa003bef5 100644 --- a/test/web/activity_pub/mrf/mention_policy_test.exs +++ b/test/web/activity_pub/mrf/mention_policy_test.exs @@ -7,7 +7,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicyTest do    alias Pleroma.Web.ActivityPub.MRF.MentionPolicy -  clear_config(:mrf_mention) +  setup do: clear_config(:mrf_mention)    test "pass filter if allow list is empty" do      Pleroma.Config.delete([:mrf_mention]) diff --git a/test/web/activity_pub/mrf/mrf_test.exs b/test/web/activity_pub/mrf/mrf_test.exs index 04709df17..c941066f2 100644 --- a/test/web/activity_pub/mrf/mrf_test.exs +++ b/test/web/activity_pub/mrf/mrf_test.exs @@ -60,7 +60,7 @@ defmodule Pleroma.Web.ActivityPub.MRFTest do    end    describe "describe/0" do -    clear_config([:instance, :rewrite_policy]) +    setup do: clear_config([:instance, :rewrite_policy])      test "it works as expected with noop policy" do        expected = %{ diff --git a/test/web/activity_pub/mrf/object_age_policy_test.exs b/test/web/activity_pub/mrf/object_age_policy_test.exs index 643609da4..0fbc5f57a 100644 --- a/test/web/activity_pub/mrf/object_age_policy_test.exs +++ b/test/web/activity_pub/mrf/object_age_policy_test.exs @@ -9,12 +9,11 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do    alias Pleroma.Web.ActivityPub.MRF.ObjectAgePolicy    alias Pleroma.Web.ActivityPub.Visibility -  clear_config([:mrf_object_age]) do -    Config.put(:mrf_object_age, -      threshold: 172_800, -      actions: [:delist, :strip_followers] -    ) -  end +  setup do: +          clear_config(:mrf_object_age, +            threshold: 172_800, +            actions: [:delist, :strip_followers] +          )    setup_all do      Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) diff --git a/test/web/activity_pub/mrf/reject_non_public_test.exs b/test/web/activity_pub/mrf/reject_non_public_test.exs index fc1d190bb..abfd32df8 100644 --- a/test/web/activity_pub/mrf/reject_non_public_test.exs +++ b/test/web/activity_pub/mrf/reject_non_public_test.exs @@ -8,7 +8,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublicTest do    alias Pleroma.Web.ActivityPub.MRF.RejectNonPublic -  clear_config([:mrf_rejectnonpublic]) +  setup do: clear_config([:mrf_rejectnonpublic])    describe "public message" do      test "it's allowed when address is public" do diff --git a/test/web/activity_pub/mrf/simple_policy_test.exs b/test/web/activity_pub/mrf/simple_policy_test.exs index df0f223f8..5aebbc675 100644 --- a/test/web/activity_pub/mrf/simple_policy_test.exs +++ b/test/web/activity_pub/mrf/simple_policy_test.exs @@ -8,18 +8,17 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    alias Pleroma.Config    alias Pleroma.Web.ActivityPub.MRF.SimplePolicy -  clear_config([:mrf_simple]) do -    Config.put(:mrf_simple, -      media_removal: [], -      media_nsfw: [], -      federated_timeline_removal: [], -      report_removal: [], -      reject: [], -      accept: [], -      avatar_removal: [], -      banner_removal: [] -    ) -  end +  setup do: +          clear_config(:mrf_simple, +            media_removal: [], +            media_nsfw: [], +            federated_timeline_removal: [], +            report_removal: [], +            reject: [], +            accept: [], +            avatar_removal: [], +            banner_removal: [] +          )    describe "when :media_removal" do      test "is empty" do diff --git a/test/web/activity_pub/mrf/subchain_policy_test.exs b/test/web/activity_pub/mrf/subchain_policy_test.exs index 221b8958e..fff66cb7e 100644 --- a/test/web/activity_pub/mrf/subchain_policy_test.exs +++ b/test/web/activity_pub/mrf/subchain_policy_test.exs @@ -13,8 +13,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SubchainPolicyTest do      "type" => "Create",      "object" => %{"content" => "hi"}    } - -  clear_config([:mrf_subchain, :match_actor]) +  setup do: clear_config([:mrf_subchain, :match_actor])    test "it matches and processes subchains when the actor matches a configured target" do      Pleroma.Config.put([:mrf_subchain, :match_actor], %{ diff --git a/test/web/activity_pub/mrf/user_allowlist_policy_test.exs b/test/web/activity_pub/mrf/user_allowlist_policy_test.exs index 87c9e1b29..724bae058 100644 --- a/test/web/activity_pub/mrf/user_allowlist_policy_test.exs +++ b/test/web/activity_pub/mrf/user_allowlist_policy_test.exs @@ -7,7 +7,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.UserAllowListPolicyTest do    alias Pleroma.Web.ActivityPub.MRF.UserAllowListPolicy -  clear_config([:mrf_user_allowlist, :localhost]) +  setup do: clear_config([:mrf_user_allowlist, :localhost])    test "pass filter if allow list is empty" do      actor = insert(:user) diff --git a/test/web/activity_pub/mrf/vocabulary_policy_test.exs b/test/web/activity_pub/mrf/vocabulary_policy_test.exs index d9207b095..69f22bb77 100644 --- a/test/web/activity_pub/mrf/vocabulary_policy_test.exs +++ b/test/web/activity_pub/mrf/vocabulary_policy_test.exs @@ -8,7 +8,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do    alias Pleroma.Web.ActivityPub.MRF.VocabularyPolicy    describe "accept" do -    clear_config([:mrf_vocabulary, :accept]) +    setup do: clear_config([:mrf_vocabulary, :accept])      test "it accepts based on parent activity type" do        Pleroma.Config.put([:mrf_vocabulary, :accept], ["Like"]) @@ -65,7 +65,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do    end    describe "reject" do -    clear_config([:mrf_vocabulary, :reject]) +    setup do: clear_config([:mrf_vocabulary, :reject])      test "it rejects based on parent activity type" do        Pleroma.Config.put([:mrf_vocabulary, :reject], ["Like"]) diff --git a/test/web/activity_pub/publisher_test.exs b/test/web/activity_pub/publisher_test.exs index 3404848d4..801da03c1 100644 --- a/test/web/activity_pub/publisher_test.exs +++ b/test/web/activity_pub/publisher_test.exs @@ -23,6 +23,8 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do      :ok    end +  setup_all do: clear_config([:instance, :federating], true) +    describe "gather_webfinger_links/1" do      test "it returns links" do        user = insert(:user) diff --git a/test/web/activity_pub/relay_test.exs b/test/web/activity_pub/relay_test.exs index e3115dcd8..040625e4d 100644 --- a/test/web/activity_pub/relay_test.exs +++ b/test/web/activity_pub/relay_test.exs @@ -68,7 +68,7 @@ defmodule Pleroma.Web.ActivityPub.RelayTest do    end    describe "publish/1" do -    clear_config([:instance, :federating]) +    setup do: clear_config([:instance, :federating])      test "returns error when activity not `Create` type" do        activity = insert(:like_activity) diff --git a/test/web/activity_pub/transmogrifier/follow_handling_test.exs b/test/web/activity_pub/transmogrifier/follow_handling_test.exs index c3d3f9830..967389fae 100644 --- a/test/web/activity_pub/transmogrifier/follow_handling_test.exs +++ b/test/web/activity_pub/transmogrifier/follow_handling_test.exs @@ -19,7 +19,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.FollowHandlingTest do    end    describe "handle_incoming" do -    clear_config([:user, :deny_follow_blocked]) +    setup do: clear_config([:user, :deny_follow_blocked])      test "it works for osada follow request" do        user = insert(:user) diff --git a/test/web/activity_pub/transmogrifier_test.exs b/test/web/activity_pub/transmogrifier_test.exs index efbca82f6..b2cabbd30 100644 --- a/test/web/activity_pub/transmogrifier_test.exs +++ b/test/web/activity_pub/transmogrifier_test.exs @@ -25,7 +25,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do      :ok    end -  clear_config([:instance, :max_remote_account_fields]) +  setup do: clear_config([:instance, :max_remote_account_fields])    describe "handle_incoming" do      test "it ignores an incoming notice if we already have it" do @@ -1351,11 +1351,8 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do    end    describe "`handle_incoming/2`, Mastodon format `replies` handling" do -    clear_config([:activitypub, :note_replies_output_limit]) do -      Pleroma.Config.put([:activitypub, :note_replies_output_limit], 5) -    end - -    clear_config([:instance, :federation_incoming_replies_max_depth]) +    setup do: clear_config([:activitypub, :note_replies_output_limit], 5) +    setup do: clear_config([:instance, :federation_incoming_replies_max_depth])      setup do        data = @@ -1394,11 +1391,8 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do    end    describe "`handle_incoming/2`, Pleroma format `replies` handling" do -    clear_config([:activitypub, :note_replies_output_limit]) do -      Pleroma.Config.put([:activitypub, :note_replies_output_limit], 5) -    end - -    clear_config([:instance, :federation_incoming_replies_max_depth]) +    setup do: clear_config([:activitypub, :note_replies_output_limit], 5) +    setup do: clear_config([:instance, :federation_incoming_replies_max_depth])      setup do        user = insert(:user) @@ -1882,7 +1876,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do    end    describe "fix_in_reply_to/2" do -    clear_config([:instance, :federation_incoming_replies_max_depth]) +    setup do: clear_config([:instance, :federation_incoming_replies_max_depth])      setup do        data = Poison.decode!(File.read!("test/fixtures/mastodon-post-activity.json")) @@ -2145,9 +2139,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do    end    describe "set_replies/1" do -    clear_config([:activitypub, :note_replies_output_limit]) do -      Pleroma.Config.put([:activitypub, :note_replies_output_limit], 2) -    end +    setup do: clear_config([:activitypub, :note_replies_output_limit], 2)      test "returns unmodified object if activity doesn't have self-replies" do        data = Poison.decode!(File.read!("test/fixtures/mastodon-post-activity.json")) diff --git a/test/web/activity_pub/utils_test.exs b/test/web/activity_pub/utils_test.exs index e5ab54dd4..e913a5148 100644 --- a/test/web/activity_pub/utils_test.exs +++ b/test/web/activity_pub/utils_test.exs @@ -177,71 +177,6 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do      end    end -  describe "fetch_ordered_collection" do -    import Tesla.Mock - -    test "fetches the first OrderedCollectionPage when an OrderedCollection is encountered" do -      mock(fn -        %{method: :get, url: "http://mastodon.com/outbox"} -> -          json(%{"type" => "OrderedCollection", "first" => "http://mastodon.com/outbox?page=true"}) - -        %{method: :get, url: "http://mastodon.com/outbox?page=true"} -> -          json(%{"type" => "OrderedCollectionPage", "orderedItems" => ["ok"]}) -      end) - -      assert Utils.fetch_ordered_collection("http://mastodon.com/outbox", 1) == ["ok"] -    end - -    test "fetches several pages in the right order one after another, but only the specified amount" do -      mock(fn -        %{method: :get, url: "http://example.com/outbox"} -> -          json(%{ -            "type" => "OrderedCollectionPage", -            "orderedItems" => [0], -            "next" => "http://example.com/outbox?page=1" -          }) - -        %{method: :get, url: "http://example.com/outbox?page=1"} -> -          json(%{ -            "type" => "OrderedCollectionPage", -            "orderedItems" => [1], -            "next" => "http://example.com/outbox?page=2" -          }) - -        %{method: :get, url: "http://example.com/outbox?page=2"} -> -          json(%{"type" => "OrderedCollectionPage", "orderedItems" => [2]}) -      end) - -      assert Utils.fetch_ordered_collection("http://example.com/outbox", 0) == [0] -      assert Utils.fetch_ordered_collection("http://example.com/outbox", 1) == [0, 1] -    end - -    test "returns an error if the url doesn't have an OrderedCollection/Page" do -      mock(fn -        %{method: :get, url: "http://example.com/not-an-outbox"} -> -          json(%{"type" => "NotAnOutbox"}) -      end) - -      assert {:error, _} = Utils.fetch_ordered_collection("http://example.com/not-an-outbox", 1) -    end - -    test "returns the what was collected if there are less pages than specified" do -      mock(fn -        %{method: :get, url: "http://example.com/outbox"} -> -          json(%{ -            "type" => "OrderedCollectionPage", -            "orderedItems" => [0], -            "next" => "http://example.com/outbox?page=1" -          }) - -        %{method: :get, url: "http://example.com/outbox?page=1"} -> -          json(%{"type" => "OrderedCollectionPage", "orderedItems" => [1]}) -      end) - -      assert Utils.fetch_ordered_collection("http://example.com/outbox", 5) == [0, 1] -    end -  end -    test "make_json_ld_header/0" do      assert Utils.make_json_ld_header() == %{               "@context" => [ diff --git a/test/web/activity_pub/views/object_view_test.exs b/test/web/activity_pub/views/object_view_test.exs index 09866e99b..de5ffc5b3 100644 --- a/test/web/activity_pub/views/object_view_test.exs +++ b/test/web/activity_pub/views/object_view_test.exs @@ -37,9 +37,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectViewTest do    end    describe "note activity's `replies` collection rendering" do -    clear_config([:activitypub, :note_replies_output_limit]) do -      Pleroma.Config.put([:activitypub, :note_replies_output_limit], 5) -    end +    setup do: clear_config([:activitypub, :note_replies_output_limit], 5)      test "renders `replies` collection for a note activity" do        user = insert(:user) diff --git a/test/web/admin_api/admin_api_controller_test.exs b/test/web/admin_api/admin_api_controller_test.exs index 8009d4386..c9e228cc8 100644 --- a/test/web/admin_api/admin_api_controller_test.exs +++ b/test/web/admin_api/admin_api_controller_test.exs @@ -43,9 +43,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    end    describe "with [:auth, :enforce_oauth_admin_scope_usage]," do -    clear_config([:auth, :enforce_oauth_admin_scope_usage]) do -      Config.put([:auth, :enforce_oauth_admin_scope_usage], true) -    end +    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], true)      test "GET /api/pleroma/admin/users/:nickname requires admin:read:accounts or broader scope",           %{admin: admin} do @@ -93,9 +91,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    end    describe "unless [:auth, :enforce_oauth_admin_scope_usage]," do -    clear_config([:auth, :enforce_oauth_admin_scope_usage]) do -      Config.put([:auth, :enforce_oauth_admin_scope_usage], false) -    end +    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)      test "GET /api/pleroma/admin/users/:nickname requires " <>             "read:accounts or admin:read:accounts or broader scope", @@ -581,13 +577,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    end    describe "POST /api/pleroma/admin/email_invite, with valid config" do -    clear_config([:instance, :registrations_open]) do -      Config.put([:instance, :registrations_open], false) -    end - -    clear_config([:instance, :invites_enabled]) do -      Config.put([:instance, :invites_enabled], true) -    end +    setup do: clear_config([:instance, :registrations_open], false) +    setup do: clear_config([:instance, :invites_enabled], true)      test "sends invitation and returns 204", %{admin: admin, conn: conn} do        recipient_email = "foo@bar.com" @@ -638,8 +629,8 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    end    describe "POST /api/pleroma/admin/users/email_invite, with invalid config" do -    clear_config([:instance, :registrations_open]) -    clear_config([:instance, :invites_enabled]) +    setup do: clear_config([:instance, :registrations_open]) +    setup do: clear_config([:instance, :invites_enabled])      test "it returns 500 if `invites_enabled` is not enabled", %{conn: conn} do        Config.put([:instance, :registrations_open], false) @@ -1888,9 +1879,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    end    describe "GET /api/pleroma/admin/config" do -    clear_config(:configurable_from_database) do -      Config.put(:configurable_from_database, true) -    end +    setup do: clear_config(:configurable_from_database, true)      test "when configuration from database is off", %{conn: conn} do        Config.put(:configurable_from_database, false) @@ -2041,9 +2030,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        end)      end -    clear_config(:configurable_from_database) do -      Config.put(:configurable_from_database, true) -    end +    setup do: clear_config(:configurable_from_database, true)      @tag capture_log: true      test "create new config setting in db", %{conn: conn} do @@ -3052,9 +3039,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    end    describe "GET /api/pleroma/admin/restart" do -    clear_config(:configurable_from_database) do -      Config.put(:configurable_from_database, true) -    end +    setup do: clear_config(:configurable_from_database, true)      test "pleroma restarts", %{conn: conn} do        capture_log(fn -> @@ -3066,7 +3051,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    end    describe "GET /api/pleroma/admin/statuses" do -    test "returns all public, unlisted, and direct statuses", %{conn: conn, admin: admin} do +    test "returns all public and unlisted statuses", %{conn: conn, admin: admin} do        blocked = insert(:user)        user = insert(:user)        User.block(admin, blocked) @@ -3085,7 +3070,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do          |> json_response(200)        refute "private" in Enum.map(response, & &1["visibility"]) -      assert length(response) == 4 +      assert length(response) == 3      end      test "returns only local statuses with local_only on", %{conn: conn} do @@ -3102,12 +3087,16 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        assert length(response) == 1      end -    test "returns private statuses with godmode on", %{conn: conn} do +    test "returns private and direct statuses with godmode on", %{conn: conn, admin: admin} do        user = insert(:user) + +      {:ok, _} = +        CommonAPI.post(user, %{"status" => "@#{admin.nickname}", "visibility" => "direct"}) +        {:ok, _} = CommonAPI.post(user, %{"status" => ".", "visibility" => "private"})        {:ok, _} = CommonAPI.post(user, %{"status" => ".", "visibility" => "public"})        conn = get(conn, "/api/pleroma/admin/statuses?godmode=true") -      assert json_response(conn, 200) |> length() == 2 +      assert json_response(conn, 200) |> length() == 3      end    end @@ -3385,6 +3374,75 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do      end    end +  describe "GET /users/:nickname/credentials" do +    test "gets the user credentials", %{conn: conn} do +      user = insert(:user) +      conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials") + +      response = assert json_response(conn, 200) +      assert response["email"] == user.email +    end + +    test "returns 403 if requested by a non-admin" do +      user = insert(:user) + +      conn = +        build_conn() +        |> assign(:user, user) +        |> get("/api/pleroma/admin/users/#{user.nickname}/credentials") + +      assert json_response(conn, :forbidden) +    end +  end + +  describe "PATCH /users/:nickname/credentials" do +    test "changes password and email", %{conn: conn, admin: admin} do +      user = insert(:user) +      assert user.password_reset_pending == false + +      conn = +        patch(conn, "/api/pleroma/admin/users/#{user.nickname}/credentials", %{ +          "password" => "new_password", +          "email" => "new_email@example.com", +          "name" => "new_name" +        }) + +      assert json_response(conn, 200) == %{"status" => "success"} + +      ObanHelpers.perform_all() + +      updated_user = User.get_by_id(user.id) + +      assert updated_user.email == "new_email@example.com" +      assert updated_user.name == "new_name" +      assert updated_user.password_hash != user.password_hash +      assert updated_user.password_reset_pending == true + +      [log_entry2, log_entry1] = ModerationLog |> Repo.all() |> Enum.sort() + +      assert ModerationLog.get_log_entry_message(log_entry1) == +               "@#{admin.nickname} updated users: @#{user.nickname}" + +      assert ModerationLog.get_log_entry_message(log_entry2) == +               "@#{admin.nickname} forced password reset for users: @#{user.nickname}" +    end + +    test "returns 403 if requested by a non-admin" do +      user = insert(:user) + +      conn = +        build_conn() +        |> assign(:user, user) +        |> patch("/api/pleroma/admin/users/#{user.nickname}/credentials", %{ +          "password" => "new_password", +          "email" => "new_email@example.com", +          "name" => "new_name" +        }) + +      assert json_response(conn, :forbidden) +    end +  end +    describe "PATCH /users/:nickname/force_password_reset" do      test "sets password_reset_pending to true", %{conn: conn} do        user = insert(:user) diff --git a/test/web/chat_channel_test.exs b/test/web/chat_channel_test.exs index 68c24a9f9..f18f3a212 100644 --- a/test/web/chat_channel_test.exs +++ b/test/web/chat_channel_test.exs @@ -21,7 +21,7 @@ defmodule Pleroma.Web.ChatChannelTest do    end    describe "message lengths" do -    clear_config([:instance, :chat_limit]) +    setup do: clear_config([:instance, :chat_limit])      test "it ignores messages of length zero", %{socket: socket} do        push(socket, "new_msg", %{"text" => ""}) diff --git a/test/web/common_api/common_api_test.exs b/test/web/common_api/common_api_test.exs index 299d968db..0da0bd2e2 100644 --- a/test/web/common_api/common_api_test.exs +++ b/test/web/common_api/common_api_test.exs @@ -17,9 +17,9 @@ defmodule Pleroma.Web.CommonAPITest do    require Pleroma.Constants -  clear_config([:instance, :safe_dm_mentions]) -  clear_config([:instance, :limit]) -  clear_config([:instance, :max_pinned_statuses]) +  setup do: clear_config([:instance, :safe_dm_mentions]) +  setup do: clear_config([:instance, :limit]) +  setup do: clear_config([:instance, :max_pinned_statuses])    test "when replying to a conversation / participation, it will set the correct context id even if no explicit reply_to is given" do      user = insert(:user) @@ -202,13 +202,15 @@ defmodule Pleroma.Web.CommonAPITest do                 CommonAPI.post(user, %{"status" => ""})      end -    test "it returns error when character limit is exceeded" do +    test "it validates character limits are correctly enforced" do        Pleroma.Config.put([:instance, :limit], 5)        user = insert(:user)        assert {:error, "The status is over the character limit"} =                 CommonAPI.post(user, %{"status" => "foobar"}) + +      assert {:ok, activity} = CommonAPI.post(user, %{"status" => "12345"})      end      test "it can handle activities that expire" do diff --git a/test/web/common_api/common_api_utils_test.exs b/test/web/common_api/common_api_utils_test.exs index b380d10d8..45fc94522 100644 --- a/test/web/common_api/common_api_utils_test.exs +++ b/test/web/common_api/common_api_utils_test.exs @@ -89,8 +89,8 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do        assert output == expected -      text = "<p>hello world!</p>\n\n<p>second paragraph</p>" -      expected = "<p>hello world!</p>\n\n<p>second paragraph</p>" +      text = "<p>hello world!</p><br/>\n<p>second paragraph</p>" +      expected = "<p>hello world!</p><br/>\n<p>second paragraph</p>"        {output, [], []} = Utils.format_input(text, "text/html") @@ -99,14 +99,14 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do      test "works for bare text/markdown" do        text = "**hello world**" -      expected = "<p><strong>hello world</strong></p>\n" +      expected = "<p><strong>hello world</strong></p>"        {output, [], []} = Utils.format_input(text, "text/markdown")        assert output == expected        text = "**hello world**\n\n*another paragraph*" -      expected = "<p><strong>hello world</strong></p>\n<p><em>another paragraph</em></p>\n" +      expected = "<p><strong>hello world</strong></p><p><em>another paragraph</em></p>"        {output, [], []} = Utils.format_input(text, "text/markdown") @@ -118,7 +118,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do        by someone        """ -      expected = "<blockquote><p>cool quote</p>\n</blockquote>\n<p>by someone</p>\n" +      expected = "<blockquote><p>cool quote</p></blockquote><p>by someone</p>"        {output, [], []} = Utils.format_input(text, "text/markdown") @@ -134,7 +134,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do        assert output == expected        text = "[b]hello world![/b]\n\nsecond paragraph!" -      expected = "<strong>hello world!</strong><br>\n<br>\nsecond paragraph!" +      expected = "<strong>hello world!</strong><br><br>second paragraph!"        {output, [], []} = Utils.format_input(text, "text/bbcode") @@ -143,7 +143,7 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do        text = "[b]hello world![/b]\n\n<strong>second paragraph!</strong>"        expected = -        "<strong>hello world!</strong><br>\n<br>\n<strong>second paragraph!</strong>" +        "<strong>hello world!</strong><br><br><strong>second paragraph!</strong>"        {output, [], []} = Utils.format_input(text, "text/bbcode") @@ -156,16 +156,14 @@ defmodule Pleroma.Web.CommonAPI.UtilsTest do        text = "**hello world**\n\n*another @user__test and @user__test google.com paragraph*" -      expected = -        ~s(<p><strong>hello world</strong></p>\n<p><em>another <span class="h-card"><a data-user="#{ -          user.id -        }" class="u-url mention" href="http://foo.com/user__test" rel="ugc">@<span>user__test</span></a></span> and <span class="h-card"><a data-user="#{ -          user.id -        }" class="u-url mention" href="http://foo.com/user__test" rel="ugc">@<span>user__test</span></a></span> <a href="http://google.com" rel="ugc">google.com</a> paragraph</em></p>\n) -        {output, _, _} = Utils.format_input(text, "text/markdown") -      assert output == expected +      assert output == +               ~s(<p><strong>hello world</strong></p><p><em>another <span class="h-card"><a data-user="#{ +                 user.id +               }" class="u-url mention" href="http://foo.com/user__test" rel="ugc">@<span>user__test</span></a></span> and <span class="h-card"><a data-user="#{ +                 user.id +               }" class="u-url mention" href="http://foo.com/user__test" rel="ugc">@<span>user__test</span></a></span> <a href="http://google.com" rel="ugc">google.com</a> paragraph</em></p>)      end    end diff --git a/test/web/federator_test.exs b/test/web/federator_test.exs index d2ee2267c..da844c24c 100644 --- a/test/web/federator_test.exs +++ b/test/web/federator_test.exs @@ -21,13 +21,10 @@ defmodule Pleroma.Web.FederatorTest do      :ok    end -  clear_config_all([:instance, :federating]) do -    Pleroma.Config.put([:instance, :federating], true) -  end - -  clear_config([:instance, :allow_relay]) -  clear_config([:instance, :rewrite_policy]) -  clear_config([:mrf_keyword]) +  setup_all do: clear_config([:instance, :federating], true) +  setup do: clear_config([:instance, :allow_relay]) +  setup do: clear_config([:instance, :rewrite_policy]) +  setup do: clear_config([:mrf_keyword])    describe "Publish an activity" do      setup do diff --git a/test/web/feed/tag_controller_test.exs b/test/web/feed/tag_controller_test.exs index 5950605e8..e863df86b 100644 --- a/test/web/feed/tag_controller_test.exs +++ b/test/web/feed/tag_controller_test.exs @@ -8,9 +8,11 @@ defmodule Pleroma.Web.Feed.TagControllerTest do    import Pleroma.Factory    import SweetXml +  alias Pleroma.Object +  alias Pleroma.Web.CommonAPI    alias Pleroma.Web.Feed.FeedView -  clear_config([:feed]) +  setup do: clear_config([:feed])    test "gets a feed (ATOM)", %{conn: conn} do      Pleroma.Config.put( @@ -19,9 +21,9 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      )      user = insert(:user) -    {:ok, activity1} = Pleroma.Web.CommonAPI.post(user, %{"status" => "yeah #PleromaArt"}) +    {:ok, activity1} = CommonAPI.post(user, %{"status" => "yeah #PleromaArt"}) -    object = Pleroma.Object.normalize(activity1) +    object = Object.normalize(activity1)      object_data =        Map.put(object.data, "attachment", [ @@ -41,14 +43,13 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      |> Ecto.Changeset.change(data: object_data)      |> Pleroma.Repo.update() -    {:ok, _activity2} = -      Pleroma.Web.CommonAPI.post(user, %{"status" => "42 This is :moominmamma #PleromaArt"}) +    {:ok, activity2} = CommonAPI.post(user, %{"status" => "42 This is :moominmamma #PleromaArt"}) -    {:ok, _activity3} = Pleroma.Web.CommonAPI.post(user, %{"status" => "This is :moominmamma"}) +    {:ok, _activity3} = CommonAPI.post(user, %{"status" => "This is :moominmamma"})      response =        conn -      |> put_req_header("content-type", "application/atom+xml") +      |> put_req_header("accept", "application/atom+xml")        |> get(tag_feed_path(conn, :feed, "pleromaart.atom"))        |> response(200) @@ -63,6 +64,21 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      assert xpath(xml, ~x"//feed/entry/author/name/text()"ls) == [user.nickname, user.nickname]      assert xpath(xml, ~x"//feed/entry/author/id/text()"ls) == [user.ap_id, user.ap_id] + +    conn = +      conn +      |> put_req_header("accept", "application/atom+xml") +      |> get("/tags/pleromaart.atom", %{"max_id" => activity2.id}) + +    assert get_resp_header(conn, "content-type") == ["application/atom+xml; charset=utf-8"] +    resp = response(conn, 200) +    xml = parse(resp) + +    assert xpath(xml, ~x"//feed/title/text()") == '#pleromaart' + +    assert xpath(xml, ~x"//feed/entry/title/text()"l) == [ +             'yeah #PleromaArt' +           ]    end    test "gets a feed (RSS)", %{conn: conn} do @@ -72,9 +88,9 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      )      user = insert(:user) -    {:ok, activity1} = Pleroma.Web.CommonAPI.post(user, %{"status" => "yeah #PleromaArt"}) +    {:ok, activity1} = CommonAPI.post(user, %{"status" => "yeah #PleromaArt"}) -    object = Pleroma.Object.normalize(activity1) +    object = Object.normalize(activity1)      object_data =        Map.put(object.data, "attachment", [ @@ -94,14 +110,13 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      |> Ecto.Changeset.change(data: object_data)      |> Pleroma.Repo.update() -    {:ok, activity2} = -      Pleroma.Web.CommonAPI.post(user, %{"status" => "42 This is :moominmamma #PleromaArt"}) +    {:ok, activity2} = CommonAPI.post(user, %{"status" => "42 This is :moominmamma #PleromaArt"}) -    {:ok, _activity3} = Pleroma.Web.CommonAPI.post(user, %{"status" => "This is :moominmamma"}) +    {:ok, _activity3} = CommonAPI.post(user, %{"status" => "This is :moominmamma"})      response =        conn -      |> put_req_header("content-type", "application/rss+xml") +      |> put_req_header("accept", "application/rss+xml")        |> get(tag_feed_path(conn, :feed, "pleromaart.rss"))        |> response(200) @@ -131,8 +146,8 @@ defmodule Pleroma.Web.Feed.TagControllerTest do               "https://peertube.moe/static/webseed/df5f464b-be8d-46fb-ad81-2d4c2d1630e3-480.mp4"             ] -    obj1 = Pleroma.Object.normalize(activity1) -    obj2 = Pleroma.Object.normalize(activity2) +    obj1 = Object.normalize(activity1) +    obj2 = Object.normalize(activity2)      assert xpath(xml, ~x"//channel/item/description/text()"sl) == [               HtmlEntities.decode(FeedView.activity_content(obj2)), @@ -141,7 +156,7 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      response =        conn -      |> put_req_header("content-type", "application/atom+xml") +      |> put_req_header("accept", "application/rss+xml")        |> get(tag_feed_path(conn, :feed, "pleromaart"))        |> response(200) @@ -150,5 +165,20 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      assert xpath(xml, ~x"//channel/description/text()"s) ==               "These are public toots tagged with #pleromaart. You can interact with them if you have an account anywhere in the fediverse." + +    conn = +      conn +      |> put_req_header("accept", "application/rss+xml") +      |> get("/tags/pleromaart.rss", %{"max_id" => activity2.id}) + +    assert get_resp_header(conn, "content-type") == ["application/rss+xml; charset=utf-8"] +    resp = response(conn, 200) +    xml = parse(resp) + +    assert xpath(xml, ~x"//channel/title/text()") == '#pleromaart' + +    assert xpath(xml, ~x"//channel/item/title/text()"l) == [ +             'yeah #PleromaArt' +           ]    end  end diff --git a/test/web/feed/user_controller_test.exs b/test/web/feed/user_controller_test.exs index 19a019060..05ad427c2 100644 --- a/test/web/feed/user_controller_test.exs +++ b/test/web/feed/user_controller_test.exs @@ -8,244 +8,207 @@ defmodule Pleroma.Web.Feed.UserControllerTest do    import Pleroma.Factory    import SweetXml +  alias Pleroma.Config    alias Pleroma.Object    alias Pleroma.User -  clear_config([:feed]) - -  test "gets a feed", %{conn: conn} do -    Pleroma.Config.put( -      [:feed, :post_title], -      %{max_length: 10, omission: "..."} -    ) - -    activity = insert(:note_activity) - -    note = -      insert(:note, -        data: %{ -          "content" => "This is :moominmamma: note ", -          "attachment" => [ -            %{ -              "url" => [%{"mediaType" => "image/png", "href" => "https://pleroma.gov/image.png"}] -            } -          ], -          "inReplyTo" => activity.data["id"] -        } -      ) +  setup do: clear_config([:instance, :federating], true) -    note_activity = insert(:note_activity, note: note) -    user = User.get_cached_by_ap_id(note_activity.data["actor"]) +  describe "feed" do +    setup do: clear_config([:feed]) -    note2 = -      insert(:note, -        user: user, -        data: %{"content" => "42 This is :moominmamma: note ", "inReplyTo" => activity.data["id"]} +    test "gets a feed", %{conn: conn} do +      Config.put( +        [:feed, :post_title], +        %{max_length: 10, omission: "..."}        ) -    _note_activity2 = insert(:note_activity, note: note2) -    object = Object.normalize(note_activity) - -    resp = -      conn -      |> put_req_header("content-type", "application/atom+xml") -      |> get(user_feed_path(conn, :feed, user.nickname)) -      |> response(200) +      activity = insert(:note_activity) + +      note = +        insert(:note, +          data: %{ +            "content" => "This is :moominmamma: note ", +            "attachment" => [ +              %{ +                "url" => [ +                  %{"mediaType" => "image/png", "href" => "https://pleroma.gov/image.png"} +                ] +              } +            ], +            "inReplyTo" => activity.data["id"] +          } +        ) + +      note_activity = insert(:note_activity, note: note) +      user = User.get_cached_by_ap_id(note_activity.data["actor"]) -    activity_titles = -      resp -      |> SweetXml.parse() -      |> SweetXml.xpath(~x"//entry/title/text()"l) +      note2 = +        insert(:note, +          user: user, +          data: %{ +            "content" => "42 This is :moominmamma: note ", +            "inReplyTo" => activity.data["id"] +          } +        ) -    assert activity_titles == ['42 This...', 'This is...'] -    assert resp =~ object.data["content"] -  end +      note_activity2 = insert(:note_activity, note: note2) +      object = Object.normalize(note_activity) -  test "returns 404 for a missing feed", %{conn: conn} do -    conn = -      conn -      |> put_req_header("content-type", "application/atom+xml") -      |> get(user_feed_path(conn, :feed, "nonexisting")) +      resp = +        conn +        |> put_req_header("accept", "application/atom+xml") +        |> get(user_feed_path(conn, :feed, user.nickname)) +        |> response(200) -    assert response(conn, 404) -  end +      activity_titles = +        resp +        |> SweetXml.parse() +        |> SweetXml.xpath(~x"//entry/title/text()"l) -  describe "feed_redirect" do -    test "undefined format. it redirects to feed", %{conn: conn} do -      note_activity = insert(:note_activity) -      user = User.get_cached_by_ap_id(note_activity.data["actor"]) +      assert activity_titles == ['42 This...', 'This is...'] +      assert resp =~ object.data["content"] -      response = +      resp =          conn -        |> put_req_header("accept", "application/xml") -        |> get("/users/#{user.nickname}") -        |> response(302) +        |> put_req_header("accept", "application/atom+xml") +        |> get("/users/#{user.nickname}/feed", %{"max_id" => note_activity2.id}) +        |> response(200) -      assert response == -               "<html><body>You are being <a href=\"#{Pleroma.Web.base_url()}/users/#{ -                 user.nickname -               }/feed.atom\">redirected</a>.</body></html>" +      activity_titles = +        resp +        |> SweetXml.parse() +        |> SweetXml.xpath(~x"//entry/title/text()"l) + +      assert activity_titles == ['This is...']      end -    test "undefined format. it returns error when user not found", %{conn: conn} do -      response = +    test "gets a rss feed", %{conn: conn} do +      Pleroma.Config.put( +        [:feed, :post_title], +        %{max_length: 10, omission: "..."} +      ) + +      activity = insert(:note_activity) + +      note = +        insert(:note, +          data: %{ +            "content" => "This is :moominmamma: note ", +            "attachment" => [ +              %{ +                "url" => [ +                  %{"mediaType" => "image/png", "href" => "https://pleroma.gov/image.png"} +                ] +              } +            ], +            "inReplyTo" => activity.data["id"] +          } +        ) + +      note_activity = insert(:note_activity, note: note) +      user = User.get_cached_by_ap_id(note_activity.data["actor"]) + +      note2 = +        insert(:note, +          user: user, +          data: %{ +            "content" => "42 This is :moominmamma: note ", +            "inReplyTo" => activity.data["id"] +          } +        ) + +      note_activity2 = insert(:note_activity, note: note2) +      object = Object.normalize(note_activity) + +      resp =          conn -        |> put_req_header("accept", "application/xml") -        |> get(user_feed_path(conn, :feed, "jimm")) -        |> response(404) +        |> put_req_header("accept", "application/rss+xml") +        |> get("/users/#{user.nickname}/feed.rss") +        |> response(200) -      assert response == ~S({"error":"Not found"}) -    end +      activity_titles = +        resp +        |> SweetXml.parse() +        |> SweetXml.xpath(~x"//item/title/text()"l) -    test "activity+json format. it redirects on actual feed of user", %{conn: conn} do -      note_activity = insert(:note_activity) -      user = User.get_cached_by_ap_id(note_activity.data["actor"]) +      assert activity_titles == ['42 This...', 'This is...'] +      assert resp =~ object.data["content"] -      response = +      resp =          conn -        |> put_req_header("accept", "application/activity+json") -        |> get("/users/#{user.nickname}") -        |> json_response(200) - -      assert response["endpoints"] == %{ -               "oauthAuthorizationEndpoint" => "#{Pleroma.Web.base_url()}/oauth/authorize", -               "oauthRegistrationEndpoint" => "#{Pleroma.Web.base_url()}/api/v1/apps", -               "oauthTokenEndpoint" => "#{Pleroma.Web.base_url()}/oauth/token", -               "sharedInbox" => "#{Pleroma.Web.base_url()}/inbox", -               "uploadMedia" => "#{Pleroma.Web.base_url()}/api/ap/upload_media" -             } - -      assert response["@context"] == [ -               "https://www.w3.org/ns/activitystreams", -               "http://localhost:4001/schemas/litepub-0.1.jsonld", -               %{"@language" => "und"} -             ] - -      assert Map.take(response, [ -               "followers", -               "following", -               "id", -               "inbox", -               "manuallyApprovesFollowers", -               "name", -               "outbox", -               "preferredUsername", -               "summary", -               "tag", -               "type", -               "url" -             ]) == %{ -               "followers" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}/followers", -               "following" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}/following", -               "id" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}", -               "inbox" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}/inbox", -               "manuallyApprovesFollowers" => false, -               "name" => user.name, -               "outbox" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}/outbox", -               "preferredUsername" => user.nickname, -               "summary" => user.bio, -               "tag" => [], -               "type" => "Person", -               "url" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}" -             } +        |> put_req_header("accept", "application/rss+xml") +        |> get("/users/#{user.nickname}/feed.rss", %{"max_id" => note_activity2.id}) +        |> response(200) + +      activity_titles = +        resp +        |> SweetXml.parse() +        |> SweetXml.xpath(~x"//item/title/text()"l) + +      assert activity_titles == ['This is...']      end -    test "activity+json format. it returns error whe use not found", %{conn: conn} do -      response = +    test "returns 404 for a missing feed", %{conn: conn} do +      conn =          conn -        |> put_req_header("accept", "application/activity+json") -        |> get("/users/jimm") -        |> json_response(404) +        |> put_req_header("accept", "application/atom+xml") +        |> get(user_feed_path(conn, :feed, "nonexisting")) -      assert response == "Not found" +      assert response(conn, 404)      end +  end -    test "json format. it redirects on actual feed of user", %{conn: conn} do +  # Note: see ActivityPubControllerTest for JSON format tests +  describe "feed_redirect" do +    test "with html format, it redirects to user feed", %{conn: conn} do        note_activity = insert(:note_activity)        user = User.get_cached_by_ap_id(note_activity.data["actor"])        response =          conn -        |> put_req_header("accept", "application/json")          |> get("/users/#{user.nickname}") -        |> json_response(200) - -      assert response["endpoints"] == %{ -               "oauthAuthorizationEndpoint" => "#{Pleroma.Web.base_url()}/oauth/authorize", -               "oauthRegistrationEndpoint" => "#{Pleroma.Web.base_url()}/api/v1/apps", -               "oauthTokenEndpoint" => "#{Pleroma.Web.base_url()}/oauth/token", -               "sharedInbox" => "#{Pleroma.Web.base_url()}/inbox", -               "uploadMedia" => "#{Pleroma.Web.base_url()}/api/ap/upload_media" -             } - -      assert response["@context"] == [ -               "https://www.w3.org/ns/activitystreams", -               "http://localhost:4001/schemas/litepub-0.1.jsonld", -               %{"@language" => "und"} -             ] - -      assert Map.take(response, [ -               "followers", -               "following", -               "id", -               "inbox", -               "manuallyApprovesFollowers", -               "name", -               "outbox", -               "preferredUsername", -               "summary", -               "tag", -               "type", -               "url" -             ]) == %{ -               "followers" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}/followers", -               "following" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}/following", -               "id" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}", -               "inbox" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}/inbox", -               "manuallyApprovesFollowers" => false, -               "name" => user.name, -               "outbox" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}/outbox", -               "preferredUsername" => user.nickname, -               "summary" => user.bio, -               "tag" => [], -               "type" => "Person", -               "url" => "#{Pleroma.Web.base_url()}/users/#{user.nickname}" -             } +        |> response(200) + +      assert response == +               Fallback.RedirectController.redirector_with_meta( +                 conn, +                 %{user: user} +               ).resp_body      end -    test "json format. it returns error whe use not found", %{conn: conn} do +    test "with html format, it returns error when user is not found", %{conn: conn} do        response =          conn -        |> put_req_header("accept", "application/json")          |> get("/users/jimm")          |> json_response(404) -      assert response == "Not found" +      assert response == %{"error" => "Not found"}      end -    test "html format. it redirects on actual feed of user", %{conn: conn} do +    test "with non-html / non-json format, it redirects to user feed in atom format", %{ +      conn: conn +    } do        note_activity = insert(:note_activity)        user = User.get_cached_by_ap_id(note_activity.data["actor"]) -      response = +      conn =          conn +        |> put_req_header("accept", "application/xml")          |> get("/users/#{user.nickname}") -        |> response(200) -      assert response == -               Fallback.RedirectController.redirector_with_meta( -                 conn, -                 %{user: user} -               ).resp_body +      assert conn.status == 302 +      assert redirected_to(conn) == "#{Pleroma.Web.base_url()}/users/#{user.nickname}/feed.atom"      end -    test "html format. it returns error when user not found", %{conn: conn} do +    test "with non-html / non-json format, it returns error when user is not found", %{conn: conn} do        response =          conn -        |> get("/users/jimm") -        |> json_response(404) +        |> put_req_header("accept", "application/xml") +        |> get(user_feed_path(conn, :feed, "jimm")) +        |> response(404) -      assert response == %{"error" => "Not found"} +      assert response == ~S({"error":"Not found"})      end    end  end diff --git a/test/web/instances/instance_test.exs b/test/web/instances/instance_test.exs index a3c93b986..e463200ca 100644 --- a/test/web/instances/instance_test.exs +++ b/test/web/instances/instance_test.exs @@ -10,9 +10,7 @@ defmodule Pleroma.Instances.InstanceTest do    import Pleroma.Factory -  clear_config_all([:instance, :federation_reachability_timeout_days]) do -    Pleroma.Config.put([:instance, :federation_reachability_timeout_days], 1) -  end +  setup_all do: clear_config([:instance, :federation_reachability_timeout_days], 1)    describe "set_reachable/1" do      test "clears `unreachable_since` of existing matching Instance record having non-nil `unreachable_since`" do diff --git a/test/web/instances/instances_test.exs b/test/web/instances/instances_test.exs index c5d6abc9c..d2618025c 100644 --- a/test/web/instances/instances_test.exs +++ b/test/web/instances/instances_test.exs @@ -7,9 +7,7 @@ defmodule Pleroma.InstancesTest do    use Pleroma.DataCase -  clear_config_all([:instance, :federation_reachability_timeout_days]) do -    Pleroma.Config.put([:instance, :federation_reachability_timeout_days], 1) -  end +  setup_all do: clear_config([:instance, :federation_reachability_timeout_days], 1)    describe "reachable?/1" do      test "returns `true` for host / url with unknown reachability status" do diff --git a/test/web/masto_fe_controller_test.exs b/test/web/masto_fe_controller_test.exs index 9a2d76e0b..1d107d56c 100644 --- a/test/web/masto_fe_controller_test.exs +++ b/test/web/masto_fe_controller_test.exs @@ -10,7 +10,7 @@ defmodule Pleroma.Web.MastodonAPI.MastoFEController do    import Pleroma.Factory -  clear_config([:instance, :public]) +  setup do: clear_config([:instance, :public])    test "put settings", %{conn: conn} do      user = insert(:user) diff --git a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs index cba68859e..b693c1a47 100644 --- a/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs +++ b/test/web/mastodon_api/controllers/account_controller/update_credentials_test.exs @@ -9,7 +9,8 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do    use Pleroma.Web.ConnCase    import Pleroma.Factory -  clear_config([:instance, :max_account_fields]) + +  setup do: clear_config([:instance, :max_account_fields])    describe "updating credentials" do      setup do: oauth_access(["write:accounts"]) @@ -75,7 +76,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do        conn =          patch(conn, "/api/v1/accounts/update_credentials", %{ -          "note" => "I drink #cofe with @#{user2.nickname}" +          "note" => "I drink #cofe with @#{user2.nickname}\n\nsuya.."          })        assert user_data = json_response(conn, 200) @@ -83,7 +84,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do        assert user_data["note"] ==                 ~s(I drink <a class="hashtag" data-tag="cofe" href="http://localhost:4001/tag/cofe">#cofe</a> with <span class="h-card"><a data-user="#{                   user2.id -               }" class="u-url mention" href="#{user2.ap_id}" rel="ugc">@<span>#{user2.nickname}</span></a></span>) +               }" class="u-url mention" href="#{user2.ap_id}" rel="ugc">@<span>#{user2.nickname}</span></a></span><br/><br/>suya..)      end      test "updates the user's locking status", %{conn: conn} do @@ -117,6 +118,18 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController.UpdateCredentialsTest do        assert user_data["pleroma"]["hide_followers"] == true      end +    test "updates the user's discoverable status", %{conn: conn} do +      assert %{"source" => %{"pleroma" => %{"discoverable" => true}}} = +               conn +               |> patch("/api/v1/accounts/update_credentials", %{discoverable: "true"}) +               |> json_response(:ok) + +      assert %{"source" => %{"pleroma" => %{"discoverable" => false}}} = +               conn +               |> patch("/api/v1/accounts/update_credentials", %{discoverable: "false"}) +               |> json_response(:ok) +    end +      test "updates the user's hide_followers_count and hide_follows_count", %{conn: conn} do        conn =          patch(conn, "/api/v1/accounts/update_credentials", %{ diff --git a/test/web/mastodon_api/controllers/account_controller_test.exs b/test/web/mastodon_api/controllers/account_controller_test.exs index 57d0f4416..a9fa0ce48 100644 --- a/test/web/mastodon_api/controllers/account_controller_test.exs +++ b/test/web/mastodon_api/controllers/account_controller_test.exs @@ -5,6 +5,7 @@  defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do    use Pleroma.Web.ConnCase +  alias Pleroma.Config    alias Pleroma.Repo    alias Pleroma.User    alias Pleroma.Web.ActivityPub.ActivityPub @@ -15,7 +16,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do    import Pleroma.Factory    describe "account fetching" do -    clear_config([:instance, :limit_to_local_content]) +    setup do: clear_config([:instance, :limit_to_local_content])      test "works by id" do        user = insert(:user) @@ -46,7 +47,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      end      test "works by nickname for remote users" do -      Pleroma.Config.put([:instance, :limit_to_local_content], false) +      Config.put([:instance, :limit_to_local_content], false)        user = insert(:user, nickname: "user@example.com", local: false)        conn = @@ -58,7 +59,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      end      test "respects limit_to_local_content == :all for remote user nicknames" do -      Pleroma.Config.put([:instance, :limit_to_local_content], :all) +      Config.put([:instance, :limit_to_local_content], :all)        user = insert(:user, nickname: "user@example.com", local: false) @@ -70,7 +71,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      end      test "respects limit_to_local_content == :unauthenticated for remote user nicknames" do -      Pleroma.Config.put([:instance, :limit_to_local_content], :unauthenticated) +      Config.put([:instance, :limit_to_local_content], :unauthenticated)        user = insert(:user, nickname: "user@example.com", local: false)        reading_user = insert(:user) @@ -140,6 +141,98 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      end    end +  defp local_and_remote_users do +    local = insert(:user) +    remote = insert(:user, local: false) +    {:ok, local: local, remote: remote} +  end + +  describe "user fetching with restrict unauthenticated profiles for local and remote" do +    setup do: local_and_remote_users() + +    setup do: clear_config([:restrict_unauthenticated, :profiles, :local], true) + +    setup do: clear_config([:restrict_unauthenticated, :profiles, :remote], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/accounts/#{local.id}") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Can't find user" +             } + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Can't find user" +             } +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/accounts/#{local.id}") +      assert %{"id" => _} = json_response(res_conn, 200) + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}") +      assert %{"id" => _} = json_response(res_conn, 200) +    end +  end + +  describe "user fetching with restrict unauthenticated profiles for local" do +    setup do: local_and_remote_users() + +    setup do: clear_config([:restrict_unauthenticated, :profiles, :local], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/accounts/#{local.id}") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Can't find user" +             } + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}") +      assert %{"id" => _} = json_response(res_conn, 200) +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/accounts/#{local.id}") +      assert %{"id" => _} = json_response(res_conn, 200) + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}") +      assert %{"id" => _} = json_response(res_conn, 200) +    end +  end + +  describe "user fetching with restrict unauthenticated profiles for remote" do +    setup do: local_and_remote_users() + +    setup do: clear_config([:restrict_unauthenticated, :profiles, :remote], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/accounts/#{local.id}") +      assert %{"id" => _} = json_response(res_conn, 200) + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Can't find user" +             } +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/accounts/#{local.id}") +      assert %{"id" => _} = json_response(res_conn, 200) + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}") +      assert %{"id" => _} = json_response(res_conn, 200) +    end +  end +    describe "user timelines" do      setup do: oauth_access(["read:statuses"]) @@ -293,6 +386,102 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      end    end +  defp local_and_remote_activities(%{local: local, remote: remote}) do +    insert(:note_activity, user: local) +    insert(:note_activity, user: remote, local: false) + +    :ok +  end + +  describe "statuses with restrict unauthenticated profiles for local and remote" do +    setup do: local_and_remote_users() +    setup :local_and_remote_activities + +    setup do: clear_config([:restrict_unauthenticated, :profiles, :local], true) + +    setup do: clear_config([:restrict_unauthenticated, :profiles, :remote], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Can't find user" +             } + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Can't find user" +             } +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses") +      assert length(json_response(res_conn, 200)) == 1 + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses") +      assert length(json_response(res_conn, 200)) == 1 +    end +  end + +  describe "statuses with restrict unauthenticated profiles for local" do +    setup do: local_and_remote_users() +    setup :local_and_remote_activities + +    setup do: clear_config([:restrict_unauthenticated, :profiles, :local], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Can't find user" +             } + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses") +      assert length(json_response(res_conn, 200)) == 1 +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses") +      assert length(json_response(res_conn, 200)) == 1 + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses") +      assert length(json_response(res_conn, 200)) == 1 +    end +  end + +  describe "statuses with restrict unauthenticated profiles for remote" do +    setup do: local_and_remote_users() +    setup :local_and_remote_activities + +    setup do: clear_config([:restrict_unauthenticated, :profiles, :remote], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses") +      assert length(json_response(res_conn, 200)) == 1 + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Can't find user" +             } +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/accounts/#{local.id}/statuses") +      assert length(json_response(res_conn, 200)) == 1 + +      res_conn = get(conn, "/api/v1/accounts/#{remote.id}/statuses") +      assert length(json_response(res_conn, 200)) == 1 +    end +  end +    describe "followers" do      setup do: oauth_access(["read:accounts"]) @@ -601,6 +790,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        [valid_params: valid_params]      end +    setup do: clear_config([:instance, :account_activation_required]) +      test "Account registration via Application", %{conn: conn} do        conn =          post(conn, "/api/v1/apps", %{ @@ -685,7 +876,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        assert json_response(res, 200)        [{127, 0, 0, 1}, {127, 0, 0, 2}, {127, 0, 0, 3}, {127, 0, 0, 4}] -      |> Stream.zip(valid_params) +      |> Stream.zip(Map.delete(valid_params, :email))        |> Enum.each(fn {ip, {attr, _}} ->          res =            conn @@ -697,6 +888,54 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        end)      end +    setup do: clear_config([:instance, :account_activation_required]) + +    test "returns bad_request if missing email params when :account_activation_required is enabled", +         %{conn: conn, valid_params: valid_params} do +      Pleroma.Config.put([:instance, :account_activation_required], true) + +      app_token = insert(:oauth_token, user: nil) +      conn = put_req_header(conn, "authorization", "Bearer " <> app_token.token) + +      res = +        conn +        |> Map.put(:remote_ip, {127, 0, 0, 5}) +        |> post("/api/v1/accounts", Map.delete(valid_params, :email)) + +      assert json_response(res, 400) == %{"error" => "Missing parameters"} + +      res = +        conn +        |> Map.put(:remote_ip, {127, 0, 0, 6}) +        |> post("/api/v1/accounts", Map.put(valid_params, :email, "")) + +      assert json_response(res, 400) == %{"error" => "{\"email\":[\"can't be blank\"]}"} +    end + +    test "allow registration without an email", %{conn: conn, valid_params: valid_params} do +      app_token = insert(:oauth_token, user: nil) +      conn = put_req_header(conn, "authorization", "Bearer " <> app_token.token) + +      res = +        conn +        |> Map.put(:remote_ip, {127, 0, 0, 7}) +        |> post("/api/v1/accounts", Map.delete(valid_params, :email)) + +      assert json_response(res, 200) +    end + +    test "allow registration with an empty email", %{conn: conn, valid_params: valid_params} do +      app_token = insert(:oauth_token, user: nil) +      conn = put_req_header(conn, "authorization", "Bearer " <> app_token.token) + +      res = +        conn +        |> Map.put(:remote_ip, {127, 0, 0, 8}) +        |> post("/api/v1/accounts", Map.put(valid_params, :email, "")) + +      assert json_response(res, 200) +    end +      test "returns forbidden if token is invalid", %{conn: conn, valid_params: valid_params} do        conn = put_req_header(conn, "authorization", "Bearer " <> "invalid-token") @@ -706,13 +945,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do    end    describe "create account by app / rate limit" do -    clear_config([Pleroma.Plugs.RemoteIp, :enabled]) do -      Pleroma.Config.put([Pleroma.Plugs.RemoteIp, :enabled], true) -    end - -    clear_config([:rate_limit, :app_account_creation]) do -      Pleroma.Config.put([:rate_limit, :app_account_creation], {10_000, 2}) -    end +    setup do: clear_config([:rate_limit, :app_account_creation], {10_000, 2})      test "respects rate limit setting", %{conn: conn} do        app_token = insert(:oauth_token, user: nil) diff --git a/test/web/mastodon_api/controllers/media_controller_test.exs b/test/web/mastodon_api/controllers/media_controller_test.exs index 203fa73b0..6ac4cf63b 100644 --- a/test/web/mastodon_api/controllers/media_controller_test.exs +++ b/test/web/mastodon_api/controllers/media_controller_test.exs @@ -22,8 +22,8 @@ defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do        [image: image]      end -    clear_config([:media_proxy]) -    clear_config([Pleroma.Upload]) +    setup do: clear_config([:media_proxy]) +    setup do: clear_config([Pleroma.Upload])      test "returns uploaded image", %{conn: conn, image: image} do        desc = "Description of the image" diff --git a/test/web/mastodon_api/controllers/notification_controller_test.exs b/test/web/mastodon_api/controllers/notification_controller_test.exs index d452ddbdd..7a0011646 100644 --- a/test/web/mastodon_api/controllers/notification_controller_test.exs +++ b/test/web/mastodon_api/controllers/notification_controller_test.exs @@ -304,6 +304,51 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do      assert [%{"id" => ^reblog_notification_id}] = json_response(conn_res, 200)    end +  test "filters notifications using include_types" do +    %{user: user, conn: conn} = oauth_access(["read:notifications"]) +    other_user = insert(:user) + +    {:ok, mention_activity} = CommonAPI.post(other_user, %{"status" => "hey @#{user.nickname}"}) +    {:ok, create_activity} = CommonAPI.post(user, %{"status" => "hey"}) +    {:ok, favorite_activity, _} = CommonAPI.favorite(create_activity.id, other_user) +    {:ok, reblog_activity, _} = CommonAPI.repeat(create_activity.id, other_user) +    {:ok, _, _, follow_activity} = CommonAPI.follow(other_user, user) + +    mention_notification_id = get_notification_id_by_activity(mention_activity) +    favorite_notification_id = get_notification_id_by_activity(favorite_activity) +    reblog_notification_id = get_notification_id_by_activity(reblog_activity) +    follow_notification_id = get_notification_id_by_activity(follow_activity) + +    conn_res = get(conn, "/api/v1/notifications", %{include_types: ["follow"]}) + +    assert [%{"id" => ^follow_notification_id}] = json_response(conn_res, 200) + +    conn_res = get(conn, "/api/v1/notifications", %{include_types: ["mention"]}) + +    assert [%{"id" => ^mention_notification_id}] = json_response(conn_res, 200) + +    conn_res = get(conn, "/api/v1/notifications", %{include_types: ["favourite"]}) + +    assert [%{"id" => ^favorite_notification_id}] = json_response(conn_res, 200) + +    conn_res = get(conn, "/api/v1/notifications", %{include_types: ["reblog"]}) + +    assert [%{"id" => ^reblog_notification_id}] = json_response(conn_res, 200) + +    result = conn |> get("/api/v1/notifications") |> json_response(200) + +    assert length(result) == 4 + +    result = +      conn +      |> get("/api/v1/notifications", %{ +        include_types: ["follow", "mention", "favourite", "reblog"] +      }) +      |> json_response(200) + +    assert length(result) == 4 +  end +    test "destroy multiple" do      %{user: user, conn: conn} = oauth_access(["read:notifications", "write:notifications"])      other_user = insert(:user) @@ -407,7 +452,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do      assert length(json_response(conn, 200)) == 1    end -  test "see move notifications with `with_move` parameter" do +  test "see move notifications" do      old_user = insert(:user)      new_user = insert(:user, also_known_as: [old_user.ap_id])      %{user: follower, conn: conn} = oauth_access(["read:notifications"]) @@ -416,11 +461,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do      Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)      Pleroma.Tests.ObanHelpers.perform_all() -    ret_conn = get(conn, "/api/v1/notifications") - -    assert json_response(ret_conn, 200) == [] - -    conn = get(conn, "/api/v1/notifications", %{"with_move" => "true"}) +    conn = get(conn, "/api/v1/notifications")      assert length(json_response(conn, 200)) == 1    end diff --git a/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs b/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs index 3cd08c189..f86274d57 100644 --- a/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs +++ b/test/web/mastodon_api/controllers/scheduled_activity_controller_test.exs @@ -11,7 +11,7 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do    import Pleroma.Factory    import Ecto.Query -  clear_config([ScheduledActivity, :enabled]) +  setup do: clear_config([ScheduledActivity, :enabled])    test "shows scheduled activities" do      %{user: user, conn: conn} = oauth_access(["read:statuses"]) diff --git a/test/web/mastodon_api/controllers/status_controller_test.exs b/test/web/mastodon_api/controllers/status_controller_test.exs index fbf63f608..d59974d50 100644 --- a/test/web/mastodon_api/controllers/status_controller_test.exs +++ b/test/web/mastodon_api/controllers/status_controller_test.exs @@ -19,9 +19,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do    import Pleroma.Factory -  clear_config([:instance, :federating]) -  clear_config([:instance, :allow_relay]) -  clear_config([:rich_media, :enabled]) +  setup do: clear_config([:instance, :federating]) +  setup do: clear_config([:instance, :allow_relay]) +  setup do: clear_config([:rich_media, :enabled])    describe "posting statuses" do      setup do: oauth_access(["write:statuses"]) @@ -476,6 +476,95 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do      assert id == to_string(activity.id)    end +  defp local_and_remote_activities do +    local = insert(:note_activity) +    remote = insert(:note_activity, local: false) +    {:ok, local: local, remote: remote} +  end + +  describe "status with restrict unauthenticated activities for local and remote" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :activities, :local], true) + +    setup do: clear_config([:restrict_unauthenticated, :activities, :remote], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/statuses/#{local.id}") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Record not found" +             } + +      res_conn = get(conn, "/api/v1/statuses/#{remote.id}") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Record not found" +             } +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) +      res_conn = get(conn, "/api/v1/statuses/#{local.id}") +      assert %{"id" => _} = json_response(res_conn, 200) + +      res_conn = get(conn, "/api/v1/statuses/#{remote.id}") +      assert %{"id" => _} = json_response(res_conn, 200) +    end +  end + +  describe "status with restrict unauthenticated activities for local" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :activities, :local], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/statuses/#{local.id}") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Record not found" +             } + +      res_conn = get(conn, "/api/v1/statuses/#{remote.id}") +      assert %{"id" => _} = json_response(res_conn, 200) +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) +      res_conn = get(conn, "/api/v1/statuses/#{local.id}") +      assert %{"id" => _} = json_response(res_conn, 200) + +      res_conn = get(conn, "/api/v1/statuses/#{remote.id}") +      assert %{"id" => _} = json_response(res_conn, 200) +    end +  end + +  describe "status with restrict unauthenticated activities for remote" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :activities, :remote], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/statuses/#{local.id}") +      assert %{"id" => _} = json_response(res_conn, 200) + +      res_conn = get(conn, "/api/v1/statuses/#{remote.id}") + +      assert json_response(res_conn, :not_found) == %{ +               "error" => "Record not found" +             } +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) +      res_conn = get(conn, "/api/v1/statuses/#{local.id}") +      assert %{"id" => _} = json_response(res_conn, 200) + +      res_conn = get(conn, "/api/v1/statuses/#{remote.id}") +      assert %{"id" => _} = json_response(res_conn, 200) +    end +  end +    test "getting a status that doesn't exist returns 404" do      %{conn: conn} = oauth_access(["read:statuses"])      activity = insert(:note_activity) @@ -514,6 +603,70 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do      assert [%{"id" => ^id1}, %{"id" => ^id2}] = Enum.sort_by(json_response(conn, :ok), & &1["id"])    end +  describe "getting statuses by ids with restricted unauthenticated for local and remote" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :activities, :local], true) + +    setup do: clear_config([:restrict_unauthenticated, :activities, :remote], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]}) + +      assert json_response(res_conn, 200) == [] +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]}) + +      assert length(json_response(res_conn, 200)) == 2 +    end +  end + +  describe "getting statuses by ids with restricted unauthenticated for local" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :activities, :local], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]}) + +      remote_id = remote.id +      assert [%{"id" => ^remote_id}] = json_response(res_conn, 200) +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]}) + +      assert length(json_response(res_conn, 200)) == 2 +    end +  end + +  describe "getting statuses by ids with restricted unauthenticated for remote" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :activities, :remote], true) + +    test "if user is unauthenticated", %{conn: conn, local: local, remote: remote} do +      res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]}) + +      local_id = local.id +      assert [%{"id" => ^local_id}] = json_response(res_conn, 200) +    end + +    test "if user is authenticated", %{local: local, remote: remote} do +      %{conn: conn} = oauth_access(["read"]) + +      res_conn = get(conn, "/api/v1/statuses", %{ids: [local.id, remote.id]}) + +      assert length(json_response(res_conn, 200)) == 2 +    end +  end +    describe "deleting a status" do      test "when you created it" do        %{user: author, conn: conn} = oauth_access(["write:statuses"]) @@ -739,9 +892,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do        %{activity: activity}      end -    clear_config([:instance, :max_pinned_statuses]) do -      Config.put([:instance, :max_pinned_statuses], 1) -    end +    setup do: clear_config([:instance, :max_pinned_statuses], 1)      test "pin status", %{conn: conn, user: user, activity: activity} do        id_str = to_string(activity.id) diff --git a/test/web/mastodon_api/controllers/timeline_controller_test.exs b/test/web/mastodon_api/controllers/timeline_controller_test.exs index 2c03b0a75..97b1c3e66 100644 --- a/test/web/mastodon_api/controllers/timeline_controller_test.exs +++ b/test/web/mastodon_api/controllers/timeline_controller_test.exs @@ -12,8 +12,6 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do    alias Pleroma.User    alias Pleroma.Web.CommonAPI -  clear_config([:instance, :public]) -    setup do      mock(fn env -> apply(HttpRequestMock, :request, [env]) end)      :ok @@ -23,9 +21,12 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do      setup do: oauth_access(["read:statuses"])      test "the home timeline", %{user: user, conn: conn} do -      following = insert(:user) +      following = insert(:user, nickname: "followed") +      third_user = insert(:user, nickname: "repeated") -      {:ok, _activity} = CommonAPI.post(following, %{"status" => "test"}) +      {:ok, _activity} = CommonAPI.post(following, %{"status" => "post"}) +      {:ok, activity} = CommonAPI.post(third_user, %{"status" => "repeated post"}) +      {:ok, _, _} = CommonAPI.repeat(activity.id, following)        ret_conn = get(conn, "/api/v1/timelines/home") @@ -33,9 +34,54 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do        {:ok, _user} = User.follow(user, following) -      conn = get(conn, "/api/v1/timelines/home") +      ret_conn = get(conn, "/api/v1/timelines/home") -      assert [%{"content" => "test"}] = json_response(conn, :ok) +      assert [ +               %{ +                 "reblog" => %{ +                   "content" => "repeated post", +                   "account" => %{ +                     "pleroma" => %{ +                       "relationship" => %{"following" => false, "followed_by" => false} +                     } +                   } +                 }, +                 "account" => %{"pleroma" => %{"relationship" => %{"following" => true}}} +               }, +               %{ +                 "content" => "post", +                 "account" => %{ +                   "acct" => "followed", +                   "pleroma" => %{"relationship" => %{"following" => true}} +                 } +               } +             ] = json_response(ret_conn, :ok) + +      {:ok, _user} = User.follow(third_user, user) + +      ret_conn = get(conn, "/api/v1/timelines/home") + +      assert [ +               %{ +                 "reblog" => %{ +                   "content" => "repeated post", +                   "account" => %{ +                     "acct" => "repeated", +                     "pleroma" => %{ +                       "relationship" => %{"following" => false, "followed_by" => true} +                     } +                   } +                 }, +                 "account" => %{"pleroma" => %{"relationship" => %{"following" => true}}} +               }, +               %{ +                 "content" => "post", +                 "account" => %{ +                   "acct" => "followed", +                   "pleroma" => %{"relationship" => %{"following" => true}} +                 } +               } +             ] = json_response(ret_conn, :ok)      end      test "the home timeline when the direct messages are excluded", %{user: user, conn: conn} do @@ -80,15 +126,6 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do        assert [%{"content" => "test"}] = json_response(conn, :ok)      end -    test "the public timeline when public is set to false", %{conn: conn} do -      Config.put([:instance, :public], false) - -      assert %{"error" => "This resource requires authentication."} == -               conn -               |> get("/api/v1/timelines/public", %{"local" => "False"}) -               |> json_response(:forbidden) -    end -      test "the public timeline includes only public statuses for an authenticated user" do        %{user: user, conn: conn} = oauth_access(["read:statuses"]) @@ -102,6 +139,98 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do      end    end +  defp local_and_remote_activities do +    insert(:note_activity) +    insert(:note_activity, local: false) +    :ok +  end + +  describe "public with restrict unauthenticated timeline for local and federated timelines" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :timelines, :local], true) + +    setup do: clear_config([:restrict_unauthenticated, :timelines, :federated], true) + +    test "if user is unauthenticated", %{conn: conn} do +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"}) + +      assert json_response(res_conn, :unauthorized) == %{ +               "error" => "authorization required for timeline view" +             } + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"}) + +      assert json_response(res_conn, :unauthorized) == %{ +               "error" => "authorization required for timeline view" +             } +    end + +    test "if user is authenticated" do +      %{conn: conn} = oauth_access(["read:statuses"]) + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"}) +      assert length(json_response(res_conn, 200)) == 1 + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"}) +      assert length(json_response(res_conn, 200)) == 2 +    end +  end + +  describe "public with restrict unauthenticated timeline for local" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :timelines, :local], true) + +    test "if user is unauthenticated", %{conn: conn} do +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"}) + +      assert json_response(res_conn, :unauthorized) == %{ +               "error" => "authorization required for timeline view" +             } + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"}) +      assert length(json_response(res_conn, 200)) == 2 +    end + +    test "if user is authenticated", %{conn: _conn} do +      %{conn: conn} = oauth_access(["read:statuses"]) + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"}) +      assert length(json_response(res_conn, 200)) == 1 + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"}) +      assert length(json_response(res_conn, 200)) == 2 +    end +  end + +  describe "public with restrict unauthenticated timeline for remote" do +    setup do: local_and_remote_activities() + +    setup do: clear_config([:restrict_unauthenticated, :timelines, :federated], true) + +    test "if user is unauthenticated", %{conn: conn} do +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"}) +      assert length(json_response(res_conn, 200)) == 1 + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"}) + +      assert json_response(res_conn, :unauthorized) == %{ +               "error" => "authorization required for timeline view" +             } +    end + +    test "if user is authenticated", %{conn: _conn} do +      %{conn: conn} = oauth_access(["read:statuses"]) + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "true"}) +      assert length(json_response(res_conn, 200)) == 1 + +      res_conn = get(conn, "/api/v1/timelines/public", %{"local" => "false"}) +      assert length(json_response(res_conn, 200)) == 2 +    end +  end +    describe "direct" do      test "direct timeline", %{conn: conn} do        user_one = insert(:user) diff --git a/test/web/mastodon_api/views/account_view_test.exs b/test/web/mastodon_api/views/account_view_test.exs index d60ed7b64..0d1c3ecb3 100644 --- a/test/web/mastodon_api/views/account_view_test.exs +++ b/test/web/mastodon_api/views/account_view_test.exs @@ -4,8 +4,11 @@  defmodule Pleroma.Web.MastodonAPI.AccountViewTest do    use Pleroma.DataCase +    import Pleroma.Factory +    alias Pleroma.User +  alias Pleroma.UserRelationship    alias Pleroma.Web.CommonAPI    alias Pleroma.Web.MastodonAPI.AccountView @@ -32,7 +35,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do          background: background_image,          nickname: "shp@shitposter.club",          name: ":karjalanpiirakka: shp", -        bio: "<script src=\"invalid-html\"></script><span>valid html</span>", +        bio: +          "<script src=\"invalid-html\"></script><span>valid html</span>. a<br>b<br/>c<br >d<br />f",          inserted_at: ~N[2017-08-15 15:47:06.597036]        }) @@ -46,7 +50,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do        followers_count: 3,        following_count: 0,        statuses_count: 5, -      note: "<span>valid html</span>", +      note: "<span>valid html</span>. a<br/>b<br/>c<br/>d<br/>f",        url: user.ap_id,        avatar: "http://localhost:4001/images/avi.png",        avatar_static: "http://localhost:4001/images/avi.png", @@ -63,7 +67,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do        fields: [],        bot: false,        source: %{ -        note: "valid html", +        note: "valid html. a\nb\nc\nd\nf",          sensitive: false,          pleroma: %{            actor_type: "Person", @@ -181,6 +185,29 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do    end    describe "relationship" do +    defp test_relationship_rendering(user, other_user, expected_result) do +      opts = %{user: user, target: other_user, relationships: nil} +      assert expected_result == AccountView.render("relationship.json", opts) + +      relationships_opt = UserRelationship.view_relationships_option(user, [other_user]) +      opts = Map.put(opts, :relationships, relationships_opt) +      assert expected_result == AccountView.render("relationship.json", opts) +    end + +    @blank_response %{ +      following: false, +      followed_by: false, +      blocking: false, +      blocked_by: false, +      muting: false, +      muting_notifications: false, +      subscribing: false, +      requested: false, +      domain_blocking: false, +      showing_reblogs: true, +      endorsed: false +    } +      test "represent a relationship for the following and followed user" do        user = insert(:user)        other_user = insert(:user) @@ -191,23 +218,21 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do        {:ok, _user_relationships} = User.mute(user, other_user, true)        {:ok, _reblog_mute} = CommonAPI.hide_reblogs(user, other_user) -      expected = %{ -        id: to_string(other_user.id), -        following: true, -        followed_by: true, -        blocking: false, -        blocked_by: false, -        muting: true, -        muting_notifications: true, -        subscribing: true, -        requested: false, -        domain_blocking: false, -        showing_reblogs: false, -        endorsed: false -      } - -      assert expected == -               AccountView.render("relationship.json", %{user: user, target: other_user}) +      expected = +        Map.merge( +          @blank_response, +          %{ +            following: true, +            followed_by: true, +            muting: true, +            muting_notifications: true, +            subscribing: true, +            showing_reblogs: false, +            id: to_string(other_user.id) +          } +        ) + +      test_relationship_rendering(user, other_user, expected)      end      test "represent a relationship for the blocking and blocked user" do @@ -219,23 +244,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do        {:ok, _user_relationship} = User.block(user, other_user)        {:ok, _user_relationship} = User.block(other_user, user) -      expected = %{ -        id: to_string(other_user.id), -        following: false, -        followed_by: false, -        blocking: true, -        blocked_by: true, -        muting: false, -        muting_notifications: false, -        subscribing: false, -        requested: false, -        domain_blocking: false, -        showing_reblogs: true, -        endorsed: false -      } +      expected = +        Map.merge( +          @blank_response, +          %{following: false, blocking: true, blocked_by: true, id: to_string(other_user.id)} +        ) -      assert expected == -               AccountView.render("relationship.json", %{user: user, target: other_user}) +      test_relationship_rendering(user, other_user, expected)      end      test "represent a relationship for the user blocking a domain" do @@ -244,8 +259,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do        {:ok, user} = User.block_domain(user, "bad.site") -      assert %{domain_blocking: true, blocking: false} = -               AccountView.render("relationship.json", %{user: user, target: other_user}) +      expected = +        Map.merge( +          @blank_response, +          %{domain_blocking: true, blocking: false, id: to_string(other_user.id)} +        ) + +      test_relationship_rendering(user, other_user, expected)      end      test "represent a relationship for the user with a pending follow request" do @@ -256,23 +276,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do        user = User.get_cached_by_id(user.id)        other_user = User.get_cached_by_id(other_user.id) -      expected = %{ -        id: to_string(other_user.id), -        following: false, -        followed_by: false, -        blocking: false, -        blocked_by: false, -        muting: false, -        muting_notifications: false, -        subscribing: false, -        requested: true, -        domain_blocking: false, -        showing_reblogs: true, -        endorsed: false -      } +      expected = +        Map.merge( +          @blank_response, +          %{requested: true, following: false, id: to_string(other_user.id)} +        ) -      assert expected == -               AccountView.render("relationship.json", %{user: user, target: other_user}) +      test_relationship_rendering(user, other_user, expected)      end    end diff --git a/test/web/mastodon_api/views/notification_view_test.exs b/test/web/mastodon_api/views/notification_view_test.exs index 4df9c3c03..7965af00a 100644 --- a/test/web/mastodon_api/views/notification_view_test.exs +++ b/test/web/mastodon_api/views/notification_view_test.exs @@ -16,6 +16,21 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do    alias Pleroma.Web.MastodonAPI.StatusView    import Pleroma.Factory +  defp test_notifications_rendering(notifications, user, expected_result) do +    result = NotificationView.render("index.json", %{notifications: notifications, for: user}) + +    assert expected_result == result + +    result = +      NotificationView.render("index.json", %{ +        notifications: notifications, +        for: user, +        relationships: nil +      }) + +    assert expected_result == result +  end +    test "Mention notification" do      user = insert(:user)      mentioned_user = insert(:user) @@ -32,10 +47,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do        created_at: Utils.to_masto_date(notification.inserted_at)      } -    result = -      NotificationView.render("index.json", %{notifications: [notification], for: mentioned_user}) - -    assert [expected] == result +    test_notifications_rendering([notification], mentioned_user, [expected])    end    test "Favourite notification" do @@ -55,9 +67,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do        created_at: Utils.to_masto_date(notification.inserted_at)      } -    result = NotificationView.render("index.json", %{notifications: [notification], for: user}) - -    assert [expected] == result +    test_notifications_rendering([notification], user, [expected])    end    test "Reblog notification" do @@ -77,9 +87,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do        created_at: Utils.to_masto_date(notification.inserted_at)      } -    result = NotificationView.render("index.json", %{notifications: [notification], for: user}) - -    assert [expected] == result +    test_notifications_rendering([notification], user, [expected])    end    test "Follow notification" do @@ -96,16 +104,12 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do        created_at: Utils.to_masto_date(notification.inserted_at)      } -    result = -      NotificationView.render("index.json", %{notifications: [notification], for: followed}) - -    assert [expected] == result +    test_notifications_rendering([notification], followed, [expected])      User.perform(:delete, follower)      notification = Notification |> Repo.one() |> Repo.preload(:activity) -    assert [] == -             NotificationView.render("index.json", %{notifications: [notification], for: followed}) +    test_notifications_rendering([notification], followed, [])    end    test "Move notification" do @@ -120,7 +124,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do      old_user = refresh_record(old_user)      new_user = refresh_record(new_user) -    [notification] = Notification.for_user(follower, %{with_move: true}) +    [notification] = Notification.for_user(follower)      expected = %{        id: to_string(notification.id), @@ -131,8 +135,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do        created_at: Utils.to_masto_date(notification.inserted_at)      } -    assert [expected] == -             NotificationView.render("index.json", %{notifications: [notification], for: follower}) +    test_notifications_rendering([notification], follower, [expected])    end    test "EmojiReact notification" do @@ -158,7 +161,6 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do        created_at: Utils.to_masto_date(notification.inserted_at)      } -    assert expected == -             NotificationView.render("show.json", %{notification: notification, for: user}) +    test_notifications_rendering([notification], user, [expected])    end  end diff --git a/test/web/mastodon_api/views/status_view_test.exs b/test/web/mastodon_api/views/status_view_test.exs index 3e1812a1f..3b6571706 100644 --- a/test/web/mastodon_api/views/status_view_test.exs +++ b/test/web/mastodon_api/views/status_view_test.exs @@ -12,10 +12,12 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do    alias Pleroma.Object    alias Pleroma.Repo    alias Pleroma.User +  alias Pleroma.UserRelationship    alias Pleroma.Web.CommonAPI    alias Pleroma.Web.CommonAPI.Utils    alias Pleroma.Web.MastodonAPI.AccountView    alias Pleroma.Web.MastodonAPI.StatusView +    import Pleroma.Factory    import Tesla.Mock @@ -212,12 +214,21 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do      {:ok, _user_relationships} = User.mute(user, other_user)      {:ok, activity} = CommonAPI.post(other_user, %{"status" => "test"}) -    status = StatusView.render("show.json", %{activity: activity}) +    relationships_opt = UserRelationship.view_relationships_option(user, [other_user]) + +    opts = %{activity: activity} +    status = StatusView.render("show.json", opts)      assert status.muted == false -    status = StatusView.render("show.json", %{activity: activity, for: user}) +    status = StatusView.render("show.json", Map.put(opts, :relationships, relationships_opt)) +    assert status.muted == false + +    for_opts = %{activity: activity, for: user} +    status = StatusView.render("show.json", for_opts) +    assert status.muted == true +    status = StatusView.render("show.json", Map.put(for_opts, :relationships, relationships_opt))      assert status.muted == true    end diff --git a/test/web/media_proxy/media_proxy_controller_test.exs b/test/web/media_proxy/media_proxy_controller_test.exs index f035dfeee..da79d38a5 100644 --- a/test/web/media_proxy/media_proxy_controller_test.exs +++ b/test/web/media_proxy/media_proxy_controller_test.exs @@ -7,8 +7,8 @@ defmodule Pleroma.Web.MediaProxy.MediaProxyControllerTest do    import Mock    alias Pleroma.Config -  clear_config(:media_proxy) -  clear_config([Pleroma.Web.Endpoint, :secret_key_base]) +  setup do: clear_config(:media_proxy) +  setup do: clear_config([Pleroma.Web.Endpoint, :secret_key_base])    test "it returns 404 when MediaProxy disabled", %{conn: conn} do      Config.put([:media_proxy, :enabled], false) @@ -52,9 +52,8 @@ defmodule Pleroma.Web.MediaProxy.MediaProxyControllerTest do      url = Pleroma.Web.MediaProxy.encode_url("https://google.fn/test.png")      invalid_url = String.replace(url, "test.png", "test-file.png")      response = get(conn, invalid_url) -    html = "<html><body>You are being <a href=\"#{url}\">redirected</a>.</body></html>"      assert response.status == 302 -    assert response.resp_body == html +    assert redirected_to(response) == url    end    test "it performs ReverseProxy.call when signature valid", %{conn: conn} do diff --git a/test/web/media_proxy/media_proxy_test.exs b/test/web/media_proxy/media_proxy_test.exs index 8f5fcf2eb..69c2d5dae 100644 --- a/test/web/media_proxy/media_proxy_test.exs +++ b/test/web/media_proxy/media_proxy_test.exs @@ -8,8 +8,8 @@ defmodule Pleroma.Web.MediaProxyTest do    import Pleroma.Web.MediaProxy    alias Pleroma.Web.MediaProxy.MediaProxyController -  clear_config([:media_proxy, :enabled]) -  clear_config(Pleroma.Upload) +  setup do: clear_config([:media_proxy, :enabled]) +  setup do: clear_config(Pleroma.Upload)    describe "when enabled" do      setup do diff --git a/test/web/metadata/opengraph_test.exs b/test/web/metadata/opengraph_test.exs index 9d7c009eb..218540e6c 100644 --- a/test/web/metadata/opengraph_test.exs +++ b/test/web/metadata/opengraph_test.exs @@ -7,7 +7,7 @@ defmodule Pleroma.Web.Metadata.Providers.OpenGraphTest do    import Pleroma.Factory    alias Pleroma.Web.Metadata.Providers.OpenGraph -  clear_config([Pleroma.Web.Metadata, :unfurl_nsfw]) +  setup do: clear_config([Pleroma.Web.Metadata, :unfurl_nsfw])    test "it renders all supported types of attachments and skips unknown types" do      user = insert(:user) diff --git a/test/web/metadata/twitter_card_test.exs b/test/web/metadata/twitter_card_test.exs index 3d75d1ed5..9e9c6853a 100644 --- a/test/web/metadata/twitter_card_test.exs +++ b/test/web/metadata/twitter_card_test.exs @@ -13,7 +13,7 @@ defmodule Pleroma.Web.Metadata.Providers.TwitterCardTest do    alias Pleroma.Web.Metadata.Utils    alias Pleroma.Web.Router -  clear_config([Pleroma.Web.Metadata, :unfurl_nsfw]) +  setup do: clear_config([Pleroma.Web.Metadata, :unfurl_nsfw])    test "it renders twitter card for user info" do      user = insert(:user, name: "Jimmy Hendriks", bio: "born 19 March 1994") diff --git a/test/web/node_info_test.exs b/test/web/node_info_test.exs index ee10ad5db..43f322606 100644 --- a/test/web/node_info_test.exs +++ b/test/web/node_info_test.exs @@ -7,8 +7,8 @@ defmodule Pleroma.Web.NodeInfoTest do    import Pleroma.Factory -  clear_config([:mrf_simple]) -  clear_config(:instance) +  setup do: clear_config([:mrf_simple]) +  setup do: clear_config(:instance)    test "GET /.well-known/nodeinfo", %{conn: conn} do      links = @@ -105,7 +105,7 @@ defmodule Pleroma.Web.NodeInfoTest do    end    describe "`metadata/federation/enabled`" do -    clear_config([:instance, :federating]) +    setup do: clear_config([:instance, :federating])      test "it shows if federation is enabled/disabled", %{conn: conn} do        Pleroma.Config.put([:instance, :federating], true) diff --git a/test/web/oauth/ldap_authorization_test.exs b/test/web/oauth/ldap_authorization_test.exs index c55b0ffc5..a8fe8a841 100644 --- a/test/web/oauth/ldap_authorization_test.exs +++ b/test/web/oauth/ldap_authorization_test.exs @@ -12,13 +12,9 @@ defmodule Pleroma.Web.OAuth.LDAPAuthorizationTest do    @skip if !Code.ensure_loaded?(:eldap), do: :skip -  clear_config_all([:ldap, :enabled]) do -    Pleroma.Config.put([:ldap, :enabled], true) -  end +  setup_all do: clear_config([:ldap, :enabled], true) -  clear_config_all(Pleroma.Web.Auth.Authenticator) do -    Pleroma.Config.put(Pleroma.Web.Auth.Authenticator, Pleroma.Web.Auth.LDAPAuthenticator) -  end +  setup_all do: clear_config(Pleroma.Web.Auth.Authenticator, Pleroma.Web.Auth.LDAPAuthenticator)    @tag @skip    test "authorizes the existing user using LDAP credentials" do diff --git a/test/web/oauth/oauth_controller_test.exs b/test/web/oauth/oauth_controller_test.exs index 5f86d999c..f2f98d768 100644 --- a/test/web/oauth/oauth_controller_test.exs +++ b/test/web/oauth/oauth_controller_test.exs @@ -17,8 +17,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do      key: "_test",      signing_salt: "cooldude"    ] - -  clear_config([:instance, :account_activation_required]) +  setup do: clear_config([:instance, :account_activation_required])    describe "in OAuth consumer mode, " do      setup do @@ -31,12 +30,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do        ]      end -    clear_config([:auth, :oauth_consumer_strategies]) do -      Pleroma.Config.put( -        [:auth, :oauth_consumer_strategies], -        ~w(twitter facebook) -      ) -    end +    setup do: clear_config([:auth, :oauth_consumer_strategies], ~w(twitter facebook))      test "GET /oauth/authorize renders auth forms, including OAuth consumer form", %{        app: app, @@ -944,7 +938,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do    end    describe "POST /oauth/token - refresh token" do -    clear_config([:oauth2, :issue_new_refresh_token]) +    setup do: clear_config([:oauth2, :issue_new_refresh_token])      test "issues a new access token with keep fresh token" do        Pleroma.Config.put([:oauth2, :issue_new_refresh_token], true) diff --git a/test/web/ostatus/ostatus_controller_test.exs b/test/web/ostatus/ostatus_controller_test.exs index 2051841c2..6787b414b 100644 --- a/test/web/ostatus/ostatus_controller_test.exs +++ b/test/web/ostatus/ostatus_controller_test.exs @@ -7,6 +7,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do    import Pleroma.Factory +  alias Pleroma.Config    alias Pleroma.Object    alias Pleroma.User    alias Pleroma.Web.CommonAPI @@ -16,22 +17,22 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do      :ok    end -  clear_config_all([:instance, :federating]) do -    Pleroma.Config.put([:instance, :federating], true) -  end +  setup do: clear_config([:instance, :federating], true) + +  # Note: see ActivityPubControllerTest for JSON format tests +  describe "GET /objects/:uuid (text/html)" do +    setup %{conn: conn} do +      conn = put_req_header(conn, "accept", "text/html") +      %{conn: conn} +    end -  describe "GET object/2" do      test "redirects to /notice/id for html format", %{conn: conn} do        note_activity = insert(:note_activity)        object = Object.normalize(note_activity)        [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, object.data["id"]))        url = "/objects/#{uuid}" -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get(url) - +      conn = get(conn, url)        assert redirected_to(conn) == "/notice/#{note_activity.id}"      end @@ -45,23 +46,25 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do        |> response(404)      end -    test "404s on nonexisting objects", %{conn: conn} do +    test "404s on non-existing objects", %{conn: conn} do        conn        |> get("/objects/123")        |> response(404)      end    end -  describe "GET activity/2" do +  # Note: see ActivityPubControllerTest for JSON format tests +  describe "GET /activities/:uuid (text/html)" do +    setup %{conn: conn} do +      conn = put_req_header(conn, "accept", "text/html") +      %{conn: conn} +    end +      test "redirects to /notice/id for html format", %{conn: conn} do        note_activity = insert(:note_activity)        [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, note_activity.data["id"])) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/activities/#{uuid}") - +      conn = get(conn, "/activities/#{uuid}")        assert redirected_to(conn) == "/notice/#{note_activity.id}"      end @@ -79,19 +82,6 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do        |> get("/activities/123")        |> response(404)      end - -    test "gets an activity in AS2 format", %{conn: conn} do -      note_activity = insert(:note_activity) -      [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, note_activity.data["id"])) -      url = "/activities/#{uuid}" - -      conn = -        conn -        |> put_req_header("accept", "application/activity+json") -        |> get(url) - -      assert json_response(conn, 200) -    end    end    describe "GET notice/2" do @@ -170,7 +160,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do        assert response(conn, 404)      end -    test "404s a nonexisting notice", %{conn: conn} do +    test "404s a non-existing notice", %{conn: conn} do        url = "/notice/123"        conn = @@ -179,10 +169,21 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do        assert response(conn, 404)      end + +    test "it requires authentication if instance is NOT federating", %{ +      conn: conn +    } do +      user = insert(:user) +      note_activity = insert(:note_activity) + +      conn = put_req_header(conn, "accept", "text/html") + +      ensure_federating_or_authenticated(conn, "/notice/#{note_activity.id}", user) +    end    end    describe "GET /notice/:id/embed_player" do -    test "render embed player", %{conn: conn} do +    setup do        note_activity = insert(:note_activity)        object = Pleroma.Object.normalize(note_activity) @@ -204,9 +205,11 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do        |> Ecto.Changeset.change(data: object_data)        |> Pleroma.Repo.update() -      conn = -        conn -        |> get("/notice/#{note_activity.id}/embed_player") +      %{note_activity: note_activity} +    end + +    test "renders embed player", %{conn: conn, note_activity: note_activity} do +      conn = get(conn, "/notice/#{note_activity.id}/embed_player")        assert Plug.Conn.get_resp_header(conn, "x-frame-options") == ["ALLOW"] @@ -272,9 +275,19 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do        |> Ecto.Changeset.change(data: object_data)        |> Pleroma.Repo.update() -      assert conn -             |> get("/notice/#{note_activity.id}/embed_player") -             |> response(404) +      conn +      |> get("/notice/#{note_activity.id}/embed_player") +      |> response(404) +    end + +    test "it requires authentication if instance is NOT federating", %{ +      conn: conn, +      note_activity: note_activity +    } do +      user = insert(:user) +      conn = put_req_header(conn, "accept", "text/html") + +      ensure_federating_or_authenticated(conn, "/notice/#{note_activity.id}/embed_player", user)      end    end  end diff --git a/test/web/pleroma_api/controllers/account_controller_test.exs b/test/web/pleroma_api/controllers/account_controller_test.exs index 245cc1579..2aa87ac30 100644 --- a/test/web/pleroma_api/controllers/account_controller_test.exs +++ b/test/web/pleroma_api/controllers/account_controller_test.exs @@ -27,9 +27,7 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do        [user: user]      end -    clear_config([:instance, :account_activation_required]) do -      Config.put([:instance, :account_activation_required], true) -    end +    setup do: clear_config([:instance, :account_activation_required], true)      test "resend account confirmation email", %{conn: conn, user: user} do        conn diff --git a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs index 4b9f5cf9a..435fb6592 100644 --- a/test/web/pleroma_api/controllers/emoji_api_controller_test.exs +++ b/test/web/pleroma_api/controllers/emoji_api_controller_test.exs @@ -12,10 +12,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiAPIControllerTest do                      Pleroma.Config.get!([:instance, :static_dir]),                      "emoji"                    ) - -  clear_config([:auth, :enforce_oauth_admin_scope_usage]) do -    Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], false) -  end +  setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)    test "shared & non-shared pack information in list_packs is ok" do      conn = build_conn() diff --git a/test/web/plugs/federating_plug_test.exs b/test/web/plugs/federating_plug_test.exs index 13edc4359..2f8aadadc 100644 --- a/test/web/plugs/federating_plug_test.exs +++ b/test/web/plugs/federating_plug_test.exs @@ -5,7 +5,7 @@  defmodule Pleroma.Web.FederatingPlugTest do    use Pleroma.Web.ConnCase -  clear_config([:instance, :federating]) +  setup do: clear_config([:instance, :federating])    test "returns and halt the conn when federating is disabled" do      Pleroma.Config.put([:instance, :federating], false) diff --git a/test/web/rich_media/helpers_test.exs b/test/web/rich_media/helpers_test.exs index 8237802a7..aa0c5c830 100644 --- a/test/web/rich_media/helpers_test.exs +++ b/test/web/rich_media/helpers_test.exs @@ -19,7 +19,7 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do      :ok    end -  clear_config([:rich_media, :enabled]) +  setup do: clear_config([:rich_media, :enabled])    test "refuses to crawl incomplete URLs" do      user = insert(:user) diff --git a/test/web/static_fe/static_fe_controller_test.exs b/test/web/static_fe/static_fe_controller_test.exs index 2ce8f9fa3..430683ea0 100644 --- a/test/web/static_fe/static_fe_controller_test.exs +++ b/test/web/static_fe/static_fe_controller_test.exs @@ -1,56 +1,41 @@  defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do    use Pleroma.Web.ConnCase +    alias Pleroma.Activity +  alias Pleroma.Config    alias Pleroma.Web.ActivityPub.Transmogrifier    alias Pleroma.Web.CommonAPI    import Pleroma.Factory -  clear_config_all([:static_fe, :enabled]) do -    Pleroma.Config.put([:static_fe, :enabled], true) -  end - -  describe "user profile page" do -    test "just the profile as HTML", %{conn: conn} do -      user = insert(:user) - -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/users/#{user.nickname}") +  setup_all do: clear_config([:static_fe, :enabled], true) +  setup do: clear_config([:instance, :federating], true) -      assert html_response(conn, 200) =~ user.nickname -    end +  setup %{conn: conn} do +    conn = put_req_header(conn, "accept", "text/html") +    user = insert(:user) -    test "renders json unless there's an html accept header", %{conn: conn} do -      user = insert(:user) +    %{conn: conn, user: user} +  end -      conn = -        conn -        |> put_req_header("accept", "application/json") -        |> get("/users/#{user.nickname}") +  describe "user profile html" do +    test "just the profile as HTML", %{conn: conn, user: user} do +      conn = get(conn, "/users/#{user.nickname}") -      assert json_response(conn, 200) +      assert html_response(conn, 200) =~ user.nickname      end      test "404 when user not found", %{conn: conn} do -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/users/limpopo") +      conn = get(conn, "/users/limpopo")        assert html_response(conn, 404) =~ "not found"      end -    test "profile does not include private messages", %{conn: conn} do -      user = insert(:user) +    test "profile does not include private messages", %{conn: conn, user: user} do        CommonAPI.post(user, %{"status" => "public"})        CommonAPI.post(user, %{"status" => "private", "visibility" => "private"}) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/users/#{user.nickname}") +      conn = get(conn, "/users/#{user.nickname}")        html = html_response(conn, 200) @@ -58,14 +43,10 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do        refute html =~ ">private<"      end -    test "pagination", %{conn: conn} do -      user = insert(:user) +    test "pagination", %{conn: conn, user: user} do        Enum.map(1..30, fn i -> CommonAPI.post(user, %{"status" => "test#{i}"}) end) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/users/#{user.nickname}") +      conn = get(conn, "/users/#{user.nickname}")        html = html_response(conn, 200) @@ -75,15 +56,11 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do        refute html =~ ">test1<"      end -    test "pagination, page 2", %{conn: conn} do -      user = insert(:user) +    test "pagination, page 2", %{conn: conn, user: user} do        activities = Enum.map(1..30, fn i -> CommonAPI.post(user, %{"status" => "test#{i}"}) end)        {:ok, a11} = Enum.at(activities, 11) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/users/#{user.nickname}?max_id=#{a11.id}") +      conn = get(conn, "/users/#{user.nickname}?max_id=#{a11.id}")        html = html_response(conn, 200) @@ -92,17 +69,17 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do        refute html =~ ">test20<"        refute html =~ ">test29<"      end + +    test "it requires authentication if instance is NOT federating", %{conn: conn, user: user} do +      ensure_federating_or_authenticated(conn, "/users/#{user.nickname}", user) +    end    end -  describe "notice rendering" do -    test "single notice page", %{conn: conn} do -      user = insert(:user) +  describe "notice html" do +    test "single notice page", %{conn: conn, user: user} do        {:ok, activity} = CommonAPI.post(user, %{"status" => "testing a thing!"}) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/notice/#{activity.id}") +      conn = get(conn, "/notice/#{activity.id}")        html = html_response(conn, 200)        assert html =~ "<header>" @@ -110,8 +87,20 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do        assert html =~ "testing a thing!"      end -    test "shows the whole thread", %{conn: conn} do +    test "filters HTML tags", %{conn: conn} do        user = insert(:user) +      {:ok, activity} = CommonAPI.post(user, %{"status" => "<script>alert('xss')</script>"}) + +      conn = +        conn +        |> put_req_header("accept", "text/html") +        |> get("/notice/#{activity.id}") + +      html = html_response(conn, 200) +      assert html =~ ~s[<script>alert('xss')</script>] +    end + +    test "shows the whole thread", %{conn: conn, user: user} do        {:ok, activity} = CommonAPI.post(user, %{"status" => "space: the final frontier"})        CommonAPI.post(user, %{ @@ -119,70 +108,47 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do          "in_reply_to_status_id" => activity.id        }) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/notice/#{activity.id}") +      conn = get(conn, "/notice/#{activity.id}")        html = html_response(conn, 200)        assert html =~ "the final frontier"        assert html =~ "voyages"      end -    test "redirect by AP object ID", %{conn: conn} do -      user = insert(:user) - +    test "redirect by AP object ID", %{conn: conn, user: user} do        {:ok, %Activity{data: %{"object" => object_url}}} =          CommonAPI.post(user, %{"status" => "beam me up"}) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get(URI.parse(object_url).path) +      conn = get(conn, URI.parse(object_url).path)        assert html_response(conn, 302) =~ "redirected"      end -    test "redirect by activity ID", %{conn: conn} do -      user = insert(:user) - +    test "redirect by activity ID", %{conn: conn, user: user} do        {:ok, %Activity{data: %{"id" => id}}} =          CommonAPI.post(user, %{"status" => "I'm a doctor, not a devops!"}) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get(URI.parse(id).path) +      conn = get(conn, URI.parse(id).path)        assert html_response(conn, 302) =~ "redirected"      end      test "404 when notice not found", %{conn: conn} do -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/notice/88c9c317") +      conn = get(conn, "/notice/88c9c317")        assert html_response(conn, 404) =~ "not found"      end -    test "404 for private status", %{conn: conn} do -      user = insert(:user) - +    test "404 for private status", %{conn: conn, user: user} do        {:ok, activity} =          CommonAPI.post(user, %{"status" => "don't show me!", "visibility" => "private"}) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/notice/#{activity.id}") +      conn = get(conn, "/notice/#{activity.id}")        assert html_response(conn, 404) =~ "not found"      end -    test "302 for remote cached status", %{conn: conn} do -      user = insert(:user) - +    test "302 for remote cached status", %{conn: conn, user: user} do        message = %{          "@context" => "https://www.w3.org/ns/activitystreams",          "to" => user.follower_address, @@ -199,12 +165,15 @@ defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do        assert {:ok, activity} = Transmogrifier.handle_incoming(message) -      conn = -        conn -        |> put_req_header("accept", "text/html") -        |> get("/notice/#{activity.id}") +      conn = get(conn, "/notice/#{activity.id}")        assert html_response(conn, 302) =~ "redirected"      end + +    test "it requires authentication if instance is NOT federating", %{conn: conn, user: user} do +      {:ok, activity} = CommonAPI.post(user, %{"status" => "testing a thing!"}) + +      ensure_federating_or_authenticated(conn, "/notice/#{activity.id}", user) +    end    end  end diff --git a/test/web/streamer/streamer_test.exs b/test/web/streamer/streamer_test.exs index 339f99bbf..a5d6e8ecf 100644 --- a/test/web/streamer/streamer_test.exs +++ b/test/web/streamer/streamer_test.exs @@ -19,8 +19,7 @@ defmodule Pleroma.Web.StreamerTest do    @streamer_timeout 150    @streamer_start_wait 10 - -  clear_config([:instance, :skip_thread_containment]) +  setup do: clear_config([:instance, :skip_thread_containment])    describe "user streams" do      setup do diff --git a/test/web/twitter_api/remote_follow_controller_test.exs b/test/web/twitter_api/remote_follow_controller_test.exs index 80a42989d..5ff8694a8 100644 --- a/test/web/twitter_api/remote_follow_controller_test.exs +++ b/test/web/twitter_api/remote_follow_controller_test.exs @@ -5,8 +5,10 @@  defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do    use Pleroma.Web.ConnCase +  alias Pleroma.Config    alias Pleroma.User    alias Pleroma.Web.CommonAPI +    import ExUnit.CaptureLog    import Pleroma.Factory @@ -15,9 +17,10 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do      :ok    end -  clear_config([:instance]) -  clear_config([:frontend_configurations, :pleroma_fe]) -  clear_config([:user, :deny_follow_blocked]) +  setup_all do: clear_config([:instance, :federating], true) +  setup do: clear_config([:instance]) +  setup do: clear_config([:frontend_configurations, :pleroma_fe]) +  setup do: clear_config([:user, :deny_follow_blocked])    describe "GET /ostatus_subscribe - remote_follow/2" do      test "adds status to pleroma instance if the `acct` is a status", %{conn: conn} do diff --git a/test/web/twitter_api/twitter_api_test.exs b/test/web/twitter_api/twitter_api_test.exs index 14eed5f27..92f9aa0f5 100644 --- a/test/web/twitter_api/twitter_api_test.exs +++ b/test/web/twitter_api/twitter_api_test.exs @@ -117,9 +117,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do    end    describe "register with one time token" do -    clear_config([:instance, :registrations_open]) do -      Pleroma.Config.put([:instance, :registrations_open], false) -    end +    setup do: clear_config([:instance, :registrations_open], false)      test "returns user on success" do        {:ok, invite} = UserInviteToken.create_invite() @@ -184,9 +182,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do    end    describe "registers with date limited token" do -    clear_config([:instance, :registrations_open]) do -      Pleroma.Config.put([:instance, :registrations_open], false) -    end +    setup do: clear_config([:instance, :registrations_open], false)      setup do        data = %{ @@ -246,9 +242,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do    end    describe "registers with reusable token" do -    clear_config([:instance, :registrations_open]) do -      Pleroma.Config.put([:instance, :registrations_open], false) -    end +    setup do: clear_config([:instance, :registrations_open], false)      test "returns user on success, after him registration fails" do        {:ok, invite} = UserInviteToken.create_invite(%{max_use: 100}) @@ -292,9 +286,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do    end    describe "registers with reusable date limited token" do -    clear_config([:instance, :registrations_open]) do -      Pleroma.Config.put([:instance, :registrations_open], false) -    end +    setup do: clear_config([:instance, :registrations_open], false)      test "returns user on success" do        {:ok, invite} = UserInviteToken.create_invite(%{expires_at: Date.utc_today(), max_use: 100}) diff --git a/test/web/twitter_api/util_controller_test.exs b/test/web/twitter_api/util_controller_test.exs index d464ce215..30e54bebd 100644 --- a/test/web/twitter_api/util_controller_test.exs +++ b/test/web/twitter_api/util_controller_test.exs @@ -6,6 +6,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do    use Pleroma.Web.ConnCase    use Oban.Testing, repo: Pleroma.Repo +  alias Pleroma.Config    alias Pleroma.Tests.ObanHelpers    alias Pleroma.User @@ -17,8 +18,8 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      :ok    end -  clear_config([:instance]) -  clear_config([:frontend_configurations, :pleroma_fe]) +  setup do: clear_config([:instance]) +  setup do: clear_config([:frontend_configurations, :pleroma_fe])    describe "POST /api/pleroma/follow_import" do      setup do: oauth_access(["follow"]) @@ -178,7 +179,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do    describe "GET /api/statusnet/config" do      test "it returns config in xml format", %{conn: conn} do -      instance = Pleroma.Config.get(:instance) +      instance = Config.get(:instance)        response =          conn @@ -195,12 +196,12 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      end      test "it returns config in json format", %{conn: conn} do -      instance = Pleroma.Config.get(:instance) -      Pleroma.Config.put([:instance, :managed_config], true) -      Pleroma.Config.put([:instance, :registrations_open], false) -      Pleroma.Config.put([:instance, :invites_enabled], true) -      Pleroma.Config.put([:instance, :public], false) -      Pleroma.Config.put([:frontend_configurations, :pleroma_fe], %{theme: "asuka-hospital"}) +      instance = Config.get(:instance) +      Config.put([:instance, :managed_config], true) +      Config.put([:instance, :registrations_open], false) +      Config.put([:instance, :invites_enabled], true) +      Config.put([:instance, :public], false) +      Config.put([:frontend_configurations, :pleroma_fe], %{theme: "asuka-hospital"})        response =          conn @@ -234,7 +235,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      end      test "returns the state of safe_dm_mentions flag", %{conn: conn} do -      Pleroma.Config.put([:instance, :safe_dm_mentions], true) +      Config.put([:instance, :safe_dm_mentions], true)        response =          conn @@ -243,7 +244,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do        assert response["site"]["safeDMMentionsEnabled"] == "1" -      Pleroma.Config.put([:instance, :safe_dm_mentions], false) +      Config.put([:instance, :safe_dm_mentions], false)        response =          conn @@ -254,8 +255,8 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      end      test "it returns the managed config", %{conn: conn} do -      Pleroma.Config.put([:instance, :managed_config], false) -      Pleroma.Config.put([:frontend_configurations, :pleroma_fe], %{theme: "asuka-hospital"}) +      Config.put([:instance, :managed_config], false) +      Config.put([:frontend_configurations, :pleroma_fe], %{theme: "asuka-hospital"})        response =          conn @@ -264,7 +265,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do        refute response["site"]["pleromafe"] -      Pleroma.Config.put([:instance, :managed_config], true) +      Config.put([:instance, :managed_config], true)        response =          conn @@ -287,7 +288,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do          }        ] -      Pleroma.Config.put(:frontend_configurations, config) +      Config.put(:frontend_configurations, config)        response =          conn @@ -317,10 +318,10 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do    end    describe "GET /api/pleroma/healthcheck" do -    clear_config([:instance, :healthcheck]) +    setup do: clear_config([:instance, :healthcheck])      test "returns 503 when healthcheck disabled", %{conn: conn} do -      Pleroma.Config.put([:instance, :healthcheck], false) +      Config.put([:instance, :healthcheck], false)        response =          conn @@ -331,7 +332,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      end      test "returns 200 when healthcheck enabled and all ok", %{conn: conn} do -      Pleroma.Config.put([:instance, :healthcheck], true) +      Config.put([:instance, :healthcheck], true)        with_mock Pleroma.Healthcheck,          system_info: fn -> %Pleroma.Healthcheck{healthy: true} end do @@ -351,7 +352,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      end      test "returns 503 when healthcheck enabled and health is false", %{conn: conn} do -      Pleroma.Config.put([:instance, :healthcheck], true) +      Config.put([:instance, :healthcheck], true)        with_mock Pleroma.Healthcheck,          system_info: fn -> %Pleroma.Healthcheck{healthy: false} end do @@ -426,6 +427,8 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do    end    describe "POST /main/ostatus - remote_subscribe/2" do +    setup do: clear_config([:instance, :federating], true) +      test "renders subscribe form", %{conn: conn} do        user = insert(:user) diff --git a/test/web/web_finger/web_finger_controller_test.exs b/test/web/web_finger/web_finger_controller_test.exs index b65bf5904..0023f1e81 100644 --- a/test/web/web_finger/web_finger_controller_test.exs +++ b/test/web/web_finger/web_finger_controller_test.exs @@ -14,9 +14,7 @@ defmodule Pleroma.Web.WebFinger.WebFingerControllerTest do      :ok    end -  clear_config_all([:instance, :federating]) do -    Pleroma.Config.put([:instance, :federating], true) -  end +  setup_all do: clear_config([:instance, :federating], true)    test "GET host-meta" do      response = diff --git a/test/workers/cron/clear_oauth_token_worker_test.exs b/test/workers/cron/clear_oauth_token_worker_test.exs index f056b1a3e..df82dc75d 100644 --- a/test/workers/cron/clear_oauth_token_worker_test.exs +++ b/test/workers/cron/clear_oauth_token_worker_test.exs @@ -8,7 +8,7 @@ defmodule Pleroma.Workers.Cron.ClearOauthTokenWorkerTest do    import Pleroma.Factory    alias Pleroma.Workers.Cron.ClearOauthTokenWorker -  clear_config([:oauth2, :clean_expired_tokens]) +  setup do: clear_config([:oauth2, :clean_expired_tokens])    test "deletes expired tokens" do      insert(:oauth_token, diff --git a/test/workers/cron/digest_emails_worker_test.exs b/test/workers/cron/digest_emails_worker_test.exs index 5d65b9fef..0a63bf4e0 100644 --- a/test/workers/cron/digest_emails_worker_test.exs +++ b/test/workers/cron/digest_emails_worker_test.exs @@ -11,7 +11,7 @@ defmodule Pleroma.Workers.Cron.DigestEmailsWorkerTest do    alias Pleroma.User    alias Pleroma.Web.CommonAPI -  clear_config([:email_notifications, :digest]) +  setup do: clear_config([:email_notifications, :digest])    setup do      Pleroma.Config.put([:email_notifications, :digest], %{ diff --git a/test/workers/cron/purge_expired_activities_worker_test.exs b/test/workers/cron/purge_expired_activities_worker_test.exs index 56c5aa409..5864f9e5f 100644 --- a/test/workers/cron/purge_expired_activities_worker_test.exs +++ b/test/workers/cron/purge_expired_activities_worker_test.exs @@ -11,7 +11,7 @@ defmodule Pleroma.Workers.Cron.PurgeExpiredActivitiesWorkerTest do    import Pleroma.Factory    import ExUnit.CaptureLog -  clear_config([ActivityExpiration, :enabled]) +  setup do: clear_config([ActivityExpiration, :enabled])    test "deletes an expiration activity" do      Pleroma.Config.put([ActivityExpiration, :enabled], true) diff --git a/test/workers/scheduled_activity_worker_test.exs b/test/workers/scheduled_activity_worker_test.exs index ab9f9c125..b312d975b 100644 --- a/test/workers/scheduled_activity_worker_test.exs +++ b/test/workers/scheduled_activity_worker_test.exs @@ -11,7 +11,7 @@ defmodule Pleroma.Workers.ScheduledActivityWorkerTest do    import Pleroma.Factory    import ExUnit.CaptureLog -  clear_config([ScheduledActivity, :enabled]) +  setup do: clear_config([ScheduledActivity, :enabled])    test "creates a status from the scheduled activity" do      Pleroma.Config.put([ScheduledActivity, :enabled], true) | 
