test_auth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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-2024 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 os
  24. import sys
  25. from typing import Iterable, Tuple, Union
  26. import pytest
  27. from radicale import xmlutils
  28. from radicale.tests import BaseTest
  29. class TestBaseAuthRequests(BaseTest):
  30. """Tests basic requests with auth.
  31. We should setup auth for each type before creating the Application object.
  32. """
  33. def _test_htpasswd(self, htpasswd_encryption: str, htpasswd_content: str,
  34. test_matrix: Union[str, Iterable[Tuple[str, str, bool]]]
  35. = "ascii") -> None:
  36. """Test htpasswd authentication with user "tmp" and password "bepo" for
  37. ``test_matrix`` "ascii" or user "😀" and password "🔑" for
  38. ``test_matrix`` "unicode"."""
  39. htpasswd_file_path = os.path.join(self.colpath, ".htpasswd")
  40. encoding: str = self.configuration.get("encoding", "stock")
  41. with open(htpasswd_file_path, "w", encoding=encoding) as f:
  42. f.write(htpasswd_content)
  43. self.configure({"auth": {"type": "htpasswd",
  44. "htpasswd_filename": htpasswd_file_path,
  45. "htpasswd_encryption": htpasswd_encryption}})
  46. if test_matrix == "ascii":
  47. test_matrix = (("tmp", "bepo", True), ("tmp", "tmp", False),
  48. ("tmp", "", False), ("unk", "unk", False),
  49. ("unk", "", False), ("", "", False))
  50. elif test_matrix == "unicode":
  51. test_matrix = (("😀", "🔑", True), ("😀", "🌹", False),
  52. ("😁", "🔑", False), ("😀", "", False),
  53. ("", "🔑", False), ("", "", False))
  54. elif isinstance(test_matrix, str):
  55. raise ValueError("Unknown test matrix %r" % test_matrix)
  56. for user, password, valid in test_matrix:
  57. self.propfind("/", check=207 if valid else 401,
  58. login="%s:%s" % (user, password))
  59. def test_htpasswd_plain(self) -> None:
  60. self._test_htpasswd("plain", "tmp:bepo")
  61. def test_htpasswd_plain_password_split(self) -> None:
  62. self._test_htpasswd("plain", "tmp:be:po", (
  63. ("tmp", "be:po", True), ("tmp", "bepo", False)))
  64. def test_htpasswd_plain_unicode(self) -> None:
  65. self._test_htpasswd("plain", "😀:🔑", "unicode")
  66. def test_htpasswd_md5(self) -> None:
  67. self._test_htpasswd("md5", "tmp:$apr1$BI7VKCZh$GKW4vq2hqDINMr8uv7lDY/")
  68. def test_htpasswd_md5_unicode(self):
  69. self._test_htpasswd(
  70. "md5", "😀:$apr1$w4ev89r1$29xO8EvJmS2HEAadQ5qy11", "unicode")
  71. def test_htpasswd_sha256(self) -> None:
  72. self._test_htpasswd("sha256", "tmp:$5$i4Ni4TQq6L5FKss5$ilpTjkmnxkwZeV35GB9cYSsDXTALBn6KtWRJAzNlCL/")
  73. def test_htpasswd_sha512(self) -> None:
  74. self._test_htpasswd("sha512", "tmp:$6$3Qhl8r6FLagYdHYa$UCH9yXCed4A.J9FQsFPYAOXImzZUMfvLa0lwcWOxWYLOF5sE/lF99auQ4jKvHY2vijxmefl7G6kMqZ8JPdhIJ/")
  75. def test_htpasswd_bcrypt(self) -> None:
  76. self._test_htpasswd("bcrypt", "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3V"
  77. "NTRI3w5KDnj8NTUKJNWfVpvRq")
  78. def test_htpasswd_bcrypt_unicode(self) -> None:
  79. self._test_htpasswd("bcrypt", "😀:$2y$10$Oyz5aHV4MD9eQJbk6GPemOs4T6edK"
  80. "6U9Sqlzr.W1mMVCS8wJUftnW", "unicode")
  81. def test_htpasswd_multi(self) -> None:
  82. self._test_htpasswd("plain", "ign:ign\ntmp:bepo")
  83. @pytest.mark.skipif(sys.platform == "win32", reason="leading and trailing "
  84. "whitespaces not allowed in file names")
  85. def test_htpasswd_whitespace_user(self) -> None:
  86. for user in (" tmp", "tmp ", " tmp "):
  87. self._test_htpasswd("plain", "%s:bepo" % user, (
  88. (user, "bepo", True), ("tmp", "bepo", False)))
  89. def test_htpasswd_whitespace_password(self) -> None:
  90. for password in (" bepo", "bepo ", " bepo "):
  91. self._test_htpasswd("plain", "tmp:%s" % password, (
  92. ("tmp", password, True), ("tmp", "bepo", False)))
  93. def test_htpasswd_comment(self) -> None:
  94. self._test_htpasswd("plain", "#comment\n #comment\n \ntmp:bepo\n\n")
  95. def test_htpasswd_lc_username(self) -> None:
  96. self.configure({"auth": {"lc_username": "True"}})
  97. self._test_htpasswd("plain", "tmp:bepo", (
  98. ("tmp", "bepo", True), ("TMP", "bepo", True), ("tmp1", "bepo", False)))
  99. def test_htpasswd_strip_domain(self) -> None:
  100. self.configure({"auth": {"strip_domain": "True"}})
  101. self._test_htpasswd("plain", "tmp:bepo", (
  102. ("tmp", "bepo", True), ("tmp@domain.example", "bepo", True), ("tmp1", "bepo", False)))
  103. def test_remote_user(self) -> None:
  104. self.configure({"auth": {"type": "remote_user"}})
  105. _, responses = self.propfind("/", """\
  106. <?xml version="1.0" encoding="utf-8"?>
  107. <propfind xmlns="DAV:">
  108. <prop>
  109. <current-user-principal />
  110. </prop>
  111. </propfind>""", REMOTE_USER="test")
  112. assert responses is not None
  113. response = responses["/"]
  114. assert not isinstance(response, int)
  115. status, prop = response["D:current-user-principal"]
  116. assert status == 200
  117. href_element = prop.find(xmlutils.make_clark("D:href"))
  118. assert href_element is not None and href_element.text == "/test/"
  119. def test_http_x_remote_user(self) -> None:
  120. self.configure({"auth": {"type": "http_x_remote_user"}})
  121. _, responses = self.propfind("/", """\
  122. <?xml version="1.0" encoding="utf-8"?>
  123. <propfind xmlns="DAV:">
  124. <prop>
  125. <current-user-principal />
  126. </prop>
  127. </propfind>""", HTTP_X_REMOTE_USER="test")
  128. assert responses is not None
  129. response = responses["/"]
  130. assert not isinstance(response, int)
  131. status, prop = response["D:current-user-principal"]
  132. assert status == 200
  133. href_element = prop.find(xmlutils.make_clark("D:href"))
  134. assert href_element is not None and href_element.text == "/test/"
  135. @pytest.mark.skipif(sys.platform == 'win32', reason="Not supported on Windows")
  136. def _test_dovecot(
  137. self, user, password, expected_status,
  138. response=b'FAIL\n1\n', mech=[b'PLAIN'], broken=None):
  139. import socket
  140. from unittest.mock import DEFAULT, patch
  141. self.configure({"auth": {"type": "dovecot",
  142. "dovecot_socket": "./dovecot.sock"}})
  143. if broken is None:
  144. broken = []
  145. handshake = b''
  146. if "version" not in broken:
  147. handshake += b'VERSION\t'
  148. if "incompatible" in broken:
  149. handshake += b'2'
  150. else:
  151. handshake += b'1'
  152. handshake += b'\t2\n'
  153. if "mech" not in broken:
  154. handshake += b'MECH\t%b\n' % b' '.join(mech)
  155. if "duplicate" in broken:
  156. handshake += b'VERSION\t1\t2\n'
  157. if "done" not in broken:
  158. handshake += b'DONE\n'
  159. with patch.multiple(
  160. 'socket.socket',
  161. connect=DEFAULT,
  162. send=DEFAULT,
  163. recv=DEFAULT
  164. ) as mock_socket:
  165. if "socket" in broken:
  166. mock_socket["connect"].side_effect = socket.error(
  167. "Testing error with the socket"
  168. )
  169. mock_socket["recv"].side_effect = [handshake, response]
  170. status, _, answer = self.request(
  171. "PROPFIND", "/",
  172. HTTP_AUTHORIZATION="Basic %s" % base64.b64encode(
  173. ("%s:%s" % (user, password)).encode()).decode())
  174. assert status == expected_status
  175. def test_dovecot_no_user(self):
  176. self._test_dovecot("", "", 401)
  177. def test_dovecot_no_password(self):
  178. self._test_dovecot("user", "", 401)
  179. def test_dovecot_broken_handshake_no_version(self):
  180. self._test_dovecot("user", "password", 401, broken=["version"])
  181. def test_dovecot_broken_handshake_incompatible(self):
  182. self._test_dovecot("user", "password", 401, broken=["incompatible"])
  183. def test_dovecot_broken_handshake_duplicate(self):
  184. self._test_dovecot(
  185. "user", "password", 207, response=b'OK\t1',
  186. broken=["duplicate"]
  187. )
  188. def test_dovecot_broken_handshake_no_mech(self):
  189. self._test_dovecot("user", "password", 401, broken=["mech"])
  190. def test_dovecot_broken_handshake_unsupported_mech(self):
  191. self._test_dovecot("user", "password", 401, mech=[b'ONE', b'TWO'])
  192. def test_dovecot_broken_handshake_no_done(self):
  193. self._test_dovecot("user", "password", 401, broken=["done"])
  194. def test_dovecot_broken_socket(self):
  195. self._test_dovecot("user", "password", 401, broken=["socket"])
  196. def test_dovecot_auth_good1(self):
  197. self._test_dovecot("user", "password", 207, response=b'OK\t1')
  198. def test_dovecot_auth_good2(self):
  199. self._test_dovecot(
  200. "user", "password", 207, response=b'OK\t1',
  201. mech=[b'PLAIN\nEXTRA\tTERM']
  202. )
  203. self._test_dovecot("user", "password", 207, response=b'OK\t1')
  204. def test_dovecot_auth_bad1(self):
  205. self._test_dovecot("user", "password", 401, response=b'FAIL\t1')
  206. def test_dovecot_auth_bad2(self):
  207. self._test_dovecot("user", "password", 401, response=b'CONT\t1')
  208. def test_dovecot_auth_id_mismatch(self):
  209. self._test_dovecot("user", "password", 401, response=b'OK\t2')
  210. def test_custom(self) -> None:
  211. """Custom authentication."""
  212. self.configure({"auth": {"type": "radicale.tests.custom.auth"}})
  213. self.propfind("/tmp/", login="tmp:")
  214. def test_none(self) -> None:
  215. self.configure({"auth": {"type": "none"}})
  216. self.propfind("/tmp/", login="tmp:")
  217. def test_denyall(self) -> None:
  218. self.configure({"auth": {"type": "denyall"}})
  219. self.propfind("/tmp/", login="tmp:", check=401)