types.py 26 KB

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