types.py 24 KB

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