You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

947 lines
31 KiB

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