cookies.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. """
  2. requests.cookies
  3. ~~~~~~~~~~~~~~~~
  4. Compatibility code to be able to use `http.cookiejar.CookieJar` with requests.
  5. requests.utils imports from here, so be careful with imports.
  6. """
  7. from __future__ import annotations
  8. import calendar
  9. import copy
  10. import time
  11. from collections.abc import Iterator, MutableMapping
  12. from http.cookiejar import Cookie, CookieJar, CookiePolicy
  13. from typing import TYPE_CHECKING, Any, TypeVar, overload
  14. from ._internal_utils import to_native_string
  15. from ._types import is_prepared as _is_prepared
  16. from .compat import Morsel, cookielib, urlparse, urlunparse
  17. if TYPE_CHECKING:
  18. from _typeshed import SupportsKeysAndGetItem
  19. from .models import PreparedRequest
  20. import threading
  21. class MockRequest:
  22. """Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.
  23. The code in `http.cookiejar.CookieJar` expects this interface in order to correctly
  24. manage cookie policies, i.e., determine whether a cookie can be set, given the
  25. domains of the request and the cookie.
  26. The original request object is read-only. The client is responsible for collecting
  27. the new headers via `get_new_headers()` and interpreting them appropriately. You
  28. probably want `get_cookie_header`, defined below.
  29. """
  30. type: str
  31. def __init__(self, request: PreparedRequest) -> None:
  32. assert _is_prepared(request)
  33. self._r = request
  34. self._new_headers: dict[str, str] = {}
  35. self.type = urlparse(self._r.url).scheme
  36. def get_type(self) -> str:
  37. return self.type
  38. def get_host(self) -> str:
  39. return urlparse(self._r.url).netloc
  40. def get_origin_req_host(self) -> str:
  41. return self.get_host()
  42. def get_full_url(self) -> str:
  43. # Only return the response's URL if the user hadn't set the Host
  44. # header
  45. if not self._r.headers.get("Host"):
  46. return self._r.url
  47. # If they did set it, retrieve it and reconstruct the expected domain
  48. host = to_native_string(self._r.headers["Host"], encoding="utf-8")
  49. parsed = urlparse(self._r.url)
  50. # Reconstruct the URL as we expect it
  51. return urlunparse(
  52. [
  53. parsed.scheme,
  54. host,
  55. parsed.path,
  56. parsed.params,
  57. parsed.query,
  58. parsed.fragment,
  59. ]
  60. )
  61. def is_unverifiable(self) -> bool:
  62. return True
  63. def has_header(self, name: str) -> bool:
  64. return name in self._r.headers or name in self._new_headers
  65. def get_header(self, name: str, default: str | None = None) -> str | None:
  66. return self._r.headers.get(name, self._new_headers.get(name, default)) # type: ignore[return-value]
  67. def add_header(self, key: str, val: str) -> None:
  68. """cookiejar has no legitimate use for this method; add it back if you find one."""
  69. raise NotImplementedError(
  70. "Cookie headers should be added with add_unredirected_header()"
  71. )
  72. def add_unredirected_header(self, name: str, value: str) -> None:
  73. self._new_headers[name] = value
  74. def get_new_headers(self) -> dict[str, str]:
  75. return self._new_headers
  76. @property
  77. def unverifiable(self) -> bool:
  78. return self.is_unverifiable()
  79. @property
  80. def origin_req_host(self) -> str:
  81. return self.get_origin_req_host()
  82. @property
  83. def host(self) -> str:
  84. return self.get_host()
  85. class MockResponse:
  86. """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
  87. ...what? Basically, expose the parsed HTTP headers from the server response
  88. the way `http.cookiejar` expects to see them.
  89. """
  90. def __init__(self, headers: Any) -> None:
  91. """Make a MockResponse for `cookiejar` to read.
  92. :param headers: a httplib.HTTPMessage or analogous carrying the headers
  93. """
  94. self._headers = headers
  95. def info(self) -> Any:
  96. return self._headers
  97. def getheaders(self, name: str) -> Any:
  98. self._headers.getheaders(name)
  99. def extract_cookies_to_jar(
  100. jar: CookieJar, request: PreparedRequest, response: Any
  101. ) -> None:
  102. """Extract the cookies from the response into a CookieJar.
  103. :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)
  104. :param request: our own requests.Request object
  105. :param response: urllib3.HTTPResponse object
  106. """
  107. if not (hasattr(response, "_original_response") and response._original_response):
  108. return
  109. # the _original_response field is the wrapped httplib.HTTPResponse object,
  110. req = MockRequest(request)
  111. # pull out the HTTPMessage with the headers and put it in the mock:
  112. res = MockResponse(response._original_response.msg)
  113. jar.extract_cookies(res, req) # type: ignore[arg-type]
  114. def get_cookie_header(jar: CookieJar, request: PreparedRequest) -> str | None:
  115. """
  116. Produce an appropriate Cookie header string to be sent with `request`, or None.
  117. :rtype: str
  118. """
  119. r = MockRequest(request)
  120. jar.add_cookie_header(r) # type: ignore[arg-type]
  121. return r.get_new_headers().get("Cookie")
  122. def remove_cookie_by_name(
  123. cookiejar: CookieJar, name: str, domain: str | None = None, path: str | None = None
  124. ) -> None:
  125. """Unsets a cookie by name, by default over all domains and paths.
  126. Wraps CookieJar.clear(), is O(n).
  127. """
  128. clearables: list[tuple[str, str, str]] = []
  129. for cookie in cookiejar:
  130. if cookie.name != name:
  131. continue
  132. if domain is not None and domain != cookie.domain:
  133. continue
  134. if path is not None and path != cookie.path:
  135. continue
  136. clearables.append((cookie.domain, cookie.path, cookie.name))
  137. for domain, path, name in clearables:
  138. cookiejar.clear(domain, path, name)
  139. class CookieConflictError(RuntimeError):
  140. """There are two cookies that meet the criteria specified in the cookie jar.
  141. Use .get and .set and include domain and path args in order to be more specific.
  142. """
  143. class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc]
  144. """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict
  145. interface.
  146. This is the CookieJar we create by default for requests and sessions that
  147. don't specify one, since some clients may expect response.cookies and
  148. session.cookies to support dict operations.
  149. Requests does not use the dict interface internally; it's just for
  150. compatibility with external client code. All requests code should work
  151. out of the box with externally provided instances of ``CookieJar``, e.g.
  152. ``LWPCookieJar`` and ``FileCookieJar``.
  153. Unlike a regular CookieJar, this class is pickleable.
  154. .. warning:: dictionary operations that are normally O(1) may be O(n).
  155. """
  156. _policy: CookiePolicy
  157. def get( # type: ignore[override]
  158. self,
  159. name: str,
  160. default: str | None = None,
  161. domain: str | None = None,
  162. path: str | None = None,
  163. ) -> str | None:
  164. """Dict-like get() that also supports optional domain and path args in
  165. order to resolve naming collisions from using one cookie jar over
  166. multiple domains.
  167. .. warning:: operation is O(n), not O(1).
  168. """
  169. try:
  170. return self._find_no_duplicates(name, domain, path)
  171. except KeyError:
  172. return default
  173. def set(
  174. self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any
  175. ) -> Cookie | None:
  176. """Dict-like set() that also supports optional domain and path args in
  177. order to resolve naming collisions from using one cookie jar over
  178. multiple domains.
  179. """
  180. # support client code that unsets cookies by assignment of a None value:
  181. if value is None:
  182. remove_cookie_by_name(
  183. self, name, domain=kwargs.get("domain"), path=kwargs.get("path")
  184. )
  185. return
  186. if isinstance(value, Morsel):
  187. c = morsel_to_cookie(value)
  188. else:
  189. c = create_cookie(name, value, **kwargs)
  190. self.set_cookie(c)
  191. return c
  192. def iterkeys(self) -> Iterator[str]:
  193. """Dict-like iterkeys() that returns an iterator of names of cookies
  194. from the jar.
  195. .. seealso:: itervalues() and iteritems().
  196. """
  197. for cookie in iter(self):
  198. yield cookie.name
  199. def keys(self) -> list[str]: # type: ignore[override]
  200. """Dict-like keys() that returns a list of names of cookies from the
  201. jar.
  202. .. seealso:: values() and items().
  203. """
  204. return list(self.iterkeys())
  205. def itervalues(self) -> Iterator[str | None]:
  206. """Dict-like itervalues() that returns an iterator of values of cookies
  207. from the jar.
  208. .. seealso:: iterkeys() and iteritems().
  209. """
  210. for cookie in iter(self):
  211. yield cookie.value
  212. def values(self) -> list[str | None]: # type: ignore[override]
  213. """Dict-like values() that returns a list of values of cookies from the
  214. jar.
  215. .. seealso:: keys() and items().
  216. """
  217. return list(self.itervalues())
  218. def iteritems(self) -> Iterator[tuple[str, str | None]]:
  219. """Dict-like iteritems() that returns an iterator of name-value tuples
  220. from the jar.
  221. .. seealso:: iterkeys() and itervalues().
  222. """
  223. for cookie in iter(self):
  224. yield cookie.name, cookie.value
  225. def items(self) -> list[tuple[str, str | None]]: # type: ignore[override]
  226. """Dict-like items() that returns a list of name-value tuples from the
  227. jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
  228. vanilla python dict of key value pairs.
  229. .. seealso:: keys() and values().
  230. """
  231. return list(self.iteritems())
  232. def list_domains(self) -> list[str]:
  233. """Utility method to list all the domains in the jar."""
  234. domains: list[str] = []
  235. for cookie in iter(self):
  236. if cookie.domain not in domains:
  237. domains.append(cookie.domain)
  238. return domains
  239. def list_paths(self) -> list[str]:
  240. """Utility method to list all the paths in the jar."""
  241. paths: list[str] = []
  242. for cookie in iter(self):
  243. if cookie.path not in paths:
  244. paths.append(cookie.path)
  245. return paths
  246. def multiple_domains(self) -> bool:
  247. """Returns True if there are multiple domains in the jar.
  248. Returns False otherwise.
  249. :rtype: bool
  250. """
  251. domains: list[str] = []
  252. for cookie in iter(self):
  253. if cookie.domain is not None and cookie.domain in domains: # type: ignore[reportUnnecessaryComparison] # defensive check
  254. return True
  255. domains.append(cookie.domain)
  256. return False # there is only one domain in jar
  257. def get_dict(
  258. self, domain: str | None = None, path: str | None = None
  259. ) -> dict[str, str | None]:
  260. """Takes as an argument an optional domain and path and returns a plain
  261. old Python dict of name-value pairs of cookies that meet the
  262. requirements.
  263. :rtype: dict
  264. """
  265. dictionary: dict[str, str | None] = {}
  266. for cookie in iter(self):
  267. if (domain is None or cookie.domain == domain) and (
  268. path is None or cookie.path == path
  269. ):
  270. dictionary[cookie.name] = cookie.value
  271. return dictionary
  272. def __iter__(self) -> Iterator[Cookie]: # type: ignore[override]
  273. """RequestCookieJar's __iter__ comes from CookieJar not MutableMapping."""
  274. return super().__iter__()
  275. def __contains__(self, name: object) -> bool:
  276. try:
  277. return super().__contains__(name)
  278. except CookieConflictError:
  279. return True
  280. def __getitem__(self, name: str) -> str | None:
  281. """Dict-like __getitem__() for compatibility with client code. Throws
  282. exception if there are more than one cookie with name. In that case,
  283. use the more explicit get() method instead.
  284. .. warning:: operation is O(n), not O(1).
  285. """
  286. return self._find_no_duplicates(name)
  287. def __setitem__(
  288. self, name: str, value: str | Morsel[dict[str, str]] | None
  289. ) -> None:
  290. """Dict-like __setitem__ for compatibility with client code. Throws
  291. exception if there is already a cookie of that name in the jar. In that
  292. case, use the more explicit set() method instead.
  293. """
  294. self.set(name, value)
  295. def __delitem__(self, name: str) -> None:
  296. """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s
  297. ``remove_cookie_by_name()``.
  298. """
  299. remove_cookie_by_name(self, name)
  300. def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:
  301. if (
  302. (value := cookie.value) is not None
  303. and value.startswith('"')
  304. and value.endswith('"')
  305. ):
  306. cookie.value = value.replace('\\"', "")
  307. return super().set_cookie(cookie, *args, **kwargs)
  308. def update( # type: ignore[override]
  309. self, other: CookieJar | SupportsKeysAndGetItem[str, str]
  310. ) -> None:
  311. """Updates this jar with cookies from another CookieJar or dict-like"""
  312. if isinstance(other, cookielib.CookieJar):
  313. for cookie in other:
  314. self.set_cookie(copy.copy(cookie))
  315. else:
  316. super().update(other)
  317. def _find(
  318. self, name: str, domain: str | None = None, path: str | None = None
  319. ) -> str | None:
  320. """Requests uses this method internally to get cookie values.
  321. If there are conflicting cookies, _find arbitrarily chooses one.
  322. See _find_no_duplicates if you want an exception thrown if there are
  323. conflicting cookies.
  324. :param name: a string containing name of cookie
  325. :param domain: (optional) string containing domain of cookie
  326. :param path: (optional) string containing path of cookie
  327. :return: cookie.value
  328. """
  329. for cookie in iter(self):
  330. if cookie.name == name:
  331. if domain is None or cookie.domain == domain:
  332. if path is None or cookie.path == path:
  333. return cookie.value
  334. raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
  335. def _find_no_duplicates(
  336. self, name: str, domain: str | None = None, path: str | None = None
  337. ) -> str:
  338. """Both ``__get_item__`` and ``get`` call this function: it's never
  339. used elsewhere in Requests.
  340. :param name: a string containing name of cookie
  341. :param domain: (optional) string containing domain of cookie
  342. :param path: (optional) string containing path of cookie
  343. :raises KeyError: if cookie is not found
  344. :raises CookieConflictError: if there are multiple cookies
  345. that match name and optionally domain and path
  346. :return: cookie.value
  347. """
  348. toReturn = None
  349. for cookie in iter(self):
  350. if cookie.name == name:
  351. if domain is None or cookie.domain == domain:
  352. if path is None or cookie.path == path:
  353. if toReturn is not None:
  354. # if there are multiple cookies that meet passed in criteria
  355. raise CookieConflictError(
  356. f"There are multiple cookies with name, {name!r}"
  357. )
  358. # we will eventually return this as long as no cookie conflict
  359. toReturn = cookie.value
  360. if toReturn is not None:
  361. return toReturn
  362. raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
  363. def __getstate__(self) -> dict[str, Any]:
  364. """Unlike a normal CookieJar, this class is pickleable."""
  365. state = self.__dict__.copy()
  366. # remove the unpickleable RLock object
  367. state.pop("_cookies_lock")
  368. return state
  369. def __setstate__(self, state: dict[str, Any]) -> None:
  370. """Unlike a normal CookieJar, this class is pickleable."""
  371. self.__dict__.update(state)
  372. if "_cookies_lock" not in self.__dict__:
  373. self._cookies_lock = threading.RLock()
  374. def copy(self) -> RequestsCookieJar:
  375. """Return a copy of this RequestsCookieJar."""
  376. new_cj = RequestsCookieJar()
  377. new_cj.set_policy(self.get_policy())
  378. new_cj.update(self)
  379. return new_cj
  380. def get_policy(self) -> CookiePolicy:
  381. """Return the CookiePolicy instance used."""
  382. return self._policy
  383. def _copy_cookie_jar(jar: CookieJar | None) -> CookieJar | None: # type: ignore[reportUnusedFunction] # cross-module usage in models.py
  384. if jar is None:
  385. return None
  386. if copy_method := getattr(jar, "copy", None):
  387. # We're dealing with an instance of RequestsCookieJar
  388. return copy_method()
  389. # We're dealing with a generic CookieJar instance
  390. new_jar = copy.copy(jar)
  391. new_jar.clear()
  392. for cookie in jar:
  393. new_jar.set_cookie(copy.copy(cookie))
  394. return new_jar
  395. def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie:
  396. """Make a cookie from underspecified parameters.
  397. By default, the pair of `name` and `value` will be set for the domain ''
  398. and sent on every request (this is sometimes called a "supercookie").
  399. """
  400. result: dict[str, Any] = {
  401. "version": 0,
  402. "name": name,
  403. "value": value,
  404. "port": None,
  405. "domain": "",
  406. "path": "/",
  407. "secure": False,
  408. "expires": None,
  409. "discard": True,
  410. "comment": None,
  411. "comment_url": None,
  412. "rest": {"HttpOnly": None},
  413. "rfc2109": False,
  414. }
  415. badargs = set(kwargs) - set(result)
  416. if badargs:
  417. raise TypeError(
  418. f"create_cookie() got unexpected keyword arguments: {list(badargs)}"
  419. )
  420. result.update(kwargs)
  421. result["port_specified"] = bool(result["port"])
  422. result["domain_specified"] = bool(result["domain"])
  423. result["domain_initial_dot"] = result["domain"].startswith(".")
  424. result["path_specified"] = bool(result["path"])
  425. return cookielib.Cookie(**result)
  426. def morsel_to_cookie(morsel: Morsel[Any]) -> Cookie:
  427. """Convert a Morsel object into a Cookie containing the one k/v pair."""
  428. expires: int | None = None
  429. if morsel["max-age"]:
  430. try:
  431. expires = int(time.time() + int(morsel["max-age"]))
  432. except ValueError:
  433. raise TypeError(f"max-age: {morsel['max-age']} must be integer")
  434. elif morsel["expires"]:
  435. time_template = "%a, %d-%b-%Y %H:%M:%S GMT"
  436. expires = calendar.timegm(time.strptime(morsel["expires"], time_template))
  437. return create_cookie(
  438. comment=morsel["comment"],
  439. comment_url=bool(morsel["comment"]),
  440. discard=False,
  441. domain=morsel["domain"],
  442. expires=expires,
  443. name=morsel.key,
  444. path=morsel["path"],
  445. port=None,
  446. rest={"HttpOnly": morsel["httponly"]},
  447. rfc2109=False,
  448. secure=bool(morsel["secure"]),
  449. value=morsel.value,
  450. version=morsel["version"] or 0,
  451. )
  452. _CookieJarT = TypeVar("_CookieJarT", bound=CookieJar)
  453. @overload
  454. def cookiejar_from_dict(
  455. cookie_dict: dict[str, str] | None,
  456. cookiejar: None = None,
  457. overwrite: bool = True,
  458. ) -> RequestsCookieJar: ...
  459. @overload
  460. def cookiejar_from_dict(
  461. cookie_dict: dict[str, str] | None,
  462. cookiejar: _CookieJarT,
  463. overwrite: bool = True,
  464. ) -> _CookieJarT: ...
  465. def cookiejar_from_dict(
  466. cookie_dict: dict[str, str] | None,
  467. cookiejar: CookieJar | None = None,
  468. overwrite: bool = True,
  469. ) -> CookieJar:
  470. """Returns a CookieJar from a key/value dictionary.
  471. :param cookie_dict: Dict of key/values to insert into CookieJar.
  472. :param cookiejar: (optional) A cookiejar to add the cookies to.
  473. :param overwrite: (optional) If False, will not replace cookies
  474. already in the jar with new ones.
  475. :rtype: CookieJar
  476. """
  477. if cookiejar is None:
  478. cookiejar = RequestsCookieJar()
  479. if cookie_dict is not None:
  480. names_from_jar = [cookie.name for cookie in cookiejar]
  481. for name in cookie_dict:
  482. if overwrite or (name not in names_from_jar):
  483. cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
  484. return cookiejar
  485. def merge_cookies(
  486. cookiejar: CookieJar, cookies: dict[str, str] | CookieJar | None
  487. ) -> CookieJar:
  488. """Add cookies to cookiejar and returns a merged CookieJar.
  489. :param cookiejar: CookieJar object to add the cookies to.
  490. :param cookies: Dictionary or CookieJar object to be added.
  491. :rtype: CookieJar
  492. """
  493. if not isinstance(cookiejar, cookielib.CookieJar): # type: ignore[reportUnnecessaryIsInstance] # runtime guard
  494. raise ValueError("You can only merge into CookieJar")
  495. if isinstance(cookies, dict):
  496. cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)
  497. elif isinstance(cookies, cookielib.CookieJar):
  498. if update_method := getattr(cookiejar, "update", None):
  499. update_method(cookies)
  500. else:
  501. for cookie_in_jar in cookies:
  502. cookiejar.set_cookie(cookie_in_jar)
  503. return cookiejar