types.py 16 KB

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