types.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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 abc
  17. import re
  18. import string
  19. import sys
  20. from collections import namedtuple
  21. from typing import (
  22. TYPE_CHECKING,
  23. Any,
  24. Dict,
  25. Iterable,
  26. Mapping,
  27. MutableMapping,
  28. Optional,
  29. Tuple,
  30. Type,
  31. TypeVar,
  32. Union,
  33. )
  34. import attr
  35. from signedjson.key import decode_verify_key_bytes
  36. from unpaddedbase64 import decode_base64
  37. from synapse.api.errors import Codes, SynapseError
  38. from synapse.util.stringutils import parse_and_validate_server_name
  39. if TYPE_CHECKING:
  40. from synapse.appservice.api import ApplicationService
  41. from synapse.storage.databases.main import DataStore
  42. # define a version of typing.Collection that works on python 3.5
  43. if sys.version_info[:3] >= (3, 6, 0):
  44. from typing import Collection
  45. else:
  46. from typing import Container, Sized
  47. T_co = TypeVar("T_co", covariant=True)
  48. class Collection(Iterable[T_co], Container[T_co], Sized): # type: ignore
  49. __slots__ = ()
  50. # Define a state map type from type/state_key to T (usually an event ID or
  51. # event)
  52. T = TypeVar("T")
  53. StateKey = Tuple[str, str]
  54. StateMap = Mapping[StateKey, T]
  55. MutableStateMap = MutableMapping[StateKey, T]
  56. # the type of a JSON-serialisable dict. This could be made stronger, but it will
  57. # do for now.
  58. JsonDict = Dict[str, Any]
  59. class Requester(
  60. namedtuple(
  61. "Requester",
  62. [
  63. "user",
  64. "access_token_id",
  65. "is_guest",
  66. "shadow_banned",
  67. "device_id",
  68. "app_service",
  69. "authenticated_entity",
  70. ],
  71. )
  72. ):
  73. """
  74. Represents the user making a request
  75. Attributes:
  76. user (UserID): id of the user making the request
  77. access_token_id (int|None): *ID* of the access token used for this
  78. request, or None if it came via the appservice API or similar
  79. is_guest (bool): True if the user making this request is a guest user
  80. shadow_banned (bool): True if the user making this request has been shadow-banned.
  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. """
  84. def serialize(self):
  85. """Converts self to a type that can be serialized as JSON, and then
  86. deserialized by `deserialize`
  87. Returns:
  88. dict
  89. """
  90. return {
  91. "user_id": self.user.to_string(),
  92. "access_token_id": self.access_token_id,
  93. "is_guest": self.is_guest,
  94. "shadow_banned": self.shadow_banned,
  95. "device_id": self.device_id,
  96. "app_server_id": self.app_service.id if self.app_service else None,
  97. "authenticated_entity": self.authenticated_entity,
  98. }
  99. @staticmethod
  100. def deserialize(store, input):
  101. """Converts a dict that was produced by `serialize` back into a
  102. Requester.
  103. Args:
  104. store (DataStore): Used to convert AS ID to AS object
  105. input (dict): A dict produced by `serialize`
  106. Returns:
  107. Requester
  108. """
  109. appservice = None
  110. if input["app_server_id"]:
  111. appservice = store.get_app_service_by_id(input["app_server_id"])
  112. return Requester(
  113. user=UserID.from_string(input["user_id"]),
  114. access_token_id=input["access_token_id"],
  115. is_guest=input["is_guest"],
  116. shadow_banned=input["shadow_banned"],
  117. device_id=input["device_id"],
  118. app_service=appservice,
  119. authenticated_entity=input["authenticated_entity"],
  120. )
  121. def create_requester(
  122. user_id: Union[str, "UserID"],
  123. access_token_id: Optional[int] = None,
  124. is_guest: Optional[bool] = False,
  125. shadow_banned: Optional[bool] = False,
  126. device_id: Optional[str] = None,
  127. app_service: Optional["ApplicationService"] = None,
  128. authenticated_entity: Optional[str] = None,
  129. ):
  130. """
  131. Create a new ``Requester`` object
  132. Args:
  133. user_id (str|UserID): id of the user making the request
  134. access_token_id (int|None): *ID* of the access token used for this
  135. request, or None if it came via the appservice API or similar
  136. is_guest (bool): True if the user making this request is a guest user
  137. shadow_banned (bool): True if the user making this request is shadow-banned.
  138. device_id (str|None): device_id which was set at authentication time
  139. app_service (ApplicationService|None): the AS requesting on behalf of the user
  140. authenticated_entity: The entity that authenticated when making the request.
  141. This is different to the user_id when an admin user or the server is
  142. "puppeting" the user.
  143. Returns:
  144. Requester
  145. """
  146. if not isinstance(user_id, UserID):
  147. user_id = UserID.from_string(user_id)
  148. if authenticated_entity is None:
  149. authenticated_entity = user_id.to_string()
  150. return Requester(
  151. user_id,
  152. access_token_id,
  153. is_guest,
  154. shadow_banned,
  155. device_id,
  156. app_service,
  157. authenticated_entity,
  158. )
  159. def get_domain_from_id(string):
  160. idx = string.find(":")
  161. if idx == -1:
  162. raise SynapseError(400, "Invalid ID: %r" % (string,))
  163. return string[idx + 1 :]
  164. def get_localpart_from_id(string):
  165. idx = string.find(":")
  166. if idx == -1:
  167. raise SynapseError(400, "Invalid ID: %r" % (string,))
  168. return string[1:idx]
  169. DS = TypeVar("DS", bound="DomainSpecificString")
  170. class DomainSpecificString(
  171. namedtuple("DomainSpecificString", ("localpart", "domain")), metaclass=abc.ABCMeta
  172. ):
  173. """Common base class among ID/name strings that have a local part and a
  174. domain name, prefixed with a sigil.
  175. Has the fields:
  176. 'localpart' : The local part of the name (without the leading sigil)
  177. 'domain' : The domain part of the name
  178. """
  179. SIGIL = abc.abstractproperty() # type: str # type: ignore
  180. # Deny iteration because it will bite you if you try to create a singleton
  181. # set by:
  182. # users = set(user)
  183. def __iter__(self):
  184. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  185. # Because this class is a namedtuple of strings and booleans, it is deeply
  186. # immutable.
  187. def __copy__(self):
  188. return self
  189. def __deepcopy__(self, memo):
  190. return self
  191. @classmethod
  192. def from_string(cls: Type[DS], s: str) -> DS:
  193. """Parse the string given by 's' into a structure object."""
  194. if len(s) < 1 or s[0:1] != cls.SIGIL:
  195. raise SynapseError(
  196. 400,
  197. "Expected %s string to start with '%s'" % (cls.__name__, cls.SIGIL),
  198. Codes.INVALID_PARAM,
  199. )
  200. parts = s[1:].split(":", 1)
  201. if len(parts) != 2:
  202. raise SynapseError(
  203. 400,
  204. "Expected %s of the form '%slocalname:domain'"
  205. % (cls.__name__, cls.SIGIL),
  206. Codes.INVALID_PARAM,
  207. )
  208. domain = parts[1]
  209. # This code will need changing if we want to support multiple domain
  210. # names on one HS
  211. return cls(localpart=parts[0], domain=domain)
  212. def to_string(self) -> str:
  213. """Return a string encoding the fields of the structure object."""
  214. return "%s%s:%s" % (self.SIGIL, self.localpart, self.domain)
  215. @classmethod
  216. def is_valid(cls: Type[DS], s: str) -> bool:
  217. """Parses the input string and attempts to ensure it is valid."""
  218. try:
  219. obj = cls.from_string(s)
  220. # Apply additional validation to the domain. This is only done
  221. # during is_valid (and not part of from_string) since it is
  222. # possible for invalid data to exist in room-state, etc.
  223. parse_and_validate_server_name(obj.domain)
  224. return True
  225. except Exception:
  226. return False
  227. __repr__ = to_string
  228. class UserID(DomainSpecificString):
  229. """Structure representing a user ID."""
  230. SIGIL = "@"
  231. class RoomAlias(DomainSpecificString):
  232. """Structure representing a room name."""
  233. SIGIL = "#"
  234. class RoomID(DomainSpecificString):
  235. """Structure representing a room id. """
  236. SIGIL = "!"
  237. class EventID(DomainSpecificString):
  238. """Structure representing an event id. """
  239. SIGIL = "$"
  240. class GroupID(DomainSpecificString):
  241. """Structure representing a group ID."""
  242. SIGIL = "+"
  243. @classmethod
  244. def from_string(cls: Type[DS], s: str) -> DS:
  245. group_id = super().from_string(s) # type: DS # type: ignore
  246. if not group_id.localpart:
  247. raise SynapseError(400, "Group ID cannot be empty", Codes.INVALID_PARAM)
  248. if contains_invalid_mxid_characters(group_id.localpart):
  249. raise SynapseError(
  250. 400,
  251. "Group ID can only contain characters a-z, 0-9, or '=_-./'",
  252. Codes.INVALID_PARAM,
  253. )
  254. return group_id
  255. mxid_localpart_allowed_characters = set(
  256. "_-./=" + string.ascii_lowercase + string.digits
  257. )
  258. def contains_invalid_mxid_characters(localpart: str) -> bool:
  259. """Check for characters not allowed in an mxid or groupid localpart
  260. Args:
  261. localpart: the localpart to be checked
  262. Returns:
  263. True if there are any naughty characters
  264. """
  265. return any(c not in mxid_localpart_allowed_characters for c in localpart)
  266. UPPER_CASE_PATTERN = re.compile(b"[A-Z_]")
  267. # the following is a pattern which matches '=', and bytes which are not allowed in a mxid
  268. # localpart.
  269. #
  270. # It works by:
  271. # * building a string containing the allowed characters (excluding '=')
  272. # * escaping every special character with a backslash (to stop '-' being interpreted as a
  273. # range operator)
  274. # * wrapping it in a '[^...]' regex
  275. # * converting the whole lot to a 'bytes' sequence, so that we can use it to match
  276. # bytes rather than strings
  277. #
  278. NON_MXID_CHARACTER_PATTERN = re.compile(
  279. ("[^%s]" % (re.escape("".join(mxid_localpart_allowed_characters - {"="})),)).encode(
  280. "ascii"
  281. )
  282. )
  283. def map_username_to_mxid_localpart(
  284. username: Union[str, bytes], case_sensitive: bool = False
  285. ) -> str:
  286. """Map a username onto a string suitable for a MXID
  287. This follows the algorithm laid out at
  288. https://matrix.org/docs/spec/appendices.html#mapping-from-other-character-sets.
  289. Args:
  290. username: username to be mapped
  291. case_sensitive: true if TEST and test should be mapped
  292. onto different mxids
  293. Returns:
  294. unicode: string suitable for a mxid localpart
  295. """
  296. if not isinstance(username, bytes):
  297. username = username.encode("utf-8")
  298. # first we sort out upper-case characters
  299. if case_sensitive:
  300. def f1(m):
  301. return b"_" + m.group().lower()
  302. username = UPPER_CASE_PATTERN.sub(f1, username)
  303. else:
  304. username = username.lower()
  305. # then we sort out non-ascii characters
  306. def f2(m):
  307. g = m.group()[0]
  308. if isinstance(g, str):
  309. # on python 2, we need to do a ord(). On python 3, the
  310. # byte itself will do.
  311. g = ord(g)
  312. return b"=%02x" % (g,)
  313. username = NON_MXID_CHARACTER_PATTERN.sub(f2, username)
  314. # we also do the =-escaping to mxids starting with an underscore.
  315. username = re.sub(b"^_", b"=5f", username)
  316. # we should now only have ascii bytes left, so can decode back to a
  317. # unicode.
  318. return username.decode("ascii")
  319. @attr.s(frozen=True, slots=True, cmp=False)
  320. class RoomStreamToken:
  321. """Tokens are positions between events. The token "s1" comes after event 1.
  322. s0 s1
  323. | |
  324. [0] V [1] V [2]
  325. Tokens can either be a point in the live event stream or a cursor going
  326. through historic events.
  327. When traversing the live event stream events are ordered by when they
  328. arrived at the homeserver.
  329. When traversing historic events the events are ordered by their depth in
  330. the event graph "topological_ordering" and then by when they arrived at the
  331. homeserver "stream_ordering".
  332. Live tokens start with an "s" followed by the "stream_ordering" id of the
  333. event it comes after. Historic tokens start with a "t" followed by the
  334. "topological_ordering" id of the event it comes after, followed by "-",
  335. followed by the "stream_ordering" id of the event it comes after.
  336. There is also a third mode for live tokens where the token starts with "m",
  337. which is sometimes used when using sharded event persisters. In this case
  338. the events stream is considered to be a set of streams (one for each writer)
  339. and the token encodes the vector clock of positions of each writer in their
  340. respective streams.
  341. The format of the token in such case is an initial integer min position,
  342. followed by the mapping of instance ID to position separated by '.' and '~':
  343. m{min_pos}~{writer1}.{pos1}~{writer2}.{pos2}. ...
  344. The `min_pos` corresponds to the minimum position all writers have persisted
  345. up to, and then only writers that are ahead of that position need to be
  346. encoded. An example token is:
  347. m56~2.58~3.59
  348. Which corresponds to a set of three (or more writers) where instances 2 and
  349. 3 (these are instance IDs that can be looked up in the DB to fetch the more
  350. commonly used instance names) are at positions 58 and 59 respectively, and
  351. all other instances are at position 56.
  352. Note: The `RoomStreamToken` cannot have both a topological part and an
  353. instance map.
  354. """
  355. topological = attr.ib(
  356. type=Optional[int],
  357. validator=attr.validators.optional(attr.validators.instance_of(int)),
  358. )
  359. stream = attr.ib(type=int, validator=attr.validators.instance_of(int))
  360. instance_map = attr.ib(
  361. type=Dict[str, int],
  362. factory=dict,
  363. validator=attr.validators.deep_mapping(
  364. key_validator=attr.validators.instance_of(str),
  365. value_validator=attr.validators.instance_of(int),
  366. mapping_validator=attr.validators.instance_of(dict),
  367. ),
  368. )
  369. def __attrs_post_init__(self):
  370. """Validates that both `topological` and `instance_map` aren't set.
  371. """
  372. if self.instance_map and self.topological:
  373. raise ValueError(
  374. "Cannot set both 'topological' and 'instance_map' on 'RoomStreamToken'."
  375. )
  376. @classmethod
  377. async def parse(cls, store: "DataStore", string: str) -> "RoomStreamToken":
  378. try:
  379. if string[0] == "s":
  380. return cls(topological=None, stream=int(string[1:]))
  381. if string[0] == "t":
  382. parts = string[1:].split("-", 1)
  383. return cls(topological=int(parts[0]), stream=int(parts[1]))
  384. if string[0] == "m":
  385. parts = string[1:].split("~")
  386. stream = int(parts[0])
  387. instance_map = {}
  388. for part in parts[1:]:
  389. key, value = part.split(".")
  390. instance_id = int(key)
  391. pos = int(value)
  392. instance_name = await store.get_name_from_instance_id(instance_id)
  393. instance_map[instance_name] = pos
  394. return cls(topological=None, stream=stream, instance_map=instance_map,)
  395. except Exception:
  396. pass
  397. raise SynapseError(400, "Invalid token %r" % (string,))
  398. @classmethod
  399. def parse_stream_token(cls, string: str) -> "RoomStreamToken":
  400. try:
  401. if string[0] == "s":
  402. return cls(topological=None, stream=int(string[1:]))
  403. except Exception:
  404. pass
  405. raise SynapseError(400, "Invalid token %r" % (string,))
  406. def copy_and_advance(self, other: "RoomStreamToken") -> "RoomStreamToken":
  407. """Return a new token such that if an event is after both this token and
  408. the other token, then its after the returned token too.
  409. """
  410. if self.topological or other.topological:
  411. raise Exception("Can't advance topological tokens")
  412. max_stream = max(self.stream, other.stream)
  413. instance_map = {
  414. instance: max(
  415. self.instance_map.get(instance, self.stream),
  416. other.instance_map.get(instance, other.stream),
  417. )
  418. for instance in set(self.instance_map).union(other.instance_map)
  419. }
  420. return RoomStreamToken(None, max_stream, instance_map)
  421. def as_historical_tuple(self) -> Tuple[int, int]:
  422. """Returns a tuple of `(topological, stream)` for historical tokens.
  423. Raises if not an historical token (i.e. doesn't have a topological part).
  424. """
  425. if self.topological is None:
  426. raise Exception(
  427. "Cannot call `RoomStreamToken.as_historical_tuple` on live token"
  428. )
  429. return (self.topological, self.stream)
  430. def get_stream_pos_for_instance(self, instance_name: str) -> int:
  431. """Get the stream position that the given writer was at at this token.
  432. This only makes sense for "live" tokens that may have a vector clock
  433. component, and so asserts that this is a "live" token.
  434. """
  435. assert self.topological is None
  436. # If we don't have an entry for the instance we can assume that it was
  437. # at `self.stream`.
  438. return self.instance_map.get(instance_name, self.stream)
  439. def get_max_stream_pos(self) -> int:
  440. """Get the maximum stream position referenced in this token.
  441. The corresponding "min" position is, by definition just `self.stream`.
  442. This is used to handle tokens that have non-empty `instance_map`, and so
  443. reference stream positions after the `self.stream` position.
  444. """
  445. return max(self.instance_map.values(), default=self.stream)
  446. async def to_string(self, store: "DataStore") -> str:
  447. if self.topological is not None:
  448. return "t%d-%d" % (self.topological, self.stream)
  449. elif self.instance_map:
  450. entries = []
  451. for name, pos in self.instance_map.items():
  452. instance_id = await store.get_id_for_instance(name)
  453. entries.append("{}.{}".format(instance_id, pos))
  454. encoded_map = "~".join(entries)
  455. return "m{}~{}".format(self.stream, encoded_map)
  456. else:
  457. return "s%d" % (self.stream,)
  458. @attr.s(slots=True, frozen=True)
  459. class StreamToken:
  460. room_key = attr.ib(
  461. type=RoomStreamToken, validator=attr.validators.instance_of(RoomStreamToken)
  462. )
  463. presence_key = attr.ib(type=int)
  464. typing_key = attr.ib(type=int)
  465. receipt_key = attr.ib(type=int)
  466. account_data_key = attr.ib(type=int)
  467. push_rules_key = attr.ib(type=int)
  468. to_device_key = attr.ib(type=int)
  469. device_list_key = attr.ib(type=int)
  470. groups_key = attr.ib(type=int)
  471. _SEPARATOR = "_"
  472. START = None # type: StreamToken
  473. @classmethod
  474. async def from_string(cls, store: "DataStore", string: str) -> "StreamToken":
  475. try:
  476. keys = string.split(cls._SEPARATOR)
  477. while len(keys) < len(attr.fields(cls)):
  478. # i.e. old token from before receipt_key
  479. keys.append("0")
  480. return cls(
  481. await RoomStreamToken.parse(store, keys[0]), *(int(k) for k in keys[1:])
  482. )
  483. except Exception:
  484. raise SynapseError(400, "Invalid Token")
  485. async def to_string(self, store: "DataStore") -> str:
  486. return self._SEPARATOR.join(
  487. [
  488. await self.room_key.to_string(store),
  489. str(self.presence_key),
  490. str(self.typing_key),
  491. str(self.receipt_key),
  492. str(self.account_data_key),
  493. str(self.push_rules_key),
  494. str(self.to_device_key),
  495. str(self.device_list_key),
  496. str(self.groups_key),
  497. ]
  498. )
  499. @property
  500. def room_stream_id(self):
  501. return self.room_key.stream
  502. def copy_and_advance(self, key, new_value) -> "StreamToken":
  503. """Advance the given key in the token to a new value if and only if the
  504. new value is after the old value.
  505. """
  506. if key == "room_key":
  507. new_token = self.copy_and_replace(
  508. "room_key", self.room_key.copy_and_advance(new_value)
  509. )
  510. return new_token
  511. new_token = self.copy_and_replace(key, new_value)
  512. new_id = int(getattr(new_token, key))
  513. old_id = int(getattr(self, key))
  514. if old_id < new_id:
  515. return new_token
  516. else:
  517. return self
  518. def copy_and_replace(self, key, new_value) -> "StreamToken":
  519. return attr.evolve(self, **{key: new_value})
  520. StreamToken.START = StreamToken(RoomStreamToken(None, 0), 0, 0, 0, 0, 0, 0, 0, 0)
  521. @attr.s(slots=True, frozen=True)
  522. class PersistedEventPosition:
  523. """Position of a newly persisted event with instance that persisted it.
  524. This can be used to test whether the event is persisted before or after a
  525. RoomStreamToken.
  526. """
  527. instance_name = attr.ib(type=str)
  528. stream = attr.ib(type=int)
  529. def persisted_after(self, token: RoomStreamToken) -> bool:
  530. return token.get_stream_pos_for_instance(self.instance_name) < self.stream
  531. def to_room_stream_token(self) -> RoomStreamToken:
  532. """Converts the position to a room stream token such that events
  533. persisted in the same room after this position will be after the
  534. returned `RoomStreamToken`.
  535. Note: no guarentees are made about ordering w.r.t. events in other
  536. rooms.
  537. """
  538. # Doing the naive thing satisfies the desired properties described in
  539. # the docstring.
  540. return RoomStreamToken(None, self.stream)
  541. class ThirdPartyInstanceID(
  542. namedtuple("ThirdPartyInstanceID", ("appservice_id", "network_id"))
  543. ):
  544. # Deny iteration because it will bite you if you try to create a singleton
  545. # set by:
  546. # users = set(user)
  547. def __iter__(self):
  548. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  549. # Because this class is a namedtuple of strings, it is deeply immutable.
  550. def __copy__(self):
  551. return self
  552. def __deepcopy__(self, memo):
  553. return self
  554. @classmethod
  555. def from_string(cls, s):
  556. bits = s.split("|", 2)
  557. if len(bits) != 2:
  558. raise SynapseError(400, "Invalid ID %r" % (s,))
  559. return cls(appservice_id=bits[0], network_id=bits[1])
  560. def to_string(self):
  561. return "%s|%s" % (self.appservice_id, self.network_id)
  562. __str__ = to_string
  563. @classmethod
  564. def create(cls, appservice_id, network_id):
  565. return cls(appservice_id=appservice_id, network_id=network_id)
  566. @attr.s(slots=True)
  567. class ReadReceipt:
  568. """Information about a read-receipt"""
  569. room_id = attr.ib()
  570. receipt_type = attr.ib()
  571. user_id = attr.ib()
  572. event_ids = attr.ib()
  573. data = attr.ib()
  574. def get_verify_key_from_cross_signing_key(key_info):
  575. """Get the key ID and signedjson verify key from a cross-signing key dict
  576. Args:
  577. key_info (dict): a cross-signing key dict, which must have a "keys"
  578. property that has exactly one item in it
  579. Returns:
  580. (str, VerifyKey): the key ID and verify key for the cross-signing key
  581. """
  582. # make sure that exactly one key is provided
  583. if "keys" not in key_info:
  584. raise ValueError("Invalid key")
  585. keys = key_info["keys"]
  586. if len(keys) != 1:
  587. raise ValueError("Invalid key")
  588. # and return that one key
  589. for key_id, key_data in keys.items():
  590. return (key_id, decode_verify_key_bytes(key_id, decode_base64(key_data)))