test_auth.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2012-2016 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2019 Unrud <unrud@outlook.com>
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. Radicale tests with simple requests and authentication.
  20. """
  21. import os
  22. import sys
  23. from typing import Iterable, Tuple, Union
  24. import pytest
  25. from radicale import Application, xmlutils
  26. from radicale.tests import BaseTest
  27. class TestBaseAuthRequests(BaseTest):
  28. """Tests basic requests with auth.
  29. We should setup auth for each type before creating the Application object.
  30. """
  31. def _test_htpasswd(self, htpasswd_encryption: str, htpasswd_content: str,
  32. test_matrix: Union[str, Iterable[Tuple[str, str, bool]]]
  33. = "ascii") -> None:
  34. """Test htpasswd authentication with user "tmp" and password "bepo" for
  35. ``test_matrix`` "ascii" or user "😀" and password "🔑" for
  36. ``test_matrix`` "unicode"."""
  37. if htpasswd_encryption == "bcrypt":
  38. try:
  39. from passlib.exc import MissingBackendError
  40. from passlib.hash import bcrypt
  41. except ImportError:
  42. pytest.skip("passlib[bcrypt] is not installed")
  43. try:
  44. bcrypt.hash("test-bcrypt-backend")
  45. except MissingBackendError:
  46. pytest.skip("bcrypt backend for passlib is not installed")
  47. htpasswd_file_path = os.path.join(self.colpath, ".htpasswd")
  48. encoding: str = self.configuration.get("encoding", "stock")
  49. with open(htpasswd_file_path, "w", encoding=encoding) as f:
  50. f.write(htpasswd_content)
  51. self.configuration.update({
  52. "auth": {"type": "htpasswd",
  53. "htpasswd_filename": htpasswd_file_path,
  54. "htpasswd_encryption": htpasswd_encryption}}, "test")
  55. self.application = Application(self.configuration)
  56. if test_matrix == "ascii":
  57. test_matrix = (("tmp", "bepo", True), ("tmp", "tmp", False),
  58. ("tmp", "", False), ("unk", "unk", False),
  59. ("unk", "", False), ("", "", False))
  60. elif test_matrix == "unicode":
  61. test_matrix = (("😀", "🔑", True), ("😀", "🌹", False),
  62. ("😁", "🔑", False), ("😀", "", False),
  63. ("", "🔑", False), ("", "", False))
  64. elif isinstance(test_matrix, str):
  65. raise ValueError("Unknown test matrix %r" % test_matrix)
  66. for user, password, valid in test_matrix:
  67. self.propfind("/", check=207 if valid else 401,
  68. login="%s:%s" % (user, password))
  69. def test_htpasswd_plain(self) -> None:
  70. self._test_htpasswd("plain", "tmp:bepo")
  71. def test_htpasswd_plain_password_split(self) -> None:
  72. self._test_htpasswd("plain", "tmp:be:po", (
  73. ("tmp", "be:po", True), ("tmp", "bepo", False)))
  74. def test_htpasswd_plain_unicode(self) -> None:
  75. self._test_htpasswd("plain", "😀:🔑", "unicode")
  76. def test_htpasswd_md5(self) -> None:
  77. self._test_htpasswd("md5", "tmp:$apr1$BI7VKCZh$GKW4vq2hqDINMr8uv7lDY/")
  78. def test_htpasswd_md5_unicode(self):
  79. self._test_htpasswd(
  80. "md5", "😀:$apr1$w4ev89r1$29xO8EvJmS2HEAadQ5qy11", "unicode")
  81. def test_htpasswd_bcrypt(self) -> None:
  82. self._test_htpasswd("bcrypt", "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3V"
  83. "NTRI3w5KDnj8NTUKJNWfVpvRq")
  84. def test_htpasswd_bcrypt_unicode(self) -> None:
  85. self._test_htpasswd("bcrypt", "😀:$2y$10$Oyz5aHV4MD9eQJbk6GPemOs4T6edK"
  86. "6U9Sqlzr.W1mMVCS8wJUftnW", "unicode")
  87. def test_htpasswd_multi(self) -> None:
  88. self._test_htpasswd("plain", "ign:ign\ntmp:bepo")
  89. @pytest.mark.skipif(sys.platform == "win32", reason="leading and trailing "
  90. "whitespaces not allowed in file names")
  91. def test_htpasswd_whitespace_user(self) -> None:
  92. for user in (" tmp", "tmp ", " tmp "):
  93. self._test_htpasswd("plain", "%s:bepo" % user, (
  94. (user, "bepo", True), ("tmp", "bepo", False)))
  95. def test_htpasswd_whitespace_password(self) -> None:
  96. for password in (" bepo", "bepo ", " bepo "):
  97. self._test_htpasswd("plain", "tmp:%s" % password, (
  98. ("tmp", password, True), ("tmp", "bepo", False)))
  99. def test_htpasswd_comment(self) -> None:
  100. self._test_htpasswd("plain", "#comment\n #comment\n \ntmp:bepo\n\n")
  101. def test_remote_user(self) -> None:
  102. self.configuration.update({"auth": {"type": "remote_user"}}, "test")
  103. self.application = Application(self.configuration)
  104. _, responses = self.propfind("/", """\
  105. <?xml version="1.0" encoding="utf-8"?>
  106. <propfind xmlns="DAV:">
  107. <prop>
  108. <current-user-principal />
  109. </prop>
  110. </propfind>""", REMOTE_USER="test")
  111. assert responses is not None
  112. response = responses["/"]
  113. assert not isinstance(response, int)
  114. status, prop = response["D:current-user-principal"]
  115. assert status == 200
  116. href_element = prop.find(xmlutils.make_clark("D:href"))
  117. assert href_element is not None and href_element.text == "/test/"
  118. def test_http_x_remote_user(self) -> None:
  119. self.configuration.update(
  120. {"auth": {"type": "http_x_remote_user"}}, "test")
  121. self.application = Application(self.configuration)
  122. _, responses = self.propfind("/", """\
  123. <?xml version="1.0" encoding="utf-8"?>
  124. <propfind xmlns="DAV:">
  125. <prop>
  126. <current-user-principal />
  127. </prop>
  128. </propfind>""", HTTP_X_REMOTE_USER="test")
  129. assert responses is not None
  130. response = responses["/"]
  131. assert not isinstance(response, int)
  132. status, prop = response["D:current-user-principal"]
  133. assert status == 200
  134. href_element = prop.find(xmlutils.make_clark("D:href"))
  135. assert href_element is not None and href_element.text == "/test/"
  136. def test_custom(self) -> None:
  137. """Custom authentication."""
  138. self.configuration.update(
  139. {"auth": {"type": "radicale.tests.custom.auth"}}, "test")
  140. self.application = Application(self.configuration)
  141. self.propfind("/tmp/", login="tmp:")