multipart 2.0.0__tar.gz → 2.0.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.
- {multipart-2.0.0 → multipart-2.0.2}/PKG-INFO +1 -1
- {multipart-2.0.0 → multipart-2.0.2}/multipart.py +113 -67
- {multipart-2.0.0 → multipart-2.0.2}/test/test_legacy_parser.py +1 -1
- {multipart-2.0.0 → multipart-2.0.2}/test/test_push_parser.py +90 -12
- {multipart-2.0.0 → multipart-2.0.2}/test/test_wsgi_parser.py +44 -2
- {multipart-2.0.0 → multipart-2.0.2}/CHANGELOG.rst +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/LICENSE +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/MAINTAINERS.rst +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/README.rst +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/pyproject.toml +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/test/__init__.py +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/test/__main__.py +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/test/test_header_utils.py +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/test/test_multdict.py +0 -0
- {multipart-2.0.0 → multipart-2.0.2}/test/utils.py +0 -0
|
@@ -11,7 +11,7 @@ License: MIT (see LICENSE file)
|
|
|
11
11
|
"""
|
|
12
12
|
|
|
13
13
|
__author__ = "Marcel Hellkamp"
|
|
14
|
-
__version__ =
|
|
14
|
+
__version__ = "2.0.2"
|
|
15
15
|
__license__ = "MIT"
|
|
16
16
|
__all__ = [
|
|
17
17
|
"MultipartError",
|
|
@@ -177,7 +177,7 @@ class MultiDict(DictMixin):
|
|
|
177
177
|
yield key, value
|
|
178
178
|
|
|
179
179
|
|
|
180
|
-
def to_bytes(data, enc="
|
|
180
|
+
def to_bytes(data, enc="utf-8"):
|
|
181
181
|
if isinstance(data, str):
|
|
182
182
|
data = data.encode(enc)
|
|
183
183
|
|
|
@@ -199,16 +199,6 @@ def copy_file(stream, target, maxread=-1, buffer_size=2**16):
|
|
|
199
199
|
size += len(part)
|
|
200
200
|
|
|
201
201
|
|
|
202
|
-
def _is_valid_charset(charset):
|
|
203
|
-
if charset in _KNOWN_CHARSETS:
|
|
204
|
-
return True
|
|
205
|
-
try:
|
|
206
|
-
codecs.lookup(charset)
|
|
207
|
-
return True
|
|
208
|
-
except (LookupError, TypeError):
|
|
209
|
-
return False
|
|
210
|
-
|
|
211
|
-
|
|
212
202
|
# -------------
|
|
213
203
|
# Header Parser
|
|
214
204
|
# -------------
|
|
@@ -345,13 +335,52 @@ def parse_content_disposition(value: str) -> tuple[str, str | None, str | None]:
|
|
|
345
335
|
##############################################################################
|
|
346
336
|
|
|
347
337
|
|
|
348
|
-
#
|
|
338
|
+
# fmt: off
|
|
339
|
+
#: Known-good header names, used to skip costly validity checks.
|
|
349
340
|
_KNOWN_HEADERS = frozenset(
|
|
350
|
-
|
|
351
|
-
)
|
|
352
|
-
_KNOWN_CHARSETS = frozenset(
|
|
353
|
-
("utf8", "utf-8", "ascii", "us-ascii", "latin1", "latin-1", "iso-8859-1")
|
|
341
|
+
("Content-Disposition", "Content-Type", "Content-Length", "Content-Range")
|
|
354
342
|
)
|
|
343
|
+
|
|
344
|
+
#: Known-good header charsets and some common aliases mapped to their actual name
|
|
345
|
+
_KNOWN_CHARSETS = {
|
|
346
|
+
alias: codecs.lookup(alias).name
|
|
347
|
+
for alias in (
|
|
348
|
+
"utf-8", "utf8",
|
|
349
|
+
"ascii", "us-ascii",
|
|
350
|
+
"iso8859-1", "iso-8859-1", "latin1", "latin-1",
|
|
351
|
+
)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
#: Python specific charsets that should never be used by valid clients.
|
|
355
|
+
_BAD_CHARSETS = {
|
|
356
|
+
"unicode-escape", "punycode", "rot-13", "raw-unicode-escape", "hex",
|
|
357
|
+
"bz2", "palmos", "undefined", "zlib", "base64", "idna", "quopri",
|
|
358
|
+
"uu", "mbcs", "oem"
|
|
359
|
+
}
|
|
360
|
+
# fmt: on
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _safe_charset(charset: str, strict: bool):
|
|
364
|
+
"""Return the actual name of a given charset or common alias while
|
|
365
|
+
rejecting problematic or unknown charsets. In strict mode, only a
|
|
366
|
+
small set of known charsets is allowed and any other charset raises
|
|
367
|
+
an exception. In non-strict mode, uncommon charsets are also allowed.
|
|
368
|
+
Unknown or known bad charsets always raise an exception."""
|
|
369
|
+
if charset == "utf-8":
|
|
370
|
+
return "utf-8"
|
|
371
|
+
if good := _KNOWN_CHARSETS.get(charset.lower()):
|
|
372
|
+
return good
|
|
373
|
+
if strict:
|
|
374
|
+
raise StrictParserError(f"Invalid or unknown charset: {charset!r}")
|
|
375
|
+
try:
|
|
376
|
+
info = codecs.lookup(charset)
|
|
377
|
+
if info.name not in _BAD_CHARSETS:
|
|
378
|
+
return info.name
|
|
379
|
+
except LookupError:
|
|
380
|
+
pass
|
|
381
|
+
raise ParserError(f"Invalid or unknown charset: {charset!r}")
|
|
382
|
+
|
|
383
|
+
|
|
355
384
|
# Parser states as constants
|
|
356
385
|
_PREAMBLE = object()
|
|
357
386
|
_HEADER = object()
|
|
@@ -359,6 +388,10 @@ _BODY = object()
|
|
|
359
388
|
_COMPLETE = object()
|
|
360
389
|
|
|
361
390
|
|
|
391
|
+
class _TaggedBytes(bytes):
|
|
392
|
+
"""A `bytes` subclass with extra meaning or metadata attached to it."""
|
|
393
|
+
|
|
394
|
+
|
|
362
395
|
class PushMultipartParser:
|
|
363
396
|
"""An incremental non-blocking parser for multipart/form-data.
|
|
364
397
|
|
|
@@ -386,7 +419,7 @@ class PushMultipartParser:
|
|
|
386
419
|
max_header_count=8, # RFC 7578 allows just 3
|
|
387
420
|
max_segment_size=inf, # unlimited
|
|
388
421
|
max_segment_count=inf, # unlimited
|
|
389
|
-
header_charset="
|
|
422
|
+
header_charset="utf-8",
|
|
390
423
|
strict=False,
|
|
391
424
|
):
|
|
392
425
|
"""Create a new parser instance.
|
|
@@ -402,7 +435,7 @@ class PushMultipartParser:
|
|
|
402
435
|
"""
|
|
403
436
|
self.boundary = to_bytes(boundary)
|
|
404
437
|
self.content_length = content_length
|
|
405
|
-
self.header_charset = header_charset
|
|
438
|
+
self.header_charset = _safe_charset(header_charset or "utf-8", strict)
|
|
406
439
|
self.max_header_size = max_header_size
|
|
407
440
|
self.max_header_count = max_header_count
|
|
408
441
|
self.max_segment_size = max_segment_size
|
|
@@ -415,8 +448,6 @@ class PushMultipartParser:
|
|
|
415
448
|
raise ParserError("Invalid characters in boundary")
|
|
416
449
|
if self.strict and len(self.boundary) > 1024:
|
|
417
450
|
raise StrictParserError("Boundary too long")
|
|
418
|
-
if not _is_valid_charset(header_charset):
|
|
419
|
-
raise ParserError(f"Invalid charset: {header_charset!r}")
|
|
420
451
|
|
|
421
452
|
# Internal parser state
|
|
422
453
|
self._delimiter = b"\r\n--" + self.boundary
|
|
@@ -426,7 +457,7 @@ class PushMultipartParser:
|
|
|
426
457
|
|
|
427
458
|
self._segment: Optional["MultipartSegment"] = None
|
|
428
459
|
self._segment_count = 0
|
|
429
|
-
self.
|
|
460
|
+
self._segment_headerlines: List[bytes] = []
|
|
430
461
|
self._segment_limit = -1
|
|
431
462
|
|
|
432
463
|
#: True if the parser was closed, either successfully by reaching the
|
|
@@ -559,7 +590,9 @@ class PushMultipartParser:
|
|
|
559
590
|
offset = nl + 2
|
|
560
591
|
continue
|
|
561
592
|
elif nl == offset: # Empty header line -> End of header section
|
|
562
|
-
self._segment = self._create_segment(
|
|
593
|
+
self._segment = self._create_segment(
|
|
594
|
+
self._collect_segment_headers()
|
|
595
|
+
)
|
|
563
596
|
yield self._segment
|
|
564
597
|
self._state = _BODY
|
|
565
598
|
offset += 2
|
|
@@ -721,56 +754,69 @@ class PushMultipartParser:
|
|
|
721
754
|
raise ParserLimitReached("Maximum segment count exceeded")
|
|
722
755
|
|
|
723
756
|
self._segment = None
|
|
724
|
-
self.
|
|
757
|
+
self._segment_headerlines = []
|
|
725
758
|
self._segment_limit = -1
|
|
726
759
|
|
|
727
760
|
def _on_segment_headerline(self, line: bytes):
|
|
728
|
-
"""
|
|
729
|
-
|
|
761
|
+
"""Collect raw header lines and enforce limits. Merge multi-line header in
|
|
762
|
+
non-strict mode only."""
|
|
730
763
|
assert line and self._segment is None
|
|
731
764
|
|
|
732
765
|
# Handle header continuation (headers split into multiple lines)
|
|
733
766
|
if line[0] in b" \t": # Multi-line header value
|
|
734
|
-
if
|
|
767
|
+
if self.strict:
|
|
735
768
|
raise StrictParserError("Unexpected segment header continuation")
|
|
736
|
-
|
|
737
|
-
|
|
769
|
+
if not self._segment_headerlines:
|
|
770
|
+
raise ParserError("Unexpected segment header continuation")
|
|
771
|
+
last = self._segment_headerlines.pop()
|
|
772
|
+
if isinstance(last, _TaggedBytes):
|
|
773
|
+
raise ParserLimitReached("Too many segment header continuations")
|
|
774
|
+
line = _TaggedBytes(last + b" " + line[1:])
|
|
738
775
|
|
|
739
776
|
# Enforce header limits
|
|
740
777
|
if len(line) > self.max_header_size:
|
|
741
778
|
raise ParserLimitReached("Maximum segment header length exceeded")
|
|
742
|
-
if len(self.
|
|
779
|
+
if len(self._segment_headerlines) >= self.max_header_count:
|
|
743
780
|
raise ParserLimitReached("Maximum segment header count exceeded")
|
|
744
781
|
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
name = name.strip().title()
|
|
754
|
-
if name not in _KNOWN_HEADERS and not _re_hname.fullmatch(name):
|
|
755
|
-
raise ParserError("Invalid segment header name")
|
|
756
|
-
value = value.strip()
|
|
757
|
-
|
|
758
|
-
if name == "Content-Length":
|
|
759
|
-
if self._segment_limit >= 0:
|
|
760
|
-
raise ParserError("Multiple segment Content-Length headers")
|
|
782
|
+
self._segment_headerlines.append(line)
|
|
783
|
+
|
|
784
|
+
def _collect_segment_headers(self):
|
|
785
|
+
"""Parse and decode all collected header lines into a (name, value) list."""
|
|
786
|
+
parsed = []
|
|
787
|
+
|
|
788
|
+
for line in self._segment_headerlines:
|
|
789
|
+
# Decode headerline into normalized (name, value) pairs
|
|
761
790
|
try:
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
raise ParserError("
|
|
767
|
-
if
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
791
|
+
name, col, value = line.decode(self.header_charset).partition(":")
|
|
792
|
+
except UnicodeDecodeError as err:
|
|
793
|
+
raise ParserError("Segment header failed to decode", err)
|
|
794
|
+
if not col:
|
|
795
|
+
raise ParserError("Malformed segment header")
|
|
796
|
+
if name not in _KNOWN_HEADERS:
|
|
797
|
+
name = name.strip().title()
|
|
798
|
+
if name not in _KNOWN_HEADERS and not _re_hname.fullmatch(name):
|
|
799
|
+
raise ParserError("Invalid segment header name")
|
|
800
|
+
value = value.lstrip(" \t")
|
|
801
|
+
parsed.append((name, value))
|
|
802
|
+
|
|
803
|
+
# Set segment read limit from Content-Length segment header
|
|
804
|
+
if name == "Content-Length":
|
|
805
|
+
if self._segment_limit >= 0:
|
|
806
|
+
raise ParserError("Multiple segment Content-Length headers")
|
|
807
|
+
try:
|
|
808
|
+
content_length = int(value)
|
|
809
|
+
if content_length < 0 or str(content_length) != value:
|
|
810
|
+
raise ValueError("Not an unsigned ASCII decimal")
|
|
811
|
+
except ValueError:
|
|
812
|
+
raise ParserError("Invalid segment Content-Length header value")
|
|
813
|
+
if content_length > self.max_segment_size:
|
|
814
|
+
raise ParserLimitReached(
|
|
815
|
+
"Segment Content-Length larger than maximum segment size"
|
|
816
|
+
)
|
|
817
|
+
self._segment_limit = content_length
|
|
772
818
|
|
|
773
|
-
|
|
819
|
+
return parsed
|
|
774
820
|
|
|
775
821
|
def _create_segment(self, headerlist: List[Tuple[str, str]]) -> "MultipartSegment":
|
|
776
822
|
"""Create and return a :class:`MultipartSegment` from a list of headers.
|
|
@@ -926,7 +972,7 @@ class MultipartParser:
|
|
|
926
972
|
stream,
|
|
927
973
|
boundary,
|
|
928
974
|
content_length=-1,
|
|
929
|
-
charset="
|
|
975
|
+
charset="utf-8",
|
|
930
976
|
strict=False,
|
|
931
977
|
buffer_size=1024 * 64,
|
|
932
978
|
header_limit=8,
|
|
@@ -1072,7 +1118,7 @@ class MultipartPart:
|
|
|
1072
1118
|
segment: "MultipartSegment",
|
|
1073
1119
|
buffer_size=2**16,
|
|
1074
1120
|
memfile_limit=2**18,
|
|
1075
|
-
charset="
|
|
1121
|
+
charset="utf-8",
|
|
1076
1122
|
):
|
|
1077
1123
|
"""Private constructor, used by :class:`MultipartParser`"""
|
|
1078
1124
|
|
|
@@ -1144,7 +1190,7 @@ class MultipartPart:
|
|
|
1144
1190
|
Warning, this may consume a lot of memory, check :attr:`size` first.
|
|
1145
1191
|
"""
|
|
1146
1192
|
|
|
1147
|
-
return self.raw.decode(self.charset)
|
|
1193
|
+
return self.raw.decode(_safe_charset(self.charset, strict=False))
|
|
1148
1194
|
|
|
1149
1195
|
@property
|
|
1150
1196
|
def raw(self):
|
|
@@ -1205,7 +1251,7 @@ def is_form_request(environ):
|
|
|
1205
1251
|
|
|
1206
1252
|
|
|
1207
1253
|
def parse_form_data(
|
|
1208
|
-
environ, charset="
|
|
1254
|
+
environ, charset="utf-8", strict=False, ignore_errors=None, **kwargs
|
|
1209
1255
|
):
|
|
1210
1256
|
"""Parses both types of form data (multipart and url-encoded) from a WSGI
|
|
1211
1257
|
environment and returns two :class:`MultiDict` instances, one for text form
|
|
@@ -1255,16 +1301,15 @@ def parse_form_data(
|
|
|
1255
1301
|
content_type, options = parse_options_header(content_type)
|
|
1256
1302
|
kwargs["charset"] = charset = options.get("charset", charset)
|
|
1257
1303
|
|
|
1258
|
-
if not _is_valid_charset(charset):
|
|
1259
|
-
raise ParserError(f"Invalid charset: {charset!r}")
|
|
1260
|
-
|
|
1261
1304
|
if content_type == "multipart/form-data":
|
|
1262
1305
|
boundary = options.get("boundary", "")
|
|
1263
1306
|
|
|
1264
1307
|
if not boundary:
|
|
1265
1308
|
raise ParserError("Missing boundary for multipart/form-data")
|
|
1266
1309
|
|
|
1267
|
-
for part in MultipartParser(
|
|
1310
|
+
for part in MultipartParser(
|
|
1311
|
+
stream, boundary, content_length, strict=strict, **kwargs
|
|
1312
|
+
):
|
|
1268
1313
|
if part.filename or not part.is_buffered():
|
|
1269
1314
|
files.append(part.name, part)
|
|
1270
1315
|
else: # TODO: Big form-fields go into the files dict. Really?
|
|
@@ -1291,6 +1336,7 @@ def parse_form_data(
|
|
|
1291
1336
|
if len(data) > mem_limit:
|
|
1292
1337
|
raise ParserLimitReached("Memory limit exceeded")
|
|
1293
1338
|
|
|
1339
|
+
charset = _safe_charset(charset, strict)
|
|
1294
1340
|
fields = data.decode(charset).split("&", part_limit)
|
|
1295
1341
|
if len(fields) > part_limit:
|
|
1296
1342
|
raise ParserLimitReached("Part limit exceeded")
|
|
@@ -1299,8 +1345,8 @@ def parse_form_data(
|
|
|
1299
1345
|
if not name:
|
|
1300
1346
|
continue
|
|
1301
1347
|
forms.append(
|
|
1302
|
-
_unquote_plus(name, encoding=charset
|
|
1303
|
-
_unquote_plus(value or "", encoding=charset
|
|
1348
|
+
_unquote_plus(name, encoding=charset),
|
|
1349
|
+
_unquote_plus(value or "", encoding=charset),
|
|
1304
1350
|
)
|
|
1305
1351
|
|
|
1306
1352
|
elif strict:
|
|
@@ -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, "
|
|
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')
|
|
@@ -35,9 +35,8 @@ def assertRaiseStrict(text):
|
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
class PushTestBase(unittest.TestCase):
|
|
38
|
-
|
|
39
38
|
def setUp(self):
|
|
40
|
-
self.
|
|
39
|
+
self._parser = None
|
|
41
40
|
self.reset()
|
|
42
41
|
self.events = []
|
|
43
42
|
|
|
@@ -51,10 +50,15 @@ class PushTestBase(unittest.TestCase):
|
|
|
51
50
|
|
|
52
51
|
def reset(self, **ka):
|
|
53
52
|
ka.setdefault("boundary", "boundary")
|
|
54
|
-
self.
|
|
53
|
+
self._parser = multipart.PushMultipartParser(**ka)
|
|
55
54
|
self.events = []
|
|
56
55
|
return self
|
|
57
56
|
|
|
57
|
+
@property
|
|
58
|
+
def parser(self):
|
|
59
|
+
assert self._parser, "Parser not prepared yet"
|
|
60
|
+
return self._parser
|
|
61
|
+
|
|
58
62
|
def parse(self, *chunks):
|
|
59
63
|
events = []
|
|
60
64
|
for chunk in chunks:
|
|
@@ -105,12 +109,58 @@ class TestPushParser(PushTestBase):
|
|
|
105
109
|
self.reset(boundary="")
|
|
106
110
|
|
|
107
111
|
def test_init_bad_boundary(self):
|
|
108
|
-
with self.assertParseError(
|
|
112
|
+
with self.assertParseError(
|
|
113
|
+
"Invalid characters in boundary", klass=multipart.ParserError
|
|
114
|
+
):
|
|
109
115
|
self.reset(boundary="foo\nbar")
|
|
110
116
|
|
|
111
|
-
def
|
|
112
|
-
|
|
117
|
+
def test_header_charset(self):
|
|
118
|
+
"""HTTP content-type headers may declare arbitrary charsets. This is officially
|
|
119
|
+
undefined and also deprected for multipart (everything should be UTF-8), but
|
|
120
|
+
still used by some real-world clients. We still should not blindly trust those,
|
|
121
|
+
as python knows some encodings with really bad performance (e.g. punycode) or
|
|
122
|
+
ones that are no real charsets in the fist place (e.g. rot-13 or base64).
|
|
123
|
+
|
|
124
|
+
In strict mode, we only allow UTF-8 (default), ISO-8859-1 and ASCII, covering all
|
|
125
|
+
modern browsers and clients. In non-strict mode we allow most supported codecs,
|
|
126
|
+
but still reject clearly broken ones (e.g. rot-13, base64, punycode).
|
|
127
|
+
"""
|
|
128
|
+
# Valid charsets -> normalize
|
|
129
|
+
self.reset(header_charset="utf8")
|
|
130
|
+
self.assertEqual(self.parser.header_charset, "utf-8")
|
|
131
|
+
self.reset(header_charset="latin1")
|
|
132
|
+
self.assertEqual(self.parser.header_charset, "iso8859-1")
|
|
133
|
+
self.reset(header_charset="US-ASCII")
|
|
134
|
+
self.assertEqual(self.parser.header_charset, "ascii")
|
|
135
|
+
|
|
136
|
+
# Unknown charsets -> reject
|
|
137
|
+
with self.assertParseError(
|
|
138
|
+
"Invalid or unknown charset", klass=multipart.ParserError
|
|
139
|
+
):
|
|
113
140
|
self.reset(header_charset="does-not-exist")
|
|
141
|
+
with self.assertParseError(
|
|
142
|
+
"Invalid or unknown charset", klass=multipart.StrictParserError
|
|
143
|
+
):
|
|
144
|
+
self.reset(header_charset="does-not-exist", strict=True)
|
|
145
|
+
|
|
146
|
+
# Unusual charsets -> accept only in non-strict mode
|
|
147
|
+
self.reset(header_charset="cp855") # allowed in non-strict mode
|
|
148
|
+
self.assertEqual(self.parser.header_charset, "cp855")
|
|
149
|
+
with self.assertParseError(
|
|
150
|
+
"Invalid or unknown charset", klass=multipart.StrictParserError
|
|
151
|
+
):
|
|
152
|
+
self.reset(header_charset="cp855", strict=True)
|
|
153
|
+
|
|
154
|
+
# Known bad charsets -> reject
|
|
155
|
+
for bad in ("rot13", "punycode"):
|
|
156
|
+
with self.assertParseError(
|
|
157
|
+
"Invalid or unknown charset", klass=multipart.ParserError
|
|
158
|
+
):
|
|
159
|
+
self.reset(header_charset=bad)
|
|
160
|
+
with self.assertParseError(
|
|
161
|
+
"Invalid or unknown charset", klass=multipart.StrictParserError
|
|
162
|
+
):
|
|
163
|
+
self.reset(header_charset=bad, strict=True)
|
|
114
164
|
|
|
115
165
|
def test_init_uncommon_header_charset(self):
|
|
116
166
|
self.reset(header_charset="cp1252")
|
|
@@ -120,7 +170,9 @@ class TestPushParser(PushTestBase):
|
|
|
120
170
|
self.reset(boundary="x" * 1025, max_header_size=1024, strict=strict)
|
|
121
171
|
|
|
122
172
|
def test_bad_chunk_type(self):
|
|
123
|
-
with self.assertParseError(
|
|
173
|
+
with self.assertParseError(
|
|
174
|
+
"Invalid chunk type", klass=multipart.ParserStateError
|
|
175
|
+
):
|
|
124
176
|
self.parse(5)
|
|
125
177
|
|
|
126
178
|
@assertRaiseStrict("Unexpected data after end of multipart stream")
|
|
@@ -241,6 +293,34 @@ class TestPushParser(PushTestBase):
|
|
|
241
293
|
with self.assertParseError("Maximum segment header length exceeded"):
|
|
242
294
|
self.parse(b"\tmoooooooooooooooooooooooooore value\r\n")
|
|
243
295
|
|
|
296
|
+
def test_header_continuation_limit(self):
|
|
297
|
+
"""Even in non-strict mode only allow one continuation per
|
|
298
|
+
segment header."""
|
|
299
|
+
self.parse(b"--boundary\r\n")
|
|
300
|
+
self.parse(b"Content-Disposition: form-data;\r\n")
|
|
301
|
+
self.parse(b'\tname="foo"\r\n')
|
|
302
|
+
with self.assertRaisesRegex(
|
|
303
|
+
multipart.ParserLimitReached,
|
|
304
|
+
"Too many segment header continuations",
|
|
305
|
+
):
|
|
306
|
+
self.parse(b" value\r\n")
|
|
307
|
+
|
|
308
|
+
def test_header_continuation_long_whitespace_padded(self):
|
|
309
|
+
self.reset(max_header_size=64)
|
|
310
|
+
self.parse(b"--boundary\r\n")
|
|
311
|
+
self.parse(b"Content-Disposition: form-data; name=foo\r\n")
|
|
312
|
+
with self.assertRaises(multipart.ParserLimitReached):
|
|
313
|
+
self.parse(b" " * 65 + b"value\r\n")
|
|
314
|
+
|
|
315
|
+
def test_header_continuation_many_unicode_whitespace(self):
|
|
316
|
+
self.reset(max_header_size=64)
|
|
317
|
+
self.parse(b"--boundary\r\n")
|
|
318
|
+
self.parse(b"Content-Disposition: form-data; name=foo\r\n")
|
|
319
|
+
# This bypasses the strict whitespace-only checks inside continuation
|
|
320
|
+
# logic which operate on bytes, but should still hit the header size limit.
|
|
321
|
+
with self.assertRaises(multipart.ParserLimitReached):
|
|
322
|
+
self.parse(b" \xc2\xa0\r\n" * 32)
|
|
323
|
+
|
|
244
324
|
def test_header_no_colon(self):
|
|
245
325
|
with self.assertParseError("Malformed segment header"):
|
|
246
326
|
self.parse(b"--boundary\r\nno-colon\r\n\r\ndata\r\n--boundary--")
|
|
@@ -564,9 +644,7 @@ class TestPushParser(PushTestBase):
|
|
|
564
644
|
|
|
565
645
|
def assert_bad_content(*content):
|
|
566
646
|
self.reset()
|
|
567
|
-
with self.assertParseError(
|
|
568
|
-
"Unexpected bytes after boundary"
|
|
569
|
-
):
|
|
647
|
+
with self.assertParseError("Unexpected bytes after boundary"):
|
|
570
648
|
self.parse(
|
|
571
649
|
"--boundary\r\n",
|
|
572
650
|
'Content-Disposition: form-data; name="bad"\r\n',
|
|
@@ -713,12 +791,12 @@ class TestPushParser(PushTestBase):
|
|
|
713
791
|
|
|
714
792
|
def test_error_property(self):
|
|
715
793
|
with self.assertRaises(multipart.MultipartError):
|
|
716
|
-
self.parse("--boundary\r\njunk\r\n--boundary--")
|
|
794
|
+
self.parse("--boundary\r\njunk\r\n\r\n--boundary--")
|
|
717
795
|
self.assertIsInstance(self.parser.error, multipart.ParserError)
|
|
718
796
|
|
|
719
797
|
def test_error_twice(self):
|
|
720
798
|
with self.assertRaises(multipart.ParserError):
|
|
721
|
-
self.parse("--boundary\r\njunk\r\n--boundary--")
|
|
799
|
+
self.parse("--boundary\r\njunk\r\n\r\n--boundary--")
|
|
722
800
|
first_error = self.parser.error
|
|
723
801
|
self.assertIsInstance(first_error, multipart.ParserError)
|
|
724
802
|
# 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
|
|
|
@@ -26,6 +27,19 @@ class TestFormParser(BaseParserTest):
|
|
|
26
27
|
self.assertEqual(files['file1'].name, 'file1')
|
|
27
28
|
self.assertEqual(files['file1'].content_type, 'image/png')
|
|
28
29
|
|
|
30
|
+
def test_multipart_strict_passed_to_parser(self):
|
|
31
|
+
self.write(
|
|
32
|
+
"--foo\r\n",
|
|
33
|
+
"Content-Disposition: form-data;\r\n", # no name
|
|
34
|
+
'\tname="text1"\r\n',
|
|
35
|
+
"\r\n",
|
|
36
|
+
"abc",
|
|
37
|
+
"\r\n--foo--",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
with self.assertRaises(multipart.StrictParserError):
|
|
41
|
+
self.parse_form_data(strict=True)
|
|
42
|
+
|
|
29
43
|
def test_empty(self):
|
|
30
44
|
self.write_end()
|
|
31
45
|
forms, files = self.parse_form_data()
|
|
@@ -47,8 +61,8 @@ class TestFormParser(BaseParserTest):
|
|
|
47
61
|
def test_urlencoded_latin1(self):
|
|
48
62
|
for ctype in ('application/x-www-form-urlencoded', 'application/x-url-encoded'):
|
|
49
63
|
self.reset().write(b'a=\xe0\xe1&e=%E8%E9')
|
|
50
|
-
self.environ['CONTENT_TYPE'] = ctype
|
|
51
|
-
forms, files = self.parse_form_data(
|
|
64
|
+
self.environ['CONTENT_TYPE'] = ctype + "; charset=iso-8859-1"
|
|
65
|
+
forms, files = self.parse_form_data()
|
|
52
66
|
self.assertEqual(forms['a'], 'àá')
|
|
53
67
|
self.assertEqual(forms['e'], 'èé')
|
|
54
68
|
|
|
@@ -60,6 +74,34 @@ class TestFormParser(BaseParserTest):
|
|
|
60
74
|
self.assertEqual(forms['a'], 'ƀ♭')
|
|
61
75
|
self.assertEqual(forms['e'], 'ḟ♮')
|
|
62
76
|
|
|
77
|
+
def test_urlencoded_uncommon_charsets(self):
|
|
78
|
+
# Allow in non-strict mode
|
|
79
|
+
for uncommon, char in (('latin8','Æ'), ('cp855','Я')):
|
|
80
|
+
d = {char: char}
|
|
81
|
+
self.reset().write(urllib.parse.urlencode(d, encoding=uncommon).encode(uncommon))
|
|
82
|
+
self.environ['CONTENT_TYPE'] = f'application/x-www-form-urlencoded; charset={uncommon}'
|
|
83
|
+
forms, files = self.parse_form_data()
|
|
84
|
+
self.assertEqual(forms, d)
|
|
85
|
+
|
|
86
|
+
# Deny in strict mode
|
|
87
|
+
for uncommon, char in (('latin8','Æ'), ('cp855','Я')):
|
|
88
|
+
d = {char: char}
|
|
89
|
+
self.reset().write(urllib.parse.urlencode(d, encoding=uncommon).encode(uncommon))
|
|
90
|
+
self.environ['CONTENT_TYPE'] = f'application/x-www-form-urlencoded; charset={uncommon}'
|
|
91
|
+
with self.assertRaises(multipart.StrictParserError):
|
|
92
|
+
forms, files = self.parse_form_data(strict=True)
|
|
93
|
+
|
|
94
|
+
def test_urlencoded_bad_charsets(self):
|
|
95
|
+
for bad in ('rot13', 'base64', 'punycode'):
|
|
96
|
+
self.reset().write(b"a=b")
|
|
97
|
+
self.environ['CONTENT_TYPE'] = f'application/x-www-form-urlencoded; charset={bad}'
|
|
98
|
+
with self.assertRaises(multipart.ParserError):
|
|
99
|
+
forms, files = self.parse_form_data(strict=True)
|
|
100
|
+
with self.assertRaises(multipart.ParserError):
|
|
101
|
+
forms, files = self.parse_form_data(strict=False, ignore_errors=False)
|
|
102
|
+
forms, files = self.parse_form_data()
|
|
103
|
+
self.assertEqual(forms, {})
|
|
104
|
+
|
|
63
105
|
def test_urlencoded_empty_name_value(self):
|
|
64
106
|
" Enpty names are skipped, empty values are just empty"
|
|
65
107
|
self.reset().write('name_only&empty_value=&=empty_name')
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|