Files
Crypto_Scam/tests/test_request_security.py

84 lines
4.1 KiB
Python

"""Requests retain their original authority through the local proxy."""
import json
import sys
import unittest
import urllib.error
import urllib.request
from email.message import Message
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parent)]
import request_security as security
import test_web_proxy as fixtures
import web_proxy
import web_sim
class AuthorityTests(unittest.TestCase):
def request(self, host='localhost:8765', origin=None, peer='127.0.0.1'):
headers = Message()
headers['Host'] = host
headers['X-Sim'] = '1'
if origin is not None:
headers['Origin'] = origin
return SimpleNamespace(headers=headers, client_address=(peer, 1000))
def test_only_local_authorities_and_same_origin_are_accepted(self):
for host, origin in [('localhost:8765', 'http://localhost:8765'),
('127.0.0.1:8765', None), ('[::1]:8765', 'http://[::1]:8765')]:
self.assertTrue(security.trusted_request(self.request(host, origin), command=True))
for host in ['attacker.example:8765', 'localhost.attacker.example', 'attacker@localhost:8765',
'localhost:bad', 'localhost:8765/path', 'localhost:8765#x', 'localhost:8765,evil']:
self.assertFalse(security.trusted_request(self.request(host)))
for origin in ['null', 'http://attacker.example', 'http://localhost:1234', 'http://evil@localhost:8765']:
self.assertFalse(security.trusted_request(self.request(origin=origin), command=True))
self.assertFalse(security.trusted_request(self.request(peer='192.168.1.1')))
def test_duplicate_host_and_missing_command_header_are_rejected(self):
req = self.request()
req.headers['Host'] = 'evil.example'
self.assertFalse(security.trusted_request(req))
req = self.request()
del req.headers['X-Sim']
self.assertFalse(security.trusted_request(req, command=True))
class ProxyIntegrationTests(unittest.TestCase):
def setUp(self):
self.sim = mock.patch.object(web_sim, 'SIM', SimpleNamespace(state=lambda: {'ok': True}), create=True)
self.sim.start()
self.addCleanup(self.sim.stop)
self.engine = fixtures.serve(web_sim.Handler)
self.backend = mock.patch.object(web_proxy, 'ENGINE', f'http://127.0.0.1:{self.engine.server_port}')
self.backend.start()
self.addCleanup(self.backend.stop)
self.proxy = fixtures.serve(web_proxy.Proxy)
for server in (self.engine, self.proxy):
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
def test_host_is_checked_at_both_boundaries(self):
for server in (self.proxy, self.engine):
for method in ('GET', 'POST'):
req = urllib.request.Request(f'http://127.0.0.1:{server.server_port}/api/state',
data=b'{}' if method == 'POST' else None, method=method,
headers={'Host': 'attacker.example', 'X-Sim': '1'})
with self.assertRaises(urllib.error.HTTPError) as error:
urllib.request.urlopen(req)
self.assertEqual(error.exception.code, 403)
def test_proxy_preserves_browser_origin_and_static_assets_are_allowlisted(self):
base = f'http://127.0.0.1:{self.proxy.server_port}'
req = urllib.request.Request(base + '/api/state', headers={'Origin': base})
with urllib.request.urlopen(req) as response:
self.assertEqual(json.load(response), {'ok': True})
for asset, kind in [('app.js', 'text/javascript'), ('app.css', 'text/css')]:
with urllib.request.urlopen(base + '/static/' + asset) as response:
self.assertIn(kind, response.headers['Content-Type'])
self.assertGreater(len(response.read()), 10)
with self.assertRaises(urllib.error.HTTPError) as error:
urllib.request.urlopen(base + '/static/../keystore.py')
self.assertEqual(error.exception.code, 404)