mozproxy 1.0__tar.gz → 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. {mozproxy-1.0 → mozproxy-2.0.0}/PKG-INFO +4 -9
  2. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/android.py +6 -2
  3. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/desktop.py +30 -12
  4. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/mitm.py +238 -45
  5. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/mitmproxy_requirements.txt +1 -1
  6. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/scripts/alt-serverplayback.py +2 -0
  7. mozproxy-2.0.0/mozproxy/backends/mitm/scripts/nav-serverplayback.py +419 -0
  8. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/driver.py +4 -6
  9. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/server.py +0 -9
  10. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy.egg-info/PKG-INFO +4 -9
  11. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy.egg-info/SOURCES.txt +1 -0
  12. mozproxy-2.0.0/mozproxy.egg-info/requires.txt +4 -0
  13. {mozproxy-1.0 → mozproxy-2.0.0}/setup.py +3 -9
  14. {mozproxy-1.0 → mozproxy-2.0.0}/tests/test_command_line.py +9 -8
  15. mozproxy-2.0.0/tests/test_proxy.py +379 -0
  16. {mozproxy-1.0 → mozproxy-2.0.0}/tests/test_recording.py +2 -3
  17. mozproxy-1.0/mozproxy.egg-info/requires.txt +0 -3
  18. mozproxy-1.0/tests/test_proxy.py +0 -212
  19. {mozproxy-1.0 → mozproxy-2.0.0}/MANIFEST.in +0 -0
  20. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/__init__.py +0 -0
  21. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/__main__.py +0 -0
  22. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/__init__.py +0 -0
  23. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/base.py +0 -0
  24. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/__init__.py +0 -0
  25. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-linux64.manifest +0 -0
  26. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-osx-arm64.manifest +0 -0
  27. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-osx.manifest +0 -0
  28. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-win.manifest +0 -0
  29. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-linux64.manifest +0 -0
  30. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-osx-arm64.manifest +0 -0
  31. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-osx.manifest +0 -0
  32. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-win.manifest +0 -0
  33. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-linux64.manifest +0 -0
  34. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-osx.manifest +0 -0
  35. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-win.manifest +0 -0
  36. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-linux64.manifest +0 -0
  37. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-osx.manifest +0 -0
  38. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-win.manifest +0 -0
  39. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-linux64.manifest +0 -0
  40. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-osx.manifest +0 -0
  41. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-win.manifest +0 -0
  42. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-linux64.manifest +0 -0
  43. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-osx.manifest +0 -0
  44. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-win.manifest +0 -0
  45. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-linux64.manifest +0 -0
  46. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-osx.manifest +0 -0
  47. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-win.manifest +0 -0
  48. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-linux64.manifest +0 -0
  49. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-osx.manifest +0 -0
  50. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-win.manifest +0 -0
  51. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/scripts/__init__.py +0 -0
  52. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/scripts/alternate-server-replay.py +0 -0
  53. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/scripts/catapult/LICENSE +0 -0
  54. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/scripts/catapult/deterministic.js +0 -0
  55. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/scripts/http_protocol_extractor.py +0 -0
  56. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/backends/mitm/scripts/inject-deterministic.py +0 -0
  57. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/recordings.py +0 -0
  58. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy/utils.py +0 -0
  59. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy.egg-info/dependency_links.txt +0 -0
  60. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy.egg-info/entry_points.txt +0 -0
  61. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy.egg-info/not-zip-safe +0 -0
  62. {mozproxy-1.0 → mozproxy-2.0.0}/mozproxy.egg-info/top_level.txt +0 -0
  63. {mozproxy-1.0 → mozproxy-2.0.0}/setup.cfg +0 -0
  64. {mozproxy-1.0 → mozproxy-2.0.0}/tests/test_mitm_addons.py +0 -0
  65. {mozproxy-1.0 → mozproxy-2.0.0}/tests/test_recordings.py +0 -0
  66. {mozproxy-1.0 → mozproxy-2.0.0}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mozproxy
3
- Version: 1.0
3
+ Version: 2.0.0
4
4
  Summary: Proxy for playback
5
5
  Home-page: https://wiki.mozilla.org/Auto-tools/Projects/Mozbase
