test_cookies.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import datetime as dt
  2. import unittest
  3. from yt_dlp import cookies
  4. from yt_dlp.cookies import (
  5. LenientSimpleCookie,
  6. LinuxChromeCookieDecryptor,
  7. MacChromeCookieDecryptor,
  8. WindowsChromeCookieDecryptor,
  9. _get_linux_desktop_environment,
  10. _LinuxDesktopEnvironment,
  11. parse_safari_cookies,
  12. pbkdf2_sha1,
  13. )
  14. class Logger:
  15. def debug(self, message, *args, **kwargs):
  16. print(f'[verbose] {message}')
  17. def info(self, message, *args, **kwargs):
  18. print(message)
  19. def warning(self, message, *args, **kwargs):
  20. self.error(message)
  21. def error(self, message, *args, **kwargs):
  22. raise Exception(message)
  23. class MonkeyPatch:
  24. def __init__(self, module, temporary_values):
  25. self._module = module
  26. self._temporary_values = temporary_values
  27. self._backup_values = {}
  28. def __enter__(self):
  29. for name, temp_value in self._temporary_values.items():
  30. self._backup_values[name] = getattr(self._module, name)
  31. setattr(self._module, name, temp_value)
  32. def __exit__(self, exc_type, exc_val, exc_tb):
  33. for name, backup_value in self._backup_values.items():
  34. setattr(self._module, name, backup_value)
  35. class TestCookies(unittest.TestCase):
  36. def test_get_desktop_environment(self):
  37. """ based on https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util_unittest.cc """
  38. test_cases = [
  39. ({}, _LinuxDesktopEnvironment.OTHER),
  40. ({'DESKTOP_SESSION': 'my_custom_de'}, _LinuxDesktopEnvironment.OTHER),
  41. ({'XDG_CURRENT_DESKTOP': 'my_custom_de'}, _LinuxDesktopEnvironment.OTHER),
  42. ({'DESKTOP_SESSION': 'gnome'}, _LinuxDesktopEnvironment.GNOME),
  43. ({'DESKTOP_SESSION': 'mate'}, _LinuxDesktopEnvironment.GNOME),
  44. ({'DESKTOP_SESSION': 'kde4'}, _LinuxDesktopEnvironment.KDE4),
  45. ({'DESKTOP_SESSION': 'kde'}, _LinuxDesktopEnvironment.KDE3),
  46. ({'DESKTOP_SESSION': 'xfce'}, _LinuxDesktopEnvironment.XFCE),
  47. ({'GNOME_DESKTOP_SESSION_ID': 1}, _LinuxDesktopEnvironment.GNOME),
  48. ({'KDE_FULL_SESSION': 1}, _LinuxDesktopEnvironment.KDE3),
  49. ({'KDE_FULL_SESSION': 1, 'DESKTOP_SESSION': 'kde4'}, _LinuxDesktopEnvironment.KDE4),
  50. ({'XDG_CURRENT_DESKTOP': 'X-Cinnamon'}, _LinuxDesktopEnvironment.CINNAMON),
  51. ({'XDG_CURRENT_DESKTOP': 'Deepin'}, _LinuxDesktopEnvironment.DEEPIN),
  52. ({'XDG_CURRENT_DESKTOP': 'GNOME'}, _LinuxDesktopEnvironment.GNOME),
  53. ({'XDG_CURRENT_DESKTOP': 'GNOME:GNOME-Classic'}, _LinuxDesktopEnvironment.GNOME),
  54. ({'XDG_CURRENT_DESKTOP': 'GNOME : GNOME-Classic'}, _LinuxDesktopEnvironment.GNOME),
  55. ({'XDG_CURRENT_DESKTOP': 'ubuntu:GNOME'}, _LinuxDesktopEnvironment.GNOME),
  56. ({'XDG_CURRENT_DESKTOP': 'Unity', 'DESKTOP_SESSION': 'gnome-fallback'}, _LinuxDesktopEnvironment.GNOME),
  57. ({'XDG_CURRENT_DESKTOP': 'KDE', 'KDE_SESSION_VERSION': '5'}, _LinuxDesktopEnvironment.KDE5),
  58. ({'XDG_CURRENT_DESKTOP': 'KDE', 'KDE_SESSION_VERSION': '6'}, _LinuxDesktopEnvironment.KDE6),
  59. ({'XDG_CURRENT_DESKTOP': 'KDE'}, _LinuxDesktopEnvironment.KDE4),
  60. ({'XDG_CURRENT_DESKTOP': 'Pantheon'}, _LinuxDesktopEnvironment.PANTHEON),
  61. ({'XDG_CURRENT_DESKTOP': 'UKUI'}, _LinuxDesktopEnvironment.UKUI),
  62. ({'XDG_CURRENT_DESKTOP': 'Unity'}, _LinuxDesktopEnvironment.UNITY),
  63. ({'XDG_CURRENT_DESKTOP': 'Unity:Unity7'}, _LinuxDesktopEnvironment.UNITY),
  64. ({'XDG_CURRENT_DESKTOP': 'Unity:Unity8'}, _LinuxDesktopEnvironment.UNITY),
  65. ]
  66. for env, expected_desktop_environment in test_cases:
  67. self.assertEqual(_get_linux_desktop_environment(env, Logger()), expected_desktop_environment)
  68. def test_chrome_cookie_decryptor_linux_derive_key(self):
  69. key = LinuxChromeCookieDecryptor.derive_key(b'abc')
  70. self.assertEqual(key, b'7\xa1\xec\xd4m\xfcA\xc7\xb19Z\xd0\x19\xdcM\x17')
  71. def test_chrome_cookie_decryptor_mac_derive_key(self):
  72. key = MacChromeCookieDecryptor.derive_key(b'abc')
  73. self.assertEqual(key, b'Y\xe2\xc0\xd0P\xf6\xf4\xe1l\xc1\x8cQ\xcb|\xcdY')
  74. def test_chrome_cookie_decryptor_linux_v10(self):
  75. with MonkeyPatch(cookies, {'_get_linux_keyring_password': lambda *args, **kwargs: b''}):
  76. encrypted_value = b'v10\xccW%\xcd\xe6\xe6\x9fM" \xa7\xb0\xca\xe4\x07\xd6'
  77. value = 'USD'
  78. decryptor = LinuxChromeCookieDecryptor('Chrome', Logger())
  79. self.assertEqual(decryptor.decrypt(encrypted_value), value)
  80. def test_chrome_cookie_decryptor_linux_v11(self):
  81. with MonkeyPatch(cookies, {'_get_linux_keyring_password': lambda *args, **kwargs: b''}):
  82. encrypted_value = b'v11#\x81\x10>`w\x8f)\xc0\xb2\xc1\r\xf4\x1al\xdd\x93\xfd\xf8\xf8N\xf2\xa9\x83\xf1\xe9o\x0elVQd'
  83. value = 'tz=Europe.London'
  84. decryptor = LinuxChromeCookieDecryptor('Chrome', Logger())
  85. self.assertEqual(decryptor.decrypt(encrypted_value), value)
  86. def test_chrome_cookie_decryptor_windows_v10(self):
  87. with MonkeyPatch(cookies, {
  88. '_get_windows_v10_key': lambda *args, **kwargs: b'Y\xef\xad\xad\xeerp\xf0Y\xe6\x9b\x12\xc2<z\x16]\n\xbb\xb8\xcb\xd7\x9bA\xc3\x14e\x99{\xd6\xf4&',
  89. }):
  90. encrypted_value = b'v10T\xb8\xf3\xb8\x01\xa7TtcV\xfc\x88\xb8\xb8\xef\x05\xb5\xfd\x18\xc90\x009\xab\xb1\x893\x85)\x87\xe1\xa9-\xa3\xad='
  91. value = '32101439'
  92. decryptor = WindowsChromeCookieDecryptor('', Logger())
  93. self.assertEqual(decryptor.decrypt(encrypted_value), value)
  94. def test_chrome_cookie_decryptor_mac_v10(self):
  95. with MonkeyPatch(cookies, {'_get_mac_keyring_password': lambda *args, **kwargs: b'6eIDUdtKAacvlHwBVwvg/Q=='}):
  96. encrypted_value = b'v10\xb3\xbe\xad\xa1[\x9fC\xa1\x98\xe0\x9a\x01\xd9\xcf\xbfc'
  97. value = '2021-06-01-22'
  98. decryptor = MacChromeCookieDecryptor('', Logger())
  99. self.assertEqual(decryptor.decrypt(encrypted_value), value)
  100. def test_safari_cookie_parsing(self):
  101. cookies = (
  102. b'cook\x00\x00\x00\x01\x00\x00\x00i\x00\x00\x01\x00\x01\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00Y'
  103. b'\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x008\x00\x00\x00B\x00\x00\x00F\x00\x00\x00H'
  104. b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x03\xa5>\xc3A\x00\x00\x80\xc3\x07:\xc3A'
  105. b'localhost\x00foo\x00/\x00test%20%3Bcookie\x00\x00\x00\x054\x07\x17 \x05\x00\x00\x00Kbplist00\xd1\x01'
  106. b'\x02_\x10\x18NSHTTPCookieAcceptPolicy\x10\x02\x08\x0b&\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00'
  107. b'\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00(')
  108. jar = parse_safari_cookies(cookies)
  109. self.assertEqual(len(jar), 1)
  110. cookie = next(iter(jar))
  111. self.assertEqual(cookie.domain, 'localhost')
  112. self.assertEqual(cookie.port, None)
  113. self.assertEqual(cookie.path, '/')
  114. self.assertEqual(cookie.name, 'foo')
  115. self.assertEqual(cookie.value, 'test%20%3Bcookie')
  116. self.assertFalse(cookie.secure)
  117. expected_expiration = dt.datetime(2021, 6, 18, 21, 39, 19, tzinfo=dt.timezone.utc)
  118. self.assertEqual(cookie.expires, int(expected_expiration.timestamp()))
  119. def test_pbkdf2_sha1(self):
  120. key = pbkdf2_sha1(b'peanuts', b' ' * 16, 1, 16)
  121. self.assertEqual(key, b'g\xe1\x8e\x0fQ\x1c\x9b\xf3\xc9`!\xaa\x90\xd9\xd34')
  122. class TestLenientSimpleCookie(unittest.TestCase):
  123. def _run_tests(self, *cases):
  124. for message, raw_cookie, expected in cases:
  125. cookie = LenientSimpleCookie(raw_cookie)
  126. with self.subTest(message, expected=expected):
  127. self.assertEqual(cookie.keys(), expected.keys(), message)
  128. for key, expected_value in expected.items():
  129. morsel = cookie[key]
  130. if isinstance(expected_value, tuple):
  131. expected_value, expected_attributes = expected_value
  132. else:
  133. expected_attributes = {}
  134. attributes = {
  135. key: value
  136. for key, value in dict(morsel).items()
  137. if value != ''
  138. }
  139. self.assertEqual(attributes, expected_attributes, message)
  140. self.assertEqual(morsel.value, expected_value, message)
  141. def test_parsing(self):
  142. self._run_tests(
  143. # Copied from https://github.com/python/cpython/blob/v3.10.7/Lib/test/test_http_cookies.py
  144. (
  145. 'Test basic cookie',
  146. 'chips=ahoy; vienna=finger',
  147. {'chips': 'ahoy', 'vienna': 'finger'},
  148. ),
  149. (
  150. 'Test quoted cookie',
  151. 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
  152. {'keebler': 'E=mc2; L="Loves"; fudge=\012;'},
  153. ),
  154. (
  155. "Allow '=' in an unquoted value",
  156. 'keebler=E=mc2',
  157. {'keebler': 'E=mc2'},
  158. ),
  159. (
  160. "Allow cookies with ':' in their name",
  161. 'key:term=value:term',
  162. {'key:term': 'value:term'},
  163. ),
  164. (
  165. "Allow '[' and ']' in cookie values",
  166. 'a=b; c=[; d=r; f=h',
  167. {'a': 'b', 'c': '[', 'd': 'r', 'f': 'h'},
  168. ),
  169. (
  170. 'Test basic cookie attributes',
  171. 'Customer="WILE_E_COYOTE"; Version=1; Path=/acme',
  172. {'Customer': ('WILE_E_COYOTE', {'version': '1', 'path': '/acme'})},
  173. ),
  174. (
  175. 'Test flag only cookie attributes',
  176. 'Customer="WILE_E_COYOTE"; HttpOnly; Secure',
  177. {'Customer': ('WILE_E_COYOTE', {'httponly': True, 'secure': True})},
  178. ),
  179. (
  180. 'Test flag only attribute with values',
  181. 'eggs=scrambled; httponly=foo; secure=bar; Path=/bacon',
  182. {'eggs': ('scrambled', {'httponly': 'foo', 'secure': 'bar', 'path': '/bacon'})},
  183. ),
  184. (
  185. "Test special case for 'expires' attribute, 4 digit year",
  186. 'Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT',
  187. {'Customer': ('W', {'expires': 'Wed, 01 Jan 2010 00:00:00 GMT'})},
  188. ),
  189. (
  190. "Test special case for 'expires' attribute, 2 digit year",
  191. 'Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT',
  192. {'Customer': ('W', {'expires': 'Wed, 01 Jan 98 00:00:00 GMT'})},
  193. ),
  194. (
  195. 'Test extra spaces in keys and values',
  196. 'eggs = scrambled ; secure ; path = bar ; foo=foo ',
  197. {'eggs': ('scrambled', {'secure': True, 'path': 'bar'}), 'foo': 'foo'},
  198. ),
  199. (
  200. 'Test quoted attributes',
  201. 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"',
  202. {'Customer': ('WILE_E_COYOTE', {'version': '1', 'path': '/acme'})},
  203. ),
  204. # Our own tests that CPython passes
  205. (
  206. "Allow ';' in quoted value",
  207. 'chips="a;hoy"; vienna=finger',
  208. {'chips': 'a;hoy', 'vienna': 'finger'},
  209. ),
  210. (
  211. 'Keep only the last set value',
  212. 'a=c; a=b',
  213. {'a': 'b'},
  214. ),
  215. )
  216. def test_lenient_parsing(self):
  217. self._run_tests(
  218. (
  219. 'Ignore and try to skip invalid cookies',
  220. 'chips={"ahoy;": 1}; vienna="finger;"',
  221. {'vienna': 'finger;'},
  222. ),
  223. (
  224. 'Ignore cookies without a name',
  225. 'a=b; unnamed; c=d',
  226. {'a': 'b', 'c': 'd'},
  227. ),
  228. (
  229. "Ignore '\"' cookie without name",
  230. 'a=b; "; c=d',
  231. {'a': 'b', 'c': 'd'},
  232. ),
  233. (
  234. 'Skip all space separated values',
  235. 'x a=b c=d x; e=f',
  236. {'a': 'b', 'c': 'd', 'e': 'f'},
  237. ),
  238. (
  239. 'Skip all space separated values',
  240. 'x a=b; data={"complex": "json", "with": "key=value"}; x c=d x',
  241. {'a': 'b', 'c': 'd'},
  242. ),
  243. (
  244. 'Expect quote mending',
  245. 'a=b; invalid="; c=d',
  246. {'a': 'b', 'c': 'd'},
  247. ),
  248. (
  249. 'Reset morsel after invalid to not capture attributes',
  250. 'a=b; invalid; Version=1; c=d',
  251. {'a': 'b', 'c': 'd'},
  252. ),
  253. (
  254. 'Reset morsel after invalid to not capture attributes',
  255. 'a=b; $invalid; $Version=1; c=d',
  256. {'a': 'b', 'c': 'd'},
  257. ),
  258. (
  259. 'Continue after non-flag attribute without value',
  260. 'a=b; path; Version=1; c=d',
  261. {'a': 'b', 'c': 'd'},
  262. ),
  263. (
  264. 'Allow cookie attributes with `$` prefix',
  265. 'Customer="WILE_E_COYOTE"; $Version=1; $Secure; $Path=/acme',
  266. {'Customer': ('WILE_E_COYOTE', {'version': '1', 'secure': True, 'path': '/acme'})},
  267. ),
  268. (
  269. 'Invalid Morsel keys should not result in an error',
  270. 'Key=Value; [Invalid]=Value; Another=Value',
  271. {'Key': 'Value', 'Another': 'Value'},
  272. ),
  273. )