appservice.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. type(x) is 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. def load_appservices(
  38. hostname: str, config_files: List[str]
  39. ) -> List[ApplicationService]:
  40. """Returns a list of Application Services from the config files."""
  41. # Dicts of value -> filename
  42. seen_as_tokens: Dict[str, str] = {}
  43. seen_ids: Dict[str, str] = {}
  44. appservices = []
  45. for config_file in config_files:
  46. try:
  47. with open(config_file) as f:
  48. appservice = _load_appservice(hostname, yaml.safe_load(f), config_file)
  49. if appservice.id in seen_ids:
  50. raise ConfigError(
  51. "Cannot reuse ID across application services: "
  52. "%s (files: %s, %s)"
  53. % (appservice.id, config_file, seen_ids[appservice.id])
  54. )
  55. seen_ids[appservice.id] = config_file
  56. if appservice.token in seen_as_tokens:
  57. raise ConfigError(
  58. "Cannot reuse as_token across application services: "
  59. "%s (files: %s, %s)"
  60. % (
  61. appservice.token,
  62. config_file,
  63. seen_as_tokens[appservice.token],
  64. )
  65. )
  66. seen_as_tokens[appservice.token] = config_file
  67. logger.info("Loaded application service: %s", appservice)
  68. appservices.append(appservice)
  69. except Exception as e:
  70. logger.error("Failed to load appservice from '%s'", config_file)
  71. logger.exception(e)
  72. raise
  73. return appservices
  74. def _load_appservice(
  75. hostname: str, as_info: JsonDict, config_filename: str
  76. ) -> ApplicationService:
  77. required_string_fields = ["id", "as_token", "hs_token", "sender_localpart"]
  78. for field in required_string_fields:
  79. if not isinstance(as_info.get(field), str):
  80. raise KeyError(
  81. "Required string field: '%s' (%s)" % (field, config_filename)
  82. )
  83. # 'url' must either be a string or explicitly null, not missing
  84. # to avoid accidentally turning off push for ASes.
  85. if not isinstance(as_info.get("url"), str) and as_info.get("url", "") is not None:
  86. raise KeyError(
  87. "Required string field or explicit null: 'url' (%s)" % (config_filename,)
  88. )
  89. localpart = as_info["sender_localpart"]
  90. if urlparse.quote(localpart) != localpart:
  91. raise ValueError("sender_localpart needs characters which are not URL encoded.")
  92. user = UserID(localpart, hostname)
  93. user_id = user.to_string()
  94. # Rate limiting for users of this AS is on by default (excludes sender)
  95. rate_limited = as_info.get("rate_limited")
  96. if not isinstance(rate_limited, bool):
  97. rate_limited = True
  98. # namespace checks
  99. if not isinstance(as_info.get("namespaces"), dict):
  100. raise KeyError("Requires 'namespaces' object.")
  101. for ns in ApplicationService.NS_LIST:
  102. # specific namespaces are optional
  103. if ns in as_info["namespaces"]:
  104. # expect a list of dicts with exclusive and regex keys
  105. for regex_obj in as_info["namespaces"][ns]:
  106. if not isinstance(regex_obj, dict):
  107. raise ValueError(
  108. "Expected namespace entry in %s to be an object, but got %s",
  109. ns,
  110. regex_obj,
  111. )
  112. if not isinstance(regex_obj.get("regex"), str):
  113. raise ValueError("Missing/bad type 'regex' key in %s", regex_obj)
  114. if not isinstance(regex_obj.get("exclusive"), bool):
  115. raise ValueError(
  116. "Missing/bad type 'exclusive' key in %s", regex_obj
  117. )
  118. # protocols check
  119. protocols = as_info.get("protocols")
  120. if protocols:
  121. if not isinstance(protocols, list):
  122. raise KeyError("Optional 'protocols' must be a list if present.")
  123. for p in protocols:
  124. if not isinstance(p, str):
  125. raise KeyError("Bad value for 'protocols' item")
  126. if as_info["url"] is None:
  127. logger.info(
  128. "(%s) Explicitly empty 'url' provided. This application service"
  129. " will not receive events or queries.",
  130. config_filename,
  131. )
  132. ip_range_whitelist = None
  133. if as_info.get("ip_range_whitelist"):
  134. ip_range_whitelist = IPSet(as_info.get("ip_range_whitelist"))
  135. supports_ephemeral = as_info.get("de.sorunome.msc2409.push_ephemeral", False)
  136. # Opt-in flag for the MSC3202-specific transactional behaviour.
  137. # When enabled, appservice transactions contain the following information:
  138. # - device One-Time Key counts
  139. # - device unused fallback key usage states
  140. # - device list changes
  141. msc3202_transaction_extensions = as_info.get("org.matrix.msc3202", False)
  142. if not isinstance(msc3202_transaction_extensions, bool):
  143. raise ValueError(
  144. "The `org.matrix.msc3202` option should be true or false if specified."
  145. )
  146. return ApplicationService(
  147. token=as_info["as_token"],
  148. url=as_info["url"],
  149. namespaces=as_info["namespaces"],
  150. hs_token=as_info["hs_token"],
  151. sender=user_id,
  152. id=as_info["id"],
  153. protocols=protocols,
  154. rate_limited=rate_limited,
  155. ip_range_whitelist=ip_range_whitelist,
  156. supports_ephemeral=supports_ephemeral,
  157. msc3202_transaction_extensions=msc3202_transaction_extensions,
  158. )