types.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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. NoReturn,
  28. Optional,
  29. Set,
  30. Tuple,
  31. Type,
  32. TypeVar,
  33. Union,
  34. )
  35. import attr
  36. from frozendict import frozendict
  37. from signedjson.key import decode_verify_key_bytes
  38. from signedjson.types import VerifyKey
  39. from typing_extensions import Final, TypedDict
  40. from unpaddedbase64 import decode_base64
  41. from zope.interface import Interface
  42. from twisted.internet.defer import CancelledError
  43. from twisted.internet.interfaces import (
  44. IReactorCore,
  45. IReactorPluggableNameResolver,
  46. IReactorSSL,
  47. IReactorTCP,
  48. IReactorThreads,
  49. IReactorTime,
  50. )
  51. from synapse.api.errors import Codes, SynapseError
  52. from synapse.util.stringutils import parse_and_validate_server_name
  53. if TYPE_CHECKING:
  54. from synapse.appservice.api import ApplicationService
  55. from synapse.storage.databases.main import DataStore, PurgeEventsStore
  56. from synapse.storage.databases.main.appservice import ApplicationServiceWorkerStore
  57. # Define a state map type from type/state_key to T (usually an event ID or
  58. # event)
  59. T = TypeVar("T")
  60. StateKey = Tuple[str, str]
  61. StateMap = Mapping[StateKey, T]
  62. MutableStateMap = MutableMapping[StateKey, T]
  63. # JSON types. These could be made stronger, but will do for now.
  64. # A JSON-serialisable dict.
  65. JsonDict = Dict[str, Any]
  66. # A JSON-serialisable mapping; roughly speaking an immutable JSONDict.
  67. # Useful when you have a TypedDict which isn't going to be mutated and you don't want
  68. # to cast to JsonDict everywhere.
  69. JsonMapping = Mapping[str, Any]
  70. # A JSON-serialisable object.
  71. JsonSerializable = object
  72. # Note that this seems to require inheriting *directly* from Interface in order
  73. # for mypy-zope to realize it is an interface.
  74. class ISynapseReactor(
  75. IReactorTCP,
  76. IReactorSSL,
  77. IReactorPluggableNameResolver,
  78. IReactorTime,
  79. IReactorCore,
  80. IReactorThreads,
  81. Interface,
  82. ):
  83. """The interfaces necessary for Synapse to function."""
  84. @attr.s(frozen=True, slots=True, auto_attribs=True)
  85. class Requester:
  86. """
  87. Represents the user making a request
  88. Attributes:
  89. user: id of the user making the request
  90. access_token_id: *ID* of the access token used for this
  91. request, or None if it came via the appservice API or similar
  92. is_guest: True if the user making this request is a guest user
  93. shadow_banned: True if the user making this request has been shadow-banned.
  94. device_id: device_id which was set at authentication time
  95. app_service: the AS requesting on behalf of the user
  96. authenticated_entity: The entity that authenticated when making the request.
  97. This is different to the user_id when an admin user or the server is
  98. "puppeting" the user.
  99. """
  100. user: "UserID"
  101. access_token_id: Optional[int]
  102. is_guest: bool
  103. shadow_banned: bool
  104. device_id: Optional[str]
  105. app_service: Optional["ApplicationService"]
  106. authenticated_entity: str
  107. def serialize(self) -> Dict[str, Any]:
  108. """Converts self to a type that can be serialized as JSON, and then
  109. deserialized by `deserialize`
  110. Returns:
  111. dict
  112. """
  113. return {
  114. "user_id": self.user.to_string(),
  115. "access_token_id": self.access_token_id,
  116. "is_guest": self.is_guest,
  117. "shadow_banned": self.shadow_banned,
  118. "device_id": self.device_id,
  119. "app_server_id": self.app_service.id if self.app_service else None,
  120. "authenticated_entity": self.authenticated_entity,
  121. }
  122. @staticmethod
  123. def deserialize(
  124. store: "ApplicationServiceWorkerStore", input: Dict[str, Any]
  125. ) -> "Requester":
  126. """Converts a dict that was produced by `serialize` back into a
  127. Requester.
  128. Args:
  129. store (DataStore): Used to convert AS ID to AS object
  130. input (dict): A dict produced by `serialize`
  131. Returns:
  132. Requester
  133. """
  134. appservice = None
  135. if input["app_server_id"]:
  136. appservice = store.get_app_service_by_id(input["app_server_id"])
  137. return Requester(
  138. user=UserID.from_string(input["user_id"]),
  139. access_token_id=input["access_token_id"],
  140. is_guest=input["is_guest"],
  141. shadow_banned=input["shadow_banned"],
  142. device_id=input["device_id"],
  143. app_service=appservice,
  144. authenticated_entity=input["authenticated_entity"],
  145. )
  146. def create_requester(
  147. user_id: Union[str, "UserID"],
  148. access_token_id: Optional[int] = None,
  149. is_guest: bool = False,
  150. shadow_banned: bool = False,
  151. device_id: Optional[str] = None,
  152. app_service: Optional["ApplicationService"] = None,
  153. authenticated_entity: Optional[str] = None,
  154. ) -> Requester:
  155. """
  156. Create a new ``Requester`` object
  157. Args:
  158. user_id: id of the user making the request
  159. access_token_id: *ID* of the access token used for this
  160. request, or None if it came via the appservice API or similar
  161. is_guest: True if the user making this request is a guest user
  162. shadow_banned: True if the user making this request is shadow-banned.
  163. device_id: device_id which was set at authentication time
  164. app_service: the AS requesting on behalf of the user
  165. authenticated_entity: The entity that authenticated when making the request.
  166. This is different to the user_id when an admin user or the server is
  167. "puppeting" the user.
  168. Returns:
  169. Requester
  170. """
  171. if not isinstance(user_id, UserID):
  172. user_id = UserID.from_string(user_id)
  173. if authenticated_entity is None:
  174. authenticated_entity = user_id.to_string()
  175. return Requester(
  176. user_id,
  177. access_token_id,
  178. is_guest,
  179. shadow_banned,
  180. device_id,
  181. app_service,
  182. authenticated_entity,
  183. )
  184. def get_domain_from_id(string: str) -> str:
  185. idx = string.find(":")
  186. if idx == -1:
  187. raise SynapseError(400, "Invalid ID: %r" % (string,))
  188. return string[idx + 1 :]
  189. def get_localpart_from_id(string: str) -> str:
  190. idx = string.find(":")
  191. if idx == -1:
  192. raise SynapseError(400, "Invalid ID: %r" % (string,))
  193. return string[1:idx]
  194. DS = TypeVar("DS", bound="DomainSpecificString")
  195. @attr.s(slots=True, frozen=True, repr=False, auto_attribs=True)
  196. class DomainSpecificString(metaclass=abc.ABCMeta):
  197. """Common base class among ID/name strings that have a local part and a
  198. domain name, prefixed with a sigil.
  199. Has the fields:
  200. 'localpart' : The local part of the name (without the leading sigil)
  201. 'domain' : The domain part of the name
  202. """
  203. SIGIL: ClassVar[str] = abc.abstractproperty() # type: ignore
  204. localpart: str
  205. domain: str
  206. # Because this is a frozen class, it is deeply immutable.
  207. def __copy__(self: DS) -> DS:
  208. return self
  209. def __deepcopy__(self: DS, memo: Dict[str, object]) -> DS:
  210. return self
  211. @classmethod
  212. def from_string(cls: Type[DS], s: str) -> DS:
  213. """Parse the string given by 's' into a structure object."""
  214. if len(s) < 1 or s[0:1] != cls.SIGIL:
  215. raise SynapseError(
  216. 400,
  217. "Expected %s string to start with '%s'" % (cls.__name__, cls.SIGIL),
  218. Codes.INVALID_PARAM,
  219. )
  220. parts = s[1:].split(":", 1)
  221. if len(parts) != 2:
  222. raise SynapseError(
  223. 400,
  224. "Expected %s of the form '%slocalname:domain'"
  225. % (cls.__name__, cls.SIGIL),
  226. Codes.INVALID_PARAM,
  227. )
  228. domain = parts[1]
  229. # This code will need changing if we want to support multiple domain
  230. # names on one HS
  231. return cls(localpart=parts[0], domain=domain)
  232. def to_string(self) -> str:
  233. """Return a string encoding the fields of the structure object."""
  234. return "%s%s:%s" % (self.SIGIL, self.localpart, self.domain)
  235. @classmethod
  236. def is_valid(cls: Type[DS], s: str) -> bool:
  237. """Parses the input string and attempts to ensure it is valid."""
  238. # TODO: this does not reject an empty localpart or an overly-long string.
  239. # See https://spec.matrix.org/v1.2/appendices/#identifier-grammar
  240. try:
  241. obj = cls.from_string(s)
  242. # Apply additional validation to the domain. This is only done
  243. # during is_valid (and not part of from_string) since it is
  244. # possible for invalid data to exist in room-state, etc.
  245. parse_and_validate_server_name(obj.domain)
  246. return True
  247. except Exception:
  248. return False
  249. __repr__ = to_string
  250. @attr.s(slots=True, frozen=True, repr=False)
  251. class UserID(DomainSpecificString):
  252. """Structure representing a user ID."""
  253. SIGIL = "@"
  254. @attr.s(slots=True, frozen=True, repr=False)
  255. class RoomAlias(DomainSpecificString):
  256. """Structure representing a room name."""
  257. SIGIL = "#"
  258. @attr.s(slots=True, frozen=True, repr=False)
  259. class RoomID(DomainSpecificString):
  260. """Structure representing a room id."""
  261. SIGIL = "!"
  262. @attr.s(slots=True, frozen=True, repr=False)
  263. class EventID(DomainSpecificString):
  264. """Structure representing an event id."""
  265. SIGIL = "$"
  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. 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: Match[bytes]) -> bytes:
  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 by converting to the hex equivalent.
  317. def f2(m: Match[bytes]) -> bytes:
  318. return b"=%02x" % (m.group()[0],)
  319. username = NON_MXID_CHARACTER_PATTERN.sub(f2, username)
  320. # we also do the =-escaping to mxids starting with an underscore.
  321. username = re.sub(b"^_", b"=5f", username)
  322. # we should now only have ascii bytes left, so can decode back to a string.
  323. return username.decode("ascii")
  324. @attr.s(frozen=True, slots=True, order=False)
  325. class RoomStreamToken:
  326. """Tokens are positions between events. The token "s1" comes after event 1.
  327. s0 s1
  328. | |
  329. [0] ▼ [1] ▼ [2]
  330. Tokens can either be a point in the live event stream or a cursor going
  331. through historic events.
  332. When traversing the live event stream, events are ordered by
  333. `stream_ordering` (when they arrived at the homeserver).
  334. When traversing historic events, events are first ordered by their `depth`
  335. (`topological_ordering` in the event graph) and tie-broken by
  336. `stream_ordering` (when the event arrived at the homeserver).
  337. If you're looking for more info about what a token with all of the
  338. underscores means, ex.
  339. `s2633508_17_338_6732159_1082514_541479_274711_265584_1`, see the docstring
  340. for `StreamToken` below.
  341. ---
  342. Live tokens start with an "s" followed by the `stream_ordering` of the event
  343. that comes before the position of the token. Said another way:
  344. `stream_ordering` uniquely identifies a persisted event. The live token
  345. means "the position just after the event identified by `stream_ordering`".
  346. An example token is:
  347. s2633508
  348. ---
  349. Historic tokens start with a "t" followed by the `depth`
  350. (`topological_ordering` in the event graph) of the event that comes before
  351. the position of the token, followed by "-", followed by the
  352. `stream_ordering` of the event that comes before the position of the token.
  353. An example token is:
  354. t426-2633508
  355. ---
  356. There is also a third mode for live tokens where the token starts with "m",
  357. which is sometimes used when using sharded event persisters. In this case
  358. the events stream is considered to be a set of streams (one for each writer)
  359. and the token encodes the vector clock of positions of each writer in their
  360. respective streams.
  361. The format of the token in such case is an initial integer min position,
  362. followed by the mapping of instance ID to position separated by '.' and '~':
  363. m{min_pos}~{writer1}.{pos1}~{writer2}.{pos2}. ...
  364. The `min_pos` corresponds to the minimum position all writers have persisted
  365. up to, and then only writers that are ahead of that position need to be
  366. encoded. An example token is:
  367. m56~2.58~3.59
  368. Which corresponds to a set of three (or more writers) where instances 2 and
  369. 3 (these are instance IDs that can be looked up in the DB to fetch the more
  370. commonly used instance names) are at positions 58 and 59 respectively, and
  371. all other instances are at position 56.
  372. Note: The `RoomStreamToken` cannot have both a topological part and an
  373. instance map.
  374. ---
  375. For caching purposes, `RoomStreamToken`s and by extension, all their
  376. attributes, must be hashable.
  377. """
  378. topological: Optional[int] = attr.ib(
  379. validator=attr.validators.optional(attr.validators.instance_of(int)),
  380. )
  381. stream: int = attr.ib(validator=attr.validators.instance_of(int))
  382. instance_map: "frozendict[str, int]" = attr.ib(
  383. factory=frozendict,
  384. validator=attr.validators.deep_mapping(
  385. key_validator=attr.validators.instance_of(str),
  386. value_validator=attr.validators.instance_of(int),
  387. mapping_validator=attr.validators.instance_of(frozendict),
  388. ),
  389. )
  390. def __attrs_post_init__(self) -> None:
  391. """Validates that both `topological` and `instance_map` aren't set."""
  392. if self.instance_map and self.topological:
  393. raise ValueError(
  394. "Cannot set both 'topological' and 'instance_map' on 'RoomStreamToken'."
  395. )
  396. @classmethod
  397. async def parse(cls, store: "PurgeEventsStore", string: str) -> "RoomStreamToken":
  398. try:
  399. if string[0] == "s":
  400. return cls(topological=None, stream=int(string[1:]))
  401. if string[0] == "t":
  402. parts = string[1:].split("-", 1)
  403. return cls(topological=int(parts[0]), stream=int(parts[1]))
  404. if string[0] == "m":
  405. parts = string[1:].split("~")
  406. stream = int(parts[0])
  407. instance_map = {}
  408. for part in parts[1:]:
  409. key, value = part.split(".")
  410. instance_id = int(key)
  411. pos = int(value)
  412. instance_name = await store.get_name_from_instance_id(instance_id) # type: ignore[attr-defined]
  413. instance_map[instance_name] = pos
  414. return cls(
  415. topological=None,
  416. stream=stream,
  417. instance_map=frozendict(instance_map),
  418. )
  419. except CancelledError:
  420. raise
  421. except Exception:
  422. pass
  423. raise SynapseError(400, "Invalid room stream token %r" % (string,))
  424. @classmethod
  425. def parse_stream_token(cls, string: str) -> "RoomStreamToken":
  426. try:
  427. if string[0] == "s":
  428. return cls(topological=None, stream=int(string[1:]))
  429. except Exception:
  430. pass
  431. raise SynapseError(400, "Invalid room stream token %r" % (string,))
  432. def copy_and_advance(self, other: "RoomStreamToken") -> "RoomStreamToken":
  433. """Return a new token such that if an event is after both this token and
  434. the other token, then its after the returned token too.
  435. """
  436. if self.topological or other.topological:
  437. raise Exception("Can't advance topological tokens")
  438. max_stream = max(self.stream, other.stream)
  439. instance_map = {
  440. instance: max(
  441. self.instance_map.get(instance, self.stream),
  442. other.instance_map.get(instance, other.stream),
  443. )
  444. for instance in set(self.instance_map).union(other.instance_map)
  445. }
  446. return RoomStreamToken(None, max_stream, frozendict(instance_map))
  447. def as_historical_tuple(self) -> Tuple[int, int]:
  448. """Returns a tuple of `(topological, stream)` for historical tokens.
  449. Raises if not an historical token (i.e. doesn't have a topological part).
  450. """
  451. if self.topological is None:
  452. raise Exception(
  453. "Cannot call `RoomStreamToken.as_historical_tuple` on live token"
  454. )
  455. return self.topological, self.stream
  456. def get_stream_pos_for_instance(self, instance_name: str) -> int:
  457. """Get the stream position that the given writer was at at this token.
  458. This only makes sense for "live" tokens that may have a vector clock
  459. component, and so asserts that this is a "live" token.
  460. """
  461. assert self.topological is None
  462. # If we don't have an entry for the instance we can assume that it was
  463. # at `self.stream`.
  464. return self.instance_map.get(instance_name, self.stream)
  465. def get_max_stream_pos(self) -> int:
  466. """Get the maximum stream position referenced in this token.
  467. The corresponding "min" position is, by definition just `self.stream`.
  468. This is used to handle tokens that have non-empty `instance_map`, and so
  469. reference stream positions after the `self.stream` position.
  470. """
  471. return max(self.instance_map.values(), default=self.stream)
  472. async def to_string(self, store: "DataStore") -> str:
  473. if self.topological is not None:
  474. return "t%d-%d" % (self.topological, self.stream)
  475. elif self.instance_map:
  476. entries = []
  477. for name, pos in self.instance_map.items():
  478. instance_id = await store.get_id_for_instance(name)
  479. entries.append(f"{instance_id}.{pos}")
  480. encoded_map = "~".join(entries)
  481. return f"m{self.stream}~{encoded_map}"
  482. else:
  483. return "s%d" % (self.stream,)
  484. class StreamKeyType:
  485. """Known stream types.
  486. A stream is a list of entities ordered by an incrementing "stream token".
  487. """
  488. ROOM: Final = "room_key"
  489. PRESENCE: Final = "presence_key"
  490. TYPING: Final = "typing_key"
  491. RECEIPT: Final = "receipt_key"
  492. ACCOUNT_DATA: Final = "account_data_key"
  493. PUSH_RULES: Final = "push_rules_key"
  494. TO_DEVICE: Final = "to_device_key"
  495. DEVICE_LIST: Final = "device_list_key"
  496. @attr.s(slots=True, frozen=True, auto_attribs=True)
  497. class StreamToken:
  498. """A collection of keys joined together by underscores in the following
  499. order and which represent the position in their respective streams.
  500. ex. `s2633508_17_338_6732159_1082514_541479_274711_265584_1`
  501. 1. `room_key`: `s2633508` which is a `RoomStreamToken`
  502. - `RoomStreamToken`'s can also look like `t426-2633508` or `m56~2.58~3.59`
  503. - See the docstring for `RoomStreamToken` for more details.
  504. 2. `presence_key`: `17`
  505. 3. `typing_key`: `338`
  506. 4. `receipt_key`: `6732159`
  507. 5. `account_data_key`: `1082514`
  508. 6. `push_rules_key`: `541479`
  509. 7. `to_device_key`: `274711`
  510. 8. `device_list_key`: `265584`
  511. 9. `groups_key`: `1` (note that this key is now unused)
  512. You can see how many of these keys correspond to the various
  513. fields in a "/sync" response:
  514. ```json
  515. {
  516. "next_batch": "s12_4_0_1_1_1_1_4_1",
  517. "presence": {
  518. "events": []
  519. },
  520. "device_lists": {
  521. "changed": []
  522. },
  523. "rooms": {
  524. "join": {
  525. "!QrZlfIDQLNLdZHqTnt:hs1": {
  526. "timeline": {
  527. "events": [],
  528. "prev_batch": "s10_4_0_1_1_1_1_4_1",
  529. "limited": false
  530. },
  531. "state": {
  532. "events": []
  533. },
  534. "account_data": {
  535. "events": []
  536. },
  537. "ephemeral": {
  538. "events": []
  539. }
  540. }
  541. }
  542. }
  543. }
  544. ```
  545. ---
  546. For caching purposes, `StreamToken`s and by extension, all their attributes,
  547. must be hashable.
  548. """
  549. room_key: RoomStreamToken = attr.ib(
  550. validator=attr.validators.instance_of(RoomStreamToken)
  551. )
  552. presence_key: int
  553. typing_key: int
  554. receipt_key: int
  555. account_data_key: int
  556. push_rules_key: int
  557. to_device_key: int
  558. device_list_key: int
  559. # Note that the groups key is no longer used and may have bogus values.
  560. groups_key: int
  561. _SEPARATOR = "_"
  562. START: ClassVar["StreamToken"]
  563. @classmethod
  564. async def from_string(cls, store: "DataStore", string: str) -> "StreamToken":
  565. try:
  566. keys = string.split(cls._SEPARATOR)
  567. while len(keys) < len(attr.fields(cls)):
  568. # i.e. old token from before receipt_key
  569. keys.append("0")
  570. return cls(
  571. await RoomStreamToken.parse(store, keys[0]), *(int(k) for k in keys[1:])
  572. )
  573. except CancelledError:
  574. raise
  575. except Exception:
  576. raise SynapseError(400, "Invalid stream token")
  577. async def to_string(self, store: "DataStore") -> str:
  578. return self._SEPARATOR.join(
  579. [
  580. await self.room_key.to_string(store),
  581. str(self.presence_key),
  582. str(self.typing_key),
  583. str(self.receipt_key),
  584. str(self.account_data_key),
  585. str(self.push_rules_key),
  586. str(self.to_device_key),
  587. str(self.device_list_key),
  588. # Note that the groups key is no longer used, but it is still
  589. # serialized so that there will not be confusion in the future
  590. # if additional tokens are added.
  591. str(self.groups_key),
  592. ]
  593. )
  594. @property
  595. def room_stream_id(self) -> int:
  596. return self.room_key.stream
  597. def copy_and_advance(self, key: str, new_value: Any) -> "StreamToken":
  598. """Advance the given key in the token to a new value if and only if the
  599. new value is after the old value.
  600. :raises TypeError: if `key` is not the one of the keys tracked by a StreamToken.
  601. """
  602. if key == StreamKeyType.ROOM:
  603. new_token = self.copy_and_replace(
  604. StreamKeyType.ROOM, self.room_key.copy_and_advance(new_value)
  605. )
  606. return new_token
  607. new_token = self.copy_and_replace(key, new_value)
  608. new_id = int(getattr(new_token, key))
  609. old_id = int(getattr(self, key))
  610. if old_id < new_id:
  611. return new_token
  612. else:
  613. return self
  614. def copy_and_replace(self, key: str, new_value: Any) -> "StreamToken":
  615. return attr.evolve(self, **{key: new_value})
  616. StreamToken.START = StreamToken(RoomStreamToken(None, 0), 0, 0, 0, 0, 0, 0, 0, 0)
  617. @attr.s(slots=True, frozen=True, auto_attribs=True)
  618. class PersistedEventPosition:
  619. """Position of a newly persisted event with instance that persisted it.
  620. This can be used to test whether the event is persisted before or after a
  621. RoomStreamToken.
  622. """
  623. instance_name: str
  624. stream: int
  625. def persisted_after(self, token: RoomStreamToken) -> bool:
  626. return token.get_stream_pos_for_instance(self.instance_name) < self.stream
  627. def to_room_stream_token(self) -> RoomStreamToken:
  628. """Converts the position to a room stream token such that events
  629. persisted in the same room after this position will be after the
  630. returned `RoomStreamToken`.
  631. Note: no guarantees are made about ordering w.r.t. events in other
  632. rooms.
  633. """
  634. # Doing the naive thing satisfies the desired properties described in
  635. # the docstring.
  636. return RoomStreamToken(None, self.stream)
  637. @attr.s(slots=True, frozen=True, auto_attribs=True)
  638. class ThirdPartyInstanceID:
  639. appservice_id: Optional[str]
  640. network_id: Optional[str]
  641. # Deny iteration because it will bite you if you try to create a singleton
  642. # set by:
  643. # users = set(user)
  644. def __iter__(self) -> NoReturn:
  645. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  646. # Because this class is a frozen class, it is deeply immutable.
  647. def __copy__(self) -> "ThirdPartyInstanceID":
  648. return self
  649. def __deepcopy__(self, memo: Dict[str, object]) -> "ThirdPartyInstanceID":
  650. return self
  651. @classmethod
  652. def from_string(cls, s: str) -> "ThirdPartyInstanceID":
  653. bits = s.split("|", 2)
  654. if len(bits) != 2:
  655. raise SynapseError(400, "Invalid ID %r" % (s,))
  656. return cls(appservice_id=bits[0], network_id=bits[1])
  657. def to_string(self) -> str:
  658. return "%s|%s" % (self.appservice_id, self.network_id)
  659. __str__ = to_string
  660. @attr.s(slots=True, frozen=True, auto_attribs=True)
  661. class ReadReceipt:
  662. """Information about a read-receipt"""
  663. room_id: str
  664. receipt_type: str
  665. user_id: str
  666. event_ids: List[str]
  667. data: JsonDict
  668. @attr.s(slots=True, frozen=True, auto_attribs=True)
  669. class DeviceListUpdates:
  670. """
  671. An object containing a diff of information regarding other users' device lists, intended for
  672. a recipient to carry out device list tracking.
  673. Attributes:
  674. changed: A set of users whose device lists have changed recently.
  675. left: A set of users who the recipient no longer needs to track the device lists of.
  676. Typically when those users no longer share any end-to-end encryption enabled rooms.
  677. """
  678. # We need to use a factory here, otherwise `set` is not evaluated at
  679. # object instantiation, but instead at class definition instantiation.
  680. # The latter happening only once, thus always giving you the same sets
  681. # across multiple DeviceListUpdates instances.
  682. # Also see: don't define mutable default arguments.
  683. changed: Set[str] = attr.ib(factory=set)
  684. left: Set[str] = attr.ib(factory=set)
  685. def __bool__(self) -> bool:
  686. return bool(self.changed or self.left)
  687. def get_verify_key_from_cross_signing_key(
  688. key_info: Mapping[str, Any]
  689. ) -> Tuple[str, VerifyKey]:
  690. """Get the key ID and signedjson verify key from a cross-signing key dict
  691. Args:
  692. key_info: a cross-signing key dict, which must have a "keys"
  693. property that has exactly one item in it
  694. Returns:
  695. the key ID and verify key for the cross-signing key
  696. """
  697. # make sure that a `keys` field is provided
  698. if "keys" not in key_info:
  699. raise ValueError("Invalid key")
  700. keys = key_info["keys"]
  701. # and that it contains exactly one key
  702. if len(keys) == 1:
  703. key_id, key_data = next(iter(keys.items()))
  704. return key_id, decode_verify_key_bytes(key_id, decode_base64(key_data))
  705. else:
  706. raise ValueError("Invalid key")
  707. @attr.s(auto_attribs=True, frozen=True, slots=True)
  708. class UserInfo:
  709. """Holds information about a user. Result of get_userinfo_by_id.
  710. Attributes:
  711. user_id: ID of the user.
  712. appservice_id: Application service ID that created this user.
  713. consent_server_notice_sent: Version of policy documents the user has been sent.
  714. consent_version: Version of policy documents the user has consented to.
  715. creation_ts: Creation timestamp of the user.
  716. is_admin: True if the user is an admin.
  717. is_deactivated: True if the user has been deactivated.
  718. is_guest: True if the user is a guest user.
  719. is_shadow_banned: True if the user has been shadow-banned.
  720. user_type: User type (None for normal user, 'support' and 'bot' other options).
  721. """
  722. user_id: UserID
  723. appservice_id: Optional[int]
  724. consent_server_notice_sent: Optional[str]
  725. consent_version: Optional[str]
  726. user_type: Optional[str]
  727. creation_ts: int
  728. is_admin: bool
  729. is_deactivated: bool
  730. is_guest: bool
  731. is_shadow_banned: bool
  732. class UserProfile(TypedDict):
  733. user_id: str
  734. display_name: Optional[str]
  735. avatar_url: Optional[str]
  736. @attr.s(auto_attribs=True, frozen=True, slots=True)
  737. class RetentionPolicy:
  738. min_lifetime: Optional[int] = None
  739. max_lifetime: Optional[int] = None