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.
 
 
 
 
 
 

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