types.py 26 KB

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