From c814948acf509cef7881fa75c969969b19239bbf Mon Sep 17 00:00:00 2001
From: Marcelo Trylesinski <marcelotryle@gmail.com>
Date: Thu, 4 Jun 2026 10:18:46 +0200
Subject: [PATCH] Reject negative `Content-Length` in `parse_form` (#297)

---
 python_multipart/multipart.py | 2 ++
 tests/test_multipart.py       | 9 +++++++++
 2 files changed, 11 insertions(+)

Index: python_multipart-0.0.28/python_multipart/multipart.py
===================================================================
--- python_multipart-0.0.28.orig/python_multipart/multipart.py
+++ python_multipart-0.0.28/python_multipart/multipart.py
@@ -1892,6 +1892,8 @@ def parse_form(
     content_length: int | float | bytes | None = headers.get("Content-Length")
     if content_length is not None:
         content_length = int(content_length)
+        if content_length < 0:
+            raise ValueError("Content-Length must be non-negative")
     else:
         content_length = float("inf")
     bytes_read = 0
Index: python_multipart-0.0.28/tests/test_multipart.py
===================================================================
--- python_multipart-0.0.28.orig/tests/test_multipart.py
+++ python_multipart-0.0.28/tests/test_multipart.py
@@ -1651,6 +1651,15 @@ class TestHelperFunctions(unittest.TestC
                 chunk_size=0,
             )
 
+    def test_parse_form_negative_content_length(self) -> None:
+        with self.assertRaisesRegex(ValueError, "Content-Length must be non-negative"):
+            parse_form(
+                {"Content-Type": b"application/octet-stream", "Content-Length": b"-1"},
+                BytesIO(b"123456789012345"),
+                lambda _: None,
+                lambda _: None,
+            )
+
 
 def suite() -> unittest.TestSuite:
     suite = unittest.TestSuite()
