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.
 
 
 
 
 
 

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