How to Enforce a Strict Referrer Policy in Python
Validate HTTP headers to enforce a strict same-origin Referrer policy, accepting only origin-only URLs or absent Referer values.
Python code
23 linesimport re
from unittest.mock import patch
def strict_referrer_policy(headers):
"""Return True if Referer header is absent or strictly same-origin."""
referer = headers.get("Referer")
if referer is None:
return True
# Strict-Origin-When-Cross-Origin allows same-origin full URL
# but here we demand same-origin only (no path or query)
return bool(re.match(r"^https?://[^/]+$", referer))
if __name__ == "__main__":
# Mock a strict browser that never sends Referer cross-origin
with patch("builtins.input", return_value=""):
test_headers = [
{}, # no referer
{"Referer": "https://example.com"},
{"Referer": "https://example.com/page?q=1"},
{"Referer": "https://other.com"},
]
for headers in test_headers:
print(f"{headers} -> {strict_referrer_policy(headers)}")
Output
{} -> True
{'Referer': 'https://example.com'} -> True
{'Referer': 'https://example.com/page?q=1'} -> False
{'Referer': 'https://other.com'} -> False
How it works
The strict_referrer_policy function checks if a Referer header is absent or matches a regex that only allows an origin URL (scheme, domain, optional port) with no path or query string. The regex ^https?://[^/]+$ ensures the Referring URL is exactly the origin, blocking any path, query, or fragment. The function returns True for same-origin requests and False for cross-origin or path-inclusive referrers, enforcing a strict policy. Using headers.get avoids KeyError and treats missing Referer as compliant. The unittest.mock.patch is used in the demo to simulate an empty input, though it's not essential to the core logic.
Common mistakes
- Not accounting for missing Referer headers, which should be allowed in strict mode
- Using a regex that permits paths like `https://example.com/page` as valid referrers
- Forgetting to consider port numbers in the origin, which the regex handles correctly
- Assuming case-insensitivity of the 'Referer' header name — use proper header parsing
Variations
- Use `urlparse` from `urllib.parse` to compare scheme and netloc instead of regex
- Implement a full Strict-Origin-When-Cross-Origin policy allowing same-origin URLs with paths
Real-world use cases
- Validating incoming requests in a web framework to block CSRF attacks from cross-origin referrers.
- Enforcing security headers compliance in a reverse proxy or API gateway.
- Writing unit tests to verify that your server only accepts requests with strict origin-only referrers.
Sponsored
More from Auth & security at scale
- ACME LetsEncrypt Mock Challenge Server in Python medium
- AES GCM encryption and decryption in Python medium
- Build a Mock OIDC Userinfo Endpoint in Python with Flask easy
- ChaCha20-Poly1305 mock in Python medium
- ECDH key agreement in Python with cryptography medium
- Enforce TLS 1.2 Minimum in Python easy
Keep learning
Related tutorials and quizzes for this topic.