6
6
  Author: Mozilla Automation and Tools team
@@ -9,16 +9,11 @@ License: MPL
9
9
  Keywords: mozilla
10
10
  Classifier: Programming Language :: Python
11
11
  Classifier: Programming Language :: Python :: 3 :: Only
12
- Classifier: Programming Language :: Python :: 3.8
13
- Classifier: Programming Language :: Python :: 3.9
14
- Classifier: Programming Language :: Python :: 3.10
15
- Classifier: Programming Language :: Python :: 3.11
16
- Classifier: Programming Language :: Python :: 3.12
17
- Classifier: Programming Language :: Python :: 3.13
18
- Requires-Python: >=3.8
12
+ Requires-Python: >=3.9
19
13
  Requires-Dist: redo
20
- Requires-Dist: mozinfo
14
+ Requires-Dist: mozinfo>=0.7
21
15
  Requires-Dist: mozlog>=6.0
16
+ Requires-Dist: mozprocess>=1.3.0
22
17
  Dynamic: author
23
18
  Dynamic: author-email
24
19
  Dynamic: classifier
@@ -103,9 +103,13 @@ class MitmproxyAndroid(Mitmproxy):
103
103
  # now use the manifest to download hostutils so we can get certutil
104
104
  tooltool_download(_dest, self.config["run_local"], self.mozproxy_dir)
105
105
 
106
- # the production bitbar container host is always linux
106
+ # bitbar hosts are linux, the Android emulator hosts are macOS
107
+ if mozinfo.os == "mac":
108
+ hostutils_glob = "host-utils*.mac"
109
+ else:
110
+ hostutils_glob = "host-utils*[!z|checksum]"
107
111
  self.certutil_path = glob.glob(
108
- os.path.join(self.mozproxy_dir, "host-utils*[!z|checksum]")
112
+ os.path.join(self.mozproxy_dir, hostutils_glob)
109
113
  )[0]
110
114
 
111
115
  # must add hostutils/certutil to the path
@@ -27,6 +27,19 @@ POLICIES_CONTENT_ON = """{
27
27
  }
28
28
  }"""
29
29
 
30
+ POLICIES_CONTENT_DIRECT = """{
31
+ "policies": {
32
+ "Certificates": {
33
+ "Install": ["%(cert)s"]
34
+ },
35
+ "Proxy": {
36
+ "Mode": "none",
37
+ "Locked": true
38
+ }
39
+ }
40
+ }"""
41
+
42
+
30
43
  POLICIES_CONTENT_OFF = """{
31
44
  "policies": {
32
45
  "Proxy": {
@@ -76,6 +89,7 @@ class MitmproxyDesktop(Mitmproxy):
76
89
  location, and turns on the the browser proxy settings
77
90
  """
78
91
  LOG.info("Installing mitmproxy CA certificate into Firefox")
92
+ self.wait_for_ca_cert(DEFAULT_CERT_PATH)
79
93
 
80
94
  # browser_path is the exe, we want the folder
81
95
  self.policies_dir = os.path.dirname(browser_path)
@@ -92,15 +106,13 @@ class MitmproxyDesktop(Mitmproxy):
92
106
  self.cert_path = self.cert_path.replace("\\", "\\\\")
93
107
 
94
108
  if not os.path.exists(self.policies_dir):
95
- LOG.info("creating folder: %s" % self.policies_dir)
109
+ LOG.info(f"creating folder: {self.policies_dir}")
96
110
  os.makedirs(self.policies_dir)
97
111
  else:
98
- LOG.info("folder already exists: %s" % self.policies_dir)
112
+ LOG.info(f"folder already exists: {self.policies_dir}")
99
113
 
100
114
  self.write_policies_json(
101
- self.policies_dir,
102
- policies_content=POLICIES_CONTENT_ON
103
- % {"cert": self.cert_path, "host": self.host, "port": self.port},
115
+ self.policies_dir, policies_content=self._policies_content()
104
116
  )
105
117
 
106
118
  # cannot continue if failed to add CA cert to Firefox, need to check
@@ -111,16 +123,25 @@ class MitmproxyDesktop(Mitmproxy):
111
123
  self.stop_mitmproxy_playback()
