Debian Codegraph @

tests/proxy.py

raw
1 import asyncio
2 import pathlib
3 import ssl
4 import threading
5 import warnings
6
7
8 try:
9 # Ignore deprecation warnings raised by mitmproxy dependencies at import time.
10 for module in ["ldap3", "mitmproxy", "passlib", "pyasn1", "pyparsing"]:
11 warnings.filterwarnings("ignore", category=DeprecationWarning, module=module)
12
13 from mitmproxy import ctx
14 from mitmproxy.addons import core, next_layer, proxyauth, proxyserver, tlsconfig
15 from mitmproxy.http import Response
16 from mitmproxy.master import Master
17 from mitmproxy.options import CONF_BASENAME, CONF_DIR, Options
18 except ImportError:
19 pass
20
21
22 class RecordFlows:
23 def __init__(self, on_running):
24 self.running = on_running
25 self.http_connects = []
26 self.tcp_flows = []
27
28 def http_connect(self, flow):
29 self.http_connects.append(flow)
30
31 def tcp_start(self, flow):
32 self.tcp_flows.append(flow)
33
34 def get_http_connects(self):
35 http_connects, self.http_connects[:] = self.http_connects[:], []
36 return http_connects
37
38 def get_tcp_flows(self):
39 tcp_flows, self.tcp_flows[:] = self.tcp_flows[:], []
40 return tcp_flows
41
42 def reset(self):
43 self.http_connects = []
44 self.tcp_flows = []
45
46
47 class AlterRequest:
48 def load(self, loader):
49 loader.add_option(
50 name="break_http_connect",
51 typespec=bool,
52 default=False,
53 help="Respond to HTTP CONNECT requests with a 999 status code.",
54 )
55 loader.add_option(
56 name="close_http_connect",
57 typespec=bool,
58 default=False,
59 help="Do not respond to HTTP CONNECT requests.",
60 )
61
62 def http_connect(self, flow):
63 if ctx.options.break_http_connect:
64 # mitmproxy can send a response with a status code not between 100
65 # and 599, while websockets treats it as a protocol error.
66 # This is used for testing HTTP parsing errors.
67 flow.response = Response.make(999, "not a valid HTTP response")
68 if ctx.options.close_http_connect:
69 flow.kill()
70
71
72 class ProxyMixin:
73 """
74 Run mitmproxy in a background thread.
75
76 While it's uncommon to run two event loops in two threads, tests for the
77 asyncio implementation rely on this class too because it starts an event
78 loop for mitm proxy once, then a new event loop for each test.
79 """
80
81 proxy_mode = None
82
83 @classmethod
84 async def run_proxy(cls):
85 cls.proxy_loop = loop = asyncio.get_event_loop()
86 cls.proxy_stop = stop = asyncio.Event()
87
88 cls.proxy_options = options = Options(
89 mode=[cls.proxy_mode],
90 # Don't intercept connections, but record them.
91 ignore_hosts=["^localhost:", "^127.0.0.1:", "^::1:"],
92 show_ignored_hosts=True,
93 )
94 cls.proxy_master = master = Master(options)
95 master.addons.add(
96 core.Core(),
97 proxyauth.ProxyAuth(),
98 proxyserver.Proxyserver(),
99 next_layer.NextLayer(),
100 tlsconfig.TlsConfig(),
101 RecordFlows(on_running=cls.proxy_ready.set),
102 AlterRequest(),
103 )
104
105 task = loop.create_task(cls.proxy_master.run())
106 await stop.wait()
107
108 for server in master.addons.get("proxyserver").servers:
109 await server.stop()
110 master.shutdown()
111 await task
112
113 @classmethod
114 def setUpClass(cls):
115 super().setUpClass()
116
117 # Ignore deprecation warnings raised by mitmproxy at run time.
118 warnings.filterwarnings(
119 "ignore", category=DeprecationWarning, module="mitmproxy"
120 )
121
122 cls.proxy_ready = threading.Event()
123 cls.proxy_thread = threading.Thread(target=asyncio.run, args=(cls.run_proxy(),))
124 cls.proxy_thread.start()
125 cls.proxy_ready.wait()
126
127 certificate = pathlib.Path(CONF_DIR) / f"{CONF_BASENAME}-ca-cert.pem"
128 certificate = certificate.expanduser()
129 cls.proxy_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
130 cls.proxy_context.load_verify_locations(bytes(certificate))
131
132 def get_http_connects(self):
133 return self.proxy_master.addons.get("recordflows").get_http_connects()
134
135 def get_tcp_flows(self):
136 return self.proxy_master.addons.get("recordflows").get_tcp_flows()
137
138 def assertNumFlows(self, num_tcp_flows):
139 self.assertEqual(len(self.get_tcp_flows()), num_tcp_flows)
140
141 def tearDown(self):
142 record_tcp_flows = self.proxy_master.addons.get("recordflows")
143 record_tcp_flows.reset()
144 super().tearDown()
145
146 @classmethod
147 def tearDownClass(cls):
148 cls.proxy_loop.call_soon_threadsafe(cls.proxy_stop.set)
149 cls.proxy_thread.join()
150 super().tearDownClass()