types.py 25 KB

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