112
124
  sys.exit()
113
125
 
126
+ def _policies_content(self):
127
+ if self.playback_mode == "direct":
128
+ return POLICIES_CONTENT_DIRECT % {"cert": self.cert_path}
129
+ return POLICIES_CONTENT_ON % {
130
+ "cert": self.cert_path,
131
+ "host": self.host,
132
+ "port": self.port,
133
+ }
134
+
114
135
  def write_policies_json(self, location, policies_content):
115
136
  policies_file = os.path.join(location, "policies.json")
116
- LOG.info("writing: %s" % policies_file)
137
+ LOG.info(f"writing: {policies_file}")
117
138
 
118
139
  with open(policies_file, "w") as fd:
119
140
  fd.write(policies_content)
120
141
 
121
142
  def read_policies_json(self, location):
122
143
  policies_file = os.path.join(location, "policies.json")
123
- LOG.info("reading: %s" % policies_file)
144
+ LOG.info(f"reading: {policies_file}")
124
145
 
125
146
  with open(policies_file) as fd:
126
147
  return fd.read()
@@ -132,15 +153,12 @@ class MitmproxyDesktop(Mitmproxy):
132
153
  contents = self.read_policies_json(self.policies_dir)
133
154
  LOG.info("Firefox policies file contents:")
134
155
  LOG.info(contents)
135
- if (
136
- POLICIES_CONTENT_ON
137
- % {"cert": self.cert_path, "host": self.host, "port": self.port}
138
- ) in contents:
156
+ if self._policies_content() in contents:
139
157
  LOG.info("Verified mitmproxy CA certificate is installed in Firefox")
140
158
  else:
141
159
  return False
142
160
  except Exception as e:
143
- LOG.info("failed to read Firefox policies file, exeption: %s" % e)
161
+ LOG.info(f"failed to read Firefox policies file, exeption: {e}")
144
162
  return False
145
163
  return True
146
164
 
@@ -12,6 +12,11 @@ import time
12
12
  import mozinfo
13
13
  from mozprocess import ProcessHandler
14
14
 
15
+ try:
16
+ import resource
17
+ except ImportError:
18
+ resource = None
19
+
15
20
  from mozproxy.backends.base import Playback
16
21
  from mozproxy.recordings import RecordingFile
17
22
  from mozproxy.utils import (
@@ -27,6 +32,15 @@ mitm_folder = os.path.dirname(os.path.realpath(__file__))
27
32
 
28
33
  # maximal allowed runtime of a mitmproxy command
29
34
  MITMDUMP_COMMAND_TIMEOUT = 30
35
+ # Direct playback needs multiple --mode listen specs (mitmproxy >= 9).
36
+ DIRECT_PLAYBACK_VERSIONS = ("11.0.0", "12.2.1")
37
+ # Direct playback keeps one server-side socket per browser connection, and
38
+ # the macOS default soft limit of 256 open files is exhausted by a single
39
+ # page. mitmdump inherits the limit from us, so raise it before spawning.
40
+ MITMPROXY_NOFILE_LIMIT = 10240
41
+
42
+ # maximal wait for mitmproxy to write its CA certificate
43
+ MITMPROXY_CERT_TIMEOUT = 60
30
44
 
31
45
 
32
46
  class Mitmproxy(Playback):
@@ -40,6 +54,11 @@ class Mitmproxy(Playback):
40
54
  "127.0.0.1" if "localhost" in self.config["host"] else self.config["host"]
41
55
  )
42
56
  self.port = None
57
+ self.http_port = None
58
+ self.https_port = None
59
+ self.playback_mode = config.get("playback_mode", "proxy")
60
+ if self.playback_mode not in ("proxy", "direct"):
61
+ raise ValueError(f"Unsupported playback mode: {self.playback_mode}")
43
62
  self.mitmproxy_proc = None
44
63
  self.mitmdump_path = None
45
64
  self.mitmdump_path_dir = None
@@ -69,17 +88,15 @@ class Mitmproxy(Playback):
69
88
 
70
89
  if not os.path.splitext(self.config.get("recording_file"))[1] == ".zip":
