Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

192 wiersze
7.4 KiB

  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import Any, Dict, List
  17. from urllib import parse as urlparse
  18. import yaml
  19. from netaddr import IPSet
  20. from synapse.appservice import ApplicationService
  21. from synapse.types import JsonDict, UserID
  22. from ._base import Config, ConfigError
  23. logger = logging.getLogger(__name__)
  24. class AppServiceConfig(Config):
  25. section = "appservice"
  26. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  27. self.app_service_config_files = config.get("app_service_config_files", [])
  28. if not isinstance(self.app_service_config_files, list) or not all(
  29. isinstance(x, str) for x in self.app_service_config_files
  30. ):
  31. raise ConfigError(
  32. "Expected '%s' to be a list of AS config files:"
  33. % (self.app_service_config_files),
  34. ("app_service_config_files",),
  35. )
  36. self.track_appservice_user_ips = config.get("track_appservice_user_ips", False)
  37. self.use_appservice_legacy_authorization = config.get(
  38. "use_appservice_legacy_authorization", False
  39. )
  40. if self.use_appservice_legacy_authorization:
  41. logger.warning(
  42. "The use of appservice legacy authorization via query params is deprecated"
  43. " and should be considered insecure."
  44. )
  45. def load_appservices(
  46. hostname: str, config_files: List[str]
  47. ) -> List[ApplicationService]:
  48. """Returns a list of Application Services from the config files."""
  49. # Dicts of value -> filename
  50. seen_as_tokens: Dict[str, str] = {}
  51. seen_ids: Dict[str, str] = {}
  52. appservices = []
  53. for config_file in config_files:
  54. try:
  55. with open(config_file) as f:
  56. appservice = _load_appservice(hostname, yaml.safe_load(f), config_file)
  57. if appservice.id in seen_ids:
  58. raise ConfigError(
  59. "Cannot reuse ID across application services: "
  60. "%s (files: %s, %s)"
  61. % (appservice.id, config_file, seen_ids[appservice.id])
  62. )
  63. seen_ids[appservice.id] = config_file
  64. if appservice.token in seen_as_tokens:
  65. raise ConfigError(
  66. "Cannot reuse as_token across application services: "
  67. "%s (files: %s, %s)"
  68. % (
  69. appservice.token,
  70. config_file,
  71. seen_as_tokens[appservice.token],
  72. )
  73. )
  74. seen_as_tokens[appservice.token] = config_file
  75. logger.info("Loaded application service: %s", appservice)
  76. appservices.append(appservice)
  77. except Exception as e:
  78. logger.error("Failed to load appservice from '%s'", config_file)
  79. logger.exception(e)
  80. raise
  81. return appservices
  82. def _load_appservice(
  83. hostname: str, as_info: JsonDict, config_filename: str
  84. ) -> ApplicationService:
  85. required_string_fields = ["id", "as_token", "hs_token", "sender_localpart"]
  86. for field in required_string_fields:
  87. if not isinstance(as_info.get(field), str):
  88. raise KeyError(
  89. "Required string field: '%s' (%s)" % (field, config_filename)
  90. )
  91. # 'url' must either be a string or explicitly null, not missing
  92. # to avoid accidentally turning off push for ASes.
  93. if not isinstance(as_info.get("url"), str) and as_info.get("url", "") is not None:
  94. raise KeyError(
  95. "Required string field or explicit null: 'url' (%s)" % (config_filename,)
  96. )
  97. localpart = as_info["sender_localpart"]
  98. if urlparse.quote(localpart) != localpart:
  99. raise ValueError("sender_localpart needs characters which are not URL encoded.")
  100. user = UserID(localpart, hostname)
  101. user_id = user.to_string()
  102. # Rate limiting for users of this AS is on by default (excludes sender)
  103. rate_limited = as_info.get("rate_limited")
  104. if not isinstance(rate_limited, bool):
  105. rate_limited = True
  106. # namespace checks
  107. if not isinstance(as_info.get("namespaces"), dict):
  108. raise KeyError("Requires 'namespaces' object.")
  109. for ns in ApplicationService.NS_LIST:
  110. # specific namespaces are optional
  111. if ns in as_info["namespaces"]:
  112. # expect a list of dicts with exclusive and regex keys
  113. for regex_obj in as_info["namespaces"][ns]:
  114. if not isinstance(regex_obj, dict):
  115. raise ValueError(
  116. "Expected namespace entry in %s to be an object, but got %s",
  117. ns,
  118. regex_obj,
  119. )
  120. if not isinstance(regex_obj.get("regex"), str):
  121. raise ValueError("Missing/bad type 'regex' key in %s", regex_obj)
  122. if not isinstance(regex_obj.get("exclusive"), bool):
  123. raise ValueError(
  124. "Missing/bad type 'exclusive' key in %s", regex_obj
  125. )
  126. # protocols check
  127. protocols = as_info.get("protocols")
  128. if protocols:
  129. if not isinstance(protocols, list):
  130. raise KeyError("Optional 'protocols' must be a list if present.")
  131. for p in protocols:
  132. if not isinstance(p, str):
  133. raise KeyError("Bad value for 'protocols' item")
  134. if as_info["url"] is None:
  135. logger.info(
  136. "(%s) Explicitly empty 'url' provided. This application service"
  137. " will not receive events or queries.",
  138. config_filename,
  139. )
  140. ip_range_whitelist = None
  141. if as_info.get("ip_range_whitelist"):
  142. ip_range_whitelist = IPSet(as_info.get("ip_range_whitelist"))
  143. supports_ephemeral = as_info.get("de.sorunome.msc2409.push_ephemeral", False)
  144. # Opt-in flag for the MSC3202-specific transactional behaviour.
  145. # When enabled, appservice transactions contain the following information:
  146. # - device One-Time Key counts
  147. # - device unused fallback key usage states
  148. # - device list changes
  149. msc3202_transaction_extensions = as_info.get("org.matrix.msc3202", False)
  150. if not isinstance(msc3202_transaction_extensions, bool):
  151. raise ValueError(
  152. "The `org.matrix.msc3202` option should be true or false if specified."
  153. )
  154. return ApplicationService(
  155. token=as_info["as_token"],
  156. url=as_info["url"],
  157. namespaces=as_info["namespaces"],
  158. hs_token=as_info["hs_token"],
  159. sender=user_id,
  160. id=as_info["id"],
  161. protocols=protocols,
  162. rate_limited=rate_limited,
  163. ip_range_whitelist=ip_range_whitelist,
  164. supports_ephemeral=supports_ephemeral,
  165. msc3202_transaction_extensions=msc3202_transaction_extensions,
  166. )