GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Simplify RFC 2231 handling to a try/except · Kludex/python-multipart@7dc606b

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • python_multipart
    • multipart.py
  • tests
    • test_multipart.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎python_multipart/multipart.py‎

Copy file name to clipboardExpand all lines: python_multipart/multipart.py
+7-36Lines changed: 7 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -157,27 +157,6 @@ class MultipartState(IntEnum):
157157
"""
158158

159159

160-
def _split_mime_parameters(value: str) -> list[str]:
161-
"""Split a MIME parameter string on semicolons that are outside quoted strings."""
162-
parts: list[str] = []
163-
start = 0
164-
in_quotes = False
165-
i = 0
166-
while i < len(value):
167-
c = value[i]
168-
if in_quotes and c == "\\":
169-
i += 2 # skip the escaped character
170-
continue
171-
if c == '"':
172-
in_quotes = not in_quotes
173-
elif c == ";" and not in_quotes:
174-
parts.append(value[start:i])
175-
start = i + 1
176-
i += 1
177-
parts.append(value[start:])
178-
return parts
179-
180-
181160
def parse_options_header(value: str | bytes | None) -> tuple[bytes, dict[bytes, bytes]]:
182161
"""Parses a Content-Type header into a value in the following format: (content_type, {parameters})."""
183162
# Uses email.message.Message to parse the header as described in PEP 594.
@@ -196,27 +175,19 @@ def parse_options_header(value: str | bytes | None) -> tuple[bytes, dict[bytes,
196175
if ";" not in value:
197176
return (value.lower().strip().encode("latin-1"), {})
198177

199-
ctype_part, params_part = value.split(";", 1)
200-
201-
# Pre-check for mixed RFC2231 parameter continuations (e.g., `filename*` and `filename*0*`).
202-
# email.message.Message.get_params() handles these maliciously formed headers
203-
# differently in Python 3.12 vs 3.13. We validate them here to ensure consistent behavior.
204-
# _split_mime_parameters is used to avoid false positives from semicolons inside quoted values.
205-
param_names = [p.split("=", 1)[0].strip().lower() for p in _split_mime_parameters(params_part) if "=" in p]
206-
for name in param_names:
207-
if "*" in name:
208-
base, _, rest = name.partition("*")
209-
if rest.rstrip("*").isdigit() and f"{base}*" in param_names:
210-
return (ctype_part.lower().strip().encode("latin-1"), {})
211-
212178
# Split at the first semicolon, to get our value and then options.
213179
# ctype, rest = value.split(b';', 1)
214180
message = Message()
215181
message["content-type"] = value
182+
# `get_params()` can raise on malformed RFC 2231 headers found via fuzzing:
183+
# - ValueError on oversized continuation indices (all supported versions).
184+
# - TypeError on mixed `filename*` + `filename*0*` continuations (Python 3.12 only;
185+
# 3.13+ silently picks a value).
186+
# TODO: drop `TypeError` once Python 3.12 reaches EOL (October 2028).
216187
try:
217188
params = message.get_params()
218-
except (TypeError, ValueError):
219-
return (ctype_part.lower().strip().encode("latin-1"), {})
189+
except (TypeError, ValueError): # pragma: no cover
190+
return (value.split(";", 1)[0].lower().strip().encode("latin-1"), {})
220191
# If there were no parameters, this would have already returned above
221192
assert params, "At least the content type value should be present"
222193
ctype = params.pop(0)[0].encode("latin-1")
Collapse file

‎tests/test_multipart.py‎

Copy file name to clipboardExpand all lines: tests/test_multipart.py
+1-9Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -310,21 +310,13 @@ def test_rejects_oversized_rfc_2231_index(self) -> None:
310310
self.assertEqual(t, b"text/plain")
311311
self.assertEqual(p, {})
312312

313+
@pytest.mark.skipif(sys.version_info >= (3, 13), reason="email parser only raises TypeError on Python 3.12")
313314
def test_rejects_mixed_rfc_2231_continuations(self) -> None:
314315
t, p = parse_options_header("text/plain; filename*=utf-8''a; filename*0*=utf-8''b")
315316

316317
self.assertEqual(t, b"text/plain")
317318
self.assertEqual(p, {})
318319

319-
def test_quoted_value_containing_rfc_2231_like_text(self) -> None:
320-
# Ensure semicolons inside quotes are ignored so "fake" parameters don't cause false splits.
321-
header = "text/plain; notes=\"a;filename*0*=utf-8''junk\"; filename*=utf-8''real.txt"
322-
t, p = parse_options_header(header)
323-
324-
self.assertEqual(t, b"text/plain")
325-
# The "filename*0*" inside the notes string should be ignored.
326-
self.assertEqual(p[b"filename"], b"real.txt")
327-
328320

329321
class TestBaseParser(unittest.TestCase):
330322
def setUp(self) -> None:

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.