Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

45.1 KB
Raw Blame
import logging
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any, NamedTuple

import pytest
from _pytest.mark import ParameterSet

from scrapy.downloadermiddlewares.cookies import CookiesMiddleware
from scrapy.downloadermiddlewares.defaultheaders import DefaultHeadersMiddleware
from scrapy.downloadermiddlewares.redirect import RedirectMiddleware
from scrapy.exceptions import NotConfigured
from scrapy.http import Request, Response
from scrapy.http.request import CookiesT, VerboseCookie
from scrapy.utils.misc import build_from_crawler
from scrapy.utils.python import to_bytes
from scrapy.utils.request import _to_verbose_cookies
from scrapy.utils.spider import DefaultSpider
from scrapy.utils.test import get_crawler

UNSET = object()


def _cookie_to_set_cookie_value(cookie: VerboseCookie) -> str | None:
    """Given a cookie defined as a dictionary with name and value keys, and
    optional path and domain keys, return the equivalent string that can be
    associated to a ``Set-Cookie`` header."""
    decoded = {}
    for key in ("name", "value", "path", "domain"):
        value = cookie.get(key)
        if value is None:
            if key in {"name", "value"}:
                return None
            continue
        if isinstance(value, (bool, float, int, str)):
            decoded[key] = str(value)
        else:
            assert isinstance(value, bytes)
            try:
                decoded[key] = value.decode()
            except UnicodeDecodeError:
                decoded[key] = value.decode("latin1", errors="replace")

    cookie_str = f"{decoded.pop('name')}={decoded.pop('value')}"
    for key, value in decoded.items():  # path, domain
        cookie_str += f"; {key.capitalize()}={value}"
    return cookie_str


def _cookies_to_set_cookie_list(cookies: CookiesT) -> Iterable[str]:
    """Given a group of cookie defined either as a dictionary or as a list of
    dictionaries (i.e. in a format supported by the cookies parameter of
    Request), return the equivalent list of strings that can be associated to a
    ``Set-Cookie`` header."""
    if not cookies:
        return []
    return filter(
        None,
        (
            _cookie_to_set_cookie_value(cookie)
            for cookie in _to_verbose_cookies(cookies)
        ),
    )


@dataclass(frozen=True)
class _DomainSet:
    """Related domains used to build cookie domain scenarios."""

    domain: str
    sub: str
    super_domain: str | None = None
    sibling: str | None = None


_DOMAIN_SETS = {
    "private": _DomainSet(
        domain="books.toscrape.com",
        sub="a.books.toscrape.com",
        super_domain="toscrape.com",
        sibling="quotes.toscrape.com",
    ),
    # Every domain here is a public suffix, except for the subdomain.
    "public": _DomainSet(
        domain="cc.ak.us",
        sub="a.cc.ak.us",
        super_domain="ak.us",
        sibling="lib.ak.us",
    ),
    "dotless": _DomainSet(domain="example-host", sub="a.example-host"),
}

_PUBLIC_SUFFIXES = frozenset({"ak.us", "cc.ak.us", "lib.ak.us"})

_OTHER_DOMAIN = "example.com"


class _Limitation(NamedTuple):
    reason: str
    dropped: bool


_SUBDOMAIN_LEAK = _Limitation(
    "Cookies that must be limited to a single host are sent to its subdomains",
    dropped=False,
)
_EMPTY_DOMAIN_DROPPED = _Limitation(
    "Cookies with an empty Domain attribute are dropped instead of being"
    " limited to the host of the request",
    dropped=True,
)
_DOTLESS_DOMAIN_DROPPED = _Limitation(
    "Cookies with a Domain attribute without dots are dropped",
    dropped=True,
)

_KNOWN_LIMITATIONS: dict[tuple[str, str], _Limitation] = {
    ("private", "unset"): _SUBDOMAIN_LEAK,
    ("private", "none"): _SUBDOMAIN_LEAK,
    ("public", "unset"): _SUBDOMAIN_LEAK,
    ("public", "none"): _SUBDOMAIN_LEAK,
    ("public", "self"): _SUBDOMAIN_LEAK,
    ("public", "dot-self"): _SUBDOMAIN_LEAK,
    ("private", "empty"): _EMPTY_DOMAIN_DROPPED,
    ("private", "dot"): _EMPTY_DOMAIN_DROPPED,
    ("public", "empty"): _EMPTY_DOMAIN_DROPPED,
    ("public", "dot"): _EMPTY_DOMAIN_DROPPED,
    ("dotless", "empty"): _EMPTY_DOMAIN_DROPPED,
    ("dotless", "dot"): _EMPTY_DOMAIN_DROPPED,
    ("dotless", "self"): _DOTLESS_DOMAIN_DROPPED,
    ("dotless", "dot-self"): _DOTLESS_DOMAIN_DROPPED,
}


def _domain_match(host: str, domain: str) -> bool:
    """Implement the domain matching algorithm of RFC 6265, section 5.1.3."""
    return host == domain or host.endswith(f".{domain}")


def _store(request_domain: str, cookie_domain: str | None) -> tuple[str, bool] | None:
    """Implement the storage model of RFC 6265, section 5.3, steps 5 and 6.

    Given the domain of the request that carried the cookie, and the value of
    the ``Domain`` attribute of the cookie (`None` if unset), return the domain
    the cookie is stored for and whether it is a host-only cookie, or `None` if
    the cookie must be ignored.
    """
    if cookie_domain is None:
        return request_domain, True
    domain = cookie_domain.removeprefix(".").lower()
    if not domain:
        return request_domain, True
    if domain in _PUBLIC_SUFFIXES:
        return (request_domain, True) if domain == request_domain else None
    if not _domain_match(request_domain, domain):
        return None
    return domain, False


