types.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  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 re
  16. import string
  17. from collections import namedtuple
  18. from synapse.api.errors import SynapseError
  19. class Requester(namedtuple("Requester", [
  20. "user", "access_token_id", "is_guest", "device_id", "app_service",
  21. ])):
  22. """
  23. Represents the user making a request
  24. Attributes:
  25. user (UserID): id of the user making the request
  26. access_token_id (int|None): *ID* of the access token used for this
  27. request, or None if it came via the appservice API or similar
  28. is_guest (bool): True if the user making this request is a guest user
  29. device_id (str|None): device_id which was set at authentication time
  30. app_service (ApplicationService|None): the AS requesting on behalf of the user
  31. """
  32. def serialize(self):
  33. """Converts self to a type that can be serialized as JSON, and then
  34. deserialized by `deserialize`
  35. Returns:
  36. dict
  37. """
  38. return {
  39. "user_id": self.user.to_string(),
  40. "access_token_id": self.access_token_id,
  41. "is_guest": self.is_guest,
  42. "device_id": self.device_id,
  43. "app_server_id": self.app_service.id if self.app_service else None,
  44. }
  45. @staticmethod
  46. def deserialize(store, input):
  47. """Converts a dict that was produced by `serialize` back into a
  48. Requester.
  49. Args:
  50. store (DataStore): Used to convert AS ID to AS object
  51. input (dict): A dict produced by `serialize`
  52. Returns:
  53. Requester
  54. """
  55. appservice = None
  56. if input["app_server_id"]:
  57. appservice = store.get_app_service_by_id(input["app_server_id"])
  58. return Requester(
  59. user=UserID.from_string(input["user_id"]),
  60. access_token_id=input["access_token_id"],
  61. is_guest=input["is_guest"],
  62. device_id=input["device_id"],
  63. app_service=appservice,
  64. )
  65. def create_requester(user_id, access_token_id=None, is_guest=False,
  66. device_id=None, app_service=None):
  67. """
  68. Create a new ``Requester`` object
  69. Args:
  70. user_id (str|UserID): id of the user making the request
  71. access_token_id (int|None): *ID* of the access token used for this
  72. request, or None if it came via the appservice API or similar
  73. is_guest (bool): True if the user making this request is a guest user
  74. device_id (str|None): device_id which was set at authentication time
  75. app_service (ApplicationService|None): the AS requesting on behalf of the user
  76. Returns:
  77. Requester
  78. """
  79. if not isinstance(user_id, UserID):
  80. user_id = UserID.from_string(user_id)
  81. return Requester(user_id, access_token_id, is_guest, device_id, app_service)
  82. def get_domain_from_id(string):
  83. idx = string.find(":")
  84. if idx == -1:
  85. raise SynapseError(400, "Invalid ID: %r" % (string,))
  86. return string[idx + 1:]
  87. def get_localpart_from_id(string):
  88. idx = string.find(":")
  89. if idx == -1:
  90. raise SynapseError(400, "Invalid ID: %r" % (string,))
  91. return string[1:idx]
  92. class DomainSpecificString(
  93. namedtuple("DomainSpecificString", ("localpart", "domain"))
  94. ):
  95. """Common base class among ID/name strings that have a local part and a
  96. domain name, prefixed with a sigil.
  97. Has the fields:
  98. 'localpart' : The local part of the name (without the leading sigil)
  99. 'domain' : The domain part of the name
  100. """
  101. # Deny iteration because it will bite you if you try to create a singleton
  102. # set by:
  103. # users = set(user)
  104. def __iter__(self):
  105. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  106. # Because this class is a namedtuple of strings and booleans, it is deeply
  107. # immutable.
  108. def __copy__(self):
  109. return self
  110. def __deepcopy__(self, memo):
  111. return self
  112. @classmethod
  113. def from_string(cls, s):
  114. """Parse the string given by 's' into a structure object."""
  115. if len(s) < 1 or s[0:1] != cls.SIGIL:
  116. raise SynapseError(400, "Expected %s string to start with '%s'" % (
  117. cls.__name__, cls.SIGIL,
  118. ))
  119. parts = s[1:].split(':', 1)
  120. if len(parts) != 2:
  121. raise SynapseError(
  122. 400, "Expected %s of the form '%slocalname:domain'" % (
  123. cls.__name__, cls.SIGIL,
  124. )
  125. )
  126. domain = parts[1]
  127. # This code will need changing if we want to support multiple domain
  128. # names on one HS
  129. return cls(localpart=parts[0], domain=domain)
  130. def to_string(self):
  131. """Return a string encoding the fields of the structure object."""
  132. return "%s%s:%s" % (self.SIGIL, self.localpart, self.domain)
  133. @classmethod
  134. def is_valid(cls, s):
  135. try:
  136. cls.from_string(s)
  137. return True
  138. except Exception:
  139. return False
  140. __repr__ = to_string
  141. class UserID(DomainSpecificString):
  142. """Structure representing a user ID."""
  143. SIGIL = "@"
  144. class RoomAlias(DomainSpecificString):
  145. """Structure representing a room name."""
  146. SIGIL = "#"
  147. class RoomID(DomainSpecificString):
  148. """Structure representing a room id. """
  149. SIGIL = "!"
  150. class EventID(DomainSpecificString):
  151. """Structure representing an event id. """
  152. SIGIL = "$"
  153. class GroupID(DomainSpecificString):
  154. """Structure representing a group ID."""
  155. SIGIL = "+"
  156. @classmethod
  157. def from_string(cls, s):
  158. group_id = super(GroupID, cls).from_string(s)
  159. if not group_id.localpart:
  160. raise SynapseError(
  161. 400,
  162. "Group ID cannot be empty",
  163. )
  164. if contains_invalid_mxid_characters(group_id.localpart):
  165. raise SynapseError(
  166. 400,
  167. "Group ID can only contain characters a-z, 0-9, or '=_-./'",
  168. )
  169. return group_id
  170. mxid_localpart_allowed_characters = set("_-./=" + string.ascii_lowercase + string.digits)
  171. def contains_invalid_mxid_characters(localpart):
  172. """Check for characters not allowed in an mxid or groupid localpart
  173. Args:
  174. localpart (basestring): the localpart to be checked
  175. Returns:
  176. bool: True if there are any naughty characters
  177. """
  178. return any(c not in mxid_localpart_allowed_characters for c in localpart)
  179. UPPER_CASE_PATTERN = re.compile(b"[A-Z_]")
  180. # the following is a pattern which matches '=', and bytes which are not allowed in a mxid
  181. # localpart.
  182. #
  183. # It works by:
  184. # * building a string containing the allowed characters (excluding '=')
  185. # * escaping every special character with a backslash (to stop '-' being interpreted as a
  186. # range operator)
  187. # * wrapping it in a '[^...]' regex
  188. # * converting the whole lot to a 'bytes' sequence, so that we can use it to match
  189. # bytes rather than strings
  190. #
  191. NON_MXID_CHARACTER_PATTERN = re.compile(
  192. ("[^%s]" % (
  193. re.escape("".join(mxid_localpart_allowed_characters - {"="}),),
  194. )).encode("ascii"),
  195. )
  196. def map_username_to_mxid_localpart(username, case_sensitive=False):
  197. """Map a username onto a string suitable for a MXID
  198. This follows the algorithm laid out at
  199. https://matrix.org/docs/spec/appendices.html#mapping-from-other-character-sets.
  200. Args:
  201. username (unicode|bytes): username to be mapped
  202. case_sensitive (bool): true if TEST and test should be mapped
  203. onto different mxids
  204. Returns:
  205. unicode: string suitable for a mxid localpart
  206. """
  207. if not isinstance(username, bytes):
  208. username = username.encode('utf-8')
  209. # first we sort out upper-case characters
  210. if case_sensitive:
  211. def f1(m):
  212. return b"_" + m.group().lower()
  213. username = UPPER_CASE_PATTERN.sub(f1, username)
  214. else:
  215. username = username.lower()
  216. # then we sort out non-ascii characters
  217. def f2(m):
  218. g = m.group()[0]
  219. if isinstance(g, str):
  220. # on python 2, we need to do a ord(). On python 3, the
  221. # byte itself will do.
  222. g = ord(g)
  223. return b"=%02x" % (g,)
  224. username = NON_MXID_CHARACTER_PATTERN.sub(f2, username)
  225. # we also do the =-escaping to mxids starting with an underscore.
  226. username = re.sub(b'^_', b'=5f', username)
  227. # we should now only have ascii bytes left, so can decode back to a
  228. # unicode.
  229. return username.decode('ascii')
  230. class StreamToken(
  231. namedtuple("Token", (
  232. "room_key",
  233. "presence_key",
  234. "typing_key",
  235. "receipt_key",
  236. "account_data_key",
  237. "push_rules_key",
  238. "to_device_key",
  239. "device_list_key",
  240. "groups_key",
  241. ))
  242. ):
  243. _SEPARATOR = "_"
  244. @classmethod
  245. def from_string(cls, string):
  246. try:
  247. keys = string.split(cls._SEPARATOR)
  248. while len(keys) < len(cls._fields):
  249. # i.e. old token from before receipt_key
  250. keys.append("0")
  251. return cls(*keys)
  252. except Exception:
  253. raise SynapseError(400, "Invalid Token")
  254. def to_string(self):
  255. return self._SEPARATOR.join([str(k) for k in self])
  256. @property
  257. def room_stream_id(self):
  258. # TODO(markjh): Awful hack to work around hacks in the presence tests
  259. # which assume that the keys are integers.
  260. if type(self.room_key) is int:
  261. return self.room_key
  262. else:
  263. return int(self.room_key[1:].split("-")[-1])
  264. def is_after(self, other):
  265. """Does this token contain events that the other doesn't?"""
  266. return (
  267. (other.room_stream_id < self.room_stream_id)
  268. or (int(other.presence_key) < int(self.presence_key))
  269. or (int(other.typing_key) < int(self.typing_key))
  270. or (int(other.receipt_key) < int(self.receipt_key))
  271. or (int(other.account_data_key) < int(self.account_data_key))
  272. or (int(other.push_rules_key) < int(self.push_rules_key))
  273. or (int(other.to_device_key) < int(self.to_device_key))
  274. or (int(other.device_list_key) < int(self.device_list_key))
  275. or (int(other.groups_key) < int(self.groups_key))
  276. )
  277. def copy_and_advance(self, key, new_value):
  278. """Advance the given key in the token to a new value if and only if the
  279. new value is after the old value.
  280. """
  281. new_token = self.copy_and_replace(key, new_value)
  282. if key == "room_key":
  283. new_id = new_token.room_stream_id
  284. old_id = self.room_stream_id
  285. else:
  286. new_id = int(getattr(new_token, key))
  287. old_id = int(getattr(self, key))
  288. if old_id < new_id:
  289. return new_token
  290. else:
  291. return self
  292. def copy_and_replace(self, key, new_value):
  293. return self._replace(**{key: new_value})
  294. StreamToken.START = StreamToken(
  295. *(["s0"] + ["0"] * (len(StreamToken._fields) - 1))
  296. )
  297. class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
  298. """Tokens are positions between events. The token "s1" comes after event 1.
  299. s0 s1
  300. | |
  301. [0] V [1] V [2]
  302. Tokens can either be a point in the live event stream or a cursor going
  303. through historic events.
  304. When traversing the live event stream events are ordered by when they
  305. arrived at the homeserver.
  306. When traversing historic events the events are ordered by their depth in
  307. the event graph "topological_ordering" and then by when they arrived at the
  308. homeserver "stream_ordering".
  309. Live tokens start with an "s" followed by the "stream_ordering" id of the
  310. event it comes after. Historic tokens start with a "t" followed by the
  311. "topological_ordering" id of the event it comes after, followed by "-",
  312. followed by the "stream_ordering" id of the event it comes after.
  313. """
  314. __slots__ = []
  315. @classmethod
  316. def parse(cls, string):
  317. try:
  318. if string[0] == 's':
  319. return cls(topological=None, stream=int(string[1:]))
  320. if string[0] == 't':
  321. parts = string[1:].split('-', 1)
  322. return cls(topological=int(parts[0]), stream=int(parts[1]))
  323. except Exception:
  324. pass
  325. raise SynapseError(400, "Invalid token %r" % (string,))
  326. @classmethod
  327. def parse_stream_token(cls, string):
  328. try:
  329. if string[0] == 's':
  330. return cls(topological=None, stream=int(string[1:]))
  331. except Exception:
  332. pass
  333. raise SynapseError(400, "Invalid token %r" % (string,))
  334. def __str__(self):
  335. if self.topological is not None:
  336. return "t%d-%d" % (self.topological, self.stream)
  337. else:
  338. return "s%d" % (self.stream,)
  339. class ThirdPartyInstanceID(
  340. namedtuple("ThirdPartyInstanceID", ("appservice_id", "network_id"))
  341. ):
  342. # Deny iteration because it will bite you if you try to create a singleton
  343. # set by:
  344. # users = set(user)
  345. def __iter__(self):
  346. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  347. # Because this class is a namedtuple of strings, it is deeply immutable.
  348. def __copy__(self):
  349. return self
  350. def __deepcopy__(self, memo):
  351. return self
  352. @classmethod
  353. def from_string(cls, s):
  354. bits = s.split("|", 2)
  355. if len(bits) != 2:
  356. raise SynapseError(400, "Invalid ID %r" % (s,))
  357. return cls(appservice_id=bits[0], network_id=bits[1])
  358. def to_string(self):
  359. return "%s|%s" % (self.appservice_id, self.network_id,)
  360. __str__ = to_string
  361. @classmethod
  362. def create(cls, appservice_id, network_id,):
  363. return cls(appservice_id=appservice_id, network_id=network_id)