test_auth.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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-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 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.configure({"auth": {"type": "htpasswd",
  52. "htpasswd_filename": htpasswd_file_path,
  53. "htpasswd_encryption": htpasswd_encryption}})
  54. if test_matrix == "ascii":
  55. test_matrix = (("tmp", "bepo", True), ("tmp", "tmp", False),
  56. ("tmp", "", False), ("unk", "unk", False),
  57. ("unk", "", False), ("", "", False))
  58. elif test_matrix == "unicode":
  59. test_matrix = (("😀", "🔑", True), ("😀", "🌹", False),
  60. ("😁", "🔑", False), ("😀", "", False),
  61. ("", "🔑", False), ("", "", False))
  62. elif isinstance(test_matrix, str):
  63. raise ValueError("Unknown test matrix %r" % test_matrix)
  64. for user, password, valid in test_matrix:
  65. self.propfind("/", check=207 if valid else 401,
  66. login="%s:%s" % (user, password))
  67. def test_htpasswd_plain(self) -> None:
  68. self._test_htpasswd("plain", "tmp:bepo")
  69. def test_htpasswd_plain_password_split(self) -> None:
  70. self._test_htpasswd("plain", "tmp:be:po", (
  71. ("tmp", "be:po", True), ("tmp", "bepo", False)))
  72. def test_htpasswd_plain_unicode(self) -> None:
  73. self._test_htpasswd("plain", "😀:🔑", "unicode")
  74. def test_htpasswd_md5(self) -> None:
  75. self._test_htpasswd("md5", "tmp:$apr1$BI7VKCZh$GKW4vq2hqDINMr8uv7lDY/")
  76. def test_htpasswd_md5_unicode(self):
  77. self._test_htpasswd(
  78. "md5", "😀:$apr1$w4ev89r1$29xO8EvJmS2HEAadQ5qy11", "unicode")
  79. def test_htpasswd_bcrypt(self) -> None:
  80. self._test_htpasswd("bcrypt", "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3V"
  81. "NTRI3w5KDnj8NTUKJNWfVpvRq")
  82. def test_htpasswd_bcrypt_unicode(self) -> None:
  83. self._test_htpasswd("bcrypt", "😀:$2y$10$Oyz5aHV4MD9eQJbk6GPemOs4T6edK"
  84. "6U9Sqlzr.W1mMVCS8wJUftnW", "unicode")
  85. def test_htpasswd_multi(self) -> None:
  86. self._test_htpasswd("plain", "ign:ign\ntmp:bepo")
  87. @pytest.mark.skipif(sys.platform == "win32", reason="leading and trailing "
  88. "whitespaces not allowed in file names")
  89. def test_htpasswd_whitespace_user(self) -> None:
  90. for user in (" tmp", "tmp ", " tmp "):
  91. self._test_htpasswd("plain", "%s:bepo" % user, (
  92. (user, "bepo", True), ("tmp", "bepo", False)))
  93. def test_htpasswd_whitespace_password(self) -> None:
  94. for password in (" bepo", "bepo ", " bepo "):
  95. self._test_htpasswd("plain", "tmp:%s" % password, (
  96. ("tmp", password, True), ("tmp", "bepo", False)))
  97. def test_htpasswd_comment(self) -> None:
  98. self._test_htpasswd("plain", "#comment\n #comment\n \ntmp:bepo\n\n")
  99. def test_remote_user(self) -> None:
  100. self.configure({"auth": {"type": "remote_user"}})
  101. _, responses = self.propfind("/", """\
  102. <?xml version="1.0" encoding="utf-8"?>
  103. <propfind xmlns="DAV:">
  104. <prop>
  105. <current-user-principal />
  106. </prop>
  107. </propfind>""", REMOTE_USER="test")
  108. assert responses is not None
  109. response = responses["/"]
  110. assert not isinstance(response, int)
  111. status, prop = response["D:current-user-principal"]
  112. assert status == 200
  113. href_element = prop.find(xmlutils.make_clark("D:href"))
  114. assert href_element is not None and href_element.text == "/test/"
  115. def test_http_x_remote_user(self) -> None:
  116. self.configure({"auth": {"type": "http_x_remote_user"}})
  117. _, responses = self.propfind("/", """\
  118. <?xml version="1.0" encoding="utf-8"?>
  119. <propfind xmlns="DAV:">
  120. <prop>
  121. <current-user-principal />
  122. </prop>
  123. </propfind>""", HTTP_X_REMOTE_USER="test")
  124. assert responses is not None
  125. response = responses["/"]
  126. assert not isinstance(response, int)
  127. status, prop = response["D:current-user-principal"]
  128. assert status == 200
  129. href_element = prop.find(xmlutils.make_clark("D:href"))
  130. assert href_element is not None and href_element.text == "/test/"
  131. def test_custom(self) -> None:
  132. """Custom authentication."""
  133. self.configure({"auth": {"type": "radicale.tests.custom.auth"}})
  134. self.propfind("/tmp/", login="tmp:")