test_auth.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2012-2016 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2022 Unrud <unrud@outlook.com>
  5. # Copyright © 2024-2025 Peter Bieringer <pb@bieringer.de>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. Radicale tests with simple requests and authentication.
  21. """
  22. import base64
  23. import logging
  24. import os
  25. import sys
  26. from typing import Iterable, Tuple, Union
  27. import pytest
  28. from radicale import xmlutils
  29. from radicale.tests import BaseTest
  30. class TestBaseAuthRequests(BaseTest):
  31. """Tests basic requests with auth.
  32. We should setup auth for each type before creating the Application object.
  33. """
  34. # test for available bcrypt module
  35. try:
  36. import bcrypt
  37. except ImportError:
  38. has_bcrypt = 0
  39. else:
  40. has_bcrypt = 1
  41. # test for available argon2 module
  42. try:
  43. import argon2
  44. from passlib.hash import argon2 # noqa: F811
  45. except ImportError:
  46. has_argon2 = 0
  47. else:
  48. has_argon2 = 1
  49. def _test_htpasswd(self, htpasswd_encryption: str, htpasswd_content: str,
  50. test_matrix: Union[str, Iterable[Tuple[str, str, bool]]]
  51. = "ascii") -> None:
  52. """Test htpasswd authentication with user "tmp" and password "bepo" for
  53. ``test_matrix`` "ascii" or user "😀" and password "🔑" for
  54. ``test_matrix`` "unicode"."""
  55. htpasswd_file_path = os.path.join(self.colpath, ".htpasswd")
  56. encoding: str = self.configuration.get("encoding", "stock")
  57. with open(htpasswd_file_path, "w", encoding=encoding) as f:
  58. f.write(htpasswd_content)
  59. self.configure({"auth": {"type": "htpasswd",
  60. "htpasswd_filename": htpasswd_file_path,
  61. "htpasswd_encryption": htpasswd_encryption}})
  62. if test_matrix == "ascii":
  63. test_matrix = (("tmp", "bepo", True), ("tmp", "tmp", False),
  64. ("tmp", "", False), ("unk", "unk", False),
  65. ("unk", "", False), ("", "", False))
  66. elif test_matrix == "unicode":
  67. test_matrix = (("😀", "🔑", True), ("😀", "🌹", False),
  68. ("😁", "🔑", False), ("😀", "", False),
  69. ("", "🔑", False), ("", "", False))
  70. elif isinstance(test_matrix, str):
  71. raise ValueError("Unknown test matrix %r" % test_matrix)
  72. for user, password, valid in test_matrix:
  73. self.propfind("/", check=207 if valid else 401,
  74. login="%s:%s" % (user, password))
  75. def test_htpasswd_plain(self) -> None:
  76. self._test_htpasswd("plain", "tmp:bepo")
  77. def test_htpasswd_plain_autodetect(self) -> None:
  78. self._test_htpasswd("autodetect", "tmp:bepo")
  79. def test_htpasswd_plain_password_split(self) -> None:
  80. self._test_htpasswd("plain", "tmp:be:po", (
  81. ("tmp", "be:po", True), ("tmp", "bepo", False)))
  82. def test_htpasswd_plain_unicode(self) -> None:
  83. self._test_htpasswd("plain", "😀:🔑", "unicode")
  84. def test_htpasswd_md5(self) -> None:
  85. self._test_htpasswd("md5", "tmp:$apr1$BI7VKCZh$GKW4vq2hqDINMr8uv7lDY/")
  86. def test_htpasswd_md5_autodetect(self) -> None:
  87. self._test_htpasswd("autodetect", "tmp:$apr1$BI7VKCZh$GKW4vq2hqDINMr8uv7lDY/")
  88. def test_htpasswd_md5_unicode(self):
  89. self._test_htpasswd(
  90. "md5", "😀:$apr1$w4ev89r1$29xO8EvJmS2HEAadQ5qy11", "unicode")
  91. def test_htpasswd_sha256(self) -> None:
  92. self._test_htpasswd("sha256", "tmp:$5$i4Ni4TQq6L5FKss5$ilpTjkmnxkwZeV35GB9cYSsDXTALBn6KtWRJAzNlCL/")
  93. def test_htpasswd_sha256_autodetect(self) -> None:
  94. self._test_htpasswd("autodetect", "tmp:$5$i4Ni4TQq6L5FKss5$ilpTjkmnxkwZeV35GB9cYSsDXTALBn6KtWRJAzNlCL/")
  95. def test_htpasswd_sha512(self) -> None:
  96. self._test_htpasswd("sha512", "tmp:$6$3Qhl8r6FLagYdHYa$UCH9yXCed4A.J9FQsFPYAOXImzZUMfvLa0lwcWOxWYLOF5sE/lF99auQ4jKvHY2vijxmefl7G6kMqZ8JPdhIJ/")
  97. def test_htpasswd_sha512_autodetect(self) -> None:
  98. self._test_htpasswd("autodetect", "tmp:$6$3Qhl8r6FLagYdHYa$UCH9yXCed4A.J9FQsFPYAOXImzZUMfvLa0lwcWOxWYLOF5sE/lF99auQ4jKvHY2vijxmefl7G6kMqZ8JPdhIJ/")
  99. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  100. def test_htpasswd_bcrypt_2a(self) -> None:
  101. self._test_htpasswd("bcrypt", "tmp:$2a$10$Mj4A9vMecAp/K7.0fMKoVOk1SjgR.RBhl06a52nvzXhxlT3HB7Reu")
  102. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  103. def test_htpasswd_bcrypt_2a_autodetect(self) -> None:
  104. self._test_htpasswd("autodetect", "tmp:$2a$10$Mj4A9vMecAp/K7.0fMKoVOk1SjgR.RBhl06a52nvzXhxlT3HB7Reu")
  105. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  106. def test_htpasswd_bcrypt_2b(self) -> None:
  107. self._test_htpasswd("bcrypt", "tmp:$2b$12$7a4z/fdmXlBIfkz0smvzW.1Nds8wpgC/bo2DVOb4OSQKWCDL1A1wu")
  108. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  109. def test_htpasswd_bcrypt_2b_autodetect(self) -> None:
  110. self._test_htpasswd("autodetect", "tmp:$2b$12$7a4z/fdmXlBIfkz0smvzW.1Nds8wpgC/bo2DVOb4OSQKWCDL1A1wu")
  111. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  112. def test_htpasswd_bcrypt_2y(self) -> None:
  113. self._test_htpasswd("bcrypt", "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3VNTRI3w5KDnj8NTUKJNWfVpvRq")
  114. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  115. def test_htpasswd_bcrypt_2y_autodetect(self) -> None:
  116. self._test_htpasswd("autodetect", "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3VNTRI3w5KDnj8NTUKJNWfVpvRq")
  117. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  118. def test_htpasswd_bcrypt_C10(self) -> None:
  119. self._test_htpasswd("bcrypt", "tmp:$2y$10$bZsWq06ECzxqi7RmulQvC.T1YHUnLW2E3jn.MU2pvVTGn1dfORt2a")
  120. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  121. def test_htpasswd_bcrypt_C10_autodetect(self) -> None:
  122. self._test_htpasswd("bcrypt", "tmp:$2y$10$bZsWq06ECzxqi7RmulQvC.T1YHUnLW2E3jn.MU2pvVTGn1dfORt2a")
  123. @pytest.mark.skipif(has_bcrypt == 0, reason="No bcrypt module installed")
  124. def test_htpasswd_bcrypt_unicode(self) -> None:
  125. self._test_htpasswd("bcrypt", "😀:$2y$10$Oyz5aHV4MD9eQJbk6GPemOs4T6edK6U9Sqlzr.W1mMVCS8wJUftnW", "unicode")
  126. @pytest.mark.skipif(has_argon2 == 0, reason="No argon2 module installed")
  127. def test_htpasswd_argon2_i(self) -> None:
  128. self._test_htpasswd("argon2", "tmp:$argon2i$v=19$m=65536,t=3,p=4$NgZg7F1rzRkDoNSaMwag9A$qmsvMKEn5zOXHm8e3O5fKzzcRo0UESwaDr/cETe5YPI")
  129. @pytest.mark.skipif(has_argon2 == 0, reason="No argon2 module installed")
  130. def test_htpasswd_argon2_d(self) -> None:
  131. self._test_htpasswd("argon2", "tmp:$argon2d$v=19$m=65536,t=3,p=4$ufe+txYiJKR0zlkLwVirVQ$MjGqRyVLes38hA6CEOkloMcTYCuLjxCKgIjtfYZ3iSM")
  132. @pytest.mark.skipif(has_argon2 == 0, reason="No argon2 module installed")
  133. def test_htpasswd_argon2_id(self) -> None:
  134. self._test_htpasswd("argon2", "tmp:$argon2id$v=19$m=65536,t=3,p=4$t7bWuneOkdIa45xTqjXGmA$ORnRJyz9kHogJs6bDgZrTBPlzi4+p023PSEABb3xX1g")
  135. def test_htpasswd_multi(self) -> None:
  136. self._test_htpasswd("plain", "ign:ign\ntmp:bepo")
  137. # login cache successful
  138. def test_htpasswd_login_cache_successful_plain(self, caplog) -> None:
  139. caplog.set_level(logging.INFO)
  140. self.configure({"auth": {"cache_logins": "True"}})
  141. self._test_htpasswd("plain", "tmp:bepo", (("tmp", "bepo", True), ("tmp", "bepo", True)))
  142. htpasswd_found = False
  143. htpasswd_cached_found = False
  144. for line in caplog.messages:
  145. if line == "Successful login: 'tmp' (htpasswd)":
  146. htpasswd_found = True
  147. elif line == "Successful login: 'tmp' (htpasswd / cached)":
  148. htpasswd_cached_found = True
  149. if (htpasswd_found is False) or (htpasswd_cached_found is False):
  150. raise ValueError("Logging misses expected log lines")
  151. # login cache failed
  152. def test_htpasswd_login_cache_failed_plain(self, caplog) -> None:
  153. caplog.set_level(logging.INFO)
  154. self.configure({"auth": {"cache_logins": "True"}})
  155. self._test_htpasswd("plain", "tmp:bepo", (("tmp", "bepo1", False), ("tmp", "bepo1", False)))
  156. htpasswd_found = False
  157. htpasswd_cached_found = False
  158. for line in caplog.messages:
  159. if line == "Failed login attempt from unknown: 'tmp' (htpasswd)":
  160. htpasswd_found = True
  161. elif line == "Failed login attempt from unknown: 'tmp' (htpasswd / cached)":
  162. htpasswd_cached_found = True
  163. if (htpasswd_found is False) or (htpasswd_cached_found is False):
  164. raise ValueError("Logging misses expected log lines")
  165. # htpasswd file cache
  166. def test_htpasswd_file_cache(self, caplog) -> None:
  167. self.configure({"auth": {"htpasswd_cache": "True"}})
  168. self._test_htpasswd("plain", "tmp:bepo")
  169. # detection of broken htpasswd file entries
  170. def test_htpasswd_broken(self) -> None:
  171. for userpass in ["tmp:", ":tmp"]:
  172. try:
  173. self._test_htpasswd("plain", userpass)
  174. except RuntimeError:
  175. pass
  176. else:
  177. raise
  178. @pytest.mark.skipif(sys.platform == "win32", reason="leading and trailing "
  179. "whitespaces not allowed in file names")
  180. def test_htpasswd_whitespace_user(self) -> None:
  181. for user in (" tmp", "tmp ", " tmp "):
  182. self._test_htpasswd("plain", "%s:bepo" % user, (
  183. (user, "bepo", True), ("tmp", "bepo", False)))
  184. def test_htpasswd_whitespace_password(self) -> None:
  185. for password in (" bepo", "bepo ", " bepo "):
  186. self._test_htpasswd("plain", "tmp:%s" % password, (
  187. ("tmp", password, True), ("tmp", "bepo", False)))
  188. def test_htpasswd_comment(self) -> None:
  189. self._test_htpasswd("plain", "#comment\n #comment\n \ntmp:bepo\n\n")
  190. def test_htpasswd_lc_username(self) -> None:
  191. self.configure({"auth": {"lc_username": "True"}})
  192. self._test_htpasswd("plain", "tmp:bepo", (
  193. ("tmp", "bepo", True), ("TMP", "bepo", True), ("tmp1", "bepo", False)))
  194. def test_htpasswd_uc_username(self) -> None:
  195. self.configure({"auth": {"uc_username": "True"}})
  196. self._test_htpasswd("plain", "TMP:bepo", (
  197. ("tmp", "bepo", True), ("TMP", "bepo", True), ("TMP1", "bepo", False)))
  198. def test_htpasswd_strip_domain(self) -> None:
  199. self.configure({"auth": {"strip_domain": "True"}})
  200. self._test_htpasswd("plain", "tmp:bepo", (
  201. ("tmp", "bepo", True), ("tmp@domain.example", "bepo", True), ("tmp1", "bepo", False)))
  202. def test_remote_user(self) -> None:
  203. self.configure({"auth": {"type": "remote_user"}})
  204. _, responses = self.propfind("/", """\
  205. <?xml version="1.0" encoding="utf-8"?>
  206. <propfind xmlns="DAV:">
  207. <prop>
  208. <current-user-principal />
  209. </prop>
  210. </propfind>""", REMOTE_USER="test")
  211. assert responses is not None
  212. response = responses["/"]
  213. assert not isinstance(response, int)
  214. status, prop = response["D:current-user-principal"]
  215. assert status == 200
  216. href_element = prop.find(xmlutils.make_clark("D:href"))
  217. assert href_element is not None and href_element.text == "/test/"
  218. def test_http_x_remote_user(self) -> None:
  219. self.configure({"auth": {"type": "http_x_remote_user"}})
  220. _, responses = self.propfind("/", """\
  221. <?xml version="1.0" encoding="utf-8"?>
  222. <propfind xmlns="DAV:">
  223. <prop>
  224. <current-user-principal />
  225. </prop>
  226. </propfind>""", HTTP_X_REMOTE_USER="test")
  227. assert responses is not None
  228. response = responses["/"]
  229. assert not isinstance(response, int)
  230. status, prop = response["D:current-user-principal"]
  231. assert status == 200
  232. href_element = prop.find(xmlutils.make_clark("D:href"))
  233. assert href_element is not None and href_element.text == "/test/"
  234. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  235. def _test_dovecot(
  236. self, user, password, expected_status, expected_rip=None,
  237. response=b'FAIL\t1', mech=[b'PLAIN'], broken=None,
  238. extra_config=None, extra_env=None):
  239. import socket
  240. from unittest.mock import DEFAULT, patch
  241. if extra_env is None:
  242. extra_env = {}
  243. if extra_config is None:
  244. extra_config = {}
  245. config = {"auth": {"type": "dovecot",
  246. "dovecot_socket": "./dovecot.sock"}}
  247. for toplvl, entries in extra_config.items():
  248. for key, val in entries.items():
  249. config[toplvl][key] = val
  250. self.configure(config)
  251. if broken is None:
  252. broken = []
  253. handshake = b''
  254. if "version" not in broken:
  255. handshake += b'VERSION\t'
  256. if "incompatible" in broken:
  257. handshake += b'2'
  258. else:
  259. handshake += b'1'
  260. handshake += b'\t2\n'
  261. if "mech" not in broken:
  262. handshake += b'MECH\t%b\n' % b' '.join(mech)
  263. if "duplicate" in broken:
  264. handshake += b'VERSION\t1\t2\n'
  265. if "done" not in broken:
  266. handshake += b'DONE\n'
  267. sent_rip = None
  268. def record_sent_data(s, data, flags=None):
  269. nonlocal sent_rip
  270. if b'\trip=' in data:
  271. sent_rip = data.split(b'\trip=')[1].split(b'\t')[0]
  272. return len(data)
  273. with patch.multiple(
  274. 'socket.socket',
  275. connect=DEFAULT,
  276. send=record_sent_data,
  277. recv=DEFAULT
  278. ) as mock_socket:
  279. if "socket" in broken:
  280. mock_socket["connect"].side_effect = socket.error(
  281. "Testing error with the socket"
  282. )
  283. mock_socket["recv"].side_effect = [handshake, response]
  284. status, _, answer = self.request(
  285. "PROPFIND", "/",
  286. HTTP_AUTHORIZATION="Basic %s" % base64.b64encode(
  287. ("%s:%s" % (user, password)).encode()).decode(),
  288. **extra_env)
  289. assert sent_rip == expected_rip
  290. assert status == expected_status
  291. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  292. def test_dovecot_no_user(self):
  293. self._test_dovecot("", "", 401)
  294. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  295. def test_dovecot_no_password(self):
  296. self._test_dovecot("user", "", 401)
  297. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  298. def test_dovecot_broken_handshake_no_version(self):
  299. self._test_dovecot("user", "password", 401, broken=["version"])
  300. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  301. def test_dovecot_broken_handshake_incompatible(self):
  302. self._test_dovecot("user", "password", 401, broken=["incompatible"])
  303. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  304. def test_dovecot_broken_handshake_duplicate(self):
  305. self._test_dovecot(
  306. "user", "password", 207, response=b'OK\t1',
  307. broken=["duplicate"]
  308. )
  309. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  310. def test_dovecot_broken_handshake_no_mech(self):
  311. self._test_dovecot("user", "password", 401, broken=["mech"])
  312. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  313. def test_dovecot_broken_handshake_unsupported_mech(self):
  314. self._test_dovecot("user", "password", 401, mech=[b'ONE', b'TWO'])
  315. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  316. def test_dovecot_broken_handshake_no_done(self):
  317. self._test_dovecot("user", "password", 401, broken=["done"])
  318. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  319. def test_dovecot_broken_socket(self):
  320. self._test_dovecot("user", "password", 401, broken=["socket"])
  321. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  322. def test_dovecot_auth_good1(self):
  323. self._test_dovecot("user", "password", 207, response=b'OK\t1')
  324. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  325. def test_dovecot_auth_good2(self):
  326. self._test_dovecot(
  327. "user", "password", 207, response=b'OK\t1',
  328. mech=[b'PLAIN\nEXTRA\tTERM']
  329. )
  330. self._test_dovecot("user", "password", 207, response=b'OK\t1')
  331. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  332. def test_dovecot_auth_bad1(self):
  333. self._test_dovecot("user", "password", 401, response=b'FAIL\t1')
  334. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  335. def test_dovecot_auth_bad2(self):
  336. self._test_dovecot("user", "password", 401, response=b'CONT\t1')
  337. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  338. def test_dovecot_auth_id_mismatch(self):
  339. self._test_dovecot("user", "password", 401, response=b'OK\t2')
  340. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  341. def test_dovecot_remote_addr(self):
  342. self._test_dovecot("user", "password", 401, expected_rip=b'172.17.16.15',
  343. extra_env={
  344. 'REMOTE_ADDR': '172.17.16.15',
  345. 'HTTP_X_REMOTE_ADDR': '127.0.0.1',
  346. })
  347. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  348. def test_dovecot_x_remote_addr(self):
  349. self._test_dovecot("user", "password", 401, expected_rip=b'172.17.16.15',
  350. extra_env={
  351. 'REMOTE_ADDR': '127.0.0.1',
  352. 'HTTP_X_REMOTE_ADDR': '172.17.16.15',
  353. },
  354. extra_config={
  355. 'auth': {"remote_ip_source": "X-Remote-Addr"},
  356. })
  357. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  358. def test_dovecot_x_remote_addr_whitespace(self):
  359. self._test_dovecot("user", "password", 401, expected_rip=b'172.17.16.15rip=127.0.0.1',
  360. extra_env={
  361. 'REMOTE_ADDR': '127.0.0.1',
  362. 'HTTP_X_REMOTE_ADDR': '172.17.16.15\trip=127.0.0.1',
  363. },
  364. extra_config={
  365. 'auth': {"remote_ip_source": "X-Remote-Addr"},
  366. })
  367. def test_custom(self) -> None:
  368. """Custom authentication."""
  369. self.configure({"auth": {"type": "radicale.tests.custom.auth"}})
  370. self.propfind("/tmp/", login="tmp:")
  371. def test_none(self) -> None:
  372. self.configure({"auth": {"type": "none"}})
  373. self.propfind("/tmp/", login="tmp:")
  374. def test_denyall(self) -> None:
  375. self.configure({"auth": {"type": "denyall"}})
  376. self.propfind("/tmp/", login="tmp:", check=401)