test_auth.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. def _test_htpasswd(self, htpasswd_encryption: str, htpasswd_content: str,
  35. test_matrix: Union[str, Iterable[Tuple[str, str, bool]]]
  36. = "ascii") -> None:
  37. """Test htpasswd authentication with user "tmp" and password "bepo" for
  38. ``test_matrix`` "ascii" or user "😀" and password "🔑" for
  39. ``test_matrix`` "unicode"."""
  40. htpasswd_file_path = os.path.join(self.colpath, ".htpasswd")
  41. encoding: str = self.configuration.get("encoding", "stock")
  42. with open(htpasswd_file_path, "w", encoding=encoding) as f:
  43. f.write(htpasswd_content)
  44. self.configure({"auth": {"type": "htpasswd",
  45. "htpasswd_filename": htpasswd_file_path,
  46. "htpasswd_encryption": htpasswd_encryption}})
  47. if test_matrix == "ascii":
  48. test_matrix = (("tmp", "bepo", True), ("tmp", "tmp", False),
  49. ("tmp", "", False), ("unk", "unk", False),
  50. ("unk", "", False), ("", "", False))
  51. elif test_matrix == "unicode":
  52. test_matrix = (("😀", "🔑", True), ("😀", "🌹", False),
  53. ("😁", "🔑", False), ("😀", "", False),
  54. ("", "🔑", False), ("", "", False))
  55. elif isinstance(test_matrix, str):
  56. raise ValueError("Unknown test matrix %r" % test_matrix)
  57. for user, password, valid in test_matrix:
  58. self.propfind("/", check=207 if valid else 401,
  59. login="%s:%s" % (user, password))
  60. def test_htpasswd_plain(self) -> None:
  61. self._test_htpasswd("plain", "tmp:bepo")
  62. def test_htpasswd_plain_password_split(self) -> None:
  63. self._test_htpasswd("plain", "tmp:be:po", (
  64. ("tmp", "be:po", True), ("tmp", "bepo", False)))
  65. def test_htpasswd_plain_unicode(self) -> None:
  66. self._test_htpasswd("plain", "😀:🔑", "unicode")
  67. def test_htpasswd_md5(self) -> None:
  68. self._test_htpasswd("md5", "tmp:$apr1$BI7VKCZh$GKW4vq2hqDINMr8uv7lDY/")
  69. def test_htpasswd_md5_unicode(self):
  70. self._test_htpasswd(
  71. "md5", "😀:$apr1$w4ev89r1$29xO8EvJmS2HEAadQ5qy11", "unicode")
  72. def test_htpasswd_sha256(self) -> None:
  73. self._test_htpasswd("sha256", "tmp:$5$i4Ni4TQq6L5FKss5$ilpTjkmnxkwZeV35GB9cYSsDXTALBn6KtWRJAzNlCL/")
  74. def test_htpasswd_sha512(self) -> None:
  75. self._test_htpasswd("sha512", "tmp:$6$3Qhl8r6FLagYdHYa$UCH9yXCed4A.J9FQsFPYAOXImzZUMfvLa0lwcWOxWYLOF5sE/lF99auQ4jKvHY2vijxmefl7G6kMqZ8JPdhIJ/")
  76. def test_htpasswd_bcrypt(self) -> None:
  77. self._test_htpasswd("bcrypt", "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3V"
  78. "NTRI3w5KDnj8NTUKJNWfVpvRq")
  79. def test_htpasswd_bcrypt_unicode(self) -> None:
  80. self._test_htpasswd("bcrypt", "😀:$2y$10$Oyz5aHV4MD9eQJbk6GPemOs4T6edK"
  81. "6U9Sqlzr.W1mMVCS8wJUftnW", "unicode")
  82. def test_htpasswd_multi(self) -> None:
  83. self._test_htpasswd("plain", "ign:ign\ntmp:bepo")
  84. # login cache successful
  85. def test_htpasswd_login_cache_successful_plain(self, caplog) -> None:
  86. caplog.set_level(logging.INFO)
  87. self.configure({"auth": {"cache_logins": "True"}})
  88. self._test_htpasswd("plain", "tmp:bepo", (("tmp", "bepo", True), ("tmp", "bepo", True)))
  89. htpasswd_found = False
  90. htpasswd_cached_found = False
  91. for line in caplog.messages:
  92. if line == "Successful login: 'tmp' (htpasswd)":
  93. htpasswd_found = True
  94. elif line == "Successful login: 'tmp' (htpasswd / cached)":
  95. htpasswd_cached_found = True
  96. if (htpasswd_found is False) or (htpasswd_cached_found is False):
  97. raise ValueError("Logging misses expected log lines")
  98. # login cache failed
  99. def test_htpasswd_login_cache_failed_plain(self, caplog) -> None:
  100. caplog.set_level(logging.INFO)
  101. self.configure({"auth": {"cache_logins": "True"}})
  102. self._test_htpasswd("plain", "tmp:bepo", (("tmp", "bepo1", False), ("tmp", "bepo1", False)))
  103. htpasswd_found = False
  104. htpasswd_cached_found = False
  105. for line in caplog.messages:
  106. if line == "Failed login attempt from unknown: 'tmp' (htpasswd)":
  107. htpasswd_found = True
  108. elif line == "Failed login attempt from unknown: 'tmp' (htpasswd / cached)":
  109. htpasswd_cached_found = True
  110. if (htpasswd_found is False) or (htpasswd_cached_found is False):
  111. raise ValueError("Logging misses expected log lines")
  112. # htpasswd file cache
  113. def test_htpasswd_file_cache(self, caplog) -> None:
  114. self.configure({"auth": {"htpasswd_cache": "True"}})
  115. self._test_htpasswd("plain", "tmp:bepo")
  116. # detection of broken htpasswd file entries
  117. def test_htpasswd_broken(self) -> None:
  118. for userpass in ["tmp:", ":tmp"]:
  119. try:
  120. self._test_htpasswd("plain", userpass)
  121. except RuntimeError:
  122. pass
  123. else:
  124. raise
  125. @pytest.mark.skipif(sys.platform == "win32", reason="leading and trailing "
  126. "whitespaces not allowed in file names")
  127. def test_htpasswd_whitespace_user(self) -> None:
  128. for user in (" tmp", "tmp ", " tmp "):
  129. self._test_htpasswd("plain", "%s:bepo" % user, (
  130. (user, "bepo", True), ("tmp", "bepo", False)))
  131. def test_htpasswd_whitespace_password(self) -> None:
  132. for password in (" bepo", "bepo ", " bepo "):
  133. self._test_htpasswd("plain", "tmp:%s" % password, (
  134. ("tmp", password, True), ("tmp", "bepo", False)))
  135. def test_htpasswd_comment(self) -> None:
  136. self._test_htpasswd("plain", "#comment\n #comment\n \ntmp:bepo\n\n")
  137. def test_htpasswd_lc_username(self) -> None:
  138. self.configure({"auth": {"lc_username": "True"}})
  139. self._test_htpasswd("plain", "tmp:bepo", (
  140. ("tmp", "bepo", True), ("TMP", "bepo", True), ("tmp1", "bepo", False)))
  141. def test_htpasswd_uc_username(self) -> None:
  142. self.configure({"auth": {"uc_username": "True"}})
  143. self._test_htpasswd("plain", "TMP:bepo", (
  144. ("tmp", "bepo", True), ("TMP", "bepo", True), ("TMP1", "bepo", False)))
  145. def test_htpasswd_strip_domain(self) -> None:
  146. self.configure({"auth": {"strip_domain": "True"}})
  147. self._test_htpasswd("plain", "tmp:bepo", (
  148. ("tmp", "bepo", True), ("tmp@domain.example", "bepo", True), ("tmp1", "bepo", False)))
  149. def test_remote_user(self) -> None:
  150. self.configure({"auth": {"type": "remote_user"}})
  151. _, responses = self.propfind("/", """\
  152. <?xml version="1.0" encoding="utf-8"?>
  153. <propfind xmlns="DAV:">
  154. <prop>
  155. <current-user-principal />
  156. </prop>
  157. </propfind>""", REMOTE_USER="test")
  158. assert responses is not None
  159. response = responses["/"]
  160. assert not isinstance(response, int)
  161. status, prop = response["D:current-user-principal"]
  162. assert status == 200
  163. href_element = prop.find(xmlutils.make_clark("D:href"))
  164. assert href_element is not None and href_element.text == "/test/"
  165. def test_http_x_remote_user(self) -> None:
  166. self.configure({"auth": {"type": "http_x_remote_user"}})
  167. _, responses = self.propfind("/", """\
  168. <?xml version="1.0" encoding="utf-8"?>
  169. <propfind xmlns="DAV:">
  170. <prop>
  171. <current-user-principal />
  172. </prop>
  173. </propfind>""", HTTP_X_REMOTE_USER="test")
  174. assert responses is not None
  175. response = responses["/"]
  176. assert not isinstance(response, int)
  177. status, prop = response["D:current-user-principal"]
  178. assert status == 200
  179. href_element = prop.find(xmlutils.make_clark("D:href"))
  180. assert href_element is not None and href_element.text == "/test/"
  181. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  182. def _test_dovecot(
  183. self, user, password, expected_status,
  184. response=b'FAIL\n1\n', mech=[b'PLAIN'], broken=None):
  185. import socket
  186. from unittest.mock import DEFAULT, patch
  187. self.configure({"auth": {"type": "dovecot",
  188. "dovecot_socket": "./dovecot.sock"}})
  189. if broken is None:
  190. broken = []
  191. handshake = b''
  192. if "version" not in broken:
  193. handshake += b'VERSION\t'
  194. if "incompatible" in broken:
  195. handshake += b'2'
  196. else:
  197. handshake += b'1'
  198. handshake += b'\t2\n'
  199. if "mech" not in broken:
  200. handshake += b'MECH\t%b\n' % b' '.join(mech)
  201. if "duplicate" in broken:
  202. handshake += b'VERSION\t1\t2\n'
  203. if "done" not in broken:
  204. handshake += b'DONE\n'
  205. with patch.multiple(
  206. 'socket.socket',
  207. connect=DEFAULT,
  208. send=DEFAULT,
  209. recv=DEFAULT
  210. ) as mock_socket:
  211. if "socket" in broken:
  212. mock_socket["connect"].side_effect = socket.error(
  213. "Testing error with the socket"
  214. )
  215. mock_socket["recv"].side_effect = [handshake, response]
  216. status, _, answer = self.request(
  217. "PROPFIND", "/",
  218. HTTP_AUTHORIZATION="Basic %s" % base64.b64encode(
  219. ("%s:%s" % (user, password)).encode()).decode())
  220. assert status == expected_status
  221. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  222. def test_dovecot_no_user(self):
  223. self._test_dovecot("", "", 401)
  224. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  225. def test_dovecot_no_password(self):
  226. self._test_dovecot("user", "", 401)
  227. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  228. def test_dovecot_broken_handshake_no_version(self):
  229. self._test_dovecot("user", "password", 401, broken=["version"])
  230. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  231. def test_dovecot_broken_handshake_incompatible(self):
  232. self._test_dovecot("user", "password", 401, broken=["incompatible"])
  233. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  234. def test_dovecot_broken_handshake_duplicate(self):
  235. self._test_dovecot(
  236. "user", "password", 207, response=b'OK\t1',
  237. broken=["duplicate"]
  238. )
  239. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  240. def test_dovecot_broken_handshake_no_mech(self):
  241. self._test_dovecot("user", "password", 401, broken=["mech"])
  242. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  243. def test_dovecot_broken_handshake_unsupported_mech(self):
  244. self._test_dovecot("user", "password", 401, mech=[b'ONE', b'TWO'])
  245. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  246. def test_dovecot_broken_handshake_no_done(self):
  247. self._test_dovecot("user", "password", 401, broken=["done"])
  248. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  249. def test_dovecot_broken_socket(self):
  250. self._test_dovecot("user", "password", 401, broken=["socket"])
  251. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  252. def test_dovecot_auth_good1(self):
  253. self._test_dovecot("user", "password", 207, response=b'OK\t1')
  254. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  255. def test_dovecot_auth_good2(self):
  256. self._test_dovecot(
  257. "user", "password", 207, response=b'OK\t1',
  258. mech=[b'PLAIN\nEXTRA\tTERM']
  259. )
  260. self._test_dovecot("user", "password", 207, response=b'OK\t1')
  261. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  262. def test_dovecot_auth_bad1(self):
  263. self._test_dovecot("user", "password", 401, response=b'FAIL\t1')
  264. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  265. def test_dovecot_auth_bad2(self):
  266. self._test_dovecot("user", "password", 401, response=b'CONT\t1')
  267. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  268. def test_dovecot_auth_id_mismatch(self):
  269. self._test_dovecot("user", "password", 401, response=b'OK\t2')
  270. def test_custom(self) -> None:
  271. """Custom authentication."""
  272. self.configure({"auth": {"type": "radicale.tests.custom.auth"}})
  273. self.propfind("/tmp/", login="tmp:")
  274. def test_none(self) -> None:
  275. self.configure({"auth": {"type": "none"}})
  276. self.propfind("/tmp/", login="tmp:")
  277. def test_denyall(self) -> None:
  278. self.configure({"auth": {"type": "denyall"}})
  279. self.propfind("/tmp/", login="tmp:", check=401)