event_auth.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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: 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(room_version_obj, 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. room_version: RoomVersion, event: EventBase, auth_events: StateMap[EventBase]
  181. ) -> None:
  182. """
  183. Confirms that the event which changes membership is an allowed change.
  184. Args:
  185. room_version: The version of the room.
  186. event: The event to check.
  187. auth_events: The current auth events of the room.
  188. Raises:
  189. AuthError if the event is not allowed.
  190. """
  191. membership = event.content["membership"]
  192. # Check if this is the room creator joining:
  193. if len(event.prev_event_ids()) == 1 and Membership.JOIN == membership:
  194. # Get room creation event:
  195. key = (EventTypes.Create, "")
  196. create = auth_events.get(key)
  197. if create and event.prev_event_ids()[0] == create.event_id:
  198. if create.content["creator"] == event.state_key:
  199. return
  200. target_user_id = event.state_key
  201. creating_domain = get_domain_from_id(event.room_id)
  202. target_domain = get_domain_from_id(target_user_id)
  203. if creating_domain != target_domain:
  204. if not _can_federate(event, auth_events):
  205. raise AuthError(403, "This room has been marked as unfederatable.")
  206. # get info about the caller
  207. key = (EventTypes.Member, event.user_id)
  208. caller = auth_events.get(key)
  209. caller_in_room = caller and caller.membership == Membership.JOIN
  210. caller_invited = caller and caller.membership == Membership.INVITE
  211. # get info about the target
  212. key = (EventTypes.Member, target_user_id)
  213. target = auth_events.get(key)
  214. target_in_room = target and target.membership == Membership.JOIN
  215. target_banned = target and target.membership == Membership.BAN
  216. key = (EventTypes.JoinRules, "")
  217. join_rule_event = auth_events.get(key)
  218. if join_rule_event:
  219. join_rule = join_rule_event.content.get("join_rule", JoinRules.INVITE)
  220. else:
  221. join_rule = JoinRules.INVITE
  222. user_level = get_user_power_level(event.user_id, auth_events)
  223. target_level = get_user_power_level(target_user_id, auth_events)
  224. # FIXME (erikj): What should we do here as the default?
  225. ban_level = _get_named_level(auth_events, "ban", 50)
  226. logger.debug(
  227. "_is_membership_change_allowed: %s",
  228. {
  229. "caller_in_room": caller_in_room,
  230. "caller_invited": caller_invited,
  231. "target_banned": target_banned,
  232. "target_in_room": target_in_room,
  233. "membership": membership,
  234. "join_rule": join_rule,
  235. "target_user_id": target_user_id,
  236. "event.user_id": event.user_id,
  237. },
  238. )
  239. if Membership.INVITE == membership and "third_party_invite" in event.content:
  240. if not _verify_third_party_invite(event, auth_events):
  241. raise AuthError(403, "You are not invited to this room.")
  242. if target_banned:
  243. raise AuthError(403, "%s is banned from the room" % (target_user_id,))
  244. return
  245. if Membership.JOIN != membership:
  246. if (
  247. caller_invited
  248. and Membership.LEAVE == membership
  249. and target_user_id == event.user_id
  250. ):
  251. return
  252. if not caller_in_room: # caller isn't joined
  253. raise AuthError(403, "%s not in room %s." % (event.user_id, event.room_id))
  254. if Membership.INVITE == membership:
  255. # TODO (erikj): We should probably handle this more intelligently
  256. # PRIVATE join rules.
  257. # Invites are valid iff caller is in the room and target isn't.
  258. if target_banned:
  259. raise AuthError(403, "%s is banned from the room" % (target_user_id,))
  260. elif target_in_room: # the target is already in the room.
  261. raise AuthError(403, "%s is already in the room." % target_user_id)
  262. else:
  263. invite_level = _get_named_level(auth_events, "invite", 0)
  264. if user_level < invite_level:
  265. raise AuthError(403, "You don't have permission to invite users")
  266. elif Membership.JOIN == membership:
  267. # Joins are valid iff caller == target and:
  268. # * They are not banned.
  269. # * They are accepting a previously sent invitation.
  270. # * They are already joined (it's a NOOP).
  271. # * The room is public or restricted.
  272. if event.user_id != target_user_id:
  273. raise AuthError(403, "Cannot force another user to join.")
  274. elif target_banned:
  275. raise AuthError(403, "You are banned from this room")
  276. elif join_rule == JoinRules.PUBLIC or (
  277. room_version.msc3083_join_rules
  278. and join_rule == JoinRules.MSC3083_RESTRICTED
  279. ):
  280. pass
  281. elif join_rule == JoinRules.INVITE:
  282. if not caller_in_room and not caller_invited:
  283. raise AuthError(403, "You are not invited to this room.")
  284. else:
  285. # TODO (erikj): may_join list
  286. # TODO (erikj): private rooms
  287. raise AuthError(403, "You are not allowed to join this room")
  288. elif Membership.LEAVE == membership:
  289. # TODO (erikj): Implement kicks.
  290. if target_banned and user_level < ban_level:
  291. raise AuthError(403, "You cannot unban user %s." % (target_user_id,))
  292. elif target_user_id != event.user_id:
  293. kick_level = _get_named_level(auth_events, "kick", 50)
  294. if user_level < kick_level or user_level <= target_level:
  295. raise AuthError(403, "You cannot kick user %s." % target_user_id)
  296. elif Membership.BAN == membership:
  297. if user_level < ban_level or user_level <= target_level:
  298. raise AuthError(403, "You don't have permission to ban")
  299. else:
  300. raise AuthError(500, "Unknown membership %s" % membership)
  301. def _check_event_sender_in_room(
  302. event: EventBase, auth_events: StateMap[EventBase]
  303. ) -> None:
  304. key = (EventTypes.Member, event.user_id)
  305. member_event = auth_events.get(key)
  306. _check_joined_room(member_event, event.user_id, event.room_id)
  307. def _check_joined_room(member: Optional[EventBase], user_id: str, room_id: str) -> None:
  308. if not member or member.membership != Membership.JOIN:
  309. raise AuthError(
  310. 403, "User %s not in room %s (%s)" % (user_id, room_id, repr(member))
  311. )
  312. def get_send_level(
  313. etype: str, state_key: Optional[str], power_levels_event: Optional[EventBase]
  314. ) -> int:
  315. """Get the power level required to send an event of a given type
  316. The federation spec [1] refers to this as "Required Power Level".
  317. https://matrix.org/docs/spec/server_server/unstable.html#definitions
  318. Args:
  319. etype: type of event
  320. state_key: state_key of state event, or None if it is not
  321. a state event.
  322. power_levels_event: power levels event
  323. in force at this point in the room
  324. Returns:
  325. power level required to send this event.
  326. """
  327. if power_levels_event:
  328. power_levels_content = power_levels_event.content
  329. else:
  330. power_levels_content = {}
  331. # see if we have a custom level for this event type
  332. send_level = power_levels_content.get("events", {}).get(etype)
  333. # otherwise, fall back to the state_default/events_default.
  334. if send_level is None:
  335. if state_key is not None:
  336. send_level = power_levels_content.get("state_default", 50)
  337. else:
  338. send_level = power_levels_content.get("events_default", 0)
  339. return int(send_level)
  340. def _can_send_event(event: EventBase, auth_events: StateMap[EventBase]) -> bool:
  341. power_levels_event = _get_power_level_event(auth_events)
  342. send_level = get_send_level(event.type, event.get("state_key"), power_levels_event)
  343. user_level = get_user_power_level(event.user_id, auth_events)
  344. if user_level < send_level:
  345. raise AuthError(
  346. 403,
  347. "You don't have permission to post that to the room. "
  348. + "user_level (%d) < send_level (%d)" % (user_level, send_level),
  349. )
  350. # Check state_key
  351. if hasattr(event, "state_key"):
  352. if event.state_key.startswith("@"):
  353. if event.state_key != event.user_id:
  354. raise AuthError(403, "You are not allowed to set others state")
  355. return True
  356. def check_redaction(
  357. room_version_obj: RoomVersion,
  358. event: EventBase,
  359. auth_events: StateMap[EventBase],
  360. ) -> bool:
  361. """Check whether the event sender is allowed to redact the target event.
  362. Returns:
  363. True if the the sender is allowed to redact the target event if the
  364. target event was created by them.
  365. False if the sender is allowed to redact the target event with no
  366. further checks.
  367. Raises:
  368. AuthError if the event sender is definitely not allowed to redact
  369. the target event.
  370. """
  371. user_level = get_user_power_level(event.user_id, auth_events)
  372. redact_level = _get_named_level(auth_events, "redact", 50)
  373. if user_level >= redact_level:
  374. return False
  375. if room_version_obj.event_format == EventFormatVersions.V1:
  376. redacter_domain = get_domain_from_id(event.event_id)
  377. if not isinstance(event.redacts, str):
  378. return False
  379. redactee_domain = get_domain_from_id(event.redacts)
  380. if redacter_domain == redactee_domain:
  381. return True
  382. else:
  383. event.internal_metadata.recheck_redaction = True
  384. return True
  385. raise AuthError(403, "You don't have permission to redact events")
  386. def _check_power_levels(
  387. room_version_obj: RoomVersion,
  388. event: EventBase,
  389. auth_events: StateMap[EventBase],
  390. ) -> None:
  391. user_list = event.content.get("users", {})
  392. # Validate users
  393. for k, v in user_list.items():
  394. try:
  395. UserID.from_string(k)
  396. except Exception:
  397. raise SynapseError(400, "Not a valid user_id: %s" % (k,))
  398. try:
  399. int(v)
  400. except Exception:
  401. raise SynapseError(400, "Not a valid power level: %s" % (v,))
  402. key = (event.type, event.state_key)
  403. current_state = auth_events.get(key)
  404. if not current_state:
  405. return
  406. user_level = get_user_power_level(event.user_id, auth_events)
  407. # Check other levels:
  408. levels_to_check = [
  409. ("users_default", None),
  410. ("events_default", None),
  411. ("state_default", None),
  412. ("ban", None),
  413. ("redact", None),
  414. ("kick", None),
  415. ("invite", None),
  416. ] # type: List[Tuple[str, Optional[str]]]
  417. old_list = current_state.content.get("users", {})
  418. for user in set(list(old_list) + list(user_list)):
  419. levels_to_check.append((user, "users"))
  420. old_list = current_state.content.get("events", {})
  421. new_list = event.content.get("events", {})
  422. for ev_id in set(list(old_list) + list(new_list)):
  423. levels_to_check.append((ev_id, "events"))
  424. # MSC2209 specifies these checks should also be done for the "notifications"
  425. # key.
  426. if room_version_obj.limit_notifications_power_levels:
  427. old_list = current_state.content.get("notifications", {})
  428. new_list = event.content.get("notifications", {})
  429. for ev_id in set(list(old_list) + list(new_list)):
  430. levels_to_check.append((ev_id, "notifications"))
  431. old_state = current_state.content
  432. new_state = event.content
  433. for level_to_check, dir in levels_to_check:
  434. old_loc = old_state
  435. new_loc = new_state
  436. if dir:
  437. old_loc = old_loc.get(dir, {})
  438. new_loc = new_loc.get(dir, {})
  439. if level_to_check in old_loc:
  440. old_level = int(old_loc[level_to_check]) # type: Optional[int]
  441. else:
  442. old_level = None
  443. if level_to_check in new_loc:
  444. new_level = int(new_loc[level_to_check]) # type: Optional[int]
  445. else:
  446. new_level = None
  447. if new_level is not None and old_level is not None:
  448. if new_level == old_level:
  449. continue
  450. if dir == "users" and level_to_check != event.user_id:
  451. if old_level == user_level:
  452. raise AuthError(
  453. 403,
  454. "You don't have permission to remove ops level equal "
  455. "to your own",
  456. )
  457. # Check if the old and new levels are greater than the user level
  458. # (if defined)
  459. old_level_too_big = old_level is not None and old_level > user_level
  460. new_level_too_big = new_level is not None and new_level > user_level
  461. if old_level_too_big or new_level_too_big:
  462. raise AuthError(
  463. 403, "You don't have permission to add ops level greater than your own"
  464. )
  465. def _get_power_level_event(auth_events: StateMap[EventBase]) -> Optional[EventBase]:
  466. return auth_events.get((EventTypes.PowerLevels, ""))
  467. def get_user_power_level(user_id: str, auth_events: StateMap[EventBase]) -> int:
  468. """Get a user's power level
  469. Args:
  470. user_id: user's id to look up in power_levels
  471. auth_events:
  472. state in force at this point in the room (or rather, a subset of
  473. it including at least the create event and power levels event.
  474. Returns:
  475. the user's power level in this room.
  476. """
  477. power_level_event = _get_power_level_event(auth_events)
  478. if power_level_event:
  479. level = power_level_event.content.get("users", {}).get(user_id)
  480. if not level:
  481. level = power_level_event.content.get("users_default", 0)
  482. if level is None:
  483. return 0
  484. else:
  485. return int(level)
  486. else:
  487. # if there is no power levels event, the creator gets 100 and everyone
  488. # else gets 0.
  489. # some things which call this don't pass the create event: hack around
  490. # that.
  491. key = (EventTypes.Create, "")
  492. create_event = auth_events.get(key)
  493. if create_event is not None and create_event.content["creator"] == user_id:
  494. return 100
  495. else:
  496. return 0
  497. def _get_named_level(auth_events: StateMap[EventBase], name: str, default: int) -> int:
  498. power_level_event = _get_power_level_event(auth_events)
  499. if not power_level_event:
  500. return default
  501. level = power_level_event.content.get(name, None)
  502. if level is not None:
  503. return int(level)
  504. else:
  505. return default
  506. def _verify_third_party_invite(event: EventBase, auth_events: StateMap[EventBase]):
  507. """
  508. Validates that the invite event is authorized by a previous third-party invite.
  509. Checks that the public key, and keyserver, match those in the third party invite,
  510. and that the invite event has a signature issued using that public key.
  511. Args:
  512. event: The m.room.member join event being validated.
  513. auth_events: All relevant previous context events which may be used
  514. for authorization decisions.
  515. Return:
  516. True if the event fulfills the expectations of a previous third party
  517. invite event.
  518. """
  519. if "third_party_invite" not in event.content:
  520. return False
  521. if "signed" not in event.content["third_party_invite"]:
  522. return False
  523. signed = event.content["third_party_invite"]["signed"]
  524. for key in {"mxid", "token"}:
  525. if key not in signed:
  526. return False
  527. token = signed["token"]
  528. invite_event = auth_events.get((EventTypes.ThirdPartyInvite, token))
  529. if not invite_event:
  530. return False
  531. if invite_event.sender != event.sender:
  532. return False
  533. if event.user_id != invite_event.user_id:
  534. return False
  535. if signed["mxid"] != event.state_key:
  536. return False
  537. if signed["token"] != token:
  538. return False
  539. for public_key_object in get_public_keys(invite_event):
  540. public_key = public_key_object["public_key"]
  541. try:
  542. for server, signature_block in signed["signatures"].items():
  543. for key_name, encoded_signature in signature_block.items():
  544. if not key_name.startswith("ed25519:"):
  545. continue
  546. verify_key = decode_verify_key_bytes(
  547. key_name, decode_base64(public_key)
  548. )
  549. verify_signed_json(signed, server, verify_key)
  550. # We got the public key from the invite, so we know that the
  551. # correct server signed the signed bundle.
  552. # The caller is responsible for checking that the signing
  553. # server has not revoked that public key.
  554. return True
  555. except (KeyError, SignatureVerifyException):
  556. continue
  557. return False
  558. def get_public_keys(invite_event):
  559. public_keys = []
  560. if "public_key" in invite_event.content:
  561. o = {"public_key": invite_event.content["public_key"]}
  562. if "key_validity_url" in invite_event.content:
  563. o["key_validity_url"] = invite_event.content["key_validity_url"]
  564. public_keys.append(o)
  565. public_keys.extend(invite_event.content.get("public_keys", []))
  566. return public_keys
  567. def auth_types_for_event(event: EventBase) -> Set[Tuple[str, str]]:
  568. """Given an event, return a list of (EventType, StateKey) that may be
  569. needed to auth the event. The returned list may be a superset of what
  570. would actually be required depending on the full state of the room.
  571. Used to limit the number of events to fetch from the database to
  572. actually auth the event.
  573. """
  574. if event.type == EventTypes.Create:
  575. return set()
  576. auth_types = {
  577. (EventTypes.PowerLevels, ""),
  578. (EventTypes.Member, event.sender),
  579. (EventTypes.Create, ""),
  580. }
  581. if event.type == EventTypes.Member:
  582. membership = event.content["membership"]
  583. if membership in [Membership.JOIN, Membership.INVITE]:
  584. auth_types.add((EventTypes.JoinRules, ""))
  585. auth_types.add((EventTypes.Member, event.state_key))
  586. if membership == Membership.INVITE:
  587. if "third_party_invite" in event.content:
  588. key = (
  589. EventTypes.ThirdPartyInvite,
  590. event.content["third_party_invite"]["signed"]["token"],
  591. )
  592. auth_types.add(key)
  593. return auth_types