types.py 15 KB

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