Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions pydotorg/middleware.py
Original file line number Diff line number Diff line change
@@ -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."""
Expand Down Expand Up @@ -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):
Expand Down
10 changes: 10 additions & 0 deletions pydotorg/tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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")