Scrapy, a fast high-level web crawling & scraping framework for Python.
Fix missing certificate and IP address on HTTP/1.1 responses without a body (#8048)
Adrian544f4d2d5237
diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.pyindex f8a170714..614c48a3b 100644--- a/scrapy/core/downloader/handlers/http11.py+++ b/scrapy/core/downloader/handlers/http11.py@@ -538,6 +538,8 @@ class _ScrapyAgent:if cast("int", txresponse.length) == 0:return {"txresponse": txresponse,+ "certificate": getattr(txresponse, "_scrapy_certificate", None),+ "ip_address": getattr(txresponse, "_scrapy_ip_address", None),}maxsize = request.meta.get("download_maxsize", self._maxsize)@@ -811,6 +813,29 @@ class _LenientHTTP11ClientProtocol(HTTP11ClientProtocol):# creates a parser.assert self._parser is not Noneself._parser.__class__ = _LenientHTTPClientParser++ # For responses without a body, twisted.web.client.Response never+ # hands its transport to a protocol, so the certificate and IP+ # address cannot be read from it later (see+ # _ResponseReader.connectionMade). self.transport, however, is the+ # connection's real transport and outlives any single request, so+ # read the certificate and IP address from it directly and stash+ # them on the response.+ assert self.transport is not None+ transport = self.transport++ def _attach_connection_info(response: IResponse) -> IResponse:+ with suppress(AttributeError):+ response._scrapy_certificate = ssl.Certificate(+ transport.getPeerCertificate()+ )+ with suppress(AttributeError):+ response._scrapy_ip_address = ipaddress.ip_address(+ transport.getPeer().host+ )+ return response++ d.addCallback(_attach_connection_info)return ddiff --git a/tests/test_crawl.py b/tests/test_crawl.pyindex c3ccc754c..26c2bc529 100644--- a/tests/test_crawl.py+++ b/tests/test_crawl.py@@ -712,20 +712,7 @@ class TestCrawlSpider:@pytest.mark.filterwarnings(r"ignore:.*You should use cryptography's X\.509 APIs:DeprecationWarning")- @pytest.mark.parametrize(- "url",- [- "/echo?body=test",- pytest.param(- "/status?n=200",- marks=pytest.mark.xfail(- 'config.getoption("--reactor") != "none"',- reason="With HTTP11DownloadHandler, responses with no body are returned early and contain no certificate",- strict=True,- ),- ),- ],- )+ @pytest.mark.parametrize("url", ["/echo?body=test", "/status?n=200"])@coroutine_testasync def test_response_ssl_certificate(self, mockserver: MockServer, url: str@@ -744,20 +731,7 @@ class TestCrawlSpider:assert cert_x509.subject.rfc4514_string() == "CN=localhost,O=Scrapy,C=IE"assert cert_x509.issuer.rfc4514_string() == "CN=localhost,O=Scrapy,C=IE"- @pytest.mark.parametrize(- "url",- [- "/echo?body=test",- pytest.param(- "/status?n=200",- marks=pytest.mark.xfail(- 'config.getoption("--reactor") != "none"',- reason="With HTTP11DownloadHandler, responses with no body are returned early and contain no ip_address",- strict=True,- ),- ),- ],- )+ @pytest.mark.parametrize("url", ["/echo?body=test", "/status?n=200"])@coroutine_testasync def test_response_ip_address(self, mockserver: MockServer, url: str) -> None:crawler = get_crawler(SingleRequestSpider)diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.pyindex 2529848b3..719d8a8c9 100644--- a/tests/utils/bases/download_handlers_http.py+++ b/tests/utils/bases/download_handlers_http.py@@ -1356,6 +1356,27 @@ class TestHttpWithCrawlerBase(ABC):assert cert_x509.subject.rfc4514_string() == "CN=localhost,O=Scrapy,C=IE"assert cert_x509.issuer.rfc4514_string() == "CN=localhost,O=Scrapy,C=IE"+ @pytest.mark.filterwarnings(+ r"ignore:.*You should use cryptography's X\.509 APIs:DeprecationWarning"+ )+ @coroutine_test+ async def test_response_ssl_certificate_empty_body(+ self, mockserver: MockServer+ ) -> None:+ if not self.is_secure:+ pytest.skip("Only applies to HTTPS")+ crawler = get_crawler(SingleRequestSpider, self.settings_dict)+ url = mockserver.url("/status?n=200", is_secure=self.is_secure)+ await crawler.crawl_async(seed=url, mockserver=mockserver)+ assert isinstance(crawler.spider, SingleRequestSpider)+ cert = crawler.spider.meta["responses"][0].certificate+ assert cert is not None+ if isinstance(cert, Certificate): # Twisted+ assert cert.getSubject().commonName == b"localhost"+ elif isinstance(cert, bytes): # DER bytes+ cert_x509 = load_der_x509_certificate(cert)+ assert cert_x509.subject.rfc4514_string() == "CN=localhost,O=Scrapy,C=IE"+@coroutine_testasync def test_response_ip_address(self, mockserver: MockServer) -> None:# copy of TestCrawl.test_response_ip_address()@@ -1368,6 +1389,17 @@ class TestHttpWithCrawlerBase(ABC):assert isinstance(ip_address, IPv4Address)assert str(ip_address) == socket.gethostbyname(expected_netloc)+ @coroutine_test+ async def test_response_ip_address_empty_body(self, mockserver: MockServer) -> None:+ crawler = get_crawler(SingleRequestSpider, self.settings_dict)+ url = mockserver.url("/status?n=200", is_secure=self.is_secure)+ expected_netloc, _ = urlparse(url).netloc.split(":")+ await crawler.crawl_async(seed=url, mockserver=mockserver)+ assert isinstance(crawler.spider, SingleRequestSpider)+ ip_address = crawler.spider.meta["responses"][0].ip_address+ assert isinstance(ip_address, IPv4Address)+ assert str(ip_address) == socket.gethostbyname(expected_netloc)+@coroutine_testasync def test_bytes_received_stop_download_callback(self, mockserver: MockServer