def _is_sent(stored: tuple[str, bool] | None, request_domain: str) -> bool:
    if stored is None:
        return False
    domain, host_only = stored
    if host_only:
        return request_domain == domain
    return _domain_match(request_domain, domain)


def _cookie_domains(domains: _DomainSet) -> Iterable[tuple[str, str | None]]:
    yield "unset", None
    yield "none", None
    yield "empty", ""
    yield "dot", "."
    for label, domain in (
        ("self", domains.domain),
        ("sub", domains.sub),
        ("super", domains.super_domain),
        ("other", _OTHER_DOMAIN),
    ):
        if domain is None:
            continue
        yield label, domain
        yield f"dot-{label}", f".{domain}"


def _targets(domains: _DomainSet) -> Iterable[tuple[str, str, tuple[str, ...]]]:
    yield "same", domains.domain, ("followup", "redirect", "relative-redirect")
    yield "other", _OTHER_DOMAIN, ("followup", "redirect")
    yield "sub", domains.sub, ("followup", "redirect")
    if domains.super_domain is not None:
        assert domains.sibling is not None
        yield "super", domains.super_domain, ("followup", "redirect")
        yield "sibling", domains.sibling, ("followup", "redirect")


def _actual_store(
    domains: _DomainSet, stored: tuple[str, bool] | None, limitation: _Limitation | None
) -> tuple[str, bool] | None:
    """Return the storage that Scrapy applies, given the RFC 6265 one and the
    known limitation that applies, if any."""
    if limitation is None:
        return stored
    if limitation.dropped:
        return None
    return domains.domain, False


def _cookie_domain_params() -> Iterable[ParameterSet]:
    for source in ("request", "response"):
        for domain_set_id, domains in _DOMAIN_SETS.items():
            for cookie_domain_id, cookie_domain in _cookie_domains(domains):
                if cookie_domain_id == "unset":
                    # Only the cookies parameter of Request can leave the
                    # domain out; a Set-Cookie header always has one.
                    if source == "response":
                        continue
                    cookies: CookiesT = {"a": "b"}
                else:
                    # domain is None for the "none" scenario.
                    cookies = [{"name": "a", "value": "b", "domain": cookie_domain}]  # type: ignore[typeddict-item]
                stored = _store(domains.domain, cookie_domain)
                limitation = _KNOWN_LIMITATIONS.get((domain_set_id, cookie_domain_id))
                actual = _actual_store(domains, stored, limitation)
                for target_id, target, transitions in _targets(domains):
                    cookies2 = _is_sent(stored, target)
                    known = limitation if _is_sent(actual, target) != cookies2 else None
                    for transition in transitions:
                        # The Cookie header of the request that carries the
                        # cookies only depends on the cookie domain, so it is
                        # only worth checking once.
                        cookies1 = (
                            cookies2
                            if source == "request"
                            and target_id == "same"
                            and transition == "followup"
                            else None
                        )
                        yield pytest.param(
                            source,
                            cookies,
                            domains.domain,
                            target,
                            transition,
                            cookies1,
                            cookies2,
                            id=(
                                f"{source}-{domain_set_id}-{cookie_domain_id}"
                                f"-{target_id}-{transition}"
                            ),
                            marks=(
                                [pytest.mark.xfail(strict=True, reason=known.reason)]
                                if known
                                else []
                            ),
                        )


_IPV6_HOST_DROPPED = "Cookies for IPv6 hosts are dropped"


def _local_host_params() -> Iterable[ParameterSet]:
    for host_id, host, host_domain in (
        ("localhost", "localhost", "localhost"),
        ("ipv4", "127.0.0.1", "127.0.0.1"),
        ("ipv6", "[::1]", "::1"),
    ):
        known: str | None
        for cookie_domain in (None, host_domain):
            if host_id == "ipv6":
                known = _IPV6_HOST_DROPPED
            elif host_id == "localhost" and cookie_domain is not None:
                known = _DOTLESS_DOMAIN_DROPPED.reason
            else:
                known = None
            for source in ("request", "response"):
                yield pytest.param(
                    source,
                    host,
                    cookie_domain,
                    id=f"{source}-{host_id}-{'self' if cookie_domain else 'unset'}",
                    marks=(
                        [pytest.mark.xfail(strict=True, reason=known)] if known else []
                    ),
                )