71
90
  LOG.error(
72
- "Recording file type (%s) should be a zip. "
91
+ f"Recording file type ({self.config.get('recording_file')}) should be a zip. "
73
92
  "Please provide a valid file type!"
74
- % self.config.get("recording_file")
75
93
  )
76
94
  raise Exception("Recording file type should be a zip")
77
95
 
78
96
  if os.path.exists(self.config.get("recording_file")):
79
97
  LOG.error(
80
- "Recording file (%s) already exists."
98
+ f"Recording file ({self.config.get('recording_file')}) already exists. "
81
99
  "Please provide a valid file path!"
82
- % self.config.get("recording_file")
83
100
  )
84
101
  raise Exception("Recording file already exists.")
85
102
 
@@ -94,6 +111,17 @@ class Mitmproxy(Playback):
94
111
  )
95
112
  raise Exception("playback_version not specified!")
96
113
 
114
+ if (
115
+ self.playback_mode == "direct"
116
+ and self.config["playback_version"] not in DIRECT_PLAYBACK_VERSIONS
117
+ ):
118
+ supported_versions = ", ".join(DIRECT_PLAYBACK_VERSIONS)
119
+ raise ValueError(
120
+ f"Direct playback does not support mitmproxy "
121
+ f"{self.config['playback_version']}; supported versions: "
122
+ f"{supported_versions}"
123
+ )
124
+
97
125
  # mozproxy_dir is where we will download all mitmproxy required files
98
126
  # when running locally it comes from obj_path via mozharness/mach
99
127
  if self.config.get("obj_path") is not None:
@@ -113,15 +141,14 @@ class Mitmproxy(Playback):
113
141
  self.mozproxy_dir = os.path.join(self.mozproxy_dir, "testing", "mozproxy")
114
142
 
115
143
  LOG.info(
116
- "mozproxy_dir used for mitmproxy downloads and exe files: %s"
117
- % self.mozproxy_dir
144
+ f"mozproxy_dir used for mitmproxy downloads and exe files: {self.mozproxy_dir}"
118
145
  )
119
146
  # setting up the MOZPROXY_DIR env variable so custom scripts know
120
147
  # where to get the data
121
148
  os.environ["MOZPROXY_DIR"] = self.mozproxy_dir
122
149
 
123
- LOG.info("Playback tool: %s" % self.config["playback_tool"])
124
- LOG.info("Playback tool version: %s" % self.config["playback_version"])
150
+ LOG.info(f"Playback tool: {self.config['playback_tool']}")
151
+ LOG.info(f"Playback tool version: {self.config['playback_version']}")
125
152
 
126
153
  def _is_test_environment(self):
