types.py 30 KB

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