class TestCookieDomains:
    """Check which domains a cookie is sent to, based on the domain of the
    request or response that carried it and on its ``Domain`` attribute."""

    def setup_method(self):
        crawler = get_crawler(DefaultSpider)
        crawler.spider = crawler._create_spider()
        self.mw = CookiesMiddleware.from_crawler(crawler)
        self.redirect_middleware = RedirectMiddleware.from_crawler(crawler)

    @pytest.mark.parametrize(
        ("source", "cookies", "domain", "target", "transition", "cookies1", "cookies2"),
        list(_cookie_domain_params()),
    )
    def test_domain(
        self,
        source: str,
        cookies: CookiesT,
        domain: str,
        target: str,
        transition: str,
        cookies1: bool | None,
        cookies2: bool,
    ) -> None:
        url1 = f"https://{domain}/a"
        url2 = "/b" if transition == "relative-redirect" else f"https://{target}/b"
        redirect = transition != "followup"

        request1 = Request(url1, cookies=cookies if source == "request" else None)
        self.mw.process_request(request1)
        if cookies1 is not None:
            assert request1.headers.get("Cookie") == (b"a=b" if cookies1 else None)

        headers: dict[str, Any] = {}
        if redirect:
            headers["Location"] = url2
        if source == "response":
            headers["Set-Cookie"] = _cookies_to_set_cookie_list(cookies)
        response = Response(url1, status=301 if redirect else 200, headers=headers)
        assert self.mw.process_response(request1, response) is response

        if redirect:
            request2 = self.redirect_middleware.process_response(request1, response)
            assert isinstance(request2, Request)
        else:
            request2 = Request(url2)
        self.mw.process_request(request2)
        assert request2.headers.get("Cookie") == (b"a=b" if cookies2 else None)

    @pytest.mark.parametrize(
        ("source", "host", "cookie_domain"), list(_local_host_params())
    )
    def test_local_host(
        self, source: str, host: str, cookie_domain: str | None
    ) -> None:
        cookies: list[VerboseCookie] = [{"name": "a", "value": "b"}]
        if cookie_domain is not None:
            cookies[0]["domain"] = cookie_domain

        url1 = f"http://{host}/a"
        request1 = Request(url1, cookies=cookies if source == "request" else None)
        self.mw.process_request(request1)

        headers = (
            {"Set-Cookie": _cookies_to_set_cookie_list(cookies)}
            if source == "response"
            else {}
        )
        response = Response(url1, headers=headers)
        assert self.mw.process_response(request1, response) is response

        request2 = Request(f"http://{host}/b")
        self.mw.process_request(request2)
        assert request2.headers.get("Cookie") == b"a=b"


