event_auth.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  3. # Copyright 2020 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from typing import List, Optional, Set, Tuple
  18. from canonicaljson import encode_canonical_json
  19. from signedjson.key import decode_verify_key_bytes
  20. from signedjson.sign import SignatureVerifyException, verify_signed_json
  21. from unpaddedbase64 import decode_base64
  22. from synapse.api.constants import EventTypes, JoinRules, Membership
  23. from synapse.api.errors import AuthError, EventSizeError, SynapseError
  24. from synapse.api.room_versions import (
  25. KNOWN_ROOM_VERSIONS,
  26. EventFormatVersions,
  27. RoomVersion,
  28. )
  29. from synapse.events import EventBase
  30. from synapse.types import StateMap, UserID, get_domain_from_id
  31. logger = logging.getLogger(__name__)
  32. def check(
  33. room_version_obj: RoomVersion,
  34. event: EventBase,
  35. auth_events: StateMap[EventBase],
  36. do_sig_check: bool = True,
  37. do_size_check: bool = True,
  38. ) -> None:
  39. """ Checks if this event is correctly authed.
  40. Args:
  41. room_version_obj: the version of the room
  42. event: the event being checked.
  43. auth_events (dict: event-key -> event): the existing room state.
  44. Raises:
  45. AuthError if the checks fail
  46. Returns:
  47. if the auth checks pass.
  48. """
  49. assert isinstance(auth_events, dict)
  50. if do_size_check:
  51. _check_size_limits(event)
  52. if not hasattr(event, "room_id"):
  53. raise AuthError(500, "Event has no room_id: %s" % event)
  54. room_id = event.room_id
  55. # We need to ensure that the auth events are actually for the same room, to
  56. # stop people from using powers they've been granted in other rooms for
  57. # example.
  58. for auth_event in auth_events.values():
  59. if auth_event.room_id != room_id:
  60. raise AuthError(
  61. 403,
  62. "During auth for event %s in room %s, found event %s in the state "
  63. "which is in room %s"
  64. % (event.event_id, room_id, auth_event.event_id, auth_event.room_id),
  65. )
  66. if do_sig_check:
  67. sender_domain = get_domain_from_id(event.sender)
  68. is_invite_via_3pid = (
  69. event.type == EventTypes.Member
  70. and event.membership == Membership.INVITE
  71. and "third_party_invite" in event.content
  72. )
  73. # Check the sender's domain has signed the event
  74. if not event.signatures.get(sender_domain):
  75. # We allow invites via 3pid to have a sender from a different
  76. # HS, as the sender must match the sender of the original
  77. # 3pid invite. This is checked further down with the
  78. # other dedicated membership checks.
  79. if not is_invite_via_3pid:
  80. raise AuthError(403, "Event not signed by sender's server")
  81. if event.format_version in (EventFormatVersions.V1,):
  82. # Only older room versions have event IDs to check.
  83. event_id_domain = get_domain_from_id(event.event_id)
  84. # Check the origin domain has signed the event
  85. if not event.signatures.get(event_id_domain):
  86. raise AuthError(403, "Event not signed by sending server")
  87. # Implementation of https://matrix.org/docs/spec/rooms/v1#authorization-rules
  88. #
  89. # 1. If type is m.room.create:
  90. if event.type == EventTypes.Create:
  91. # 1b. If the domain of the room_id does not match the domain of the sender,
  92. # reject.
  93. sender_domain = get_domain_from_id(event.sender)
  94. room_id_domain = get_domain_from_id(event.room_id)
  95. if room_id_domain != sender_domain:
  96. raise AuthError(
  97. 403, "Creation event's room_id domain does not match sender's"
  98. )
  99. # 1c. If content.room_version is present and is not a recognised version, reject
  100. room_version_prop = event.content.get("room_version", "1")
  101. if room_version_prop not in KNOWN_ROOM_VERSIONS:
  102. raise AuthError(
  103. 403,
  104. "room appears to have unsupported version %s" % (room_version_prop,),
  105. )
  106. logger.debug("Allowing! %s", event)
  107. return
  108. # 3. If event does not have a m.room.create in its auth_events, reject.
  109. creation_event = auth_events.get((EventTypes.Create, ""), None)
  110. if not creation_event:
  111. raise AuthError(403, "No create event in auth events")
  112. # additional check for m.federate
  113. creating_domain = get_domain_from_id(event.room_id)
  114. originating_domain = get_domain_from_id(event.sender)
  115. if creating_domain != originating_domain:
  116. if not _can_federate(event, auth_events):
  117. raise AuthError(403, "This room has been marked as unfederatable.")
  118. # 4. If type is m.room.aliases
  119. if event.type == EventTypes.Aliases and room_version_obj.special_case_aliases_auth:
  120. # 4a. If event has no state_key, reject
  121. if not event.is_state():
  122. raise AuthError(403, "Alias event must be a state event")
  123. if not event.state_key:
  124. raise AuthError(403, "Alias event must have non-empty state_key")
  125. # 4b. If sender's domain doesn't matches [sic] state_key, reject
  126. sender_domain = get_domain_from_id(event.sender)
  127. if event.state_key != sender_domain:
  128. raise AuthError(
  129. 403, "Alias event's state_key does not match sender's domain"
  130. )
  131. # 4c. Otherwise, allow.
  132. logger.debug("Allowing! %s", event)
  133. return
  134. if logger.isEnabledFor(logging.DEBUG):
  135. logger.debug("Auth events: %s", [a.event_id for a in auth_events.values()])
  136. if event.type == EventTypes.Member:
  137. _is_membership_change_allowed(event, auth_events)
  138. logger.debug("Allowing! %s", event)
  139. return
  140. _check_event_sender_in_room(event, auth_events)
  141. # Special case to allow m.room.third_party_invite events wherever
  142. # a user is allowed to issue invites. Fixes
  143. # https://github.com/vector-im/vector-web/issues/1208 hopefully
  144. if event.type == EventTypes.ThirdPartyInvite:
  145. user_level = get_user_power_level(event.user_id, auth_events)
  146. invite_level = _get_named_level(auth_events, "invite", 0)
  147. if user_level < invite_level:
  148. raise AuthError(403, "You don't have permission to invite users")
  149. else:
  150. logger.debug("Allowing! %s", event)
  151. return
  152. _can_send_event(event, auth_events)
  153. if event.type == EventTypes.PowerLevels:
  154. _check_power_levels(room_version_obj, event, auth_events)
  155. if event.type == EventTypes.Redaction:
  156. check_redaction(room_version_obj, event, auth_events)
  157. logger.debug("Allowing! %s", event)
  158. def _check_size_limits(event: EventBase) -> None:
  159. def too_big(field):
  160. raise EventSizeError("%s too large" % (field,))
  161. if len(event.user_id) > 255:
  162. too_big("user_id")
  163. if len(event.room_id) > 255:
  164. too_big("room_id")
  165. if event.is_state() and len(event.state_key) > 255:
  166. too_big("state_key")
  167. if len(event.type) > 255:
  168. too_big("type")
  169. if len(event.event_id) > 255:
  170. too_big("event_id")
  171. if len(encode_canonical_json(event.get_pdu_json())) > 65536:
  172. too_big("event")
  173. def _can_federate(event: EventBase, auth_events: StateMap[EventBase]) -> bool:
  174. creation_event = auth_events.get((EventTypes.Create, ""))
  175. # There should always be a creation event, but if not don't federate.
  176. if not creation_event:
  177. return False
  178. return creation_event.content.get("m.federate", True) is True
  179. def _is_membership_change_allowed(
  180. event: EventBase, auth_events: StateMap[EventBase]
  181. ) -> None:
  182. membership = event.content["membership"]
  183. # Check if this is the room creator joining:
  184. if len(event.prev_event_ids()) == 1 and Membership.JOIN == membership:
  185. # Get room creation event:
  186. key = (EventTypes.Create, "")
  187. create = auth_events.get(key)
  188. if create and event.prev_event_ids()[0] == create.event_id:
  189. if create.content["creator"] == event.state_key:
  190. return
  191. target_user_id = event.state_key
  192. creating_domain = get_domain_from_id(event.room_id)
  193. target_domain = get_domain_from_id(target_user_id)
  194. if creating_domain != target_domain:
  195. if not _can_federate(event, auth_events):
  196. raise AuthError(403, "This room has been marked as unfederatable.")
  197. # get info about the caller
  198. key = (EventTypes.Member, event.user_id)
  199. caller = auth_events.get(key)
  200. caller_in_room = caller and caller.membership == Membership.JOIN
  201. caller_invited = caller and caller.membership == Membership.INVITE
  202. # get info about the target
  203. key = (EventTypes.Member, target_user_id)
  204. target = auth_events.get(key)
  205. target_in_room = target and target.membership == Membership.JOIN
  206. target_banned = target and target.membership == Membership.BAN
  207. key = (EventTypes.JoinRules, "")
  208. join_rule_event = auth_events.get(key)
  209. if join_rule_event:
  210. join_rule = join_rule_event.content.get("join_rule", JoinRules.INVITE)
  211. else:
  212. join_rule = JoinRules.INVITE
  213. user_level = get_user_power_level(event.user_id, auth_events)
  214. target_level = get_user_power_level(target_user_id, auth_events)
  215. # FIXME (erikj): What should we do here as the default?
  216. ban_level = _get_named_level(auth_events, "ban", 50)
  217. logger.debug(
  218. "_is_membership_change_allowed: %s",
  219. {
  220. "caller_in_room": caller_in_room,
  221. "caller_invited": caller_invited,
  222. "target_banned": target_banned,
  223. "target_in_room": target_in_room,
  224. "membership": membership,
  225. "join_rule": join_rule,
  226. "target_user_id": target_user_id,
  227. "event.user_id": event.user_id,
  228. },
  229. )
  230. if Membership.INVITE == membership and "third_party_invite" in event.content:
  231. if not _verify_third_party_invite(event, auth_events):
  232. raise AuthError(403, "You are not invited to this room.")
  233. if target_banned:
  234. raise AuthError(403, "%s is banned from the room" % (target_user_id,))
  235. return
  236. if Membership.JOIN != membership:
  237. if (
  238. caller_invited
  239. and Membership.LEAVE == membership
  240. and target_user_id == event.user_id
  241. ):
  242. return
  243. if not caller_in_room: # caller isn't joined
  244. raise AuthError(403, "%s not in room %s." % (event.user_id, event.room_id))
  245. if Membership.INVITE == membership:
  246. # TODO (erikj): We should probably handle this more intelligently
  247. # PRIVATE join rules.
  248. # Invites are valid iff caller is in the room and target isn't.
  249. if target_banned:
  250. raise AuthError(403, "%s is banned from the room" % (target_user_id,))
  251. elif target_in_room: # the target is already in the room.
  252. raise AuthError(403, "%s is already in the room." % target_user_id)
  253. else:
  254. invite_level = _get_named_level(auth_events, "invite", 0)
  255. if user_level < invite_level:
  256. raise AuthError(403, "You don't have permission to invite users")
  257. elif Membership.JOIN == membership:
  258. # Joins are valid iff caller == target and they were:
  259. # invited: They are accepting the invitation
  260. # joined: It's a NOOP
  261. if event.user_id != target_user_id:
  262. raise AuthError(403, "Cannot force another user to join.")
  263. elif target_banned:
  264. raise AuthError(403, "You are banned from this room")
  265. elif join_rule == JoinRules.PUBLIC:
  266. pass
  267. elif join_rule == JoinRules.INVITE:
  268. if not caller_in_room and not caller_invited:
  269. raise AuthError(403, "You are not invited to this room.")
  270. else:
  271. # TODO (erikj): may_join list
  272. # TODO (erikj): private rooms
  273. raise AuthError(403, "You are not allowed to join this room")
  274. elif Membership.LEAVE == membership:
  275. # TODO (erikj): Implement kicks.
  276. if target_banned and user_level < ban_level:
  277. raise AuthError(403, "You cannot unban user %s." % (target_user_id,))
  278. elif target_user_id != event.user_id:
  279. kick_level = _get_named_level(auth_events, "kick", 50)
  280. if user_level < kick_level or user_level <= target_level:
  281. raise AuthError(403, "You cannot kick user %s." % target_user_id)
  282. elif Membership.BAN == membership:
  283. if user_level < ban_level or user_level <= target_level:
  284. raise AuthError(403, "You don't have permission to ban")
  285. else:
  286. raise AuthError(500, "Unknown membership %s" % membership)
  287. def _check_event_sender_in_room(
  288. event: EventBase, auth_events: StateMap[EventBase]
  289. ) -> None:
  290. key = (EventTypes.Member, event.user_id)
  291. member_event = auth_events.get(key)
  292. _check_joined_room(member_event, event.user_id, event.room_id)
  293. def _check_joined_room(member: Optional[EventBase], user_id: str, room_id: str) -> None:
  294. if not member or member.membership != Membership.JOIN:
  295. raise AuthError(
  296. 403, "User %s not in room %s (%s)" % (user_id, room_id, repr(member))
  297. )
  298. def get_send_level(
  299. etype: str, state_key: Optional[str], power_levels_event: Optional[EventBase]
  300. ) -> int:
  301. """Get the power level required to send an event of a given type
  302. The federation spec [1] refers to this as "Required Power Level".
  303. https://matrix.org/docs/spec/server_server/unstable.html#definitions
  304. Args:
  305. etype: type of event
  306. state_key: state_key of state event, or None if it is not
  307. a state event.
  308. power_levels_event: power levels event
  309. in force at this point in the room
  310. Returns:
  311. power level required to send this event.
  312. """
  313. if power_levels_event:
  314. power_levels_content = power_levels_event.content
  315. else:
  316. power_levels_content = {}
  317. # see if we have a custom level for this event type
  318. send_level = power_levels_content.get("events", {}).get(etype)
  319. # otherwise, fall back to the state_default/events_default.
  320. if send_level is None:
  321. if state_key is not None:
  322. send_level = power_levels_content.get("state_default", 50)
  323. else:
  324. send_level = power_levels_content.get("events_default", 0)
  325. return int(send_level)
  326. def _can_send_event(event: EventBase, auth_events: StateMap[EventBase]) -> bool:
  327. power_levels_event = _get_power_level_event(auth_events)
  328. send_level = get_send_level(event.type, event.get("state_key"), power_levels_event)
  329. user_level = get_user_power_level(event.user_id, auth_events)
  330. if user_level < send_level:
  331. raise AuthError(
  332. 403,
  333. "You don't have permission to post that to the room. "
  334. + "user_level (%d) < send_level (%d)" % (user_level, send_level),
  335. )
  336. # Check state_key
  337. if hasattr(event, "state_key"):
  338. if event.state_key.startswith("@"):
  339. if event.state_key != event.user_id:
  340. raise AuthError(403, "You are not allowed to set others state")
  341. return True
  342. def check_redaction(
  343. room_version_obj: RoomVersion, event: EventBase, auth_events: StateMap[EventBase],
  344. ) -> bool:
  345. """Check whether the event sender is allowed to redact the target event.
  346. Returns:
  347. True if the the sender is allowed to redact the target event if the
  348. target event was created by them.
  349. False if the sender is allowed to redact the target event with no
  350. further checks.
  351. Raises:
  352. AuthError if the event sender is definitely not allowed to redact
  353. the target event.
  354. """
  355. user_level = get_user_power_level(event.user_id, auth_events)
  356. redact_level = _get_named_level(auth_events, "redact", 50)
  357. if user_level >= redact_level:
  358. return False
  359. if room_version_obj.event_format == EventFormatVersions.V1:
  360. redacter_domain = get_domain_from_id(event.event_id)
  361. redactee_domain = get_domain_from_id(event.redacts)
  362. if redacter_domain == redactee_domain:
  363. return True
  364. else:
  365. event.internal_metadata.recheck_redaction = True
  366. return True
  367. raise AuthError(403, "You don't have permission to redact events")
  368. def _check_power_levels(
  369. room_version_obj: RoomVersion, event: EventBase, auth_events: StateMap[EventBase],
  370. ) -> None:
  371. user_list = event.content.get("users", {})
  372. # Validate users
  373. for k, v in user_list.items():
  374. try:
  375. UserID.from_string(k)
  376. except Exception:
  377. raise SynapseError(400, "Not a valid user_id: %s" % (k,))
  378. try:
  379. int(v)
  380. except Exception:
  381. raise SynapseError(400, "Not a valid power level: %s" % (v,))
  382. key = (event.type, event.state_key)
  383. current_state = auth_events.get(key)
  384. if not current_state:
  385. return
  386. user_level = get_user_power_level(event.user_id, auth_events)
  387. # Check other levels:
  388. levels_to_check = [
  389. ("users_default", None),
  390. ("events_default", None),
  391. ("state_default", None),
  392. ("ban", None),
  393. ("redact", None),
  394. ("kick", None),
  395. ("invite", None),
  396. ] # type: List[Tuple[str, Optional[str]]]
  397. old_list = current_state.content.get("users", {})
  398. for user in set(list(old_list) + list(user_list)):
  399. levels_to_check.append((user, "users"))
  400. old_list = current_state.content.get("events", {})
  401. new_list = event.content.get("events", {})
  402. for ev_id in set(list(old_list) + list(new_list)):
  403. levels_to_check.append((ev_id, "events"))
  404. # MSC2209 specifies these checks should also be done for the "notifications"
  405. # key.
  406. if room_version_obj.limit_notifications_power_levels:
  407. old_list = current_state.content.get("notifications", {})
  408. new_list = event.content.get("notifications", {})
  409. for ev_id in set(list(old_list) + list(new_list)):
  410. levels_to_check.append((ev_id, "notifications"))
  411. old_state = current_state.content
  412. new_state = event.content
  413. for level_to_check, dir in levels_to_check:
  414. old_loc = old_state
  415. new_loc = new_state
  416. if dir:
  417. old_loc = old_loc.get(dir, {})
  418. new_loc = new_loc.get(dir, {})
  419. if level_to_check in old_loc:
  420. old_level = int(old_loc[level_to_check]) # type: Optional[int]
  421. else:
  422. old_level = None
  423. if level_to_check in new_loc:
  424. new_level = int(new_loc[level_to_check]) # type: Optional[int]
  425. else:
  426. new_level = None
  427. if new_level is not None and old_level is not None:
  428. if new_level == old_level:
  429. continue
  430. if dir == "users" and level_to_check != event.user_id:
  431. if old_level == user_level:
  432. raise AuthError(
  433. 403,
  434. "You don't have permission to remove ops level equal "
  435. "to your own",
  436. )
  437. # Check if the old and new levels are greater than the user level
  438. # (if defined)
  439. old_level_too_big = old_level is not None and old_level > user_level
  440. new_level_too_big = new_level is not None and new_level > user_level
  441. if old_level_too_big or new_level_too_big:
  442. raise AuthError(
  443. 403, "You don't have permission to add ops level greater than your own"
  444. )
  445. def _get_power_level_event(auth_events: StateMap[EventBase]) -> Optional[EventBase]:
  446. return auth_events.get((EventTypes.PowerLevels, ""))
  447. def get_user_power_level(user_id: str, auth_events: StateMap[EventBase]) -> int:
  448. """Get a user's power level
  449. Args:
  450. user_id: user's id to look up in power_levels
  451. auth_events:
  452. state in force at this point in the room (or rather, a subset of
  453. it including at least the create event and power levels event.
  454. Returns:
  455. the user's power level in this room.
  456. """
  457. power_level_event = _get_power_level_event(auth_events)
  458. if power_level_event:
  459. level = power_level_event.content.get("users", {}).get(user_id)
  460. if not level:
  461. level = power_level_event.content.get("users_default", 0)
  462. if level is None:
  463. return 0
  464. else:
  465. return int(level)
  466. else:
  467. # if there is no power levels event, the creator gets 100 and everyone
  468. # else gets 0.
  469. # some things which call this don't pass the create event: hack around
  470. # that.
  471. key = (EventTypes.Create, "")
  472. create_event = auth_events.get(key)
  473. if create_event is not None and create_event.content["creator"] == user_id:
  474. return 100
  475. else:
  476. return 0
  477. def _get_named_level(auth_events: StateMap[EventBase], name: str, default: int) -> int:
  478. power_level_event = _get_power_level_event(auth_events)
  479. if not power_level_event:
  480. return default
  481. level = power_level_event.content.get(name, None)
  482. if level is not None:
  483. return int(level)
  484. else:
  485. return default
  486. def _verify_third_party_invite(event: EventBase, auth_events: StateMap[EventBase]):
  487. """
  488. Validates that the invite event is authorized by a previous third-party invite.
  489. Checks that the public key, and keyserver, match those in the third party invite,
  490. and that the invite event has a signature issued using that public key.
  491. Args:
  492. event: The m.room.member join event being validated.
  493. auth_events: All relevant previous context events which may be used
  494. for authorization decisions.
  495. Return:
  496. True if the event fulfills the expectations of a previous third party
  497. invite event.
  498. """
  499. if "third_party_invite" not in event.content:
  500. return False
  501. if "signed" not in event.content["third_party_invite"]:
  502. return False
  503. signed = event.content["third_party_invite"]["signed"]
  504. for key in {"mxid", "token"}:
  505. if key not in signed:
  506. return False
  507. token = signed["token"]
  508. invite_event = auth_events.get((EventTypes.ThirdPartyInvite, token))
  509. if not invite_event:
  510. return False
  511. if invite_event.sender != event.sender:
  512. return False
  513. if event.user_id != invite_event.user_id:
  514. return False
  515. if signed["mxid"] != event.state_key:
  516. return False
  517. if signed["token"] != token:
  518. return False
  519. for public_key_object in get_public_keys(invite_event):
  520. public_key = public_key_object["public_key"]
  521. try:
  522. for server, signature_block in signed["signatures"].items():
  523. for key_name, encoded_signature in signature_block.items():
  524. if not key_name.startswith("ed25519:"):
  525. continue
  526. verify_key = decode_verify_key_bytes(
  527. key_name, decode_base64(public_key)
  528. )
  529. verify_signed_json(signed, server, verify_key)
  530. # We got the public key from the invite, so we know that the
  531. # correct server signed the signed bundle.
  532. # The caller is responsible for checking that the signing
  533. # server has not revoked that public key.
  534. return True
  535. except (KeyError, SignatureVerifyException):
  536. continue
  537. return False
  538. def get_public_keys(invite_event):
  539. public_keys = []
  540. if "public_key" in invite_event.content:
  541. o = {"public_key": invite_event.content["public_key"]}
  542. if "key_validity_url" in invite_event.content:
  543. o["key_validity_url"] = invite_event.content["key_validity_url"]
  544. public_keys.append(o)
  545. public_keys.extend(invite_event.content.get("public_keys", []))
  546. return public_keys
  547. def auth_types_for_event(event: EventBase) -> Set[Tuple[str, str]]:
  548. """Given an event, return a list of (EventType, StateKey) that may be
  549. needed to auth the event. The returned list may be a superset of what
  550. would actually be required depending on the full state of the room.
  551. Used to limit the number of events to fetch from the database to
  552. actually auth the event.
  553. """
  554. if event.type == EventTypes.Create:
  555. return set()
  556. auth_types = {
  557. (EventTypes.PowerLevels, ""),
  558. (EventTypes.Member, event.sender),
  559. (EventTypes.Create, ""),
  560. }
  561. if event.type == EventTypes.Member:
  562. membership = event.content["membership"]
  563. if membership in [Membership.JOIN, Membership.INVITE]:
  564. auth_types.add((EventTypes.JoinRules, ""))
  565. auth_types.add((EventTypes.Member, event.state_key))
  566. if membership == Membership.INVITE:
  567. if "third_party_invite" in event.content:
  568. key = (
  569. EventTypes.ThirdPartyInvite,
  570. event.content["third_party_invite"]["signed"]["token"],
  571. )
  572. auth_types.add(key)
  573. return auth_types