base.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2020 Unrud <unrud@outlook.com>
  3. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  4. #
  5. # This library is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  17. import io
  18. import logging
  19. import posixpath
  20. import sys
  21. import xml.etree.ElementTree as ET
  22. from typing import Optional
  23. from radicale import (auth, config, hook, httputils, pathutils, rights,
  24. storage, types, web, xmlutils)
  25. from radicale.log import logger
  26. # HACK: https://github.com/tiran/defusedxml/issues/54
  27. import defusedxml.ElementTree as DefusedET # isort:skip
  28. sys.modules["xml.etree"].ElementTree = ET # type:ignore[attr-defined]
  29. class ApplicationBase:
  30. configuration: config.Configuration
  31. _auth: auth.BaseAuth
  32. _storage: storage.BaseStorage
  33. _rights: rights.BaseRights
  34. _web: web.BaseWeb
  35. _encoding: str
  36. _permit_delete_collection: bool
  37. _hook: hook.BaseHook
  38. def __init__(self, configuration: config.Configuration) -> None:
  39. self.configuration = configuration
  40. self._auth = auth.load(configuration)
  41. self._storage = storage.load(configuration)
  42. self._rights = rights.load(configuration)
  43. self._web = web.load(configuration)
  44. self._encoding = configuration.get("encoding", "request")
  45. self._log_bad_put_request_content = configuration.get("logging", "bad_put_request_content")
  46. self._hook = hook.load(configuration)
  47. def _read_xml_request_body(self, environ: types.WSGIEnviron
  48. ) -> Optional[ET.Element]:
  49. content = httputils.decode_request(
  50. self.configuration, environ,
  51. httputils.read_raw_request_body(self.configuration, environ))
  52. if not content:
  53. return None
  54. try:
  55. xml_content = DefusedET.fromstring(content)
  56. except ET.ParseError as e:
  57. logger.debug("Request content (Invalid XML):\n%s", content)
  58. raise RuntimeError("Failed to parse XML: %s" % e) from e
  59. if logger.isEnabledFor(logging.DEBUG):
  60. logger.debug("Request content:\n%s",
  61. xmlutils.pretty_xml(xml_content))
  62. return xml_content
  63. def _xml_response(self, xml_content: ET.Element) -> bytes:
  64. if logger.isEnabledFor(logging.DEBUG):
  65. logger.debug("Response content:\n%s",
  66. xmlutils.pretty_xml(xml_content))
  67. f = io.BytesIO()
  68. ET.ElementTree(xml_content).write(f, encoding=self._encoding,
  69. xml_declaration=True)
  70. return f.getvalue()
  71. def _webdav_error_response(self, status: int, human_tag: str
  72. ) -> types.WSGIResponse:
  73. """Generate XML error response."""
  74. headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
  75. content = self._xml_response(xmlutils.webdav_error(human_tag))
  76. return status, headers, content
  77. class Access:
  78. """Helper class to check access rights of an item"""
  79. user: str
  80. path: str
  81. parent_path: str
  82. permissions: str
  83. _rights: rights.BaseRights
  84. _parent_permissions: Optional[str]
  85. def __init__(self, rights: rights.BaseRights, user: str, path: str
  86. ) -> None:
  87. self._rights = rights
  88. self.user = user
  89. self.path = path
  90. self.parent_path = pathutils.unstrip_path(
  91. posixpath.dirname(pathutils.strip_path(path)), True)
  92. self.permissions = self._rights.authorization(self.user, self.path)
  93. self._parent_permissions = None
  94. @property
  95. def parent_permissions(self) -> str:
  96. if self.path == self.parent_path:
  97. return self.permissions
  98. if self._parent_permissions is None:
  99. self._parent_permissions = self._rights.authorization(
  100. self.user, self.parent_path)
  101. return self._parent_permissions
  102. def check(self, permission: str,
  103. item: Optional[types.CollectionOrItem] = None) -> bool:
  104. if permission not in "rw":
  105. raise ValueError("Invalid permission argument: %r" % permission)
  106. if not item:
  107. permissions = permission + permission.upper()
  108. parent_permissions = permission
  109. elif isinstance(item, storage.BaseCollection):
  110. if item.tag:
  111. permissions = permission
  112. else:
  113. permissions = permission.upper()
  114. parent_permissions = ""
  115. else:
  116. permissions = ""
  117. parent_permissions = permission
  118. return bool(rights.intersect(self.permissions, permissions) or (
  119. self.path != self.parent_path and
  120. rights.intersect(self.parent_permissions, parent_permissions)))