class TestCookiesMiddleware:
    @staticmethod
    def assertCookieValEqual(first: bytes | str | None, second: bytes | str) -> None:
        def split_cookies(cookies: bytes | str) -> list[bytes]:
            return sorted([s.strip() for s in to_bytes(cookies).split(b";")])

        assert first is not None
        assert split_cookies(first) == split_cookies(second)

    def setup_method(self):
        crawler = get_crawler(DefaultSpider)
        crawler.spider = crawler._create_spider()
        self.mw = build_from_crawler(CookiesMiddleware, crawler)
        self.redirect_middleware = build_from_crawler(RedirectMiddleware, crawler)

    def teardown_method(self):
        del self.mw
        del self.redirect_middleware

    def test_basic(self):
        req = Request("http://scrapytest.org/")
        assert self.mw.process_request(req) is None
        assert "Cookie" not in req.headers

        headers = {"Set-Cookie": "C1=value1; path=/"}
        res = Response("http://scrapytest.org/", headers=headers)
        assert self.mw.process_response(req, res) is res

        req2 = Request("http://scrapytest.org/sub1/")
        assert self.mw.process_request(req2) is None
        assert req2.headers.get("Cookie") == b"C1=value1"

    def test_setting_false_cookies_enabled(self):
        with pytest.raises(NotConfigured):
            build_from_crawler(
                CookiesMiddleware, get_crawler(settings_dict={"COOKIES_ENABLED": False})
            )

    def test_setting_default_cookies_enabled(self):
        assert isinstance(
            build_from_crawler(CookiesMiddleware, get_crawler()), CookiesMiddleware
        )

    def test_setting_true_cookies_enabled(self):
        assert isinstance(
            build_from_crawler(
                CookiesMiddleware, get_crawler(settings_dict={"COOKIES_ENABLED": True})
            ),
            CookiesMiddleware,
        )

    def test_setting_enabled_cookies_debug(
        self, caplog: pytest.LogCaptureFixture
    ) -> None:
        crawler = get_crawler(settings_dict={"COOKIES_DEBUG": True})
        mw = build_from_crawler(CookiesMiddleware, crawler)
        caplog.clear()
        with caplog.at_level(
            logging.DEBUG, logger="scrapy.downloadermiddlewares.cookies"
        ):
            req = Request("http://scrapytest.org/")
            res = Response(
                "http://scrapytest.org/", headers={"Set-Cookie": "C1=value1; path=/"}
            )
            mw.process_response(req, res)
            req2 = Request("http://scrapytest.org/sub1/")
            mw.process_request(req2)

        assert caplog.record_tuples == [
            (
                "scrapy.downloadermiddlewares.cookies",
                logging.DEBUG,
                (
                    "Received cookies from: <200 http://scrapytest.org/>\n"
                    "Set-Cookie: C1=value1; path=/\n"
                ),
            ),
            (
                "scrapy.downloadermiddlewares.cookies",
                logging.DEBUG,
                (
                    "Sending cookies to: <GET http://scrapytest.org/sub1/>\n"
                    "Cookie: C1=value1\n"
                ),
            ),
        ]

    def test_debug_no_cookies(self, caplog: pytest.LogCaptureFixture) -> None:
        crawler = get_crawler(settings_dict={"COOKIES_DEBUG": True})
        mw = build_from_crawler(CookiesMiddleware, crawler)
        caplog.clear()
        with caplog.at_level(
            logging.DEBUG, logger="scrapy.downloadermiddlewares.cookies"
        ):
            req = Request("http://scrapytest.org/")
            res = Response("http://scrapytest.org/")  # no Set-Cookie header
            mw.process_response(req, res)
            mw.process_request(req)  # no cookies to send either
        # no log output since cl is empty in both cases
        assert caplog.record_tuples == []

    def test_setting_disabled_cookies_debug(
        self, caplog: pytest.LogCaptureFixture
    ) -> None:
        crawler = get_crawler(settings_dict={"COOKIES_DEBUG": False})
        mw = build_from_crawler(CookiesMiddleware, crawler)
        caplog.clear()
        with caplog.at_level(
            logging.DEBUG, logger="scrapy.downloadermiddlewares.cookies"
        ):
            req = Request("http://scrapytest.org/")
            res = Response(
                "http://scrapytest.org/", headers={"Set-Cookie": "C1=value1; path=/"}
            )
            mw.process_response(req, res)
            req2 = Request("http://scrapytest.org/sub1/")
            mw.process_request(req2)

        assert caplog.record_tuples == []

    def test_do_not_break_on_non_utf8_header(self):
        req = Request("http://scrapytest.org/")
        assert self.mw.process_request(req) is None
        assert "Cookie" not in req.headers

        headers = {"Set-Cookie": b"C1=in\xa3valid; path=/", "Other": b"ignore\xa3me"}
        res = Response("http://scrapytest.org/", headers=headers)
        assert self.mw.process_response(req, res) is res

        req2 = Request("http://scrapytest.org/sub1/")
        assert self.mw.process_request(req2) is None
        assert "Cookie" in req2.headers

    def test_dont_merge_cookies(self):
        # merge some cookies into jar
        headers = {"Set-Cookie": "C1=value1; path=/"}
        req = Request("http://scrapytest.org/")
        res = Response("http://scrapytest.org/", headers=headers)
        assert self.mw.process_response(req, res) is res

        # test Cookie header is not seted to request
        req = Request("http://scrapytest.org/dontmerge", meta={"dont_merge_cookies": 1})
        assert self.mw.process_request(req) is None
        assert "Cookie" not in req.headers

        # check that returned cookies are not merged back to jar
        res = Response(
            "http://scrapytest.org/dontmerge",
            headers={"Set-Cookie": "dont=mergeme; path=/"},
        )
        assert self.mw.process_response(req, res) is res

        # check that cookies are merged back
        req = Request("http://scrapytest.org/mergeme")
        assert self.mw.process_request(req) is None
        assert req.headers.get("Cookie") == b"C1=value1"

        # check that cookies are merged when dont_merge_cookies is passed as 0
        req = Request("http://scrapytest.org/mergeme", meta={"dont_merge_cookies": 0})
        assert self.mw.process_request(req) is None
        assert req.headers.get("Cookie") == b"C1=value1"

    def test_complex_cookies(self):
        # merge some cookies into jar
        cookies: list[VerboseCookie] = [
            {
                "name": "C1",
                "value": "value1",
                "path": "/foo",
                "domain": "scrapytest.org",
            },
            {
                "name": "C2",
                "value": "value2",
                "path": "/bar",
                "domain": "scrapytest.org",
            },
            {
                "name": "C3",
                "value": "value3",
                "path": "/foo",
                "domain": "scrapytest.org",
            },
            {"name": "C4", "value": "value4", "path": "/foo", "domain": "scrapy.org"},
        ]

        req = Request("http://scrapytest.org/", cookies=cookies)
        self.mw.process_request(req)

        # embed C1 and C3 for scrapytest.org/foo
        req = Request("http://scrapytest.org/foo")
        self.mw.process_request(req)
        assert req.headers.get("Cookie") in (
            b"C1=value1; C3=value3",
            b"C3=value3; C1=value1",
        )

        # embed C2 for scrapytest.org/bar
        req = Request("http://scrapytest.org/bar")
        self.mw.process_request(req)
        assert req.headers.get("Cookie") == b"C2=value2"

        # embed nothing for scrapytest.org/baz
        req = Request("http://scrapytest.org/baz")
        self.mw.process_request(req)
        assert "Cookie" not in req.headers

    def test_merge_request_cookies(self):
        req = Request("http://scrapytest.org/", cookies={"galleta": "salada"})
        assert self.mw.process_request(req) is None
        assert req.headers.get("Cookie") == b"galleta=salada"

        headers = {"Set-Cookie": "C1=value1; path=/"}
        res = Response("http://scrapytest.org/", headers=headers)
        assert self.mw.process_response(req, res) is res

        req2 = Request("http://scrapytest.org/sub1/")
        assert self.mw.process_request(req2) is None

        self.assertCookieValEqual(
            req2.headers.get("Cookie"), b"C1=value1; galleta=salada"
        )

    def test_cookiejar_key(self):
        req = Request(
            "http://scrapytest.org/",
            cookies={"galleta": "salada"},
            meta={"cookiejar": "store1"},
        )
        assert self.mw.process_request(req) is None
        assert req.headers.get("Cookie") == b"galleta=salada"

        headers = {"Set-Cookie": "C1=value1; path=/"}
        res = Response("http://scrapytest.org/", headers=headers, request=req)
        assert self.mw.process_response(req, res) is res

        req2 = Request("http://scrapytest.org/", meta=res.meta)
        assert self.mw.process_request(req2) is None
        self.assertCookieValEqual(
            req2.headers.get("Cookie"), b"C1=value1; galleta=salada"
        )

        req3 = Request(
            "http://scrapytest.org/",
            cookies={"galleta": "dulce"},
            meta={"cookiejar": "store2"},
        )
        assert self.mw.process_request(req3) is None
        assert req3.headers.get("Cookie") == b"galleta=dulce"

        headers = {"Set-Cookie": "C2=value2; path=/"}
        res2 = Response("http://scrapytest.org/", headers=headers, request=req3)
        assert self.mw.process_response(req3, res2) is res2

        req4 = Request("http://scrapytest.org/", meta=res2.meta)
        assert self.mw.process_request(req4) is None
        self.assertCookieValEqual(
            req4.headers.get("Cookie"), b"C2=value2; galleta=dulce"
        )

        # cookies from hosts with port
        req5_1 = Request("http://scrapytest.org:1104/")
        assert self.mw.process_request(req5_1) is None

        headers = {"Set-Cookie": "C1=value1; path=/"}
        res5_1 = Response(
            "http://scrapytest.org:1104/", headers=headers, request=req5_1
        )
        assert self.mw.process_response(req5_1, res5_1) is res5_1

        req5_2 = Request("http://scrapytest.org:1104/some-redirected-path")
        assert self.mw.process_request(req5_2) is None
        assert req5_2.headers.get("Cookie") == b"C1=value1"

        req5_3 = Request("http://scrapytest.org/some-redirected-path")
        assert self.mw.process_request(req5_3) is None
        assert req5_3.headers.get("Cookie") == b"C1=value1"

        # skip cookie retrieval for not http request
        req6 = Request("file:///scrapy/sometempfile")
        assert self.mw.process_request(req6) is None
        assert req6.headers.get("Cookie") is None

    def test_local_domain(self):
        request = Request("http://example-host/", cookies={"currencyCookie": "USD"})
        assert self.mw.process_request(request) is None
        assert "Cookie" in request.headers
        assert request.headers["Cookie"] == b"currencyCookie=USD"

    @pytest.mark.parametrize(
        ("url", "domain"),
        [
            ("http://example-host/", "example-host.local"),
            ("http://127.0.0.1/", "127.0.0.1"),
            pytest.param(
                "http://example-host/",
                "example-host",
                marks=pytest.mark.xfail(
                    reason=(
                        "http.cookiejar accepts a dotless domain for a dotless "
                        "host but never returns the resulting cookie"
                    )
                ),
            ),
        ],
    )
    def test_explicit_local_domain(self, url: str, domain: str) -> None:
        request = Request(
            url, cookies=[{"name": "currencyCookie", "value": "USD", "domain": domain}]
        )
        assert self.mw.process_request(request) is None
        assert request.headers.get("Cookie") == b"currencyCookie=USD"

    @pytest.mark.xfail(reason="Cookie header is not currently being processed")
    def test_keep_cookie_from_default_request_headers_middleware(self):
        DEFAULT_REQUEST_HEADERS = {"Cookie": "default=value; asdf=qwerty"}
        mw_default_headers = DefaultHeadersMiddleware(DEFAULT_REQUEST_HEADERS.items())
        # overwrite with values from 'cookies' request argument
        req1 = Request("http://example.org", cookies={"default": "something"})
        assert mw_default_headers.process_request(req1) is None
        assert self.mw.process_request(req1) is None
        self.assertCookieValEqual(
            req1.headers["Cookie"], b"default=something; asdf=qwerty"
        )
        # keep both
        req2 = Request("http://example.com", cookies={"a": "b"})
        assert mw_default_headers.process_request(req2) is None
        assert self.mw.process_request(req2) is None
        self.assertCookieValEqual(
            req2.headers["Cookie"], b"default=value; a=b; asdf=qwerty"
        )

    @pytest.mark.xfail(reason="Cookie header is not currently being processed")
    def test_keep_cookie_header(self):
        # keep only cookies from 'Cookie' request header
        req1 = Request("http://scrapytest.org", headers={"Cookie": "a=b; c=d"})
        assert self.mw.process_request(req1) is None
        self.assertCookieValEqual(req1.headers["Cookie"], "a=b; c=d")
        # keep cookies from both 'Cookie' request header and 'cookies' keyword
        req2 = Request(
            "http://scrapytest.org", headers={"Cookie": "a=b; c=d"}, cookies={"e": "f"}
        )
        assert self.mw.process_request(req2) is None
        self.assertCookieValEqual(req2.headers["Cookie"], "a=b; c=d; e=f")
        # overwrite values from 'Cookie' request header with 'cookies' keyword
        req3 = Request(
            "http://scrapytest.org",
            headers={"Cookie": "a=b; c=d"},
            cookies={"a": "new", "e": "f"},
        )
        assert self.mw.process_request(req3) is None
        self.assertCookieValEqual(req3.headers["Cookie"], "a=new; c=d; e=f")

    @pytest.mark.parametrize(
        "cookies",
        [
            # UTF8-encoded bytes
            {"a": "á".encode()},
            # non UTF8-encoded bytes
            {"a": "á".encode("latin1")},
            # string
            {"a": "á"},
            # key as bytes
            {b"a": "á"},
            # key and value as bytes
            {b"a": "á".encode()},
        ],
    )
    def test_request_cookies_encoding(self, cookies: CookiesT) -> None:
        req = Request("http://example.org", cookies=cookies)
        assert self.mw.process_request(req) is None
        self.assertCookieValEqual(req.headers["Cookie"], b"a=\xc3\xa1")

    @pytest.mark.xfail(reason="Cookie header is not currently being processed")
    def test_request_headers_cookie_encoding(self):
        # 1) UTF8-encoded bytes
        req1 = Request("http://example.org", headers={"Cookie": "a=á".encode()})
        assert self.mw.process_request(req1) is None
        self.assertCookieValEqual(req1.headers["Cookie"], b"a=\xc3\xa1")

        # 2) Non UTF8-encoded bytes
        req2 = Request("http://example.org", headers={"Cookie": "a=á".encode("latin1")})
        assert self.mw.process_request(req2) is None
        self.assertCookieValEqual(req2.headers["Cookie"], b"a=\xc3\xa1")

        # 3) String
        req3 = Request("http://example.org", headers={"Cookie": "a=á"})
        assert self.mw.process_request(req3) is None
        self.assertCookieValEqual(req3.headers["Cookie"], b"a=\xc3\xa1")

    def test_invalid_cookies(self, caplog: pytest.LogCaptureFixture) -> None:
        """
        Invalid cookies are logged as warnings and discarded
        """
        caplog.clear()
        with caplog.at_level(logging.INFO, logger="scrapy.utils.request"):
            cookies1 = [{"value": "bar"}, {"name": "key", "value": "value1"}]
            req1 = Request("http://example.org/1", cookies=cookies1)  # type: ignore[arg-type]
            assert self.mw.process_request(req1) is None
            cookies2 = [{"name": "foo"}, {"name": "key", "value": "value2"}]
            req2 = Request("http://example.org/2", cookies=cookies2)  # type: ignore[arg-type]
            assert self.mw.process_request(req2) is None
            cookies3 = [{"name": "foo", "value": None}, {"name": "key", "value": ""}]
            req3 = Request("http://example.org/3", cookies=cookies3)  # type: ignore[arg-type]
            assert self.mw.process_request(req3) is None
        assert caplog.record_tuples == [
            (
                "scrapy.utils.request",
                logging.WARNING,
                (
                    "Invalid cookie found in request <GET http://example.org/1>:"
                    " {'value': 'bar', 'secure': False} ('name' is missing)"
                ),
            ),
            (
                "scrapy.utils.request",
                logging.WARNING,
                (
                    "Invalid cookie found in request <GET http://example.org/2>:"
                    " {'name': 'foo', 'secure': False} ('value' is missing)"
                ),
            ),
            (
                "scrapy.utils.request",
                logging.WARNING,
                (
                    "Invalid cookie found in request <GET http://example.org/3>:"
                    " {'name': 'foo', 'value': None, 'secure': False} ('value' is missing)"
                ),
            ),
        ]
        self.assertCookieValEqual(req1.headers["Cookie"], "key=value1")
        self.assertCookieValEqual(req2.headers["Cookie"], "key=value2")
        self.assertCookieValEqual(req3.headers["Cookie"], "key=")

    def test_primitive_type_cookies(self):
        # Boolean
        req1 = Request("http://example.org", cookies={"a": True})
        assert self.mw.process_request(req1) is None
        self.assertCookieValEqual(req1.headers["Cookie"], b"a=True")

        # Float
        req2 = Request("http://example.org", cookies={"a": 9.5})
        assert self.mw.process_request(req2) is None
        self.assertCookieValEqual(req2.headers["Cookie"], b"a=9.5")

        # Integer
        req3 = Request("http://example.org", cookies={"a": 10})
        assert self.mw.process_request(req3) is None
        self.assertCookieValEqual(req3.headers["Cookie"], b"a=10")

        # String
        req4 = Request("http://example.org", cookies={"a": "b"})
        assert self.mw.process_request(req4) is None
        self.assertCookieValEqual(req4.headers["Cookie"], b"a=b")

    def _test_cookie_redirect(
        self,
        source: str | dict[str, Any],
        target: str | dict[str, Any],
        *,
        cookies1: bool,
        cookies2: bool,
    ) -> None:
        input_cookies: CookiesT = {"a": "b"}

        if not isinstance(source, dict):
            source = {"url": source}
        if not isinstance(target, dict):
            target = {"url": target}
        target.setdefault("status", 301)

        request1 = Request(cookies=input_cookies, **source)
        self.mw.process_request(request1)
        cookies = request1.headers.get("Cookie")
        assert cookies == (b"a=b" if cookies1 else None)

        response = Response(
            headers={
                "Location": target["url"],
            },
            **target,
        )
        assert self.mw.process_response(request1, response) == response

        request2 = self.redirect_middleware.process_response(request1, response)
        assert isinstance(request2, Request)

        self.mw.process_request(request2)
        cookies = request2.headers.get("Cookie")
        assert cookies == (b"a=b" if cookies2 else None)

    def test_cookie_redirect_same_domain(self):
        self._test_cookie_redirect(
            "https://toscrape.com",
            "https://toscrape.com",
            cookies1=True,
            cookies2=True,
        )

    def test_cookie_redirect_same_domain_forcing_get(self):
        self._test_cookie_redirect(
            "https://toscrape.com",
            {"url": "https://toscrape.com", "status": 302},
            cookies1=True,
            cookies2=True,
        )

    def test_cookie_redirect_different_domain(self):
        self._test_cookie_redirect(
            "https://toscrape.com",
            "https://example.com",
            cookies1=True,
            cookies2=False,
        )

    def test_cookie_redirect_different_domain_forcing_get(self):
        self._test_cookie_redirect(
            "https://toscrape.com",
            {"url": "https://example.com", "status": 302},
            cookies1=True,
            cookies2=False,
        )

    def _test_cookie_header_redirect(
        self,
        source: str | dict[str, Any],
        target: str | dict[str, Any],
        *,
        cookies2: bool,
    ) -> None:
        """Test the handling of a user-defined Cookie header when building a
        redirect follow-up request.

        We follow RFC 6265 for cookie handling. The Cookie header can only
        contain a list of key-value pairs (i.e. no additional cookie
        parameters like Domain or Path). Because of that, we follow the same
        rules that we would follow for the handling of the Set-Cookie response
        header when the Domain is not set: the cookies must be limited to the
        target URL domain (not even subdomains can receive those cookies).

        .. note:: This method tests the scenario where the cookie middleware is
                  disabled. Because of known issue #1992, when the cookies
                  middleware is enabled we do not need to be concerned about
                  the Cookie header getting leaked to unintended domains,
                  because the middleware empties the header from every request.
        """
        if not isinstance(source, dict):
            source = {"url": source}
        if not isinstance(target, dict):
            target = {"url": target}
        target.setdefault("status", 301)

        request1 = Request(headers={"Cookie": b"a=b"}, **source)

        response = Response(
            headers={
                "Location": target["url"],
            },
            **target,
        )

        request2 = self.redirect_middleware.process_response(request1, response)
        assert isinstance(request2, Request)

        cookies = request2.headers.get("Cookie")
        assert cookies == (b"a=b" if cookies2 else None)

    def test_cookie_header_redirect_same_domain(self):
        self._test_cookie_header_redirect(
            "https://toscrape.com",
            "https://toscrape.com",
            cookies2=True,
        )

    def test_cookie_header_redirect_same_domain_forcing_get(self):
        self._test_cookie_header_redirect(
            "https://toscrape.com",
            {"url": "https://toscrape.com", "status": 302},
            cookies2=True,
        )

    def test_cookie_header_redirect_different_domain(self):
        self._test_cookie_header_redirect(
            "https://toscrape.com",
            "https://example.com",
            cookies2=False,
        )

    def test_cookie_header_redirect_different_domain_forcing_get(self):
        self._test_cookie_header_redirect(
            "https://toscrape.com",
            {"url": "https://example.com", "status": 302},
            cookies2=False,
        )

    def _test_user_set_cookie_domain_followup(
        self,
        url1: str,
        url2: str,
        domain: str,
        *,
        cookies1: bool,
        cookies2: bool,
    ) -> None:
        input_cookies: list[VerboseCookie] = [
            {
                "name": "a",
                "value": "b",
                "domain": domain,
            }
        ]

        request1 = Request(url1, cookies=input_cookies)
        self.mw.process_request(request1)
        cookies = request1.headers.get("Cookie")
        assert cookies == (b"a=b" if cookies1 else None)

        request2 = Request(url2)
        self.mw.process_request(request2)
        cookies = request2.headers.get("Cookie")
        assert cookies == (b"a=b" if cookies2 else None)

    def test_user_set_cookie_domain_suffix_private(self):
        self._test_user_set_cookie_domain_followup(
            "https://books.toscrape.com",
            "https://quotes.toscrape.com",
            "toscrape.com",
            cookies1=True,
            cookies2=True,
        )

    def test_user_set_cookie_domain_suffix_public_period(self):
        self._test_user_set_cookie_domain_followup(
            "https://foo.co.uk",
            "https://bar.co.uk",
            "co.uk",
            cookies1=False,
            cookies2=False,
        )

    def test_user_set_cookie_domain_suffix_public_private(self):
        self._test_user_set_cookie_domain_followup(
            "https://foo.blogspot.com",
            "https://bar.blogspot.com",
            "blogspot.com",
            cookies1=False,
            cookies2=False,
        )

    def test_user_set_cookie_domain_public_period(self):
        self._test_user_set_cookie_domain_followup(
            "https://co.uk",
            "https://co.uk",
            "co.uk",
            cookies1=True,
            cookies2=True,
        )

    def _test_server_set_cookie_domain_followup(
        self,
        url1: str,
        url2: str,
        domain: str,
        *,
        cookies: bool,
    ) -> None:
        request1 = Request(url1)
        self.mw.process_request(request1)

        input_cookies: list[VerboseCookie] = [
            {
                "name": "a",
                "value": "b",
                "domain": domain,
            }
        ]

        headers = {
            "Set-Cookie": _cookies_to_set_cookie_list(input_cookies),
        }
        response = Response(url1, status=200, headers=headers)
        assert self.mw.process_response(request1, response) == response

        request2 = Request(url2)
        self.mw.process_request(request2)
        actual_cookies = request2.headers.get("Cookie")
        assert actual_cookies == (b"a=b" if cookies else None)

    def test_server_set_cookie_domain_suffix_private(self):
        self._test_server_set_cookie_domain_followup(
            "https://books.toscrape.com",
            "https://quotes.toscrape.com",
            "toscrape.com",
            cookies=True,
        )

    def test_server_set_cookie_domain_suffix_public_period(self):
        self._test_server_set_cookie_domain_followup(
            "https://foo.co.uk",
            "https://bar.co.uk",
            "co.uk",
            cookies=False,
        )

    def test_server_set_cookie_domain_suffix_public_private(self):
        self._test_server_set_cookie_domain_followup(
            "https://foo.blogspot.com",
            "https://bar.blogspot.com",
            "blogspot.com",
            cookies=False,
        )

    def test_server_set_cookie_domain_public_period(self):
        self._test_server_set_cookie_domain_followup(
            "https://co.uk",
            "https://co.uk",
            "co.uk",
            cookies=True,
        )

    def _test_cookie_redirect_scheme_change(
        self,
        secure: bool | object,
        from_scheme: str,
        to_scheme: str,
        cookies1: bool,
        cookies2: bool,
        cookies3: bool,
    ) -> None:
        """When a redirect causes the URL scheme to change from *from_scheme*
        to *to_scheme*, while domain and port remain the same, and given a
        cookie on the initial request with its secure attribute set to
        *secure*, check if the cookie should be set on the Cookie header of the
        initial request (*cookies1*), if it should be kept by the redirect
        middleware (*cookies2*), and if it should be present on the Cookie
        header in the redirected request (*cookie3*)."""
        cookie: VerboseCookie = {"name": "a", "value": "b"}
        if secure is not UNSET:
            assert isinstance(secure, bool)
            cookie["secure"] = secure
        input_cookies = [cookie]

        request1 = Request(f"{from_scheme}://a.example", cookies=input_cookies)
        self.mw.process_request(request1)
        cookies = request1.headers.get("Cookie")
        assert cookies == (b"a=b" if cookies1 else None)

        response = Response(
            f"{from_scheme}://a.example",
            headers={"Location": f"{to_scheme}://a.example"},
            status=301,
        )
        assert self.mw.process_response(request1, response) == response

        request2 = self.redirect_middleware.process_response(request1, response)
        assert isinstance(request2, Request)
        cookies = request2.headers.get("Cookie")
        assert cookies == (b"a=b" if cookies2 else None)

        self.mw.process_request(request2)
        cookies = request2.headers.get("Cookie")
        assert cookies == (b"a=b" if cookies3 else None)

    def test_cookie_redirect_secure_undefined_downgrade(self):
        self._test_cookie_redirect_scheme_change(
            secure=UNSET,
            from_scheme="https",
            to_scheme="http",
            cookies1=True,
            cookies2=False,
            cookies3=False,
        )

    def test_cookie_redirect_secure_undefined_upgrade(self):
        self._test_cookie_redirect_scheme_change(
            secure=UNSET,
            from_scheme="http",
            to_scheme="https",
            cookies1=True,
            cookies2=True,
            cookies3=True,
        )

    def test_cookie_redirect_secure_false_downgrade(self):
        self._test_cookie_redirect_scheme_change(
            secure=False,
            from_scheme="https",
            to_scheme="http",
            cookies1=True,
            cookies2=False,
            cookies3=True,
        )

    def test_cookie_redirect_secure_false_upgrade(self):
        self._test_cookie_redirect_scheme_change(
            secure=False,
            from_scheme="http",
            to_scheme="https",
            cookies1=True,
            cookies2=True,
            cookies3=True,
        )

    def test_cookie_redirect_secure_true_downgrade(self):
        self._test_cookie_redirect_scheme_change(
            secure=True,
            from_scheme="https",
            to_scheme="http",
            cookies1=True,
            cookies2=False,
            cookies3=False,
        )

    def test_cookie_redirect_secure_true_upgrade(self):
        self._test_cookie_redirect_scheme_change(
            secure=True,
            from_scheme="http",
            to_scheme="https",
            cookies1=False,
            cookies2=False,
            cookies3=True,
        )

    @pytest.mark.parametrize(
        ("scheme", "set_cookie", "accepted"),
        [
            ("https", "__Secure-a=b; Secure", True),
            ("https", "__secure-a=b; Secure", True),
            ("https", "__Secure-a=b", False),
            ("http", "__Secure-a=b; Secure", False),
            ("https", "__Host-a=b; Secure; Path=/", True),
            ("https", "__host-a=b; Secure; Path=/", True),
            ("https", "__Host-a=b; Path=/", False),
            ("http", "__Host-a=b; Secure; Path=/", False),
            ("https", "__Host-a=b; Secure; Path=/; Domain=a.example", False),
            ("https", "__Host-a=b; Secure; Path=/sub", False),
            ("https", "__Host-a=b; Secure", False),
            ("https", "__Hosta=b", True),
            ("http", "a=b", True),
        ],
    )
    def test_server_set_cookie_name_prefix(
        self, scheme: str, set_cookie: str, accepted: bool
    ) -> None:
        url = f"{scheme}://a.example/"
        request = Request(url)
        response = Response(url, headers={"Set-Cookie": set_cookie})
        assert self.mw.process_response(request, response) is response

        request2 = Request(url)
        self.mw.process_request(request2)
        assert (request2.headers.get("Cookie") is not None) == accepted

    @pytest.mark.parametrize(
        "cookie",
        [
            {"name": "__Secure-a", "value": "b", "secure": False},
            {"name": "__Host-a", "value": "b"},
            {"name": "__Host-a", "value": "b", "domain": "a.example"},
        ],
    )
    def test_request_cookie_name_prefix(self, cookie: VerboseCookie) -> None:
        request = Request("https://a.example/sub/", cookies=[cookie])
        self.mw.process_request(request)
        assert request.headers.get("Cookie") is not None

    def test_hostless_url(self):
        request = Request("data:,", cookies={"a": "b"})
        assert self.mw.process_request(request) is None
        assert "Cookie" not in request.headers