1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
|
import os
import unittest
from unittest import mock
import tornado.httpclient
import tornado.testing
import tornado.web
import tornado.websocket
import mopidy
from mopidy.http import handlers
class StaticFileHandlerTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
return tornado.web.Application(
[
(
r"/(.*)",
handlers.StaticFileHandler,
{
"path": os.path.dirname(__file__),
"default_filename": "test_handlers.py",
},
)
]
)
def test_static_handler(self):
response = self.fetch("/test_handlers.py", method="GET")
assert 200 == response.code
assert response.headers["X-Mopidy-Version"] == mopidy.__version__
assert response.headers["Cache-Control"] == "no-cache"
def test_static_default_filename(self):
response = self.fetch("/", method="GET")
assert 200 == response.code
assert response.headers["X-Mopidy-Version"] == mopidy.__version__
assert response.headers["Cache-Control"] == "no-cache"
class WebSocketHandlerTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
self.core = mock.Mock()
return tornado.web.Application(
[
(
r"/ws/?",
handlers.WebSocketHandler,
{
"core": self.core,
"allowed_origins": frozenset(),
"csrf_protection": True,
},
)
]
)
def connection(self, **kwargs):
conn_kwargs = {
"url": self.get_url("/ws").replace("http", "ws"),
}
conn_kwargs.update(kwargs)
request = tornado.httpclient.HTTPRequest(**conn_kwargs)
return tornado.websocket.websocket_connect(request)
@tornado.testing.gen_test
def test_invalid_json_rpc_request_doesnt_crash_handler(self):
# An uncaught error would result in no message, so this is just a
# simplistic test to verify this.
conn = yield self.connection()
conn.write_message("invalid request")
message = yield conn.read_message()
assert message
@tornado.testing.gen_test
def test_broadcast_makes_it_to_client(self):
conn = yield self.connection()
handlers.WebSocketHandler.broadcast("message", self.io_loop)
message = yield conn.read_message()
assert message == "message"
@tornado.testing.gen_test
def test_broadcast_to_client_that_just_closed_connection(self):
conn = yield self.connection()
conn.stream.close()
handlers.WebSocketHandler.broadcast("message", self.io_loop)
@tornado.testing.gen_test
def test_broadcast_to_client_without_ws_connection_present(self):
yield self.connection()
# Tornado checks for ws_connection and raises WebSocketClosedError
# if it is missing, this test case simulates winning a race were
# this has happened but we have not yet been removed from clients.
for client in handlers.WebSocketHandler.clients:
client.ws_connection = None
handlers.WebSocketHandler.broadcast("message", self.io_loop)
@tornado.testing.gen_test
def test_good_origin(self):
headers = {"Origin": "http://localhost", "Host": "localhost"}
conn = yield self.connection(headers=headers)
assert conn
@tornado.testing.gen_test
def test_bad_origin(self):
headers = {"Origin": "http://foobar", "Host": "localhost"}
with self.assertRaises(tornado.httpclient.HTTPClientError) as e:
_ = yield self.connection(headers=headers)
assert e.exception.code == 403
class JsonRpcHandlerTestBase(tornado.testing.AsyncHTTPTestCase):
csrf_protection = True
def setUp(self):
super().setUp()
self.headers = {"Host": "localhost:6680"}
def get_app(self):
self.core = mock.Mock()
return tornado.web.Application(
[
(
r"/rpc",
handlers.JsonRpcHandler,
{
"core": self.core,
"allowed_origins": set(),
"csrf_protection": self.csrf_protection,
},
)
]
)
def assert_extra_response_headers(self, headers):
assert headers["Cache-Control"] == "no-cache"
assert headers["X-Mopidy-Version"] == mopidy.__version__
assert headers["Accept"] == "application/json"
assert headers["Content-Type"] == "application/json; utf-8"
def get_cors_response_headers(self):
yield (
"Access-Control-Allow-Origin",
self.headers.get("Origin"),
)
yield (
"Access-Control-Allow-Headers",
"Content-Type",
)
def test_head(self):
response = self.fetch("/rpc", method="HEAD")
assert response.code == 200
self.assert_extra_response_headers(response.headers)
class JsonRpcHandlerTestCSRFEnabled(JsonRpcHandlerTestBase):
def test_options_sets_cors_headers(self):
self.headers.update({"Origin": "http://localhost:6680"})
response = self.fetch("/rpc", method="OPTIONS", headers=self.headers)
assert response.code == 204
for k, v in self.get_cors_response_headers():
self.assertEqual(response.headers[k], v)
def test_options_bad_origin_forbidden(self):
self.headers.update({"Origin": "http://foo:6680"})
response = self.fetch("/rpc", method="OPTIONS", headers=self.headers)
assert response.code == 403
assert response.reason == "Access denied for origin http://foo:6680"
for k, _ in self.get_cors_response_headers():
self.assertNotIn(k, response.headers)
def test_options_no_origin_forbidden(self):
response = self.fetch("/rpc", method="OPTIONS", headers=self.headers)
assert response.code == 403
assert response.reason == "Access denied for origin None"
for k, _ in self.get_cors_response_headers():
self.assertNotIn(k, response.headers)
def test_post_no_content_type_unsupported(self):
response = self.fetch(
"/rpc", method="POST", body="hi", headers=self.headers
)
assert response.code == 415
for k, _ in self.get_cors_response_headers():
self.assertNotIn(k, response.headers)
def test_post_wrong_content_type_unsupported(self):
self.headers.update({"Content-Type": "application/cats"})
response = self.fetch(
"/rpc", method="POST", body="hi", headers=self.headers
)
assert response.code == 415
assert response.reason == "Content-Type must be application/json"
for k, _ in self.get_cors_response_headers():
self.assertNotIn(k, response.headers)
def test_post_no_origin_ok_but_doesnt_set_cors_headers(self):
self.headers.update({"Content-Type": "application/json"})
response = self.fetch(
"/rpc", method="POST", body="hi", headers=self.headers
)
assert response.code == 200
for k, _ in self.get_cors_response_headers():
self.assertNotIn(k, response.headers)
def test_post_with_origin_ok_sets_cors_headers(self):
self.headers.update(
{"Content-Type": "application/json", "Origin": "http://foobar:6680"}
)
response = self.fetch(
"/rpc", method="POST", body="hi", headers=self.headers
)
assert response.code == 200
self.assert_extra_response_headers(response.headers)
for k, v in self.get_cors_response_headers():
self.assertEqual(response.headers[k], v)
class JsonRpcHandlerTestCSRFDisabled(JsonRpcHandlerTestBase):
csrf_protection = False
def test_options_no_origin_success(self):
response = self.fetch("/rpc", method="OPTIONS", headers=self.headers)
assert response.code == 204
def test_post_no_content_type_ok(self):
response = self.fetch(
"/rpc", method="POST", body="hi", headers=self.headers
)
assert response.code == 200
for k, _ in self.get_cors_response_headers():
self.assertNotIn(k, response.headers)
class CheckOriginTests(unittest.TestCase):
def setUp(self):
self.headers = {"Host": "localhost:6680"}
self.allowed = set()
def test_missing_origin_blocked(self):
assert not handlers.check_origin(None, self.headers, self.allowed)
def test_empty_origin_allowed(self):
assert handlers.check_origin("", self.headers, self.allowed)
def test_chrome_file_origin_allowed(self):
assert handlers.check_origin("file://", self.headers, self.allowed)
def test_firefox_null_origin_allowed(self):
assert handlers.check_origin("null", self.headers, self.allowed)
def test_same_host_origin_allowed(self):
assert handlers.check_origin(
"http://localhost:6680", self.headers, self.allowed
)
def test_different_host_origin_blocked(self):
assert not handlers.check_origin(
"http://other:6680", self.headers, self.allowed
)
def test_different_port_blocked(self):
assert not handlers.check_origin(
"http://localhost:80", self.headers, self.allowed
)
def test_extra_origin_allowed(self):
self.allowed.add("other:6680")
assert handlers.check_origin(
"http://other:6680", self.headers, self.allowed
)
|