From f60926e95f06980ba6ed7327295eb34ce5be780e Mon Sep 17 00:00:00 2001 From: Alc-Alc Date: Mon, 23 Nov 2026 17:58:45 +0530 Subject: [PATCH 1/2] fix: only use plain path segments as the section Surrogate-Key --- pydotorg/middleware.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/pydotorg/middleware.py b/pydotorg/middleware.py index b495f3aeb..fa3a98f22 100644 --- a/pydotorg/middleware.py +++ b/pydotorg/middleware.py @@ -1,7 +1,11 @@ """Middleware for cache control and surrogate keys.""" +import re + from django.conf import settings +SECTION_KEY_RE = re.compile(r"[A-Za-z0-9._-]+") + class AdminNoCaching: """Middleware to ensure the admin is not cached by Fastly or other caches.""" @@ -32,16 +36,20 @@ def __init__(self, get_response): def get_section_key(self, path): """Extract section surrogate key from URL path. + The first segment is only used when it is a plain name (letters, digits, + ".", "_", "-"), so the key is always a single valid header token. + Examples: /downloads/ -> downloads /downloads/release/python-3141/ -> downloads /events/python-events/ -> events / -> None + /downloads. 3/ -> None """ - parts = path.strip("/").split("/") - if parts and parts[0]: - return parts[0] + section = path.strip("/").split("/")[0] + if SECTION_KEY_RE.fullmatch(section): + return section return None def __call__(self, request): From 4468922f82352f275222bd38d981cb7ee6c095ae Mon Sep 17 00:00:00 2001 From: Alc-Alc Date: Mon, 23 Nov 2026 17:59:04 +0530 Subject: [PATCH 2/2] test: cover unsafe path segments in GlobalSurrogateKey --- pydotorg/tests/test_middleware.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pydotorg/tests/test_middleware.py b/pydotorg/tests/test_middleware.py index cde44681e..282419614 100644 --- a/pydotorg/tests/test_middleware.py +++ b/pydotorg/tests/test_middleware.py @@ -44,6 +44,9 @@ def test_get_section_key(self): # returns None self.assertIsNone(middleware.get_section_key("/")) + self.assertIsNone(middleware.get_section_key("/downloads. \r3")) + self.assertIsNone(middleware.get_section_key("/\nURL")) + self.assertIsNone(middleware.get_section_key("/downloads. 3")) self.assertEqual(middleware.get_section_key("/downloads"), "downloads") self.assertEqual(middleware.get_section_key("downloads/"), "downloads") @@ -65,3 +68,10 @@ def test_surrogate_key_header_homepage(self): self.assertTrue(response.has_header("Surrogate-Key")) surrogate_key = response["Surrogate-Key"] self.assertEqual(surrogate_key, "pydotorg-app") + + @override_settings(GLOBAL_SURROGATE_KEY="pydotorg-app") + def test_surrogate_key_header_skips_unsafe_section(self): + """A CR or LF in the first path segment must not reach the header.""" + response = self.client.get("/downloads.%20%0D3") + self.assertEqual(response.status_code, 404) + self.assertEqual(response["Surrogate-Key"], "pydotorg-app")