127
154
  """Check if running under pytest.
@@ -158,6 +185,32 @@ class Mitmproxy(Playback):
158
185
  finally:
159
186
  sys.exit(128 + sig)
160
187
 
188
+ def _build_replay_paths(self):
189
+ """Return the deduped, deterministic list of recording paths to pass
190
+ to mitmproxy. Logs each path so failures can be attributed to a
191
+ specific recording in mitmproxy.log."""
192
+ seen = set()
193
+ paths = []
194
+ for playback_file in self.playback_files:
195
+ normalized = os.path.normpath(playback_file.recording_path)
196
+ if normalized in seen:
197
+ LOG.warning(f"Duplicate playback file ignored: {normalized}")
198
+ continue
199
+ if not os.path.exists(normalized):
200
+ LOG.error(
201
+ f"Playback file is missing on disk and will be skipped: {normalized}"
202
+ )
203
+ continue
204
+ seen.add(normalized)
205
+ paths.append(normalized)
206
+
207
+ if not paths:
208
+ raise Exception("No usable playback recordings after dedupe; aborting.")
209
+
210
+ for path in paths:
211
+ LOG.info(f"mitmproxy recording: {path}")
212
+ return paths
213
+
161
214
  def generate_mitmdump_path(self):
162
215
  mitmdump_path_tail = ["mitmdump"]
163
216
  if (
@@ -176,7 +229,7 @@ class Mitmproxy(Playback):
176
229
  self.mitmdump_path_dir = os.path.normpath(
177
230
  os.path.join(
178
231
  self.mozproxy_dir,
179
- "mitmdump-%s" % self.config["playback_version"],
232
+ f"mitmdump-{self.config['playback_version']}",
180
233
  )
181
234
  )
182
235
  self.mitmdump_path = os.path.normpath(
@@ -189,8 +242,7 @@ class Mitmproxy(Playback):
189
242
  manifest = os.path.join(
190
243
  here,
191
244
  "manifests",
192
- "mitmproxy-rel-bin-%s-{platform}.manifest"
193
- % self.config["playback_version"],
245
+ f"mitmproxy-rel-bin-{self.config['playback_version']}-{{platform}}.manifest",
194
246
  )
195
247
  transformed_manifest = transform_platform(
196
248
  manifest,
@@ -208,7 +260,7 @@ class Mitmproxy(Playback):
208
260
  else:
209
261
  # Download and unpack mitmproxy binary
210
262
  download_path = self.mitmdump_path_dir
211
- LOG.info("create mitmproxy %s dir" % self.config["playback_version"])
263
+ LOG.info(f"create mitmproxy {self.config['playback_version']} dir")
212
264
  if not os.path.exists(download_path):
213
265
  os.makedirs(download_path)
214
266
 
@@ -228,7 +280,7 @@ class Mitmproxy(Playback):
228
280
  manifest = json.load(manifest_file)
229
281
  for file in manifest:
230
282
  zip_path = os.path.join(self.mozproxy_dir, file["filename"])
231
- LOG.info("Adding %s to recording list" % zip_path)
283
+ LOG.info(f"Adding {zip_path} to recording list")
232
284
  self.playback_files.append(RecordingFile(zip_path))
233
285
 
234
286
  def download_playback_files(self):
@@ -249,20 +301,19 @@ class Mitmproxy(Playback):
249
301
  dest = os.path.join(self.mozproxy_dir, os.path.basename(playback_file))
250
302
  download_file_from_url(playback_file, self.mozproxy_dir, extract=False)
251
303
  # Add Downloaded file to playback_files list
252
- LOG.info("Adding %s to recording list" % dest)
304
+ LOG.info(f"Adding {dest} to recording list")
253
305
  self.playback_files.append(RecordingFile(dest))
254
306
  continue
255
307
 
256
308
  if not os.path.exists(playback_file):
257
309
  LOG.error(
258
- "Zip or manifest file path (%s) does not exist. Please provide a valid path!"
259
- % playback_file
310
+ f"Zip or manifest file path ({playback_file}) does not exist. Please provide a valid path!"
260
311
  )
261
312
  raise Exception("Zip or manifest file path does not exist")
262
313
 
263
314
  if os.path.splitext(playback_file)[1] == ".zip":
264
315
  # zip file path provided
265
- LOG.info("Adding %s to recording list" % playback_file)
316
+ LOG.info(f"Adding {playback_file} to recording list")
266
317
  self.playback_files.append(RecordingFile(playback_file))
267
318
  elif os.path.splitext(playback_file)[1] == ".manifest":
268
319
  # manifest file path provided
@@ -318,10 +369,16 @@ class Mitmproxy(Playback):
318
369
  """Startup mitmproxy and replay the specified flow file"""
319
370
  if self.mitmproxy_proc is not None:
320
371
  raise Exception("Proxy already started.")
321
- self.port = get_available_port()
372
+ if self.playback_mode == "direct":
373
+ self.http_port = get_available_port()
374
+ self.https_port = get_available_port()
375
+ while self.https_port == self.http_port:
376
+ self.https_port = get_available_port()
377
+ else:
378
+ self.port = get_available_port()
322
379
 
323
- LOG.info("mitmdump path: %s" % mitmdump_path)
324
- LOG.info("browser path: %s" % browser_path)
380
+ LOG.info(f"mitmdump path: {mitmdump_path}")
381
+ LOG.info(f"browser path: {browser_path}")
325
382
 
326
383
  # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path
327
384
  env = os.environ.copy()
@@ -331,13 +388,25 @@ class Mitmproxy(Playback):
331
388
  if self.config.get("verbose", False):
332
389
  # Generate mitmproxy verbose logs
333
390
  command.extend(["-v"])
334
- # add proxy host and port options
335
- command.extend(["--listen-host", self.host, "--listen-port", str(self.port)])
391
+
392
+ command.extend(["--listen-host", self.host])
393
+ if self.playback_mode == "direct":
394
+ command.extend([
395
+ "--mode",
396
+ f"reverse:http://example.invalid@{self.http_port}",
397
+ "--mode",
398
+ f"reverse:https://example.invalid@{self.https_port}",
399
+ "--set",
400
+ "keep_host_header=true",
401
+ "--set",
402
+ "upstream_cert=false",
403
+ ])
404
+ else:
405
+ command.extend(["--listen-port", str(self.port)])
336
406
 
337
407
  # record mode
338
408
  if self.record_mode:
339
409
  # generate recording script paths
340
-
341
410
  command.extend([
342
411
  "--save-stream-file",
343
412
  os.path.normpath(self.recording.recording_path),
@@ -354,7 +423,42 @@ class Mitmproxy(Playback):
354
423
  )
355
424
  # playback mode
356
425
  elif len(self.playback_files) > 0:
357
- if self.config["playback_version"] in ["8.1.1", "11.0.0", "12.2.1"]:
426
+ if (
427
+ self.config.get("test_name", "").startswith("nav-bench")
428
+ and self.config["playback_version"] == "12.2.1"
429
+ ):
430
+ # Common dynamic / anti-bot / session params to strip from
431
+ # URL matching during replay. Without this, sites like reddit
432
+ # produce per-session tokens (?solution=, ?token=, ?_=) that
433
+ # change between recording and playback, causing mitmproxy to
434
+ # 404 every page load.
435
+ ignore_params = ",".join([
436
+ "solution",
437
+ "token",
438
+ "jsc_orig_r",
439
+ "js_challenge",
440
+ "_",
441
+ "t",
442
+ "ts",
443
+ "timestamp",
444
+ "cb",
445
+ "callback",
446
+ "ref",
447
+ "ref_",
448
+ "pd_rd_r",
449
+ "pd_rd_w",
450
+ "pd_rd_wg",
451
+ "pf_rd_p",
452
+ "pf_rd_r",
453
+ "qid",
454
+ "sr",
455
+ "sprefix",
456
+ "psc",
457
+ "dib",
458
+ "dib_tag",
459
+ "browsertime_run",
460
+ ])
461
+ replay_paths = self._build_replay_paths()
358
462
  command.extend([
359
463
  "--set",
360
464
  "websocket=false",
@@ -369,12 +473,39 @@ class Mitmproxy(Playback):
369
473
  "--set",
370
474
  "tls_version_client_min=TLS1_2",
371
475
  "--set",
372
- "alt_server_replay={}".format(
373
- ",".join([
374
- os.path.normpath(playback_file.recording_path)
375
- for playback_file in self.playback_files
376
- ])
476
+ f"server_replay_ignore_params={ignore_params}",
477
+ # Force script log calls (replay.match/kill/miss) into
478
+ # the mitmproxy.log file so we can debug iteration-N
479
+ # hangs. Without this, ctx.log/logger output is
480
+ # filtered to warnings only.
481
+ "--set",
482
+ "termlog_verbosity=info",
483
+ "--set",
484
+ f"alt_server_replay={','.join(replay_paths)}",
485
+ "--scripts",
486
+ os.path.normpath(
487
+ os.path.join(mitm_folder, "scripts", "nav-serverplayback.py")
377
488
  ),
489
+ ])
490
+ elif self.config["playback_version"] in ["8.1.1", "11.0.0", "12.2.1"]:
491
+ replay_paths = self._build_replay_paths()
492
+ command.extend([
493
+ "--set",
494
+ "websocket=false",
495
+ "--set",
496
+ "connection_strategy=lazy",
497
+ "--set",
498
+ "alt_server_replay_nopop=true",
499
+ "--set",
500
+ "alt_server_replay_kill_extra=true",
501
+ "--set",
502
+ "alt_server_replay_order_reversed=true",
503
+ "--set",
504
+ "tls_version_client_min=TLS1_2",
505
+ "--set",
506
+ "termlog_verbosity=info",
507
+ "--set",
508
+ f"alt_server_replay={','.join(replay_paths)}",
378
509
  "--scripts",
379
510
  os.path.normpath(
380
511
  os.path.join(mitm_folder, "scripts", "alt-serverplayback.py")
@@ -409,6 +540,9 @@ class Mitmproxy(Playback):
409
540
  else:
410
541
  raise Exception("Mitmproxy version is unknown!")
411
542
 
543
+ if self.playback_mode == "direct":
544
+ command.extend(["--set", "alt_server_replay_ignore_port=true"])
545
+
412
546
  else:
413
547
  raise Exception(
414
548
  "Mitmproxy can't start playback! Playback settings missing."
@@ -419,26 +553,42 @@ class Mitmproxy(Playback):
419
553
  if not os.path.dirname(self.browser_path) in env["PATH"]:
420
554
  env["PATH"] = os.path.dirname(self.browser_path) + os.pathsep + env["PATH"]
421
555
 
422
- LOG.info("Starting mitmproxy playback using env path: %s" % env["PATH"])
423
- LOG.info("Starting mitmproxy playback using command: %s" % " ".join(command))
556
+ mitmproxy_log_path = os.path.join(self.upload_dir, "mitmproxy.log")
557
+ LOG.info(f"Starting mitmproxy playback using env path: {env['PATH']}")
558
+ LOG.info(f"Starting mitmproxy playback using command: {' '.join(command)}")
559
+ # Announce the log path so anyone debugging a hang in CI knows
560
+ # where to look. mitmproxy.log captures replay.match/kill/miss
561
+ # lines from the replay script and is uploaded with the rest
562
+ # of the artifacts.
563
+ LOG.info(f"mitmproxy log file: {mitmproxy_log_path}")
424
564
  # to turn off mitmproxy log output, use these params for Popen:
425
565
  # Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
426
- self.mitmproxy_proc = ProcessHandler(
427
- command,
428
- logfile=os.path.join(self.upload_dir, "mitmproxy.log"),
429
- env=env,
430
- storeOutput=False,
431
- )
432
- self.mitmproxy_proc.run()
566
+ previous_limit = self._raise_nofile_limit()
567
+ try:
568
+ self.mitmproxy_proc = ProcessHandler(
569
+ command,
570
+ logfile=mitmproxy_log_path,
571
+ env=env,
572
+ storeOutput=False,
573
+ )
574
+ self.mitmproxy_proc.run()
575
+ finally:
576
+ self._restore_nofile_limit(previous_limit)
577
+
433
578
  end_time = time.time() + MITMDUMP_COMMAND_TIMEOUT
434
579
 
580
+ ports = (
581
+ [self.http_port, self.https_port]
582
+ if self.playback_mode == "direct"
583
+ else [self.port]
584
+ )
435
585
  ready = False
436
586
  while time.time() < end_time:
437
- ready = self.check_proxy(host=self.host, port=self.port)
587
+ ready = all(self.check_proxy(host=self.host, port=port) for port in ports)
438
588
  if ready:
589
+ listening = ", ".join(f"{self.host}:{port}" for port in ports)
439
590
  LOG.info(
440
- "Mitmproxy playback successfully started on %s:%d as pid %d"
441
- % (self.host, self.port, self.mitmproxy_proc.pid)
591
+ f"Mitmproxy playback successfully started on {listening} as pid {self.mitmproxy_proc.pid}"
442
592
  )
443
593
  return
444
594
  time.sleep(0.25)
@@ -448,12 +598,43 @@ class Mitmproxy(Playback):
448
598
  self.stop_mitmproxy_playback()
449
599
  sys.exit(1) # XXX why do we need to do that? a raise is not enough?
450
600
 
601
+ def _raise_nofile_limit(self):
602
+ """Raise the open file soft limit so that the spawned mitmdump inherits
603
+ it. Returns the previous limits, or None if nothing changed."""
604
+ if resource is None or self.playback_mode != "direct":
605
+ return None
606
+ soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
607
+ if soft >= MITMPROXY_NOFILE_LIMIT:
608
+ return None
609
+ new_soft = MITMPROXY_NOFILE_LIMIT
610
+ if hard != resource.RLIM_INFINITY:
611
+ new_soft = min(new_soft, hard)
612
+ if new_soft <= soft:
613
+ return None
614
+ try:
615
+ resource.setrlimit(resource.RLIMIT_NOFILE, (new_soft, hard))
616
+ except (ValueError, OSError) as e:
617
+ LOG.warning(f"Could not raise RLIMIT_NOFILE from {soft} to {new_soft}: {e}")
618
+ return None
619
+ LOG.info(
620
+ f"Raised RLIMIT_NOFILE soft limit from {soft} to {new_soft} for mitmproxy"
621
+ )
622
+ return (soft, hard)
623
+
624
+ def _restore_nofile_limit(self, previous_limit):
625
+ if previous_limit is None or resource is None:
626
+ return
627
+ try:
628
+ resource.setrlimit(resource.RLIMIT_NOFILE, previous_limit)
629
+ except (ValueError, OSError) as e:
630
+ LOG.warning(f"Could not restore RLIMIT_NOFILE to {previous_limit}: {e}")
631
+
451
632
  def stop_mitmproxy_playback(self):
452
633
  """Stop the mitproxy server playback"""
453
634
  if self.mitmproxy_proc is None or self.mitmproxy_proc.poll() is not None:
454
635
  return
455
636
  LOG.info(
456
- "Stopping mitmproxy playback, killing process %d" % self.mitmproxy_proc.pid
637
+ f"Stopping mitmproxy playback, killing process {self.mitmproxy_proc.pid}"
457
638
  )
458
639
  # On Windows, mozprocess brutally kills mitmproxy with TerminateJobObject
459
640
  # The process has no chance to gracefully shutdown.
@@ -480,17 +661,29 @@ class Mitmproxy(Playback):
480
661
 
481
662
  if exit_code in [ERROR_CONTROL_C_EXIT, ERROR_CONTROL_C_EXIT_DECIMAL]:
482
663
  LOG.info(
483
- "Successfully killed the mitmproxy playback process"
484
- " with exit code %d" % exit_code
664
+ f"Successfully killed the mitmproxy playback process with exit code {exit_code}"
485
665
  )
486
666
  return
487
667
  log_func = LOG.error
488
668
  if self.ignore_mitmdump_exit_failure:
489
669
  log_func = LOG.info
490
- log_func("Mitmproxy exited with error code %d" % exit_code)
670
+ log_func(f"Mitmproxy exited with error code {exit_code}")
491
671
  else:
492
672
  LOG.info("Successfully killed the mitmproxy playback process")
493
673
 
674
+ def wait_for_ca_cert(self, cert_path):
675
+ """mitmproxy writes the cert only after loading all recordings, long
676
+ after the listen socket we otherwise wait on starts accepting."""
677
+ end_time = time.time() + MITMPROXY_CERT_TIMEOUT
678
+ while time.time() < end_time:
679
+ if os.path.exists(cert_path):
680
+ return
681
+ time.sleep(0.25)
682
+ raise Exception(
683
+ f"mitmproxy did not write its CA certificate to {cert_path} within "
684
+ f"{MITMPROXY_CERT_TIMEOUT}s"
685
+ )
686
+
494
687
  def check_proxy(self, host, port):
495
688
  """Check that mitmproxy process is working by doing a socket call using the proxy settings
496
689
  :param host: Host of the proxy server
@@ -4,7 +4,7 @@ blinker==1.4
4
4
  pycparser==2.17
5
5
  cffi==1.10.0
6
6
  brotlipy==0.6.0
7
- certifi==2017.4.17
7
+ certifi==2026.10.23
8
8
  click==6.7
9
9
  construct==2.8.12
10
10
  cryptography==1.8.2
@@ -12,6 +12,8 @@
12
12
  # * TO DO: remove the replay packages that don't have any content in their response package,
13
13
  # see Bug 1739418: https://bugzilla.mozilla.org/show_bug.cgi?id=1739418
14
14
 
15
+ from __future__ import annotations
16
+
15
17
  import hashlib
16
18
  import traceback
17
19
  import urllib