base.py 5.0 KB

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