1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Integration.MastodonWebsocketTest do
8 import ExUnit.CaptureLog
11 alias Pleroma.Integration.WebsocketClient
12 alias Pleroma.Web.CommonAPI
13 alias Pleroma.Web.OAuth
15 @moduletag needs_streamer: true, capture_log: true
17 @path Pleroma.Web.Endpoint.url()
19 |> Map.put(:scheme, "ws")
20 |> Map.put(:path, "/api/v1/streaming")
23 def start_socket(qs \\ nil, headers \\ []) do
30 WebsocketClient.start_link(self(), path, headers)
33 test "refuses invalid requests" do
35 assert {:error, {404, _}} = start_socket()
36 assert {:error, {404, _}} = start_socket("?stream=ncjdk")
41 test "requires authentication and a valid token for protected streams" do
43 assert {:error, {401, _}} = start_socket("?stream=user&access_token=aaaaaaaaaaaa")
44 assert {:error, {401, _}} = start_socket("?stream=user")
49 test "allows public streams without authentication" do
50 assert {:ok, _} = start_socket("?stream=public")
51 assert {:ok, _} = start_socket("?stream=public:local")
52 assert {:ok, _} = start_socket("?stream=hashtag&tag=lain")
55 test "receives well formatted events" do
57 {:ok, _} = start_socket("?stream=public")
58 {:ok, activity} = CommonAPI.post(user, %{status: "nice echo chamber"})
60 assert_receive {:text, raw_json}, 1_000
61 assert {:ok, json} = Jason.decode(raw_json)
63 assert "update" == json["event"]
64 assert json["payload"]
65 assert {:ok, json} = Jason.decode(json["payload"])
68 Pleroma.Web.MastodonAPI.StatusView.render("show.json", activity: activity, for: nil)
72 assert json == view_json
75 describe "with a valid user token" do
79 OAuth.App.register_changeset(%OAuth.App{}, %{
80 client_name: "client",
88 {:ok, auth} = OAuth.Authorization.create_authorization(app, user)
90 {:ok, token} = OAuth.Token.exchange_token(app, auth)
92 %{user: user, token: token}
95 test "accepts valid tokens", state do
96 assert {:ok, _} = start_socket("?stream=user&access_token=#{state.token.token}")
99 test "accepts the 'user' stream", %{token: token} = _state do
100 assert {:ok, _} = start_socket("?stream=user&access_token=#{token.token}")
103 assert {:error, {401, _}} = start_socket("?stream=user")
108 test "accepts the 'user:notification' stream", %{token: token} = _state do
109 assert {:ok, _} = start_socket("?stream=user:notification&access_token=#{token.token}")
112 assert {:error, {401, _}} = start_socket("?stream=user:notification")
117 test "accepts valid token on Sec-WebSocket-Protocol header", %{token: token} do
118 assert {:ok, _} = start_socket("?stream=user", [{"Sec-WebSocket-Protocol", token.token}])
121 assert {:error, {401, _}} =
122 start_socket("?stream=user", [{"Sec-WebSocket-Protocol", "I am a friend"}])