Skip to content

Commit

Permalink
Use trust_x_header and test it.
Browse files Browse the repository at this point in the history
  • Loading branch information
jhnstrk committed Dec 8, 2024
1 parent f1c5a28 commit 1e12a71
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion python_multipart/multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -1798,7 +1798,10 @@ def create_form_parser(
content_type = content_type.decode("latin-1")

# File names are optional.
file_name = headers.get("X-File-Name")
if trust_x_headers:
file_name = headers.get("X-File-Name")
else:
file_name = None

# Instantiate a form parser.
form_parser = FormParser(content_type, on_field, on_file, boundary=boundary, file_name=file_name, config=config)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -1368,6 +1368,7 @@ def on_header_begin() -> None:
self.assertEqual(calls, 3)


@parametrize_class
class TestHelperFunctions(unittest.TestCase):
def test_create_form_parser(self) -> None:
r = create_form_parser({"Content-Type": b"application/octet-stream"}, None, None)
Expand All @@ -1390,6 +1391,24 @@ def test_parse_form(self) -> None:
# 15 - i.e. all data is written.
self.assertEqual(on_file.call_args[0][0].size, 15)

@parametrize("trust_x_headers", [True, False])
def test_parse_form_trust_x_false(self, trust_x_headers: bool) -> None:
on_field = Mock()
on_file = Mock()

headers = {"Content-Type": b"application/octet-stream", "X-File-Name": b"foo.txt"}
parser = create_form_parser(headers, on_field, on_file, trust_x_headers=trust_x_headers)
parser.write(b"123456789012345")
parser.finalize()

assert on_file.call_count == 1

# The first argument (a File Object) name should come from the X header only if allowed.
if trust_x_headers:
self.assertEqual(on_file.call_args[0][0].file_name, b"foo.txt")
else:
self.assertEqual(on_file.call_args[0][0].file_name, None)

def test_parse_form_content_length(self) -> None:
files: list[FileProtocol] = []

Expand Down

0 comments on commit 1e12a71

Please sign in to comment.