test_cookies.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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_linux_v10_meta24(self):
  87. with MonkeyPatch(cookies, {'_get_linux_keyring_password': lambda *args, **kwargs: b''}):
  88. encrypted_value = b'v10\x1f\xe4\x0e[\x83\x0c\xcc*kPi \xce\x8d\x1d\xbb\x80\r\x11\t\xbb\x9e^Hy\x94\xf4\x963\x9f\x82\xba\xfe\xa1\xed\xb9\xf1)\x00710\x92\xc8/<\x96B'
  89. value = 'DE'
  90. decryptor = LinuxChromeCookieDecryptor('Chrome', Logger(), meta_version=24)
  91. self.assertEqual(decryptor.decrypt(encrypted_value), value)
  92. def test_chrome_cookie_decryptor_windows_v10(self):
  93. with MonkeyPatch(cookies, {
  94. '_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&',
  95. }):
  96. 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='
  97. value = '32101439'
  98. decryptor = WindowsChromeCookieDecryptor('', Logger())
  99. self.assertEqual(decryptor.decrypt(encrypted_value), value)
  100. def test_chrome_cookie_decryptor_windows_v10_meta24(self):
  101. with MonkeyPatch(cookies, {
  102. '_get_windows_v10_key': lambda *args, **kwargs: b'\xea\x8b\x02\xc3\xc6\xc5\x99\xc3\xa3[ j\xfa\xf6\xfcU\xac\x13u\xdc\x0c\x0e\xf1\x03\x90\xb6\xdf\xbb\x8fL\xb1\xb2',
  103. }):
  104. encrypted_value = b'v10dN\xe1\xacy\x84^\xe1I\xact\x03r\xfb\xe2\xce{^\x0e<(\xb0y\xeb\x01\xfb@"\x9e\x8c\xa53~\xdb*\x8f\xac\x8b\xe3\xfd3\x06\xe5\x93\x19OyOG\xb2\xfb\x1d$\xc0\xda\x13j\x9e\xfe\xc5\xa3\xa8\xfe\xd9'
  105. value = '1234'
  106. decryptor = WindowsChromeCookieDecryptor('', Logger(), meta_version=24)
  107. self.assertEqual(decryptor.decrypt(encrypted_value), value)
  108. def test_chrome_cookie_decryptor_mac_v10(self):
  109. with MonkeyPatch(cookies, {'_get_mac_keyring_password': lambda *args, **kwargs: b'6eIDUdtKAacvlHwBVwvg/Q=='}):
  110. encrypted_value = b'v10\xb3\xbe\xad\xa1[\x9fC\xa1\x98\xe0\x9a\x01\xd9\xcf\xbfc'
  111. value = '2021-06-01-22'
  112. decryptor = MacChromeCookieDecryptor('', Logger())
  113. self.assertEqual(decryptor.decrypt(encrypted_value), value)
  114. def test_safari_cookie_parsing(self):
  115. cookies = (
  116. 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'
  117. b'\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x008\x00\x00\x00B\x00\x00\x00F\x00\x00\x00H'
  118. b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x03\xa5>\xc3A\x00\x00\x80\xc3\x07:\xc3A'
  119. b'localhost\x00foo\x00/\x00test%20%3Bcookie\x00\x00\x00\x054\x07\x17 \x05\x00\x00\x00Kbplist00\xd1\x01'
  120. b'\x02_\x10\x18NSHTTPCookieAcceptPolicy\x10\x02\x08\x0b&\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00'
  121. b'\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00(')
  122. jar = parse_safari_cookies(cookies)
  123. self.assertEqual(len(jar), 1)
  124. cookie = next(iter(jar))
  125. self.assertEqual(cookie.domain, 'localhost')
  126. self.assertEqual(cookie.port, None)
  127. self.assertEqual(cookie.path, '/')
  128. self.assertEqual(cookie.name, 'foo')
  129. self.assertEqual(cookie.value, 'test%20%3Bcookie')
  130. self.assertFalse(cookie.secure)
  131. expected_expiration = dt.datetime(2021, 6, 18, 21, 39, 19, tzinfo=dt.timezone.utc)
  132. self.assertEqual(cookie.expires, int(expected_expiration.timestamp()))
  133. def test_pbkdf2_sha1(self):
  134. key = pbkdf2_sha1(b'peanuts', b' ' * 16, 1, 16)
  135. self.assertEqual(key, b'g\xe1\x8e\x0fQ\x1c\x9b\xf3\xc9`!\xaa\x90\xd9\xd34')
  136. class TestLenientSimpleCookie(unittest.TestCase):
  137. def _run_tests(self, *cases):
  138. for message, raw_cookie, expected in cases:
  139. cookie = LenientSimpleCookie(raw_cookie)
  140. with self.subTest(message, expected=expected):
  141. self.assertEqual(cookie.keys(), expected.keys(), message)
  142. for key, expected_value in expected.items():
  143. morsel = cookie[key]
  144. if isinstance(expected_value, tuple):
  145. expected_value, expected_attributes = expected_value
  146. else:
  147. expected_attributes = {}
  148. attributes = {
  149. key: value
  150. for key, value in dict(morsel).items()
  151. if value != ''
  152. }
  153. self.assertEqual(attributes, expected_attributes, message)
  154. self.assertEqual(morsel.value, expected_value, message)
  155. def test_parsing(self):
  156. self._run_tests(
  157. # Copied from https://github.com/python/cpython/blob/v3.10.7/Lib/test/test_http_cookies.py
  158. (
  159. 'Test basic cookie',
  160. 'chips=ahoy; vienna=finger',
  161. {'chips': 'ahoy', 'vienna': 'finger'},
  162. ),
  163. (
  164. 'Test quoted cookie',
  165. 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
  166. {'keebler': 'E=mc2; L="Loves"; fudge=\012;'},
  167. ),
  168. (
  169. "Allow '=' in an unquoted value",
  170. 'keebler=E=mc2',
  171. {'keebler': 'E=mc2'},
  172. ),
  173. (
  174. "Allow cookies with ':' in their name",
  175. 'key:term=value:term',
  176. {'key:term': 'value:term'},
  177. ),
  178. (
  179. "Allow '[' and ']' in cookie values",
  180. 'a=b; c=[; d=r; f=h',
  181. {'a': 'b', 'c': '[', 'd': 'r', 'f': 'h'},
  182. ),
  183. (
  184. 'Test basic cookie attributes',
  185. 'Customer="WILE_E_COYOTE"; Version=1; Path=/acme',
  186. {'Customer': ('WILE_E_COYOTE', {'version': '1', 'path': '/acme'})},
  187. ),
  188. (
  189. 'Test flag only cookie attributes',
  190. 'Customer="WILE_E_COYOTE"; HttpOnly; Secure',
  191. {'Customer': ('WILE_E_COYOTE', {'httponly': True, 'secure': True})},
  192. ),
  193. (
  194. 'Test flag only attribute with values',
  195. 'eggs=scrambled; httponly=foo; secure=bar; Path=/bacon',
  196. {'eggs': ('scrambled', {'httponly': 'foo', 'secure': 'bar', 'path': '/bacon'})},
  197. ),
  198. (
  199. "Test special case for 'expires' attribute, 4 digit year",
  200. 'Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT',
  201. {'Customer': ('W', {'expires': 'Wed, 01 Jan 2010 00:00:00 GMT'})},
  202. ),
  203. (
  204. "Test special case for 'expires' attribute, 2 digit year",
  205. 'Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT',
  206. {'Customer': ('W', {'expires': 'Wed, 01 Jan 98 00:00:00 GMT'})},
  207. ),
  208. (
  209. 'Test extra spaces in keys and values',
  210. 'eggs = scrambled ; secure ; path = bar ; foo=foo ',
  211. {'eggs': ('scrambled', {'secure': True, 'path': 'bar'}), 'foo': 'foo'},
  212. ),
  213. (
  214. 'Test quoted attributes',
  215. 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"',
  216. {'Customer': ('WILE_E_COYOTE', {'version': '1', 'path': '/acme'})},
  217. ),
  218. # Our own tests that CPython passes
  219. (
  220. "Allow ';' in quoted value",
  221. 'chips="a;hoy"; vienna=finger',
  222. {'chips': 'a;hoy', 'vienna': 'finger'},
  223. ),
  224. (
  225. 'Keep only the last set value',
  226. 'a=c; a=b',
  227. {'a': 'b'},
  228. ),
  229. )
  230. def test_lenient_parsing(self):
  231. self._run_tests(
  232. (
  233. 'Ignore and try to skip invalid cookies',
  234. 'chips={"ahoy;": 1}; vienna="finger;"',
  235. {'vienna': 'finger;'},
  236. ),
  237. (
  238. 'Ignore cookies without a name',
  239. 'a=b; unnamed; c=d',
  240. {'a': 'b', 'c': 'd'},
  241. ),
  242. (
  243. "Ignore '\"' cookie without name",
  244. 'a=b; "; c=d',
  245. {'a': 'b', 'c': 'd'},
  246. ),
  247. (
  248. 'Skip all space separated values',
  249. 'x a=b c=d x; e=f',
  250. {'a': 'b', 'c': 'd', 'e': 'f'},
  251. ),
  252. (
  253. 'Skip all space separated values',
  254. 'x a=b; data={"complex": "json", "with": "key=value"}; x c=d x',
  255. {'a': 'b', 'c': 'd'},
  256. ),
  257. (
  258. 'Expect quote mending',
  259. 'a=b; invalid="; c=d',
  260. {'a': 'b', 'c': 'd'},
  261. ),
  262. (
  263. 'Reset morsel after invalid to not capture attributes',
  264. 'a=b; invalid; Version=1; c=d',
  265. {'a': 'b', 'c': 'd'},
  266. ),
  267. (
  268. 'Reset morsel after invalid to not capture attributes',
  269. 'a=b; $invalid; $Version=1; c=d',
  270. {'a': 'b', 'c': 'd'},
  271. ),
  272. (
  273. 'Continue after non-flag attribute without value',
  274. 'a=b; path; Version=1; c=d',
  275. {'a': 'b', 'c': 'd'},
  276. ),
  277. (
  278. 'Allow cookie attributes with `$` prefix',
  279. 'Customer="WILE_E_COYOTE"; $Version=1; $Secure; $Path=/acme',
  280. {'Customer': ('WILE_E_COYOTE', {'version': '1', 'secure': True, 'path': '/acme'})},
  281. ),
  282. (
  283. 'Invalid Morsel keys should not result in an error',
  284. 'Key=Value; [Invalid]=Value; Another=Value',
  285. {'Key': 'Value', 'Another': 'Value'},
  286. ),
  287. )