types.py 26 KB

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