multipart 1.3.0__tar.gz → 1.3.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multipart
3
- Version: 1.3.0
3
+ Version: 1.3.2
4
4
  Summary: Parser for multipart/form-data
5
5
  Author-email: Marcel Hellkamp <marc@gsites.de>
6
6
  Requires-Python: >=3.8
@@ -12,7 +12,7 @@ License: MIT (see LICENSE file)
12
12
 
13
13
 
14
14
  __author__ = "Marcel Hellkamp"
15
- __version__ = '1.3.0'
15
+ __version__ = '1.3.2'
16
16
  __license__ = "MIT"
17
17
  __all__ = [
18
18
  "MultipartError",
@@ -30,6 +30,7 @@ __all__ = [
30
30
 
31
31
 
32
32
  import re
33
+ import codecs
33
34
  from io import BufferedRandom, BytesIO
34
35
  from typing import (
35
36
  Generator,
@@ -169,7 +170,7 @@ class MultiDict(DictMixin):
169
170
  yield key, value
170
171
 
171
172
 
172
- def to_bytes(data, enc="utf8"):
173
+ def to_bytes(data, enc="utf-8"):
173
174
  if isinstance(data, str):
174
175
  data = data.encode(enc)
175
176
 
@@ -216,7 +217,7 @@ class _cached_property:
216
217
  _token = "[a-zA-Z0-9-!#$%&'*+.^_`|~]+"
217
218
  _re_token = re.compile("^%s$" % _token, re.ASCII)
218
219
  # A token or quoted-string (simple qs | token | slow qs)
219
- _value = r'"[^\\"]*"|%s|"(?:\\.|[^"])*"' % _token
220
+ _value = r'"[^\\"]*"|%s|"(?:\\.|[^\\"])*"' % _token
220
221
  # A "; key=value" pair from content-disposition header
221
222
  _option = r"; *(%s) *= *(%s)" % (_token, _value)
222
223
  _re_option = re.compile(_option)
@@ -307,6 +308,49 @@ def parse_options_header(header, options=None, unquote=header_unquote):
307
308
  ################################## SansIO Parser #############################
308
309
  ##############################################################################
309
310
 
311
+ # Constants used by the parser
312
+ _HEADER_EXPECTED = frozenset(["Content-Disposition", "Content-Type", "Content-Length"])
313
+
314
+ # fmt: off
315
+ #: Known-good header charsets and some common aliases mapped to their actual name
316
+ _KNOWN_CHARSETS = {
317
+ alias: codecs.lookup(alias).name
318
+ for alias in (
319
+ "utf-8", "utf8",
320
+ "ascii", "us-ascii",
321
+ "iso8859-1", "iso-8859-1", "latin1", "latin-1",
322
+ )
323
+ }
324
+
325
+ #: Python specific charsets that should never be used by valid clients.
326
+ _BAD_CHARSETS = {
327
+ "unicode-escape", "punycode", "rot-13", "raw-unicode-escape", "hex",
328
+ "bz2", "palmos", "undefined", "zlib", "base64", "idna", "quopri",
329
+ "uu", "mbcs", "oem"
330
+ }
331
+ # fmt: on
332
+
333
+
334
+ def _safe_charset(charset: str, strict: bool):
335
+ """Return the actual name of a given charset or common alias while
336
+ rejecting problematic or unknown charsets. In strict mode, only a
337
+ small set of known charsets is allowed and any other charset raises
338
+ an exception. In non-strict mode, uncommon charsets are also allowed.
339
+ Unknown or known bad charsets always raise an exception."""
340
+ if charset == "utf-8":
341
+ return "utf-8"
342
+ if good := _KNOWN_CHARSETS.get(charset.lower()):
343
+ return good
344
+ if strict:
345
+ raise StrictParserError(f"Invalid or unknown charset: {charset!r}")
346
+ try:
347
+ info = codecs.lookup(charset)
348
+ if info.name not in _BAD_CHARSETS:
349
+ return info.name
350
+ except LookupError:
351
+ pass
352
+ raise ParserError(f"Invalid or unknown charset: {charset!r}")
353
+
310
354
 
311
355
  # Parser states as constants
312
356
  _PREAMBLE = "PREAMBLE"
@@ -342,7 +386,7 @@ class PushMultipartParser:
342
386
  max_header_count=8, # RFC 7578 allows just 3
343
387
  max_segment_size=inf, # unlimited
344
388
  max_segment_count=inf, # unlimited
345
- header_charset="utf8",
389
+ header_charset="utf-8",
346
390
  strict=False,
347
391
  ):
348
392
  """Create a new parser instance.
@@ -358,7 +402,7 @@ class PushMultipartParser:
358
402
  """
359
403
  self.boundary = to_bytes(boundary)
360
404
  self.content_length = content_length
361
- self.header_charset = header_charset
405
+ self.header_charset = _safe_charset(header_charset or "utf-8", strict)
362
406
  self.max_header_size = max_header_size
363
407
  self.max_header_count = max_header_count
364
408
  self.max_segment_size = max_segment_size
@@ -707,8 +751,10 @@ class MultipartSegment:
707
751
  if line[0] in b" \t": # Multi-line header value
708
752
  if not self.headerlist or parser.strict:
709
753
  raise StrictParserError("Unexpected segment header continuation")
754
+ if line.isspace():
755
+ raise ParserError("Empty segment header continuation")
710
756
  prev = ": ".join(self.headerlist.pop())
711
- line = prev.encode(parser.header_charset) + b" " + line.strip()
757
+ line = prev.encode(parser.header_charset) + b" " + line[1:]
712
758
 
713
759
  if len(line) > parser.max_header_size:
714
760
  raise ParserLimitReached("Maximum segment header length exceeded")
@@ -720,8 +766,9 @@ class MultipartSegment:
720
766
  name = name.strip()
721
767
  if not col or not name:
722
768
  raise ParserError("Malformed segment header")
723
- if " " in name or not name.isascii() or not name.isprintable():
724
- raise ParserError("Invalid segment header name")
769
+ if name not in _HEADER_EXPECTED:
770
+ if " " in name or not name.isascii() or not name.isprintable():
771
+ raise ParserError("Invalid segment header name")
725
772
  except UnicodeDecodeError as err:
726
773
  raise ParserError("Segment header failed to decode", err)
727
774
 
@@ -748,8 +795,14 @@ class MultipartSegment:
748
795
  elif h == "Content-Type":
749
796
  self.content_type, args = parse_options_header(v)
750
797
  self.charset = args.get("charset")
751
- elif h == "Content-Length" and v.isdecimal():
752
- self._clen = int(v)
798
+ elif h == "Content-Length":
799
+ try:
800
+ content_length = int(v)
801
+ if content_length < 0 or str(content_length) != v:
802
+ raise ValueError("Not an unsigned ASCII decimal")
803
+ self._clen = content_length
804
+ except ValueError:
805
+ pass # Will be an error in 1.4
753
806
 
754
807
  if self.name is None:
755
808
  raise ParserError("Missing Content-Disposition segment header")
@@ -794,7 +847,7 @@ class MultipartParser:
794
847
  stream,
795
848
  boundary,
796
849
  content_length=-1,
797
- charset="utf8",
850
+ charset="utf-8",
798
851
  strict=False,
799
852
  buffer_size=1024 * 64,
800
853
  header_limit=8,
@@ -936,7 +989,7 @@ class MultipartPart:
936
989
  segment: "MultipartSegment",
937
990
  buffer_size=2**16,
938
991
  memfile_limit=2**18,
939
- charset="utf8",
992
+ charset="utf-8",
940
993
  ):
941
994
  """Private constructor, used by :class:`MultipartParser`"""
942
995
 
@@ -1007,7 +1060,7 @@ class MultipartPart:
1007
1060
  Warning, this may consume a lot of memory, check :attr:`size` first.
1008
1061
  """
1009
1062
 
1010
- return self.raw.decode(self.charset)
1063
+ return self.raw.decode(_safe_charset(self.charset, strict=False))
1011
1064
 
1012
1065
  @property
1013
1066
  def raw(self):
@@ -1068,7 +1121,7 @@ def is_form_request(environ):
1068
1121
 
1069
1122
 
1070
1123
  def parse_form_data(
1071
- environ, charset="utf8", strict=False, ignore_errors=None, **kwargs
1124
+ environ, charset="utf-8", strict=False, ignore_errors=None, **kwargs
1072
1125
  ):
1073
1126
  """Parses both types of form data (multipart and url-encoded) from a WSGI
1074
1127
  environment and returns two :class:`MultiDict` instances, one for text form
@@ -1147,6 +1200,7 @@ def parse_form_data(
1147
1200
  if len(data) > mem_limit:
1148
1201
  raise ParserLimitReached("Memory limit exceeded")
1149
1202
 
1203
+ charset = _safe_charset(charset, strict)
1150
1204
  data = data.decode(charset)
1151
1205
  data = parse_qs(data, keep_blank_values=True, encoding=charset)
1152
1206
 
@@ -113,7 +113,7 @@ class TestMultipartParser(BaseParserTest):
113
113
  self.assertEqual(part.size, 3)
114
114
  self.assertEqual(part.name, "file1")
115
115
  self.assertEqual(part.filename, "random.png")
116
- self.assertEqual(part.charset, "utf8")
116
+ self.assertEqual(part.charset, "utf-8")
117
117
  self.assertEqual(part.headerlist, [
118
118
  ('Content-Disposition','form-data; name="file1"; filename="random.png"'),
119
119
  ('Content-Type','image/png')
@@ -150,6 +150,53 @@ class TestPushParser(PushTestBase):
150
150
  with self.assertParseError("Invalid line break in segment header"):
151
151
  self.parse(b"--boundary\r\nfoo:bar\nbar:baz")
152
152
 
153
+ def test_header_charset(self):
154
+ """HTTP content-type headers may declare arbitrary charsets. This is officially
155
+ undefined and also deprected for multipart (everything should be UTF-8), but
156
+ still used by some real-world clients. We still should not blindly trust those,
157
+ as python knows some encodings with really bad performance (e.g. punycode) or
158
+ ones that are no real charsets in the fist place (e.g. rot-13 or base64).
159
+
160
+ In strict mode, we only allow UTF-8 (default), ISO-8859-1 and ASCII, covering all
161
+ modern browsers and clients. In non-strict mode we allow most supported codecs,
162
+ but still reject clearly broken ones (e.g. rot-13, base64, punycode).
163
+ """
164
+ # Valid charsets -> normalize
165
+ self.reset(header_charset="utf8")
166
+ self.assertEqual(self.parser.header_charset, "utf-8")
167
+ self.reset(header_charset="latin1")
168
+ self.assertEqual(self.parser.header_charset, "iso8859-1")
169
+ self.reset(header_charset="US-ASCII")
170
+ self.assertEqual(self.parser.header_charset, "ascii")
171
+
172
+ # Unknown charsets -> reject
173
+ with self.assertParseError("Invalid or unknown charset"):
174
+ self.reset(header_charset="does-not-exist")
175
+ with self.assertRaisesRegex(
176
+ multipart.StrictParserError, "Invalid or unknown charset"
177
+ ):
178
+ self.reset(header_charset="does-not-exist", strict=True)
179
+
180
+ # Unusual charsets -> accept only in non-strict mode
181
+ self.reset(header_charset="cp855") # allowed in non-strict mode
182
+ self.assertEqual(self.parser.header_charset, "cp855")
183
+ with self.assertRaisesRegex(
184
+ multipart.StrictParserError, "Invalid or unknown charset"
185
+ ):
186
+ self.reset(header_charset="cp855", strict=True)
187
+
188
+ # Known bad charsets -> reject
189
+ for bad in ("rot13", "punycode"):
190
+ with self.assertParseError("Invalid or unknown charset"):
191
+ self.reset(header_charset=bad)
192
+ with self.assertRaisesRegex(
193
+ multipart.StrictParserError, "Invalid or unknown charset"
194
+ ):
195
+ self.reset(header_charset=bad, strict=True)
196
+
197
+ def test_init_uncommon_header_charset(self):
198
+ self.reset(header_charset="cp1252")
199
+
153
200
  def test_header_size_limit(self):
154
201
  self.reset(max_header_size=1024)
155
202
  self.parse(b"--boundary\r\n")
@@ -195,6 +242,20 @@ class TestPushParser(PushTestBase):
195
242
  with self.assertParseError("Maximum segment header length exceeded"):
196
243
  self.parse(b"\tmoooooooooooooooooooooooooore value\r\n")
197
244
 
245
+ def test_header_continuation_long_whitespace_padded(self):
246
+ self.reset(max_header_size=64)
247
+ self.parse(b"--boundary\r\n")
248
+ self.parse(b"Content-Disposition: form-data; name=foo\r\n")
249
+ with self.assertRaises(multipart.ParserLimitReached):
250
+ self.parse(b" " * 65 + b"value\r\n")
251
+
252
+ def test_header_continuation_whitespace(self):
253
+ self.parse(b"--boundary\r\n")
254
+ self.parse(b"Content-Disposition: form-data; name=foo\r\n")
255
+ # Do not allow whitespace only continuations.
256
+ with self.assertRaises(multipart.ParserError):
257
+ self.parse(b" \r\n")
258
+
198
259
  def test_header_bad_name(self):
199
260
  self.reset()
200
261
  with self.assertParseError("Malformed segment header"):
@@ -463,12 +524,12 @@ class TestPushParser(PushTestBase):
463
524
 
464
525
  def test_error_property(self):
465
526
  with self.assertRaises(multipart.MultipartError):
466
- self.parse('--boundary\r\njunk\r\n--boundary--')
527
+ self.parse('--boundary\r\njunk\r\n\r\n--boundary--')
467
528
  self.assertIsInstance(self.parser.error, multipart.ParserError)
468
529
 
469
530
  def test_error_twice(self):
470
531
  with self.assertRaises(multipart.ParserError):
471
- self.parse('--boundary\r\njunk\r\n--boundary--')
532
+ self.parse('--boundary\r\njunk\r\n\r\n--boundary--')
472
533
  first_error = self.parser.error
473
534
  self.assertIsInstance(first_error, multipart.ParserError)
474
535
  # The first error should stick
@@ -1,5 +1,6 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  from .utils import BaseParserTest
3
+ import urllib.parse
3
4
 
4
5
  import multipart
5
6
 
@@ -43,8 +44,8 @@ class TestFormParser(BaseParserTest):
43
44
  def test_urlencoded_latin1(self):
44
45
  for ctype in ('application/x-www-form-urlencoded', 'application/x-url-encoded'):
45
46
  self.reset().write(b'a=\xe0\xe1&e=%E8%E9')
46
- self.environ['CONTENT_TYPE'] = ctype
47
- forms, files = self.parse_form_data(charset='iso-8859-1')
47
+ self.environ['CONTENT_TYPE'] = ctype + "; charset=iso-8859-1"
48
+ forms, files = self.parse_form_data()
48
49
  self.assertEqual(forms['a'], 'àá')
49
50
  self.assertEqual(forms['e'], 'èé')
50
51
 
@@ -56,6 +57,46 @@ class TestFormParser(BaseParserTest):
56
57
  self.assertEqual(forms['a'], 'ƀ♭')
57
58
  self.assertEqual(forms['e'], 'ḟ♮')
58
59
 
60
+ def test_urlencoded_uncommon_charsets(self):
61
+ # Allow in non-strict mode
62
+ for uncommon, char in (('latin8', 'Æ'), ('cp855', 'Я')):
63
+ d = {char: char}
64
+ self.reset().write(
65
+ urllib.parse.urlencode(d, encoding=uncommon).encode(uncommon)
66
+ )
67
+ self.environ['CONTENT_TYPE'] = (
68
+ f'application/x-www-form-urlencoded; charset={uncommon}'
69
+ )
70
+ forms, files = self.parse_form_data()
71
+ self.assertEqual(forms, d)
72
+
73
+ # Deny in strict mode
74
+ for uncommon, char in (('latin8', 'Æ'), ('cp855', 'Я')):
75
+ d = {char: char}
76
+ self.reset().write(
77
+ urllib.parse.urlencode(d, encoding=uncommon).encode(uncommon)
78
+ )
79
+ self.environ['CONTENT_TYPE'] = (
80
+ f'application/x-www-form-urlencoded; charset={uncommon}'
81
+ )
82
+ with self.assertRaises(multipart.StrictParserError):
83
+ forms, files = self.parse_form_data(strict=True)
84
+
85
+ def test_urlencoded_bad_charsets(self):
86
+ for bad in ('rot13', 'base64', 'punycode'):
87
+ self.reset().write(b"a=b")
88
+ self.environ['CONTENT_TYPE'] = (
89
+ f'application/x-www-form-urlencoded; charset={bad}'
90
+ )
91
+ with self.assertRaises(multipart.ParserError):
92
+ forms, files = self.parse_form_data(strict=True)
93
+ with self.assertRaises(multipart.ParserError):
94
+ forms, files = self.parse_form_data(
95
+ strict=False, ignore_errors=False
96
+ )
97
+ forms, files = self.parse_form_data()
98
+ self.assertEqual(forms, {})
99
+
59
100
  def test_empty(self):
60
101
  with self.assertRaises(multipart.MultipartError):
61
102
  self.parse_form_data(strict=True)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes