appservice.py 6.6 KB

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