types.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. import attr
  19. from synapse.api.errors import SynapseError
  20. class Requester(
  21. namedtuple(
  22. "Requester", ["user", "access_token_id", "is_guest", "device_id", "app_service"]
  23. )
  24. ):
  25. """
  26. Represents the user making a request
  27. Attributes:
  28. user (UserID): id of the user making the request
  29. access_token_id (int|None): *ID* of the access token used for this
  30. request, or None if it came via the appservice API or similar
  31. is_guest (bool): True if the user making this request is a guest user
  32. device_id (str|None): device_id which was set at authentication time
  33. app_service (ApplicationService|None): the AS requesting on behalf of the user
  34. """
  35. def serialize(self):
  36. """Converts self to a type that can be serialized as JSON, and then
  37. deserialized by `deserialize`
  38. Returns:
  39. dict
  40. """
  41. return {
  42. "user_id": self.user.to_string(),
  43. "access_token_id": self.access_token_id,
  44. "is_guest": self.is_guest,
  45. "device_id": self.device_id,
  46. "app_server_id": self.app_service.id if self.app_service else None,
  47. }
  48. @staticmethod
  49. def deserialize(store, input):
  50. """Converts a dict that was produced by `serialize` back into a
  51. Requester.
  52. Args:
  53. store (DataStore): Used to convert AS ID to AS object
  54. input (dict): A dict produced by `serialize`
  55. Returns:
  56. Requester
  57. """
  58. appservice = None
  59. if input["app_server_id"]:
  60. appservice = store.get_app_service_by_id(input["app_server_id"])
  61. return Requester(
  62. user=UserID.from_string(input["user_id"]),
  63. access_token_id=input["access_token_id"],
  64. is_guest=input["is_guest"],
  65. device_id=input["device_id"],
  66. app_service=appservice,
  67. )
  68. def create_requester(
  69. user_id, access_token_id=None, is_guest=False, device_id=None, app_service=None
  70. ):
  71. """
  72. Create a new ``Requester`` object
  73. Args:
  74. user_id (str|UserID): id of the user making the request
  75. access_token_id (int|None): *ID* of the access token used for this
  76. request, or None if it came via the appservice API or similar
  77. is_guest (bool): True if the user making this request is a guest user
  78. device_id (str|None): device_id which was set at authentication time
  79. app_service (ApplicationService|None): the AS requesting on behalf of the user
  80. Returns:
  81. Requester
  82. """
  83. if not isinstance(user_id, UserID):
  84. user_id = UserID.from_string(user_id)
  85. return Requester(user_id, access_token_id, is_guest, device_id, app_service)
  86. def get_domain_from_id(string):
  87. idx = string.find(":")
  88. if idx == -1:
  89. raise SynapseError(400, "Invalid ID: %r" % (string,))
  90. return string[idx + 1 :]
  91. def get_localpart_from_id(string):
  92. idx = string.find(":")
  93. if idx == -1:
  94. raise SynapseError(400, "Invalid ID: %r" % (string,))
  95. return string[1:idx]
  96. class DomainSpecificString(namedtuple("DomainSpecificString", ("localpart", "domain"))):
  97. """Common base class among ID/name strings that have a local part and a
  98. domain name, prefixed with a sigil.
  99. Has the fields:
  100. 'localpart' : The local part of the name (without the leading sigil)
  101. 'domain' : The domain part of the name
  102. """
  103. # Deny iteration because it will bite you if you try to create a singleton
  104. # set by:
  105. # users = set(user)
  106. def __iter__(self):
  107. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  108. # Because this class is a namedtuple of strings and booleans, it is deeply
  109. # immutable.
  110. def __copy__(self):
  111. return self
  112. def __deepcopy__(self, memo):
  113. return self
  114. @classmethod
  115. def from_string(cls, s):
  116. """Parse the string given by 's' into a structure object."""
  117. if len(s) < 1 or s[0:1] != cls.SIGIL:
  118. raise SynapseError(
  119. 400, "Expected %s string to start with '%s'" % (cls.__name__, cls.SIGIL)
  120. )
  121. parts = s[1:].split(":", 1)
  122. if len(parts) != 2:
  123. raise SynapseError(
  124. 400,
  125. "Expected %s of the form '%slocalname:domain'"
  126. % (cls.__name__, cls.SIGIL),
  127. )
  128. domain = parts[1]
  129. # This code will need changing if we want to support multiple domain
  130. # names on one HS
  131. return cls(localpart=parts[0], domain=domain)
  132. def to_string(self):
  133. """Return a string encoding the fields of the structure object."""
  134. return "%s%s:%s" % (self.SIGIL, self.localpart, self.domain)
  135. @classmethod
  136. def is_valid(cls, s):
  137. try:
  138. cls.from_string(s)
  139. return True
  140. except Exception:
  141. return False
  142. __repr__ = to_string
  143. class UserID(DomainSpecificString):
  144. """Structure representing a user ID."""
  145. SIGIL = "@"
  146. class RoomAlias(DomainSpecificString):
  147. """Structure representing a room name."""
  148. SIGIL = "#"
  149. class RoomID(DomainSpecificString):
  150. """Structure representing a room id. """
  151. SIGIL = "!"
  152. class EventID(DomainSpecificString):
  153. """Structure representing an event id. """
  154. SIGIL = "$"
  155. class GroupID(DomainSpecificString):
  156. """Structure representing a group ID."""
  157. SIGIL = "+"
  158. @classmethod
  159. def from_string(cls, s):
  160. group_id = super(GroupID, cls).from_string(s)
  161. if not group_id.localpart:
  162. raise SynapseError(400, "Group ID cannot be empty")
  163. if contains_invalid_mxid_characters(group_id.localpart):
  164. raise SynapseError(
  165. 400, "Group ID can only contain characters a-z, 0-9, or '=_-./'"
  166. )
  167. return group_id
  168. mxid_localpart_allowed_characters = set(
  169. "_-./=" + string.ascii_lowercase + string.digits
  170. )
  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]" % (re.escape("".join(mxid_localpart_allowed_characters - {"="})),)).encode(
  193. "ascii"
  194. )
  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(
  232. "Token",
  233. (
  234. "room_key",
  235. "presence_key",
  236. "typing_key",
  237. "receipt_key",
  238. "account_data_key",
  239. "push_rules_key",
  240. "to_device_key",
  241. "device_list_key",
  242. "groups_key",
  243. ),
  244. )
  245. ):
  246. _SEPARATOR = "_"
  247. @classmethod
  248. def from_string(cls, string):
  249. try:
  250. keys = string.split(cls._SEPARATOR)
  251. while len(keys) < len(cls._fields):
  252. # i.e. old token from before receipt_key
  253. keys.append("0")
  254. return cls(*keys)
  255. except Exception:
  256. raise SynapseError(400, "Invalid Token")
  257. def to_string(self):
  258. return self._SEPARATOR.join([str(k) for k in self])
  259. @property
  260. def room_stream_id(self):
  261. # TODO(markjh): Awful hack to work around hacks in the presence tests
  262. # which assume that the keys are integers.
  263. if type(self.room_key) is int:
  264. return self.room_key
  265. else:
  266. return int(self.room_key[1:].split("-")[-1])
  267. def is_after(self, other):
  268. """Does this token contain events that the other doesn't?"""
  269. return (
  270. (other.room_stream_id < self.room_stream_id)
  271. or (int(other.presence_key) < int(self.presence_key))
  272. or (int(other.typing_key) < int(self.typing_key))
  273. or (int(other.receipt_key) < int(self.receipt_key))
  274. or (int(other.account_data_key) < int(self.account_data_key))
  275. or (int(other.push_rules_key) < int(self.push_rules_key))
  276. or (int(other.to_device_key) < int(self.to_device_key))
  277. or (int(other.device_list_key) < int(self.device_list_key))
  278. or (int(other.groups_key) < int(self.groups_key))
  279. )
  280. def copy_and_advance(self, key, new_value):
  281. """Advance the given key in the token to a new value if and only if the
  282. new value is after the old value.
  283. """
  284. new_token = self.copy_and_replace(key, new_value)
  285. if key == "room_key":
  286. new_id = new_token.room_stream_id
  287. old_id = self.room_stream_id
  288. else:
  289. new_id = int(getattr(new_token, key))
  290. old_id = int(getattr(self, key))
  291. if old_id < new_id:
  292. return new_token
  293. else:
  294. return self
  295. def copy_and_replace(self, key, new_value):
  296. return self._replace(**{key: new_value})
  297. StreamToken.START = StreamToken(*(["s0"] + ["0"] * (len(StreamToken._fields) - 1)))
  298. class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
  299. """Tokens are positions between events. The token "s1" comes after event 1.
  300. s0 s1
  301. | |
  302. [0] V [1] V [2]
  303. Tokens can either be a point in the live event stream or a cursor going
  304. through historic events.
  305. When traversing the live event stream events are ordered by when they
  306. arrived at the homeserver.
  307. When traversing historic events the events are ordered by their depth in
  308. the event graph "topological_ordering" and then by when they arrived at the
  309. homeserver "stream_ordering".
  310. Live tokens start with an "s" followed by the "stream_ordering" id of the
  311. event it comes after. Historic tokens start with a "t" followed by the
  312. "topological_ordering" id of the event it comes after, followed by "-",
  313. followed by the "stream_ordering" id of the event it comes after.
  314. """
  315. __slots__ = []
  316. @classmethod
  317. def parse(cls, string):
  318. try:
  319. if string[0] == "s":
  320. return cls(topological=None, stream=int(string[1:]))
  321. if string[0] == "t":
  322. parts = string[1:].split("-", 1)
  323. return cls(topological=int(parts[0]), stream=int(parts[1]))
  324. except Exception:
  325. pass
  326. raise SynapseError(400, "Invalid token %r" % (string,))
  327. @classmethod
  328. def parse_stream_token(cls, string):
  329. try:
  330. if string[0] == "s":
  331. return cls(topological=None, stream=int(string[1:]))
  332. except Exception:
  333. pass
  334. raise SynapseError(400, "Invalid token %r" % (string,))
  335. def __str__(self):
  336. if self.topological is not None:
  337. return "t%d-%d" % (self.topological, self.stream)
  338. else:
  339. return "s%d" % (self.stream,)
  340. class ThirdPartyInstanceID(
  341. namedtuple("ThirdPartyInstanceID", ("appservice_id", "network_id"))
  342. ):
  343. # Deny iteration because it will bite you if you try to create a singleton
  344. # set by:
  345. # users = set(user)
  346. def __iter__(self):
  347. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  348. # Because this class is a namedtuple of strings, it is deeply immutable.
  349. def __copy__(self):
  350. return self
  351. def __deepcopy__(self, memo):
  352. return self
  353. @classmethod
  354. def from_string(cls, s):
  355. bits = s.split("|", 2)
  356. if len(bits) != 2:
  357. raise SynapseError(400, "Invalid ID %r" % (s,))
  358. return cls(appservice_id=bits[0], network_id=bits[1])
  359. def to_string(self):
  360. return "%s|%s" % (self.appservice_id, self.network_id)
  361. __str__ = to_string
  362. @classmethod
  363. def create(cls, appservice_id, network_id):
  364. return cls(appservice_id=appservice_id, network_id=network_id)
  365. @attr.s(slots=True)
  366. class ReadReceipt(object):
  367. """Information about a read-receipt"""
  368. room_id = attr.ib()
  369. receipt_type = attr.ib()
  370. user_id = attr.ib()
  371. event_ids = attr.ib()
  372. data = attr.ib()