From 954df085a5ac8c71a1cc845ef93712d6b96ee818 Mon Sep 17 00:00:00 2001 From: John Stark Date: Mon, 16 Dec 2024 20:59:24 +0100 Subject: [PATCH] Check for field name and raise if not found --- python_multipart/multipart.py | 8 +++++--- tests/test_multipart.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/python_multipart/multipart.py b/python_multipart/multipart.py index 7338e67..ebfeaf3 100644 --- a/python_multipart/multipart.py +++ b/python_multipart/multipart.py @@ -1562,7 +1562,7 @@ def __init__( def on_start() -> None: nonlocal file - file = FileClass(file_name, config=cast("FileConfig", self.config)) + file = FileClass(file_name, b"", config=cast("FileConfig", self.config)) def on_data(data: bytes, start: int, end: int) -> None: nonlocal file @@ -1692,9 +1692,11 @@ def on_headers_finished() -> None: disp, options = parse_options_header(content_disp) # Get the field and filename. - field_name = options.get(b"name", b"") + field_name = options.get(b"name") file_name = options.get(b"filename") - # TODO: check for errors + if field_name is None: + raise FormParserError('Field name not found in Content-Disposition: "{!r}"'.format(content_disp)) + # TODO: check for other errors # Create the proper class. content_type_b = headers.get("content-type") diff --git a/tests/test_multipart.py b/tests/test_multipart.py index a29b7ae..3c5546f 100644 --- a/tests/test_multipart.py +++ b/tests/test_multipart.py @@ -1235,6 +1235,23 @@ def on_file(f: FileProtocol) -> None: f.finalize() self.assert_file_data(files[0], b"Test") + def test_bad_content_disposition(self) -> None: + # Field name is required. + data = ( + b"----boundary\r\nContent-Disposition: form-data;\r\n" + b"Content-Type: text/plain\r\n" + b"Test\r\n----boundary--\r\n" + ) + + on_field = Mock() + on_file = Mock() + + f = FormParser("multipart/form-data", on_field, on_file, boundary="--boundary") + + with self.assertRaises(FormParserError): + f.write(data) + f.finalize() + def test_handles_None_fields(self) -> None: fields: list[Field] = []