Scrapy, a fast high-level web crawling & scraping framework for Python.
Merge remote-tracking branch 'cwxj-rr6w-m6w7/fix-referer-policy-handling' into 2.14
Adrian Chaves945b787a2635
diff --cc docs/news.rstindex a7d8e50f3,dfa4a36f6..ee9d7c017--- a/docs/news.rst+++ b/docs/news.rst@@@ -11,59 -11,18 +11,71 @@@ Scrapy 2.14.2 (unreleasedSecurity bug fixes~~~~~~~~~~~~~~~~~~+ - Values from the ``Referrer-Policy`` header of HTTP responses are no longer+ executed as Python callables. See the `cwxj-rr6w-m6w7`_ security advisory+ for details.++ .. _cwxj-rr6w-m6w7: https://github.com/scrapy/scrapy/security/advisories/GHSA-cwxj-rr6w-m6w7++- In line with the `standard+ <https://fetch.spec.whatwg.org/#http-redirect-fetch>`__, 301 redirects of+ ``POST`` requests turn into ``GET`` requests.++ Turning into a ``GET`` request implies not only a method change, but also+ omitting the body and ``Content-*`` headers in the redirect request. On+ cross-origin redirects (e.g. cross-domain), this is effectively a security+ bug fix for scenarios where the body contains secrets.++Deprecations+~~~~~~~~~~~~++- Using a response URL string as the first parameter on calls to+ :meth:`scrapy.spidermiddlewares.referer.RefererMiddleware.policy` is+ deprecated. Pass a :class:`~scrapy.http.Response` instead.++ The parameter has also been renamed to ``response`` to reflect this change.+ The old parameter name (``resp_or_url``) is deprecated.++ New features+ ~~~~~~~~~~~~+-- Added a new setting, :setting:`REFERER_POLICIES`, to allow customizing++- Added a new setting, :setting:`REFERER_POLICIES`, to allow customizing+ supported referrer policies.++Bug fixes+~~~~~~~~~++- Made additional redirect scenarios convert to ``GET`` in line with the+ `standard <https://fetch.spec.whatwg.org/#http-redirect-fetch>`__:++ - Only ``POST`` 302 redirects turn into ``GET`` requests, other methods+ are preserved.++ - ``HEAD`` 303 redirects do not turn into ``GET`` requests.++ - ``GET`` 303 redirects do not get their body or standard ``Content-*``+ headers removed.++- Redirects where the original request body is dropped now also get their+ ``Content-Encoding``, ``Content-Language`` and ``Content-Location`` headers+ removed, in addition to ``Content-Type`` and ``Content-Length`` that were+ already being removed.++- Redirects now maintain the source URL fragment if the redirect URL doesn't+ have one. This may be useful when using browser-based download handlers,+ like those of `scrapy-playwright`_ or `scrapy-zyte-api`_, and letting+ Scrapy handle redirects.++ .. _scrapy-playwright: https://github.com/scrapy-plugins/scrapy-playwright+ .. _scrapy-zyte-api: https://scrapy-zyte-api.readthedocs.io/en/latest/++- The ``Referer`` header is now removed on redirect if+ :class:`~scrapy.spidermiddlewares.referer.RefererMiddleware` is disabled.++- The handling of the ``Referer`` header on redirects now accounts for the+ ``Referer-Policy`` header of the response that triggers the redirect+ request.+.. _release-2.14.1:Scrapy 2.14.1 (2026-01-12)diff --cc scrapy/spidermiddlewares/referer.pyindex 5825f6467,d49c1814b..4251a9e7b--- a/scrapy/spidermiddlewares/referer.py+++ b/scrapy/spidermiddlewares/referer.py@@@ -9,11 -9,10 +9,8 @@@ import warningfrom abc import ABC, abstractmethodfrom typing import TYPE_CHECKING, castfrom urllib.parse import urlparse+from warnings import warn--from w3lib.url import safe_url_string----from scrapy import Spider, signalsfrom scrapy.exceptions import NotConfiguredfrom scrapy.http import Request, Responsefrom scrapy.spidermiddlewares.base import BaseSpiderMiddleware@@@ -343,55 -324,90 +322,108 @@@ class RefererMiddleware(BaseSpiderMiddldef from_crawler(cls, crawler: Crawler) -> Self:if not crawler.settings.getbool("REFERER_ENABLED"):raise NotConfigured- mw = cls(crawler.settings)-- # Note: this hook is a bit of a hack to intercept redirections- crawler.signals.connect(mw.request_scheduled, signal=signals.request_scheduled)-- return mw+ return cls(crawler.settings)- def policy(self, resp_or_url: Response | str, request: Request) -> ReferrerPolicy:- """- Determine Referrer-Policy to use from a parent Response (or URL),- and a Request to be sent.+ def policy(+ self,+ response: Response | str | None = None,+ request: Request | None = None,+ **kwargs,+ ) -> ReferrerPolicy:+ """Return the referrer policy to use for *request* based on *request*+ meta, *response* and settings.- if a valid policy is set in Request meta, it is used.- - if the policy is set in meta but is wrong (e.g. a typo error),- the policy from settings is used- - if the policy is not set in Request meta,- but there is a Referrer-policy header in the parent response,- it is used if valid+ - if the policy is set in meta but is wrong (e.g. a typo error), the+ policy from settings is used+ - if the policy is not set in Request meta, but there is a+ Referrer-Policy header in the parent response, it is used if valid- otherwise, the policy from settings is used."""+ if "resp_or_url" in kwargs:+ if response is not None:+ raise TypeError("Cannot pass both 'response' and 'resp_or_url'")+ response = kwargs.pop("resp_or_url")+ warn(+ "Passing 'resp_or_url' is deprecated, use 'response' instead.",+ DeprecationWarning,+ stacklevel=2,+ )+ if response is None:+ raise TypeError("Missing required argument: 'response'")+ if request is None:+ raise TypeError("Missing required argument: 'request'")+ if isinstance(response, str):+ warn(+ "Passing a response URL to RefererMiddleware.policy() instead "+ "of a Response object is deprecated.",+ DeprecationWarning,+ stacklevel=2,+ )+ allow_import_path = Truepolicy_name = request.meta.get("referrer_policy")- if policy_name is None and isinstance(resp_or_url, Response):- policy_header = resp_or_url.headers.get("Referrer-Policy")+ if policy_name is None and isinstance(response, Response):+ policy_header = response.headers.get("Referrer-Policy")if policy_header is not None:policy_name = to_unicode(policy_header.decode("latin1"))+ allow_import_path = Falseif policy_name is None:return self.default_policy()-- cls = _load_policy_class(policy_name, warning_only=True)+ cls = self._load_policy_class(+ policy_name, warning_only=True, allow_import_path=allow_import_path+ )return cls() if cls else self.default_policy()+ def _load_policy_class(+ self,+ policy: str,+ warning_only: bool = False,+ *,+ allow_import_path: bool = False,+ ) -> type[ReferrerPolicy] | None:+ """Load the :class:`ReferrerPolicy` class to use for *policy*.-+++ *policy* may be any of the following:++ - A standard policy name, e.g. ``"no-referrer"``,+ ``"origin-when-cross-origin"``, etc.++ - The special ``"scrapy-default"`` policy.++ - The import path of a :class:`ReferrerPolicy` subclass, e.g.+ ``"scrapy.spidermiddlewares.referer.NoReferrerPolicy"`` or+ ``"myproject.policies.CustomReferrerPolicy"``.++ If *warning_only* is ``False`` (default) and *policy* cannot be turned+ into a :class:`ReferrerPolicy` subclass, a :exc:`RuntimeError` is+ raised. If *warning_only* is ``True``, a warning is logged and ``None``+ is returned instead.++ If *allow_import_path* is ``False`` (default), import paths are not+ allowed, resulting in :exc:`RuntimeError` or ``None``. If ``True``,+ they are allowed. Use ``True`` only if you trust the source of the+ *policy* value.+ """+ if allow_import_path:+ try:+ return cast("type[ReferrerPolicy]", load_object(policy))+ except ValueError:+ pass+ policy_names = [+ policy_name.strip() for policy_name in policy.lower().split(",")+ ]+ # https://www.w3.org/TR/referrer-policy/#parse-referrer-policy-from-header+ for policy_name in policy_names[::-1]:+ if policy_name in self.policies:+ return self.policies[policy_name]+ msg = f"Could not load referrer policy {policy!r}"+ if not allow_import_path and _looks_like_import_path(policy):+ msg += " (import paths from the response Referrer-Policy header are not allowed)"+ if not warning_only:+ raise RuntimeError(msg)+ warnings.warn(msg, RuntimeWarning)+ return None+def get_processed_request(self, request: Request, response: Response | None) -> Request | None:diff --cc tests/test_spidermiddleware_referer.pyindex b4090b78c,0c7e360c9..444839019--- a/tests/test_spidermiddleware_referer.py+++ b/tests/test_spidermiddleware_referer.py@@@ -1,7 -1,7 +1,7 @@@from __future__ import annotationsimport warnings--from typing import TYPE_CHECKING, Any, cast++from typing import Anyfrom urllib.parse import urlparseimport pytest@@@ -30,15 -31,16 +30,10 @@@ from scrapy.spidermiddlewares.referer iStrictOriginWhenCrossOriginPolicy,UnsafeUrlPolicy,)+ from scrapy.utils.defer import deferred_f_from_coro_ffrom scrapy.utils.misc import build_from_crawler--from scrapy.utils.spider import DefaultSpiderfrom scrapy.utils.test import get_crawler--if TYPE_CHECKING:-- from collections.abc import Sequence---- from scrapy.crawler import Crawler--class TestRefererMiddleware:req_meta: dict[str, Any] = {}@@@ -970,58 -972,490 +965,161 @@@ class TestPolicyHeaderPrecedence004resp_headers = {"Referrer-Policy": ""}-class TestReferrerOnRedirect(TestRefererMiddleware):- settings = {"REFERRER_POLICY": "scrapy.spidermiddlewares.referer.UnsafeUrlPolicy"}- scenarii: Sequence[- tuple[str, str, tuple[tuple[int, str], ...], bytes | None, bytes | None]- ] = [ # type: ignore[assignment]- (- "http://scrapytest.org/1", # parent- "http://scrapytest.org/2", # target- (- # redirections: code, URL- (301, "http://scrapytest.org/3"),- (301, "http://scrapytest.org/4"),- ),- b"http://scrapytest.org/1", # expected initial referer- b"http://scrapytest.org/1", # expected referer for the redirection request- ),- (- "https://scrapytest.org/1",- "https://scrapytest.org/2",- (- # redirecting to non-secure URL- (301, "http://scrapytest.org/3"),- ),- b"https://scrapytest.org/1",- b"https://scrapytest.org/1",- ),- (- "https://scrapytest.org/1",- "https://scrapytest.com/2",- (- # redirecting to non-secure URL: different origin- (301, "http://scrapytest.com/3"),- ),- b"https://scrapytest.org/1",- b"https://scrapytest.org/1",- ),- ]-- @pytest.fixture- def crawler(self) -> Crawler:- crawler = get_crawler(DefaultSpider, self.settings)- crawler.spider = crawler._create_spider()- return crawler-- @pytest.fixture- def referrermw(self, crawler: Crawler) -> RefererMiddleware:- return RefererMiddleware.from_crawler(crawler)-- @pytest.fixture- def redirectmw(self, crawler: Crawler) -> RedirectMiddleware:- return RedirectMiddleware.from_crawler(crawler)-- def test( # type: ignore[override]- self,- crawler: Crawler,- referrermw: RefererMiddleware,- redirectmw: RedirectMiddleware,- ) -> None:- for (- parent,- target,- redirections,- init_referrer,- final_referrer,- ) in self.scenarii:- response = self.get_response(parent)- request = self.get_request(target)-- out = list(referrermw.process_spider_output(response, [request]))- assert out[0].headers.get("Referer") == init_referrer-- for status, url in redirections:- response = Response(- request.url, headers={"Location": url}, status=status- )- request = cast(- "Request", redirectmw.process_response(request, response)- )- assert crawler.spider- referrermw.request_scheduled(request, crawler.spider)-- assert isinstance(request, Request)- assert request.headers.get("Referer") == final_referrer---class TestReferrerOnRedirectNoReferrer(TestReferrerOnRedirect):- """- No Referrer policy never sets the "Referer" header.- HTTP redirections should not change that.- """-- settings = {"REFERRER_POLICY": "no-referrer"}- scenarii = [- (- "http://scrapytest.org/1", # parent- "http://scrapytest.org/2", # target- (- # redirections: code, URL- (301, "http://scrapytest.org/3"),- (301, "http://scrapytest.org/4"),- ),- None, # expected initial "Referer"- None, # expected "Referer" for the redirection request- ),- (- "https://scrapytest.org/1",- "https://scrapytest.org/2",- ((301, "http://scrapytest.org/3"),),- None,- None,- ),- (- "https://scrapytest.org/1",- "https://example.com/2", # different origin- ((301, "http://scrapytest.com/3"),),- None,- None,- ),- ]---class TestReferrerOnRedirectSameOrigin(TestReferrerOnRedirect):- """- Same Origin policy sends the full URL as "Referer" if the target origin- is the same as the parent response (same protocol, same domain, same port).-- HTTP redirections to a different domain or a lower secure level- should have the "Referer" removed.- """-- settings = {"REFERRER_POLICY": "same-origin"}- scenarii = [- (- "http://scrapytest.org/101", # origin- "http://scrapytest.org/102", # target- (- # redirections: code, URL- (301, "http://scrapytest.org/103"),- (301, "http://scrapytest.org/104"),- ),- b"http://scrapytest.org/101", # expected initial "Referer"- b"http://scrapytest.org/101", # expected referer for the redirection request- ),- (- "https://scrapytest.org/201",- "https://scrapytest.org/202",- (- # redirecting from secure to non-secure URL == different origin- (301, "http://scrapytest.org/203"),- ),- b"https://scrapytest.org/201",- None,- ),- (- "https://scrapytest.org/301",- "https://scrapytest.org/302",- (- # different domain == different origin- (301, "http://example.com/303"),- ),- b"https://scrapytest.org/301",- None,- ),- ]---class TestReferrerOnRedirectStrictOrigin(TestReferrerOnRedirect):- """- Strict Origin policy will always send the "origin" as referrer- (think of it as the parent URL without the path part),- unless the security level is lower and no "Referer" is sent.-- Redirections from secure to non-secure URLs should have the- "Referrer" header removed if necessary.- """-- settings = {"REFERRER_POLICY": POLICY_STRICT_ORIGIN}- scenarii = [- (- "http://scrapytest.org/101",- "http://scrapytest.org/102",- (- (301, "http://scrapytest.org/103"),- (301, "http://scrapytest.org/104"),- ),- b"http://scrapytest.org/", # send origin- b"http://scrapytest.org/", # redirects to same origin: send origin- ),- (- "https://scrapytest.org/201",- "https://scrapytest.org/202",- (- # redirecting to non-secure URL: no referrer- (301, "http://scrapytest.org/203"),- ),- b"https://scrapytest.org/",- None,- ),- (- "https://scrapytest.org/301",- "https://scrapytest.org/302",- (- # redirecting to non-secure URL (different domain): no referrer- (301, "http://example.com/303"),- ),- b"https://scrapytest.org/",- None,- ),- (- "http://scrapy.org/401",- "http://example.com/402",- ((301, "http://scrapytest.org/403"),),- b"http://scrapy.org/",- b"http://scrapy.org/",- ),- (- "https://scrapy.org/501",- "https://example.com/502",- (- # HTTPS all along, so origin referrer is kept as-is- (301, "https://google.com/503"),- (301, "https://facebook.com/504"),- ),- b"https://scrapy.org/",- b"https://scrapy.org/",- ),- (- "https://scrapytest.org/601",- "http://scrapytest.org/602", # TLS to non-TLS: no referrer- (- (- 301,- "https://scrapytest.org/603",- ), # TLS URL again: (still) no referrer- ),- None,- None,- ),- ]---class TestReferrerOnRedirectOriginWhenCrossOrigin(TestReferrerOnRedirect):- """- Origin When Cross-Origin policy sends the full URL as "Referer",- unless the target's origin is different (different domain, different protocol)- in which case only the origin is sent.-- Redirections to a different origin should strip the "Referer"- to the parent origin.- """-- settings = {"REFERRER_POLICY": POLICY_ORIGIN_WHEN_CROSS_ORIGIN}- scenarii = [- (- "http://scrapytest.org/101", # origin- "http://scrapytest.org/102", # target + redirection- (- # redirections: code, URL- (301, "http://scrapytest.org/103"),- (301, "http://scrapytest.org/104"),- ),- b"http://scrapytest.org/101", # expected initial referer- b"http://scrapytest.org/101", # expected referer for the redirection request- ),- (- "https://scrapytest.org/201",- "https://scrapytest.org/202",- (- # redirecting to non-secure URL: send origin- (301, "http://scrapytest.org/203"),- ),- b"https://scrapytest.org/201",- b"https://scrapytest.org/",- ),- (- "https://scrapytest.org/301",- "https://scrapytest.org/302",- (- # redirecting to non-secure URL (different domain): send origin- (301, "http://example.com/303"),- ),- b"https://scrapytest.org/301",- b"https://scrapytest.org/",- ),- (- "http://scrapy.org/401",- "http://example.com/402",- ((301, "http://scrapytest.org/403"),),- b"http://scrapy.org/",- b"http://scrapy.org/",- ),- (- "https://scrapy.org/501",- "https://example.com/502",- (- # all different domains: send origin- (301, "https://google.com/503"),- (301, "https://facebook.com/504"),- ),- b"https://scrapy.org/",- b"https://scrapy.org/",- ),- (- "https://scrapytest.org/301",- "http://scrapytest.org/302", # TLS to non-TLS: send origin- ((301, "https://scrapytest.org/303"),), # TLS URL again: send origin (also)- b"https://scrapytest.org/",- b"https://scrapytest.org/",- ),- ]---class TestReferrerOnRedirectStrictOriginWhenCrossOrigin(TestReferrerOnRedirect):- """- Strict Origin When Cross-Origin policy sends the full URL as "Referer",- unless the target's origin is different (different domain, different protocol)- in which case only the origin is sent...- Unless there's also a downgrade in security and then the "Referer" header- is not sent.-- Redirections to a different origin should strip the "Referer" to the parent origin,- and from https:// to http:// will remove the "Referer" header.- """-- settings = {"REFERRER_POLICY": POLICY_STRICT_ORIGIN_WHEN_CROSS_ORIGIN}- scenarii = [- (- "http://scrapytest.org/101", # origin- "http://scrapytest.org/102", # target + redirection- (- # redirections: code, URL- (301, "http://scrapytest.org/103"),- (301, "http://scrapytest.org/104"),- ),- b"http://scrapytest.org/101", # expected initial referer- b"http://scrapytest.org/101", # expected referer for the redirection request- ),- (- "https://scrapytest.org/201",- "https://scrapytest.org/202",- (- # redirecting to non-secure URL: do not send the "Referer" header- (301, "http://scrapytest.org/203"),- ),- b"https://scrapytest.org/201",- None,- ),- (- "https://scrapytest.org/301",- "https://scrapytest.org/302",- (- # redirecting to non-secure URL (different domain): send origin- (301, "http://example.com/303"),- ),- b"https://scrapytest.org/301",- None,- ),- (- "http://scrapy.org/401",- "http://example.com/402",- ((301, "http://scrapytest.org/403"),),- b"http://scrapy.org/",- b"http://scrapy.org/",- ),- (- "https://scrapy.org/501",- "https://example.com/502",- (- # all different domains: send origin- (301, "https://google.com/503"),- (301, "https://facebook.com/504"),- ),- b"https://scrapy.org/",- b"https://scrapy.org/",- ),- (- "https://scrapytest.org/601",- "http://scrapytest.org/602", # TLS to non-TLS: do not send "Referer"- (- (- 301,- "https://scrapytest.org/603",- ), # TLS URL again: (still) send nothing- ),- None,- None,- ),- ]+class TestPolicyMethodResponseParamRename:+ def setup_method(self):+ self.crawler = get_crawler()+ self.mw = build_from_crawler(RefererMiddleware, self.crawler)+ self.request = Request("http://www.example.com")+ self.response = Response("http://www.example.com")++ def test_pos_string(self):+ with warnings.catch_warnings(record=True) as w:+ self.mw.policy("http://old.com", self.request)+ found = False+ for warning in w:+ if "Passing a response URL" in str(warning.message):+ found = True+ break+ assert found++ def test_pos_response(self):+ with warnings.catch_warnings(record=True) as w:+ self.mw.policy(self.response, self.request)+ for warning in w:+ assert "resp_or_url" not in str(warning.message)++ def test_key_resp_or_url(self):+ with warnings.catch_warnings(record=True) as w:+ self.mw.policy(resp_or_url=self.response, request=self.request)+ found = False+ for warning in w:- if "Passing 'resp_or_url' is deprecated, use 'response' instead" in str(warning.message):++ if "Passing 'resp_or_url' is deprecated, use 'response' instead" in str(++ warning.message++ ):+ found = True+ break+ assert found++ def test_key_response(self):+ with warnings.catch_warnings(record=True) as w:+ self.mw.policy(response=self.response, request=self.request)+ for warning in w:+ assert "resp_or_url" not in str(warning.message)++ def test_key_response_string(self):- with warnings.catch_warnings(record=True) as w:++ with warnings.catch_warnings(record=True) as w:+ warnings.simplefilter("always")+ self.mw.policy(response="http://old.com", request=self.request)+ found = False+ for warning in w:+ if "Passing a response URL" in str(warning.message):+ found = True+ break+ assert found++ def test_both_resp_or_url_and_response(self):- with pytest.raises(TypeError, match="Cannot pass both 'response' and 'resp_or_url'"):- self.mw.policy(response=self.response, resp_or_url=self.response, request=self.request)--++ with pytest.raises(++ TypeError, match="Cannot pass both 'response' and 'resp_or_url'"++ ):++ self.mw.policy(++ response=self.response, resp_or_url=self.response, request=self.request++ )+++ @deferred_f_from_coro_f+ async def test_response_policy_only_supports_policy_names():+ crawler = get_crawler(settings_dict={"REFERRER_POLICY": "no-referrer"})+ mw = build_from_crawler(RefererMiddleware, crawler)++ async def input_result():+ yield Request("https://example.com/")++ response = Response(+ "https://example.com/",+ headers={+ "Referrer-Policy": "scrapy.spidermiddlewares.referer.NoReferrerWhenDowngradePolicy"+ },+ )+ with pytest.warns(+ RuntimeWarning,+ match=r"Could not load referrer policy 'scrapy\.spidermiddlewares\.referer\.NoReferrerWhenDowngradePolicy' \(import paths from the response Referrer-Policy header are not allowed\)",+ ):+ output = [+ request+ async for request in mw.process_spider_output_async(+ response, input_result()+ )+ ]+ assert len(output) == 1+ assert b"Referer" not in output[0].headers++ response = Response(+ "https://example.com/",+ headers={"Referrer-Policy": "no-referrer-when-downgrade"},+ )+ output = [+ request+ async for request in mw.process_spider_output_async(response, input_result())+ ]+ assert len(output) == 1+ assert output[0].headers == {b"Referer": [b"https://example.com/"]}+++ @deferred_f_from_coro_f+ async def test_referer_policies_setting():+ crawler = get_crawler(+ settings_dict={+ "REFERRER_POLICY": "no-referrer",+ "REFERRER_POLICIES": {+ "no-referrer-when-downgrade": None,+ "custom-policy": CustomPythonOrgPolicy,+ "": CustomPythonOrgPolicy,+ },+ }+ )+ mw = build_from_crawler(RefererMiddleware, crawler)++ async def input_result():+ yield Request("https://example.com/")++ # "no-referrer-when-downgrade": None,+ response = Response(+ "https://example.com/",+ headers={"Referrer-Policy": "no-referrer-when-downgrade"},+ )+ with pytest.warns(+ RuntimeWarning,+ match=r"Could not load referrer policy 'no-referrer-when-downgrade'",+ ):+ output = [+ request+ async for request in mw.process_spider_output_async(+ response, input_result()+ )+ ]+ assert len(output) == 1+ assert b"Referer" not in output[0].headers++ # "custom-policy": CustomPythonOrgPolicy,+ response = Response(+ "https://example.com/",+ headers={"Referrer-Policy": "custom-policy"},+ )+ output = [+ request+ async for request in mw.process_spider_output_async(response, input_result())+ ]+ assert len(output) == 1+ assert output[0].headers == {b"Referer": [b"https://python.org/"]}++ # "": CustomPythonOrgPolicy,+ response = Response(+ "https://example.com/",+ headers={"Referrer-Policy": ""},+ )+ output = [+ request+ async for request in mw.process_spider_output_async(response, input_result())+ ]+ assert len(output) == 1+ assert output[0].headers == {b"Referer": [b"https://python.org/"]}