matrix-synapse 1.143.0rc2__cp310-abi3-manylinux_2_28_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1058) hide show
  1. matrix_synapse-1.143.0rc2.dist-info/AUTHORS.rst +51 -0
  2. matrix_synapse-1.143.0rc2.dist-info/LICENSE-AGPL-3.0 +661 -0
  3. matrix_synapse-1.143.0rc2.dist-info/LICENSE-COMMERCIAL +6 -0
  4. matrix_synapse-1.143.0rc2.dist-info/METADATA +385 -0
  5. matrix_synapse-1.143.0rc2.dist-info/RECORD +1058 -0
  6. matrix_synapse-1.143.0rc2.dist-info/WHEEL +4 -0
  7. matrix_synapse-1.143.0rc2.dist-info/entry_points.txt +14 -0
  8. synapse/__init__.py +97 -0
  9. synapse/_scripts/__init__.py +0 -0
  10. synapse/_scripts/export_signing_key.py +109 -0
  11. synapse/_scripts/generate_config.py +83 -0
  12. synapse/_scripts/generate_log_config.py +56 -0
  13. synapse/_scripts/generate_signing_key.py +55 -0
  14. synapse/_scripts/generate_workers_map.py +318 -0
  15. synapse/_scripts/hash_password.py +95 -0
  16. synapse/_scripts/move_remote_media_to_new_store.py +128 -0
  17. synapse/_scripts/register_new_matrix_user.py +402 -0
  18. synapse/_scripts/review_recent_signups.py +212 -0
  19. synapse/_scripts/synapse_port_db.py +1604 -0
  20. synapse/_scripts/synctl.py +365 -0
  21. synapse/_scripts/update_synapse_database.py +130 -0
  22. synapse/api/__init__.py +20 -0
  23. synapse/api/auth/__init__.py +207 -0
  24. synapse/api/auth/base.py +406 -0
  25. synapse/api/auth/internal.py +299 -0
  26. synapse/api/auth/mas.py +436 -0
  27. synapse/api/auth/msc3861_delegated.py +617 -0
  28. synapse/api/auth_blocking.py +144 -0
  29. synapse/api/constants.py +362 -0
  30. synapse/api/errors.py +907 -0
  31. synapse/api/filtering.py +537 -0
  32. synapse/api/presence.py +102 -0
  33. synapse/api/ratelimiting.py +480 -0
  34. synapse/api/room_versions.py +535 -0
  35. synapse/api/urls.py +118 -0
  36. synapse/app/__init__.py +60 -0
  37. synapse/app/_base.py +862 -0
  38. synapse/app/admin_cmd.py +388 -0
  39. synapse/app/appservice.py +30 -0
  40. synapse/app/client_reader.py +30 -0
  41. synapse/app/complement_fork_starter.py +206 -0
  42. synapse/app/event_creator.py +29 -0
  43. synapse/app/federation_reader.py +30 -0
  44. synapse/app/federation_sender.py +30 -0
  45. synapse/app/frontend_proxy.py +30 -0
  46. synapse/app/generic_worker.py +474 -0
  47. synapse/app/homeserver.py +505 -0
  48. synapse/app/media_repository.py +30 -0
  49. synapse/app/phone_stats_home.py +296 -0
  50. synapse/app/pusher.py +30 -0
  51. synapse/app/synchrotron.py +30 -0
  52. synapse/app/user_dir.py +31 -0
  53. synapse/appservice/__init__.py +458 -0
  54. synapse/appservice/api.py +567 -0
  55. synapse/appservice/scheduler.py +564 -0
  56. synapse/config/__init__.py +27 -0
  57. synapse/config/__main__.py +62 -0
  58. synapse/config/_base.py +1106 -0
  59. synapse/config/_base.pyi +215 -0
  60. synapse/config/_util.py +99 -0
  61. synapse/config/account_validity.py +116 -0
  62. synapse/config/api.py +141 -0
  63. synapse/config/appservice.py +210 -0
  64. synapse/config/auth.py +80 -0
  65. synapse/config/auto_accept_invites.py +43 -0
  66. synapse/config/background_updates.py +44 -0
  67. synapse/config/cache.py +231 -0
  68. synapse/config/captcha.py +90 -0
  69. synapse/config/cas.py +116 -0
  70. synapse/config/consent.py +73 -0
  71. synapse/config/database.py +184 -0
  72. synapse/config/emailconfig.py +367 -0
  73. synapse/config/experimental.py +595 -0
  74. synapse/config/federation.py +114 -0
  75. synapse/config/homeserver.py +141 -0
  76. synapse/config/jwt.py +55 -0
  77. synapse/config/key.py +447 -0
  78. synapse/config/logger.py +390 -0
  79. synapse/config/mas.py +192 -0
  80. synapse/config/matrixrtc.py +66 -0
  81. synapse/config/metrics.py +84 -0
  82. synapse/config/modules.py +40 -0
  83. synapse/config/oembed.py +185 -0
  84. synapse/config/oidc.py +509 -0
  85. synapse/config/password_auth_providers.py +82 -0
  86. synapse/config/push.py +64 -0
  87. synapse/config/ratelimiting.py +254 -0
  88. synapse/config/redis.py +74 -0
  89. synapse/config/registration.py +296 -0
  90. synapse/config/repository.py +311 -0
  91. synapse/config/retention.py +162 -0
  92. synapse/config/room.py +88 -0
  93. synapse/config/room_directory.py +165 -0
  94. synapse/config/saml2.py +251 -0
  95. synapse/config/server.py +1170 -0
  96. synapse/config/server_notices.py +84 -0
  97. synapse/config/spam_checker.py +66 -0
  98. synapse/config/sso.py +121 -0
  99. synapse/config/stats.py +54 -0
  100. synapse/config/third_party_event_rules.py +40 -0
  101. synapse/config/tls.py +192 -0
  102. synapse/config/tracer.py +71 -0
  103. synapse/config/user_directory.py +47 -0
  104. synapse/config/user_types.py +42 -0
  105. synapse/config/voip.py +59 -0
  106. synapse/config/workers.py +642 -0
  107. synapse/crypto/__init__.py +20 -0
  108. synapse/crypto/context_factory.py +278 -0
  109. synapse/crypto/event_signing.py +194 -0
  110. synapse/crypto/keyring.py +931 -0
  111. synapse/event_auth.py +1266 -0
  112. synapse/events/__init__.py +667 -0
  113. synapse/events/auto_accept_invites.py +216 -0
  114. synapse/events/builder.py +387 -0
  115. synapse/events/presence_router.py +243 -0
  116. synapse/events/snapshot.py +559 -0
  117. synapse/events/utils.py +924 -0
  118. synapse/events/validator.py +305 -0
  119. synapse/federation/__init__.py +22 -0
  120. synapse/federation/federation_base.py +382 -0
  121. synapse/federation/federation_client.py +2132 -0
  122. synapse/federation/federation_server.py +1540 -0
  123. synapse/federation/persistence.py +70 -0
  124. synapse/federation/send_queue.py +531 -0
  125. synapse/federation/sender/__init__.py +1164 -0
  126. synapse/federation/sender/per_destination_queue.py +886 -0
  127. synapse/federation/sender/transaction_manager.py +210 -0
  128. synapse/federation/transport/__init__.py +28 -0
  129. synapse/federation/transport/client.py +1199 -0
  130. synapse/federation/transport/server/__init__.py +334 -0
  131. synapse/federation/transport/server/_base.py +429 -0
  132. synapse/federation/transport/server/federation.py +910 -0
  133. synapse/federation/units.py +133 -0
  134. synapse/handlers/__init__.py +20 -0
  135. synapse/handlers/account.py +162 -0
  136. synapse/handlers/account_data.py +360 -0
  137. synapse/handlers/account_validity.py +361 -0
  138. synapse/handlers/admin.py +615 -0
  139. synapse/handlers/appservice.py +989 -0
  140. synapse/handlers/auth.py +2481 -0
  141. synapse/handlers/cas.py +413 -0
  142. synapse/handlers/deactivate_account.py +363 -0
  143. synapse/handlers/delayed_events.py +599 -0
  144. synapse/handlers/device.py +1870 -0
  145. synapse/handlers/devicemessage.py +399 -0
  146. synapse/handlers/directory.py +545 -0
  147. synapse/handlers/e2e_keys.py +1834 -0
  148. synapse/handlers/e2e_room_keys.py +455 -0
  149. synapse/handlers/event_auth.py +390 -0
  150. synapse/handlers/events.py +201 -0
  151. synapse/handlers/federation.py +2039 -0
  152. synapse/handlers/federation_event.py +2419 -0
  153. synapse/handlers/identity.py +812 -0
  154. synapse/handlers/initial_sync.py +528 -0
  155. synapse/handlers/jwt.py +120 -0
  156. synapse/handlers/message.py +2347 -0
  157. synapse/handlers/oidc.py +1801 -0
  158. synapse/handlers/pagination.py +768 -0
  159. synapse/handlers/password_policy.py +102 -0
  160. synapse/handlers/presence.py +2633 -0
  161. synapse/handlers/profile.py +655 -0
  162. synapse/handlers/push_rules.py +164 -0
  163. synapse/handlers/read_marker.py +79 -0
  164. synapse/handlers/receipts.py +351 -0
  165. synapse/handlers/register.py +1059 -0
  166. synapse/handlers/relations.py +623 -0
  167. synapse/handlers/reports.py +98 -0
  168. synapse/handlers/room.py +2448 -0
  169. synapse/handlers/room_list.py +632 -0
  170. synapse/handlers/room_member.py +2365 -0
  171. synapse/handlers/room_member_worker.py +146 -0
  172. synapse/handlers/room_policy.py +186 -0
  173. synapse/handlers/room_summary.py +1057 -0
  174. synapse/handlers/saml.py +524 -0
  175. synapse/handlers/search.py +723 -0
  176. synapse/handlers/send_email.py +209 -0
  177. synapse/handlers/set_password.py +71 -0
  178. synapse/handlers/sliding_sync/__init__.py +1701 -0
  179. synapse/handlers/sliding_sync/extensions.py +969 -0
  180. synapse/handlers/sliding_sync/room_lists.py +2262 -0
  181. synapse/handlers/sliding_sync/store.py +128 -0
  182. synapse/handlers/sso.py +1291 -0
  183. synapse/handlers/state_deltas.py +82 -0
  184. synapse/handlers/stats.py +321 -0
  185. synapse/handlers/sync.py +3106 -0
  186. synapse/handlers/thread_subscriptions.py +190 -0
  187. synapse/handlers/typing.py +606 -0
  188. synapse/handlers/ui_auth/__init__.py +48 -0
  189. synapse/handlers/ui_auth/checkers.py +332 -0
  190. synapse/handlers/user_directory.py +783 -0
  191. synapse/handlers/worker_lock.py +371 -0
  192. synapse/http/__init__.py +105 -0
  193. synapse/http/additional_resource.py +62 -0
  194. synapse/http/client.py +1373 -0
  195. synapse/http/connectproxyclient.py +316 -0
  196. synapse/http/federation/__init__.py +19 -0
  197. synapse/http/federation/matrix_federation_agent.py +490 -0
  198. synapse/http/federation/srv_resolver.py +196 -0
  199. synapse/http/federation/well_known_resolver.py +367 -0
  200. synapse/http/matrixfederationclient.py +1873 -0
  201. synapse/http/proxy.py +290 -0
  202. synapse/http/proxyagent.py +497 -0
  203. synapse/http/replicationagent.py +202 -0
  204. synapse/http/request_metrics.py +309 -0
  205. synapse/http/server.py +1110 -0
  206. synapse/http/servlet.py +1018 -0
  207. synapse/http/site.py +825 -0
  208. synapse/http/types.py +27 -0
  209. synapse/logging/__init__.py +31 -0
  210. synapse/logging/_remote.py +261 -0
  211. synapse/logging/_terse_json.py +95 -0
  212. synapse/logging/context.py +1209 -0
  213. synapse/logging/formatter.py +62 -0
  214. synapse/logging/handlers.py +99 -0
  215. synapse/logging/loggers.py +25 -0
  216. synapse/logging/opentracing.py +1132 -0
  217. synapse/logging/scopecontextmanager.py +160 -0
  218. synapse/media/_base.py +830 -0
  219. synapse/media/filepath.py +417 -0
  220. synapse/media/media_repository.py +1580 -0
  221. synapse/media/media_storage.py +702 -0
  222. synapse/media/oembed.py +277 -0
  223. synapse/media/preview_html.py +556 -0
  224. synapse/media/storage_provider.py +195 -0
  225. synapse/media/thumbnailer.py +833 -0
  226. synapse/media/url_previewer.py +875 -0
  227. synapse/metrics/__init__.py +748 -0
  228. synapse/metrics/_gc.py +219 -0
  229. synapse/metrics/_reactor_metrics.py +171 -0
  230. synapse/metrics/_types.py +38 -0
  231. synapse/metrics/background_process_metrics.py +555 -0
  232. synapse/metrics/common_usage_metrics.py +94 -0
  233. synapse/metrics/jemalloc.py +248 -0
  234. synapse/module_api/__init__.py +2131 -0
  235. synapse/module_api/callbacks/__init__.py +50 -0
  236. synapse/module_api/callbacks/account_validity_callbacks.py +106 -0
  237. synapse/module_api/callbacks/media_repository_callbacks.py +157 -0
  238. synapse/module_api/callbacks/ratelimit_callbacks.py +78 -0
  239. synapse/module_api/callbacks/spamchecker_callbacks.py +991 -0
  240. synapse/module_api/callbacks/third_party_event_rules_callbacks.py +592 -0
  241. synapse/module_api/errors.py +42 -0
  242. synapse/notifier.py +970 -0
  243. synapse/push/__init__.py +212 -0
  244. synapse/push/bulk_push_rule_evaluator.py +635 -0
  245. synapse/push/clientformat.py +126 -0
  246. synapse/push/emailpusher.py +333 -0
  247. synapse/push/httppusher.py +564 -0
  248. synapse/push/mailer.py +1010 -0
  249. synapse/push/presentable_names.py +216 -0
  250. synapse/push/push_tools.py +114 -0
  251. synapse/push/push_types.py +141 -0
  252. synapse/push/pusher.py +87 -0
  253. synapse/push/pusherpool.py +501 -0
  254. synapse/push/rulekinds.py +33 -0
  255. synapse/py.typed +0 -0
  256. synapse/replication/__init__.py +20 -0
  257. synapse/replication/http/__init__.py +68 -0
  258. synapse/replication/http/_base.py +468 -0
  259. synapse/replication/http/account_data.py +297 -0
  260. synapse/replication/http/deactivate_account.py +81 -0
  261. synapse/replication/http/delayed_events.py +62 -0
  262. synapse/replication/http/devices.py +254 -0
  263. synapse/replication/http/federation.py +334 -0
  264. synapse/replication/http/login.py +106 -0
  265. synapse/replication/http/membership.py +364 -0
  266. synapse/replication/http/presence.py +133 -0
  267. synapse/replication/http/push.py +156 -0
  268. synapse/replication/http/register.py +172 -0
  269. synapse/replication/http/send_events.py +182 -0
  270. synapse/replication/http/state.py +82 -0
  271. synapse/replication/http/streams.py +101 -0
  272. synapse/replication/tcp/__init__.py +56 -0
  273. synapse/replication/tcp/client.py +552 -0
  274. synapse/replication/tcp/commands.py +569 -0
  275. synapse/replication/tcp/context.py +41 -0
  276. synapse/replication/tcp/external_cache.py +156 -0
  277. synapse/replication/tcp/handler.py +922 -0
  278. synapse/replication/tcp/protocol.py +608 -0
  279. synapse/replication/tcp/redis.py +509 -0
  280. synapse/replication/tcp/resource.py +348 -0
  281. synapse/replication/tcp/streams/__init__.py +96 -0
  282. synapse/replication/tcp/streams/_base.py +765 -0
  283. synapse/replication/tcp/streams/events.py +287 -0
  284. synapse/replication/tcp/streams/federation.py +92 -0
  285. synapse/replication/tcp/streams/partial_state.py +80 -0
  286. synapse/res/providers.json +29 -0
  287. synapse/res/templates/_base.html +29 -0
  288. synapse/res/templates/account_previously_renewed.html +6 -0
  289. synapse/res/templates/account_renewed.html +6 -0
  290. synapse/res/templates/add_threepid.html +8 -0
  291. synapse/res/templates/add_threepid.txt +6 -0
  292. synapse/res/templates/add_threepid_failure.html +7 -0
  293. synapse/res/templates/add_threepid_success.html +6 -0
  294. synapse/res/templates/already_in_use.html +12 -0
  295. synapse/res/templates/already_in_use.txt +10 -0
  296. synapse/res/templates/auth_success.html +21 -0
  297. synapse/res/templates/invalid_token.html +6 -0
  298. synapse/res/templates/mail-Element.css +7 -0
  299. synapse/res/templates/mail-Vector.css +7 -0
  300. synapse/res/templates/mail-expiry.css +4 -0
  301. synapse/res/templates/mail.css +156 -0
  302. synapse/res/templates/notice_expiry.html +46 -0
  303. synapse/res/templates/notice_expiry.txt +7 -0
  304. synapse/res/templates/notif.html +51 -0
  305. synapse/res/templates/notif.txt +22 -0
  306. synapse/res/templates/notif_mail.html +59 -0
  307. synapse/res/templates/notif_mail.txt +10 -0
  308. synapse/res/templates/password_reset.html +10 -0
  309. synapse/res/templates/password_reset.txt +7 -0
  310. synapse/res/templates/password_reset_confirmation.html +15 -0
  311. synapse/res/templates/password_reset_failure.html +7 -0
  312. synapse/res/templates/password_reset_success.html +6 -0
  313. synapse/res/templates/recaptcha.html +42 -0
  314. synapse/res/templates/registration.html +12 -0
  315. synapse/res/templates/registration.txt +10 -0
  316. synapse/res/templates/registration_failure.html +6 -0
  317. synapse/res/templates/registration_success.html +6 -0
  318. synapse/res/templates/registration_token.html +18 -0
  319. synapse/res/templates/room.html +33 -0
  320. synapse/res/templates/room.txt +9 -0
  321. synapse/res/templates/sso.css +129 -0
  322. synapse/res/templates/sso_account_deactivated.html +25 -0
  323. synapse/res/templates/sso_auth_account_details.html +186 -0
  324. synapse/res/templates/sso_auth_account_details.js +116 -0
  325. synapse/res/templates/sso_auth_bad_user.html +26 -0
  326. synapse/res/templates/sso_auth_confirm.html +27 -0
  327. synapse/res/templates/sso_auth_success.html +26 -0
  328. synapse/res/templates/sso_error.html +71 -0
  329. synapse/res/templates/sso_footer.html +19 -0
  330. synapse/res/templates/sso_login_idp_picker.html +60 -0
  331. synapse/res/templates/sso_new_user_consent.html +30 -0
  332. synapse/res/templates/sso_partial_profile.html +19 -0
  333. synapse/res/templates/sso_redirect_confirm.html +39 -0
  334. synapse/res/templates/style.css +33 -0
  335. synapse/res/templates/terms.html +27 -0
  336. synapse/rest/__init__.py +197 -0
  337. synapse/rest/admin/__init__.py +390 -0
  338. synapse/rest/admin/_base.py +72 -0
  339. synapse/rest/admin/background_updates.py +171 -0
  340. synapse/rest/admin/devices.py +221 -0
  341. synapse/rest/admin/event_reports.py +173 -0
  342. synapse/rest/admin/events.py +69 -0
  343. synapse/rest/admin/experimental_features.py +137 -0
  344. synapse/rest/admin/federation.py +243 -0
  345. synapse/rest/admin/media.py +540 -0
  346. synapse/rest/admin/registration_tokens.py +358 -0
  347. synapse/rest/admin/rooms.py +1061 -0
  348. synapse/rest/admin/scheduled_tasks.py +70 -0
  349. synapse/rest/admin/server_notice_servlet.py +132 -0
  350. synapse/rest/admin/statistics.py +132 -0
  351. synapse/rest/admin/username_available.py +58 -0
  352. synapse/rest/admin/users.py +1606 -0
  353. synapse/rest/client/__init__.py +20 -0
  354. synapse/rest/client/_base.py +113 -0
  355. synapse/rest/client/account.py +930 -0
  356. synapse/rest/client/account_data.py +319 -0
  357. synapse/rest/client/account_validity.py +103 -0
  358. synapse/rest/client/appservice_ping.py +125 -0
  359. synapse/rest/client/auth.py +218 -0
  360. synapse/rest/client/auth_metadata.py +122 -0
  361. synapse/rest/client/capabilities.py +121 -0
  362. synapse/rest/client/delayed_events.py +165 -0
  363. synapse/rest/client/devices.py +587 -0
  364. synapse/rest/client/directory.py +211 -0
  365. synapse/rest/client/events.py +116 -0
  366. synapse/rest/client/filter.py +112 -0
  367. synapse/rest/client/initial_sync.py +65 -0
  368. synapse/rest/client/keys.py +678 -0
  369. synapse/rest/client/knock.py +104 -0
  370. synapse/rest/client/login.py +750 -0
  371. synapse/rest/client/login_token_request.py +127 -0
  372. synapse/rest/client/logout.py +93 -0
  373. synapse/rest/client/matrixrtc.py +52 -0
  374. synapse/rest/client/media.py +285 -0
  375. synapse/rest/client/mutual_rooms.py +93 -0
  376. synapse/rest/client/notifications.py +137 -0
  377. synapse/rest/client/openid.py +109 -0
  378. synapse/rest/client/password_policy.py +69 -0
  379. synapse/rest/client/presence.py +131 -0
  380. synapse/rest/client/profile.py +291 -0
  381. synapse/rest/client/push_rule.py +331 -0
  382. synapse/rest/client/pusher.py +181 -0
  383. synapse/rest/client/read_marker.py +104 -0
  384. synapse/rest/client/receipts.py +165 -0
  385. synapse/rest/client/register.py +1067 -0
  386. synapse/rest/client/relations.py +138 -0
  387. synapse/rest/client/rendezvous.py +76 -0
  388. synapse/rest/client/reporting.py +207 -0
  389. synapse/rest/client/room.py +1669 -0
  390. synapse/rest/client/room_keys.py +426 -0
  391. synapse/rest/client/room_upgrade_rest_servlet.py +112 -0
  392. synapse/rest/client/sendtodevice.py +85 -0
  393. synapse/rest/client/sync.py +1131 -0
  394. synapse/rest/client/tags.py +129 -0
  395. synapse/rest/client/thirdparty.py +130 -0
  396. synapse/rest/client/thread_subscriptions.py +247 -0
  397. synapse/rest/client/tokenrefresh.py +52 -0
  398. synapse/rest/client/transactions.py +149 -0
  399. synapse/rest/client/user_directory.py +90 -0
  400. synapse/rest/client/versions.py +191 -0
  401. synapse/rest/client/voip.py +88 -0
  402. synapse/rest/consent/__init__.py +0 -0
  403. synapse/rest/consent/consent_resource.py +210 -0
  404. synapse/rest/health.py +38 -0
  405. synapse/rest/key/__init__.py +20 -0
  406. synapse/rest/key/v2/__init__.py +40 -0
  407. synapse/rest/key/v2/local_key_resource.py +125 -0
  408. synapse/rest/key/v2/remote_key_resource.py +302 -0
  409. synapse/rest/media/__init__.py +0 -0
  410. synapse/rest/media/config_resource.py +53 -0
  411. synapse/rest/media/create_resource.py +90 -0
  412. synapse/rest/media/download_resource.py +110 -0
  413. synapse/rest/media/media_repository_resource.py +113 -0
  414. synapse/rest/media/preview_url_resource.py +77 -0
  415. synapse/rest/media/thumbnail_resource.py +142 -0
  416. synapse/rest/media/upload_resource.py +187 -0
  417. synapse/rest/media/v1/__init__.py +39 -0
  418. synapse/rest/media/v1/_base.py +23 -0
  419. synapse/rest/media/v1/media_storage.py +23 -0
  420. synapse/rest/media/v1/storage_provider.py +23 -0
  421. synapse/rest/synapse/__init__.py +20 -0
  422. synapse/rest/synapse/client/__init__.py +93 -0
  423. synapse/rest/synapse/client/federation_whitelist.py +66 -0
  424. synapse/rest/synapse/client/jwks.py +77 -0
  425. synapse/rest/synapse/client/new_user_consent.py +115 -0
  426. synapse/rest/synapse/client/oidc/__init__.py +45 -0
  427. synapse/rest/synapse/client/oidc/backchannel_logout_resource.py +42 -0
  428. synapse/rest/synapse/client/oidc/callback_resource.py +48 -0
  429. synapse/rest/synapse/client/password_reset.py +129 -0
  430. synapse/rest/synapse/client/pick_idp.py +107 -0
  431. synapse/rest/synapse/client/pick_username.py +153 -0
  432. synapse/rest/synapse/client/rendezvous.py +58 -0
  433. synapse/rest/synapse/client/saml2/__init__.py +42 -0
  434. synapse/rest/synapse/client/saml2/metadata_resource.py +46 -0
  435. synapse/rest/synapse/client/saml2/response_resource.py +52 -0
  436. synapse/rest/synapse/client/sso_register.py +56 -0
  437. synapse/rest/synapse/client/unsubscribe.py +88 -0
  438. synapse/rest/synapse/mas/__init__.py +71 -0
  439. synapse/rest/synapse/mas/_base.py +55 -0
  440. synapse/rest/synapse/mas/devices.py +239 -0
  441. synapse/rest/synapse/mas/users.py +469 -0
  442. synapse/rest/well_known.py +148 -0
  443. synapse/server.py +1257 -0
  444. synapse/server_notices/__init__.py +0 -0
  445. synapse/server_notices/consent_server_notices.py +136 -0
  446. synapse/server_notices/resource_limits_server_notices.py +215 -0
  447. synapse/server_notices/server_notices_manager.py +388 -0
  448. synapse/server_notices/server_notices_sender.py +67 -0
  449. synapse/server_notices/worker_server_notices_sender.py +46 -0
  450. synapse/spam_checker_api/__init__.py +31 -0
  451. synapse/state/__init__.py +1022 -0
  452. synapse/state/v1.py +369 -0
  453. synapse/state/v2.py +984 -0
  454. synapse/static/client/login/index.html +47 -0
  455. synapse/static/client/login/js/jquery-3.4.1.min.js +2 -0
  456. synapse/static/client/login/js/login.js +291 -0
  457. synapse/static/client/login/spinner.gif +0 -0
  458. synapse/static/client/login/style.css +79 -0
  459. synapse/static/index.html +63 -0
  460. synapse/storage/__init__.py +43 -0
  461. synapse/storage/_base.py +245 -0
  462. synapse/storage/admin_client_config.py +25 -0
  463. synapse/storage/background_updates.py +1188 -0
  464. synapse/storage/controllers/__init__.py +57 -0
  465. synapse/storage/controllers/persist_events.py +1237 -0
  466. synapse/storage/controllers/purge_events.py +455 -0
  467. synapse/storage/controllers/state.py +950 -0
  468. synapse/storage/controllers/stats.py +119 -0
  469. synapse/storage/database.py +2719 -0
  470. synapse/storage/databases/__init__.py +175 -0
  471. synapse/storage/databases/main/__init__.py +420 -0
  472. synapse/storage/databases/main/account_data.py +1059 -0
  473. synapse/storage/databases/main/appservice.py +473 -0
  474. synapse/storage/databases/main/cache.py +911 -0
  475. synapse/storage/databases/main/censor_events.py +225 -0
  476. synapse/storage/databases/main/client_ips.py +815 -0
  477. synapse/storage/databases/main/delayed_events.py +562 -0
  478. synapse/storage/databases/main/deviceinbox.py +1271 -0
  479. synapse/storage/databases/main/devices.py +2578 -0
  480. synapse/storage/databases/main/directory.py +212 -0
  481. synapse/storage/databases/main/e2e_room_keys.py +689 -0
  482. synapse/storage/databases/main/end_to_end_keys.py +1894 -0
  483. synapse/storage/databases/main/event_federation.py +2508 -0
  484. synapse/storage/databases/main/event_push_actions.py +1933 -0
  485. synapse/storage/databases/main/events.py +3765 -0
  486. synapse/storage/databases/main/events_bg_updates.py +2910 -0
  487. synapse/storage/databases/main/events_forward_extremities.py +126 -0
  488. synapse/storage/databases/main/events_worker.py +2786 -0
  489. synapse/storage/databases/main/experimental_features.py +130 -0
  490. synapse/storage/databases/main/filtering.py +231 -0
  491. synapse/storage/databases/main/keys.py +291 -0
  492. synapse/storage/databases/main/lock.py +553 -0
  493. synapse/storage/databases/main/media_repository.py +1068 -0
  494. synapse/storage/databases/main/metrics.py +460 -0
  495. synapse/storage/databases/main/monthly_active_users.py +443 -0
  496. synapse/storage/databases/main/openid.py +60 -0
  497. synapse/storage/databases/main/presence.py +509 -0
  498. synapse/storage/databases/main/profile.py +539 -0
  499. synapse/storage/databases/main/purge_events.py +521 -0
  500. synapse/storage/databases/main/push_rule.py +970 -0
  501. synapse/storage/databases/main/pusher.py +793 -0
  502. synapse/storage/databases/main/receipts.py +1341 -0
  503. synapse/storage/databases/main/registration.py +3072 -0
  504. synapse/storage/databases/main/rejections.py +37 -0
  505. synapse/storage/databases/main/relations.py +1116 -0
  506. synapse/storage/databases/main/room.py +2779 -0
  507. synapse/storage/databases/main/roommember.py +2110 -0
  508. synapse/storage/databases/main/search.py +939 -0
  509. synapse/storage/databases/main/session.py +151 -0
  510. synapse/storage/databases/main/signatures.py +94 -0
  511. synapse/storage/databases/main/sliding_sync.py +603 -0
  512. synapse/storage/databases/main/state.py +1002 -0
  513. synapse/storage/databases/main/state_deltas.py +329 -0
  514. synapse/storage/databases/main/stats.py +789 -0
  515. synapse/storage/databases/main/stream.py +2577 -0
  516. synapse/storage/databases/main/tags.py +360 -0
  517. synapse/storage/databases/main/task_scheduler.py +225 -0
  518. synapse/storage/databases/main/thread_subscriptions.py +589 -0
  519. synapse/storage/databases/main/transactions.py +675 -0
  520. synapse/storage/databases/main/ui_auth.py +420 -0
  521. synapse/storage/databases/main/user_directory.py +1330 -0
  522. synapse/storage/databases/main/user_erasure_store.py +117 -0
  523. synapse/storage/databases/state/__init__.py +22 -0
  524. synapse/storage/databases/state/bg_updates.py +497 -0
  525. synapse/storage/databases/state/deletion.py +557 -0
  526. synapse/storage/databases/state/store.py +948 -0
  527. synapse/storage/engines/__init__.py +70 -0
  528. synapse/storage/engines/_base.py +154 -0
  529. synapse/storage/engines/postgres.py +261 -0
  530. synapse/storage/engines/sqlite.py +199 -0
  531. synapse/storage/invite_rule.py +112 -0
  532. synapse/storage/keys.py +40 -0
  533. synapse/storage/prepare_database.py +730 -0
  534. synapse/storage/push_rule.py +28 -0
  535. synapse/storage/roommember.py +88 -0
  536. synapse/storage/schema/README.md +4 -0
  537. synapse/storage/schema/__init__.py +186 -0
  538. synapse/storage/schema/common/delta/25/00background_updates.sql +40 -0
  539. synapse/storage/schema/common/delta/35/00background_updates_add_col.sql +36 -0
  540. synapse/storage/schema/common/delta/58/00background_update_ordering.sql +38 -0
  541. synapse/storage/schema/common/full_schemas/72/full.sql.postgres +8 -0
  542. synapse/storage/schema/common/full_schemas/72/full.sql.sqlite +6 -0
  543. synapse/storage/schema/common/schema_version.sql +60 -0
  544. synapse/storage/schema/main/delta/12/v12.sql +82 -0
  545. synapse/storage/schema/main/delta/13/v13.sql +38 -0
  546. synapse/storage/schema/main/delta/14/v14.sql +42 -0
  547. synapse/storage/schema/main/delta/15/appservice_txns.sql +50 -0
  548. synapse/storage/schema/main/delta/15/presence_indices.sql +2 -0
  549. synapse/storage/schema/main/delta/15/v15.sql +24 -0
  550. synapse/storage/schema/main/delta/16/events_order_index.sql +4 -0
  551. synapse/storage/schema/main/delta/16/remote_media_cache_index.sql +2 -0
  552. synapse/storage/schema/main/delta/16/remove_duplicates.sql +9 -0
  553. synapse/storage/schema/main/delta/16/room_alias_index.sql +3 -0
  554. synapse/storage/schema/main/delta/16/unique_constraints.sql +72 -0
  555. synapse/storage/schema/main/delta/16/users.sql +56 -0
  556. synapse/storage/schema/main/delta/17/drop_indexes.sql +37 -0
  557. synapse/storage/schema/main/delta/17/server_keys.sql +43 -0
  558. synapse/storage/schema/main/delta/17/user_threepids.sql +9 -0
  559. synapse/storage/schema/main/delta/18/server_keys_bigger_ints.sql +51 -0
  560. synapse/storage/schema/main/delta/19/event_index.sql +38 -0
  561. synapse/storage/schema/main/delta/20/dummy.sql +1 -0
  562. synapse/storage/schema/main/delta/20/pushers.py +93 -0
  563. synapse/storage/schema/main/delta/21/end_to_end_keys.sql +53 -0
  564. synapse/storage/schema/main/delta/21/receipts.sql +57 -0
  565. synapse/storage/schema/main/delta/22/receipts_index.sql +41 -0
  566. synapse/storage/schema/main/delta/22/user_threepids_unique.sql +19 -0
  567. synapse/storage/schema/main/delta/24/stats_reporting.sql +37 -0
  568. synapse/storage/schema/main/delta/25/fts.py +81 -0
  569. synapse/storage/schema/main/delta/25/guest_access.sql +44 -0
  570. synapse/storage/schema/main/delta/25/history_visibility.sql +44 -0
  571. synapse/storage/schema/main/delta/25/tags.sql +57 -0
  572. synapse/storage/schema/main/delta/26/account_data.sql +36 -0
  573. synapse/storage/schema/main/delta/27/account_data.sql +55 -0
  574. synapse/storage/schema/main/delta/27/forgotten_memberships.sql +45 -0
  575. synapse/storage/schema/main/delta/27/ts.py +61 -0
  576. synapse/storage/schema/main/delta/28/event_push_actions.sql +46 -0
  577. synapse/storage/schema/main/delta/28/events_room_stream.sql +39 -0
  578. synapse/storage/schema/main/delta/28/public_roms_index.sql +39 -0
  579. synapse/storage/schema/main/delta/28/receipts_user_id_index.sql +41 -0
  580. synapse/storage/schema/main/delta/28/upgrade_times.sql +40 -0
  581. synapse/storage/schema/main/delta/28/users_is_guest.sql +41 -0
  582. synapse/storage/schema/main/delta/29/push_actions.sql +54 -0
  583. synapse/storage/schema/main/delta/30/alias_creator.sql +35 -0
  584. synapse/storage/schema/main/delta/30/as_users.py +82 -0
  585. synapse/storage/schema/main/delta/30/deleted_pushers.sql +44 -0
  586. synapse/storage/schema/main/delta/30/presence_stream.sql +49 -0
  587. synapse/storage/schema/main/delta/30/public_rooms.sql +42 -0
  588. synapse/storage/schema/main/delta/30/push_rule_stream.sql +57 -0
  589. synapse/storage/schema/main/delta/30/threepid_guest_access_tokens.sql +43 -0
  590. synapse/storage/schema/main/delta/31/invites.sql +61 -0
  591. synapse/storage/schema/main/delta/31/local_media_repository_url_cache.sql +46 -0
  592. synapse/storage/schema/main/delta/31/pushers_0.py +92 -0
  593. synapse/storage/schema/main/delta/31/pushers_index.sql +41 -0
  594. synapse/storage/schema/main/delta/31/search_update.py +65 -0
  595. synapse/storage/schema/main/delta/32/events.sql +35 -0
  596. synapse/storage/schema/main/delta/32/openid.sql +9 -0
  597. synapse/storage/schema/main/delta/32/pusher_throttle.sql +42 -0
  598. synapse/storage/schema/main/delta/32/remove_indices.sql +52 -0
  599. synapse/storage/schema/main/delta/32/reports.sql +44 -0
  600. synapse/storage/schema/main/delta/33/access_tokens_device_index.sql +36 -0
  601. synapse/storage/schema/main/delta/33/devices.sql +40 -0
  602. synapse/storage/schema/main/delta/33/devices_for_e2e_keys.sql +38 -0
  603. synapse/storage/schema/main/delta/33/devices_for_e2e_keys_clear_unknown_device.sql +39 -0
  604. synapse/storage/schema/main/delta/33/event_fields.py +61 -0
  605. synapse/storage/schema/main/delta/33/remote_media_ts.py +43 -0
  606. synapse/storage/schema/main/delta/33/user_ips_index.sql +36 -0
  607. synapse/storage/schema/main/delta/34/appservice_stream.sql +42 -0
  608. synapse/storage/schema/main/delta/34/cache_stream.py +50 -0
  609. synapse/storage/schema/main/delta/34/device_inbox.sql +43 -0
  610. synapse/storage/schema/main/delta/34/push_display_name_rename.sql +39 -0
  611. synapse/storage/schema/main/delta/34/received_txn_purge.py +36 -0
  612. synapse/storage/schema/main/delta/35/contains_url.sql +36 -0
  613. synapse/storage/schema/main/delta/35/device_outbox.sql +58 -0
  614. synapse/storage/schema/main/delta/35/device_stream_id.sql +40 -0
  615. synapse/storage/schema/main/delta/35/event_push_actions_index.sql +36 -0
  616. synapse/storage/schema/main/delta/35/public_room_list_change_stream.sql +52 -0
  617. synapse/storage/schema/main/delta/35/stream_order_to_extrem.sql +56 -0
  618. synapse/storage/schema/main/delta/36/readd_public_rooms.sql +45 -0
  619. synapse/storage/schema/main/delta/37/remove_auth_idx.py +89 -0
  620. synapse/storage/schema/main/delta/37/user_threepids.sql +71 -0
  621. synapse/storage/schema/main/delta/38/postgres_fts_gist.sql +38 -0
  622. synapse/storage/schema/main/delta/39/appservice_room_list.sql +48 -0
  623. synapse/storage/schema/main/delta/39/device_federation_stream_idx.sql +35 -0
  624. synapse/storage/schema/main/delta/39/event_push_index.sql +36 -0
  625. synapse/storage/schema/main/delta/39/federation_out_position.sql +41 -0
  626. synapse/storage/schema/main/delta/39/membership_profile.sql +39 -0
  627. synapse/storage/schema/main/delta/40/current_state_idx.sql +36 -0
  628. synapse/storage/schema/main/delta/40/device_inbox.sql +40 -0
  629. synapse/storage/schema/main/delta/40/device_list_streams.sql +79 -0
  630. synapse/storage/schema/main/delta/40/event_push_summary.sql +57 -0
  631. synapse/storage/schema/main/delta/40/pushers.sql +58 -0
  632. synapse/storage/schema/main/delta/41/device_list_stream_idx.sql +36 -0
  633. synapse/storage/schema/main/delta/41/device_outbound_index.sql +35 -0
  634. synapse/storage/schema/main/delta/41/event_search_event_id_idx.sql +36 -0
  635. synapse/storage/schema/main/delta/41/ratelimit.sql +41 -0
  636. synapse/storage/schema/main/delta/42/current_state_delta.sql +48 -0
  637. synapse/storage/schema/main/delta/42/device_list_last_id.sql +52 -0
  638. synapse/storage/schema/main/delta/42/event_auth_state_only.sql +36 -0
  639. synapse/storage/schema/main/delta/42/user_dir.py +88 -0
  640. synapse/storage/schema/main/delta/43/blocked_rooms.sql +40 -0
  641. synapse/storage/schema/main/delta/43/quarantine_media.sql +36 -0
  642. synapse/storage/schema/main/delta/43/url_cache.sql +35 -0
  643. synapse/storage/schema/main/delta/43/user_share.sql +52 -0
  644. synapse/storage/schema/main/delta/44/expire_url_cache.sql +60 -0
  645. synapse/storage/schema/main/delta/45/group_server.sql +186 -0
  646. synapse/storage/schema/main/delta/45/profile_cache.sql +47 -0
  647. synapse/storage/schema/main/delta/46/drop_refresh_tokens.sql +36 -0
  648. synapse/storage/schema/main/delta/46/drop_unique_deleted_pushers.sql +54 -0
  649. synapse/storage/schema/main/delta/46/group_server.sql +51 -0
  650. synapse/storage/schema/main/delta/46/local_media_repository_url_idx.sql +43 -0
  651. synapse/storage/schema/main/delta/46/user_dir_null_room_ids.sql +54 -0
  652. synapse/storage/schema/main/delta/46/user_dir_typos.sql +43 -0
  653. synapse/storage/schema/main/delta/47/last_access_media.sql +35 -0
  654. synapse/storage/schema/main/delta/47/postgres_fts_gin.sql +36 -0
  655. synapse/storage/schema/main/delta/47/push_actions_staging.sql +47 -0
  656. synapse/storage/schema/main/delta/48/add_user_consent.sql +37 -0
  657. synapse/storage/schema/main/delta/48/add_user_ips_last_seen_index.sql +36 -0
  658. synapse/storage/schema/main/delta/48/deactivated_users.sql +44 -0
  659. synapse/storage/schema/main/delta/48/group_unique_indexes.py +67 -0
  660. synapse/storage/schema/main/delta/48/groups_joinable.sql +41 -0
  661. synapse/storage/schema/main/delta/49/add_user_consent_server_notice_sent.sql +39 -0
  662. synapse/storage/schema/main/delta/49/add_user_daily_visits.sql +40 -0
  663. synapse/storage/schema/main/delta/49/add_user_ips_last_seen_only_index.sql +36 -0
  664. synapse/storage/schema/main/delta/50/add_creation_ts_users_index.sql +38 -0
  665. synapse/storage/schema/main/delta/50/erasure_store.sql +40 -0
  666. synapse/storage/schema/main/delta/50/make_event_content_nullable.py +102 -0
  667. synapse/storage/schema/main/delta/51/e2e_room_keys.sql +58 -0
  668. synapse/storage/schema/main/delta/51/monthly_active_users.sql +46 -0
  669. synapse/storage/schema/main/delta/52/add_event_to_state_group_index.sql +38 -0
  670. synapse/storage/schema/main/delta/52/device_list_streams_unique_idx.sql +55 -0
  671. synapse/storage/schema/main/delta/52/e2e_room_keys.sql +72 -0
  672. synapse/storage/schema/main/delta/53/add_user_type_to_users.sql +38 -0
  673. synapse/storage/schema/main/delta/53/drop_sent_transactions.sql +35 -0
  674. synapse/storage/schema/main/delta/53/event_format_version.sql +35 -0
  675. synapse/storage/schema/main/delta/53/user_dir_populate.sql +49 -0
  676. synapse/storage/schema/main/delta/53/user_ips_index.sql +49 -0
  677. synapse/storage/schema/main/delta/53/user_share.sql +63 -0
  678. synapse/storage/schema/main/delta/53/user_threepid_id.sql +48 -0
  679. synapse/storage/schema/main/delta/53/users_in_public_rooms.sql +47 -0
  680. synapse/storage/schema/main/delta/54/account_validity_with_renewal.sql +49 -0
  681. synapse/storage/schema/main/delta/54/add_validity_to_server_keys.sql +42 -0
  682. synapse/storage/schema/main/delta/54/delete_forward_extremities.sql +42 -0
  683. synapse/storage/schema/main/delta/54/drop_legacy_tables.sql +49 -0
  684. synapse/storage/schema/main/delta/54/drop_presence_list.sql +35 -0
  685. synapse/storage/schema/main/delta/54/relations.sql +46 -0
  686. synapse/storage/schema/main/delta/54/stats.sql +99 -0
  687. synapse/storage/schema/main/delta/54/stats2.sql +47 -0
  688. synapse/storage/schema/main/delta/55/access_token_expiry.sql +37 -0
  689. synapse/storage/schema/main/delta/55/track_threepid_validations.sql +50 -0
  690. synapse/storage/schema/main/delta/55/users_alter_deactivated.sql +38 -0
  691. synapse/storage/schema/main/delta/56/add_spans_to_device_lists.sql +39 -0
  692. synapse/storage/schema/main/delta/56/current_state_events_membership.sql +41 -0
  693. synapse/storage/schema/main/delta/56/current_state_events_membership_mk2.sql +43 -0
  694. synapse/storage/schema/main/delta/56/delete_keys_from_deleted_backups.sql +44 -0
  695. synapse/storage/schema/main/delta/56/destinations_failure_ts.sql +44 -0
  696. synapse/storage/schema/main/delta/56/destinations_retry_interval_type.sql.postgres +18 -0
  697. synapse/storage/schema/main/delta/56/device_stream_id_insert.sql +39 -0
  698. synapse/storage/schema/main/delta/56/devices_last_seen.sql +43 -0
  699. synapse/storage/schema/main/delta/56/drop_unused_event_tables.sql +39 -0
  700. synapse/storage/schema/main/delta/56/event_expiry.sql +40 -0
  701. synapse/storage/schema/main/delta/56/event_labels.sql +49 -0
  702. synapse/storage/schema/main/delta/56/event_labels_background_update.sql +36 -0
  703. synapse/storage/schema/main/delta/56/fix_room_keys_index.sql +37 -0
  704. synapse/storage/schema/main/delta/56/hidden_devices.sql +37 -0
  705. synapse/storage/schema/main/delta/56/hidden_devices_fix.sql.sqlite +42 -0
  706. synapse/storage/schema/main/delta/56/nuke_empty_communities_from_db.sql +48 -0
  707. synapse/storage/schema/main/delta/56/public_room_list_idx.sql +35 -0
  708. synapse/storage/schema/main/delta/56/redaction_censor.sql +35 -0
  709. synapse/storage/schema/main/delta/56/redaction_censor2.sql +41 -0
  710. synapse/storage/schema/main/delta/56/redaction_censor3_fix_update.sql.postgres +25 -0
  711. synapse/storage/schema/main/delta/56/redaction_censor4.sql +35 -0
  712. synapse/storage/schema/main/delta/56/remove_tombstoned_rooms_from_directory.sql +38 -0
  713. synapse/storage/schema/main/delta/56/room_key_etag.sql +36 -0
  714. synapse/storage/schema/main/delta/56/room_membership_idx.sql +37 -0
  715. synapse/storage/schema/main/delta/56/room_retention.sql +52 -0
  716. synapse/storage/schema/main/delta/56/signing_keys.sql +75 -0
  717. synapse/storage/schema/main/delta/56/signing_keys_nonunique_signatures.sql +41 -0
  718. synapse/storage/schema/main/delta/56/stats_separated.sql +175 -0
  719. synapse/storage/schema/main/delta/56/unique_user_filter_index.py +46 -0
  720. synapse/storage/schema/main/delta/56/user_external_ids.sql +43 -0
  721. synapse/storage/schema/main/delta/56/users_in_public_rooms_idx.sql +36 -0
  722. synapse/storage/schema/main/delta/57/delete_old_current_state_events.sql +41 -0
  723. synapse/storage/schema/main/delta/57/device_list_remote_cache_stale.sql +44 -0
  724. synapse/storage/schema/main/delta/57/local_current_membership.py +111 -0
  725. synapse/storage/schema/main/delta/57/remove_sent_outbound_pokes.sql +40 -0
  726. synapse/storage/schema/main/delta/57/rooms_version_column.sql +43 -0
  727. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.postgres +35 -0
  728. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.sqlite +22 -0
  729. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.postgres +39 -0
  730. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.sqlite +23 -0
  731. synapse/storage/schema/main/delta/58/02remove_dup_outbound_pokes.sql +41 -0
  732. synapse/storage/schema/main/delta/58/03persist_ui_auth.sql +55 -0
  733. synapse/storage/schema/main/delta/58/05cache_instance.sql.postgres +30 -0
  734. synapse/storage/schema/main/delta/58/06dlols_unique_idx.py +83 -0
  735. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.postgres +33 -0
  736. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.sqlite +44 -0
  737. synapse/storage/schema/main/delta/58/07persist_ui_auth_ips.sql +44 -0
  738. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.postgres +18 -0
  739. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.sqlite +18 -0
  740. synapse/storage/schema/main/delta/58/09shadow_ban.sql +37 -0
  741. synapse/storage/schema/main/delta/58/10_pushrules_enabled_delete_obsolete.sql +47 -0
  742. synapse/storage/schema/main/delta/58/10drop_local_rejections_stream.sql +41 -0
  743. synapse/storage/schema/main/delta/58/10federation_pos_instance_name.sql +41 -0
  744. synapse/storage/schema/main/delta/58/11dehydration.sql +39 -0
  745. synapse/storage/schema/main/delta/58/11fallback.sql +43 -0
  746. synapse/storage/schema/main/delta/58/11user_id_seq.py +38 -0
  747. synapse/storage/schema/main/delta/58/12room_stats.sql +51 -0
  748. synapse/storage/schema/main/delta/58/13remove_presence_allow_inbound.sql +36 -0
  749. synapse/storage/schema/main/delta/58/14events_instance_name.sql +35 -0
  750. synapse/storage/schema/main/delta/58/14events_instance_name.sql.postgres +28 -0
  751. synapse/storage/schema/main/delta/58/15_catchup_destination_rooms.sql +61 -0
  752. synapse/storage/schema/main/delta/58/15unread_count.sql +45 -0
  753. synapse/storage/schema/main/delta/58/16populate_stats_process_rooms_fix.sql +41 -0
  754. synapse/storage/schema/main/delta/58/17_catchup_last_successful.sql +40 -0
  755. synapse/storage/schema/main/delta/58/18stream_positions.sql +41 -0
  756. synapse/storage/schema/main/delta/58/19instance_map.sql.postgres +25 -0
  757. synapse/storage/schema/main/delta/58/19txn_id.sql +59 -0
  758. synapse/storage/schema/main/delta/58/20instance_name_event_tables.sql +36 -0
  759. synapse/storage/schema/main/delta/58/20user_daily_visits.sql +37 -0
  760. synapse/storage/schema/main/delta/58/21as_device_stream.sql +36 -0
  761. synapse/storage/schema/main/delta/58/21drop_device_max_stream_id.sql +1 -0
  762. synapse/storage/schema/main/delta/58/22puppet_token.sql +36 -0
  763. synapse/storage/schema/main/delta/58/22users_have_local_media.sql +2 -0
  764. synapse/storage/schema/main/delta/58/23e2e_cross_signing_keys_idx.sql +36 -0
  765. synapse/storage/schema/main/delta/58/24drop_event_json_index.sql +38 -0
  766. synapse/storage/schema/main/delta/58/25user_external_ids_user_id_idx.sql +36 -0
  767. synapse/storage/schema/main/delta/58/26access_token_last_validated.sql +37 -0
  768. synapse/storage/schema/main/delta/58/27local_invites.sql +37 -0
  769. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.postgres +16 -0
  770. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.sqlite +62 -0
  771. synapse/storage/schema/main/delta/59/01ignored_user.py +85 -0
  772. synapse/storage/schema/main/delta/59/02shard_send_to_device.sql +37 -0
  773. synapse/storage/schema/main/delta/59/03shard_send_to_device_sequence.sql.postgres +25 -0
  774. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql +71 -0
  775. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql.postgres +16 -0
  776. synapse/storage/schema/main/delta/59/04drop_account_data.sql +36 -0
  777. synapse/storage/schema/main/delta/59/05cache_invalidation.sql +36 -0
  778. synapse/storage/schema/main/delta/59/06chain_cover_index.sql +36 -0
  779. synapse/storage/schema/main/delta/59/06shard_account_data.sql +39 -0
  780. synapse/storage/schema/main/delta/59/06shard_account_data.sql.postgres +32 -0
  781. synapse/storage/schema/main/delta/59/07shard_account_data_fix.sql +37 -0
  782. synapse/storage/schema/main/delta/59/08delete_pushers_for_deactivated_accounts.sql +39 -0
  783. synapse/storage/schema/main/delta/59/08delete_stale_pushers.sql +39 -0
  784. synapse/storage/schema/main/delta/59/09rejected_events_metadata.sql +45 -0
  785. synapse/storage/schema/main/delta/59/10delete_purged_chain_cover.sql +36 -0
  786. synapse/storage/schema/main/delta/59/11add_knock_members_to_stats.sql +39 -0
  787. synapse/storage/schema/main/delta/59/11drop_thumbnail_constraint.sql.postgres +22 -0
  788. synapse/storage/schema/main/delta/59/12account_validity_token_used_ts_ms.sql +37 -0
  789. synapse/storage/schema/main/delta/59/12presence_stream_instance.sql +37 -0
  790. synapse/storage/schema/main/delta/59/12presence_stream_instance_seq.sql.postgres +20 -0
  791. synapse/storage/schema/main/delta/59/13users_to_send_full_presence_to.sql +53 -0
  792. synapse/storage/schema/main/delta/59/14refresh_tokens.sql +53 -0
  793. synapse/storage/schema/main/delta/59/15locks.sql +56 -0
  794. synapse/storage/schema/main/delta/59/16federation_inbound_staging.sql +51 -0
  795. synapse/storage/schema/main/delta/60/01recreate_stream_ordering.sql.postgres +45 -0
  796. synapse/storage/schema/main/delta/60/02change_stream_ordering_columns.sql.postgres +30 -0
  797. synapse/storage/schema/main/delta/61/01change_appservices_txns.sql.postgres +23 -0
  798. synapse/storage/schema/main/delta/61/01insertion_event_lookups.sql +68 -0
  799. synapse/storage/schema/main/delta/61/02drop_redundant_room_depth_index.sql +37 -0
  800. synapse/storage/schema/main/delta/61/03recreate_min_depth.py +74 -0
  801. synapse/storage/schema/main/delta/62/01insertion_event_extremities.sql +43 -0
  802. synapse/storage/schema/main/delta/63/01create_registration_tokens.sql +42 -0
  803. synapse/storage/schema/main/delta/63/02delete_unlinked_email_pushers.sql +39 -0
  804. synapse/storage/schema/main/delta/63/02populate-rooms-creator.sql +36 -0
  805. synapse/storage/schema/main/delta/63/03session_store.sql +42 -0
  806. synapse/storage/schema/main/delta/63/04add_presence_stream_not_offline_index.sql +37 -0
  807. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.postgres +23 -0
  808. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.sqlite +37 -0
  809. synapse/storage/schema/main/delta/65/01msc2716_insertion_event_edges.sql +38 -0
  810. synapse/storage/schema/main/delta/65/03remove_hidden_devices_from_device_inbox.sql +41 -0
  811. synapse/storage/schema/main/delta/65/04_local_group_updates.sql +37 -0
  812. synapse/storage/schema/main/delta/65/05_remove_room_stats_historical_and_user_stats_historical.sql +38 -0
  813. synapse/storage/schema/main/delta/65/06remove_deleted_devices_from_device_inbox.sql +53 -0
  814. synapse/storage/schema/main/delta/65/07_arbitrary_relations.sql +37 -0
  815. synapse/storage/schema/main/delta/65/08_device_inbox_background_updates.sql +37 -0
  816. synapse/storage/schema/main/delta/65/10_expirable_refresh_tokens.sql +47 -0
  817. synapse/storage/schema/main/delta/65/11_devices_auth_provider_session.sql +46 -0
  818. synapse/storage/schema/main/delta/67/01drop_public_room_list_stream.sql +37 -0
  819. synapse/storage/schema/main/delta/68/01event_columns.sql +45 -0
  820. synapse/storage/schema/main/delta/68/02_msc2409_add_device_id_appservice_stream_type.sql +40 -0
  821. synapse/storage/schema/main/delta/68/03_delete_account_data_for_deactivated_accounts.sql +39 -0
  822. synapse/storage/schema/main/delta/68/04_refresh_tokens_index_next_token_id.sql +47 -0
  823. synapse/storage/schema/main/delta/68/04partial_state_rooms.sql +60 -0
  824. synapse/storage/schema/main/delta/68/05_delete_non_strings_from_event_search.sql.sqlite +22 -0
  825. synapse/storage/schema/main/delta/68/05partial_state_rooms_triggers.py +80 -0
  826. synapse/storage/schema/main/delta/68/06_msc3202_add_device_list_appservice_stream_type.sql +42 -0
  827. synapse/storage/schema/main/delta/69/01as_txn_seq.py +54 -0
  828. synapse/storage/schema/main/delta/69/01device_list_oubound_by_room.sql +57 -0
  829. synapse/storage/schema/main/delta/69/02cache_invalidation_index.sql +37 -0
  830. synapse/storage/schema/main/delta/70/01clean_table_purged_rooms.sql +39 -0
  831. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.postgres +43 -0
  832. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.sqlite +47 -0
  833. synapse/storage/schema/main/delta/71/01remove_noop_background_updates.sql +80 -0
  834. synapse/storage/schema/main/delta/71/02event_push_summary_unique.sql +37 -0
  835. synapse/storage/schema/main/delta/72/01add_room_type_to_state_stats.sql +38 -0
  836. synapse/storage/schema/main/delta/72/01event_push_summary_receipt.sql +54 -0
  837. synapse/storage/schema/main/delta/72/02event_push_actions_index.sql +38 -0
  838. synapse/storage/schema/main/delta/72/03bg_populate_events_columns.py +57 -0
  839. synapse/storage/schema/main/delta/72/03drop_event_reference_hashes.sql +36 -0
  840. synapse/storage/schema/main/delta/72/03remove_groups.sql +50 -0
  841. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.postgres +17 -0
  842. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.sqlite +40 -0
  843. synapse/storage/schema/main/delta/72/05receipts_event_stream_ordering.sql +38 -0
  844. synapse/storage/schema/main/delta/72/05remove_unstable_private_read_receipts.sql +38 -0
  845. synapse/storage/schema/main/delta/72/06add_consent_ts_to_users.sql +35 -0
  846. synapse/storage/schema/main/delta/72/06thread_notifications.sql +49 -0
  847. synapse/storage/schema/main/delta/72/07force_update_current_state_events_membership.py +67 -0
  848. synapse/storage/schema/main/delta/72/07thread_receipts.sql.postgres +30 -0
  849. synapse/storage/schema/main/delta/72/07thread_receipts.sql.sqlite +70 -0
  850. synapse/storage/schema/main/delta/72/08begin_cache_invalidation_seq_at_2.sql.postgres +23 -0
  851. synapse/storage/schema/main/delta/72/08thread_receipts.sql +39 -0
  852. synapse/storage/schema/main/delta/72/09partial_indices.sql.sqlite +56 -0
  853. synapse/storage/schema/main/delta/73/01event_failed_pull_attempts.sql +48 -0
  854. synapse/storage/schema/main/delta/73/02add_pusher_enabled.sql +35 -0
  855. synapse/storage/schema/main/delta/73/02room_id_indexes_for_purging.sql +41 -0
  856. synapse/storage/schema/main/delta/73/03pusher_device_id.sql +39 -0
  857. synapse/storage/schema/main/delta/73/03users_approved_column.sql +39 -0
  858. synapse/storage/schema/main/delta/73/04partial_join_details.sql +42 -0
  859. synapse/storage/schema/main/delta/73/04pending_device_list_updates.sql +47 -0
  860. synapse/storage/schema/main/delta/73/05old_push_actions.sql.postgres +22 -0
  861. synapse/storage/schema/main/delta/73/05old_push_actions.sql.sqlite +24 -0
  862. synapse/storage/schema/main/delta/73/06thread_notifications_thread_id_idx.sql +42 -0
  863. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.postgres +23 -0
  864. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.sqlite +76 -0
  865. synapse/storage/schema/main/delta/73/09partial_joined_via_destination.sql +37 -0
  866. synapse/storage/schema/main/delta/73/09threads_table.sql +49 -0
  867. synapse/storage/schema/main/delta/73/10_update_sqlite_fts4_tokenizer.py +71 -0
  868. synapse/storage/schema/main/delta/73/10login_tokens.sql +54 -0
  869. synapse/storage/schema/main/delta/73/11event_search_room_id_n_distinct.sql.postgres +33 -0
  870. synapse/storage/schema/main/delta/73/12refactor_device_list_outbound_pokes.sql +72 -0
  871. synapse/storage/schema/main/delta/73/13add_device_lists_index.sql +39 -0
  872. synapse/storage/schema/main/delta/73/20_un_partial_stated_room_stream.sql +51 -0
  873. synapse/storage/schema/main/delta/73/21_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  874. synapse/storage/schema/main/delta/73/22_rebuild_user_dir_stats.sql +48 -0
  875. synapse/storage/schema/main/delta/73/22_un_partial_stated_event_stream.sql +53 -0
  876. synapse/storage/schema/main/delta/73/23_fix_thread_index.sql +52 -0
  877. synapse/storage/schema/main/delta/73/23_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  878. synapse/storage/schema/main/delta/73/24_events_jump_to_date_index.sql +36 -0
  879. synapse/storage/schema/main/delta/73/25drop_presence.sql +36 -0
  880. synapse/storage/schema/main/delta/74/01_user_directory_stale_remote_users.sql +58 -0
  881. synapse/storage/schema/main/delta/74/02_set_device_id_for_pushers_bg_update.sql +38 -0
  882. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.postgres +29 -0
  883. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.sqlite +23 -0
  884. synapse/storage/schema/main/delta/74/03_room_membership_index.sql +38 -0
  885. synapse/storage/schema/main/delta/74/04_delete_e2e_backup_keys_for_deactivated_users.sql +36 -0
  886. synapse/storage/schema/main/delta/74/04_membership_tables_event_stream_ordering_triggers.py +87 -0
  887. synapse/storage/schema/main/delta/74/05_events_txn_id_device_id.sql +72 -0
  888. synapse/storage/schema/main/delta/74/90COMMENTS_destinations.sql.postgres +52 -0
  889. synapse/storage/schema/main/delta/76/01_add_profiles_full_user_id_column.sql +39 -0
  890. synapse/storage/schema/main/delta/76/02_add_user_filters_full_user_id_column.sql +39 -0
  891. synapse/storage/schema/main/delta/76/03_per_user_experimental_features.sql +46 -0
  892. synapse/storage/schema/main/delta/76/04_add_room_forgetter.sql +43 -0
  893. synapse/storage/schema/main/delta/77/01_add_profiles_not_valid_check.sql.postgres +16 -0
  894. synapse/storage/schema/main/delta/77/02_add_user_filters_not_valid_check.sql.postgres +16 -0
  895. synapse/storage/schema/main/delta/77/03bg_populate_full_user_id_profiles.sql +35 -0
  896. synapse/storage/schema/main/delta/77/04bg_populate_full_user_id_user_filters.sql +35 -0
  897. synapse/storage/schema/main/delta/77/05thread_notifications_backfill.sql +67 -0
  898. synapse/storage/schema/main/delta/77/06thread_notifications_not_null.sql.sqlite +102 -0
  899. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions.sql.postgres +27 -0
  900. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions_staging.sql.postgres +27 -0
  901. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_summary.sql.postgres +29 -0
  902. synapse/storage/schema/main/delta/77/14bg_indices_event_stream_ordering.sql +39 -0
  903. synapse/storage/schema/main/delta/78/01_validate_and_update_profiles.py +99 -0
  904. synapse/storage/schema/main/delta/78/02_validate_and_update_user_filters.py +100 -0
  905. synapse/storage/schema/main/delta/78/03_remove_unused_indexes_user_filters.py +72 -0
  906. synapse/storage/schema/main/delta/78/03event_extremities_constraints.py +65 -0
  907. synapse/storage/schema/main/delta/78/04_add_full_user_id_index_user_filters.py +32 -0
  908. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.postgres +102 -0
  909. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.sqlite +72 -0
  910. synapse/storage/schema/main/delta/79/04_mitigate_stream_ordering_update_race.py +70 -0
  911. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.postgres +69 -0
  912. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.sqlite +65 -0
  913. synapse/storage/schema/main/delta/80/01_users_alter_locked.sql +35 -0
  914. synapse/storage/schema/main/delta/80/02_read_write_locks_unlogged.sql.postgres +30 -0
  915. synapse/storage/schema/main/delta/80/02_scheduled_tasks.sql +47 -0
  916. synapse/storage/schema/main/delta/80/03_read_write_locks_triggers.sql.postgres +37 -0
  917. synapse/storage/schema/main/delta/80/04_read_write_locks_deadlock.sql.postgres +71 -0
  918. synapse/storage/schema/main/delta/82/02_scheduled_tasks_index.sql +35 -0
  919. synapse/storage/schema/main/delta/82/04_add_indices_for_purging_rooms.sql +39 -0
  920. synapse/storage/schema/main/delta/82/05gaps.sql +44 -0
  921. synapse/storage/schema/main/delta/83/01_drop_old_tables.sql +43 -0
  922. synapse/storage/schema/main/delta/83/03_instance_name_receipts.sql.sqlite +17 -0
  923. synapse/storage/schema/main/delta/83/05_cross_signing_key_update_grant.sql +34 -0
  924. synapse/storage/schema/main/delta/83/06_event_push_summary_room.sql +36 -0
  925. synapse/storage/schema/main/delta/84/01_auth_links_stats.sql.postgres +20 -0
  926. synapse/storage/schema/main/delta/84/02_auth_links_index.sql +16 -0
  927. synapse/storage/schema/main/delta/84/03_auth_links_analyze.sql.postgres +16 -0
  928. synapse/storage/schema/main/delta/84/04_access_token_index.sql +15 -0
  929. synapse/storage/schema/main/delta/85/01_add_suspended.sql +14 -0
  930. synapse/storage/schema/main/delta/85/02_add_instance_names.sql +27 -0
  931. synapse/storage/schema/main/delta/85/03_new_sequences.sql.postgres +54 -0
  932. synapse/storage/schema/main/delta/85/04_cleanup_device_federation_outbox.sql +15 -0
  933. synapse/storage/schema/main/delta/85/05_add_instance_names_converted_pos.sql +16 -0
  934. synapse/storage/schema/main/delta/85/06_add_room_reports.sql +20 -0
  935. synapse/storage/schema/main/delta/86/01_authenticate_media.sql +15 -0
  936. synapse/storage/schema/main/delta/86/02_receipts_event_id_index.sql +15 -0
  937. synapse/storage/schema/main/delta/87/01_sliding_sync_memberships.sql +169 -0
  938. synapse/storage/schema/main/delta/87/02_per_connection_state.sql +81 -0
  939. synapse/storage/schema/main/delta/87/03_current_state_index.sql +19 -0
  940. synapse/storage/schema/main/delta/88/01_add_delayed_events.sql +43 -0
  941. synapse/storage/schema/main/delta/88/01_custom_profile_fields.sql +15 -0
  942. synapse/storage/schema/main/delta/88/02_fix_sliding_sync_membership_snapshots_forgotten_column.sql +21 -0
  943. synapse/storage/schema/main/delta/88/03_add_otk_ts_added_index.sql +18 -0
  944. synapse/storage/schema/main/delta/88/04_current_state_delta_index.sql +18 -0
  945. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.postgres +19 -0
  946. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.sqlite +19 -0
  947. synapse/storage/schema/main/delta/88/05_sliding_sync_room_config_index.sql +20 -0
  948. synapse/storage/schema/main/delta/88/06_events_received_ts_index.sql +17 -0
  949. synapse/storage/schema/main/delta/89/01_sliding_sync_membership_snapshot_index.sql +15 -0
  950. synapse/storage/schema/main/delta/90/01_add_column_participant_room_memberships_table.sql +16 -0
  951. synapse/storage/schema/main/delta/91/01_media_hash.sql +28 -0
  952. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.postgres +16 -0
  953. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.sqlite +16 -0
  954. synapse/storage/schema/main/delta/92/02_remove_populate_participant_bg_update.sql +17 -0
  955. synapse/storage/schema/main/delta/92/04_ss_membership_snapshot_idx.sql +16 -0
  956. synapse/storage/schema/main/delta/92/04_thread_subscriptions.sql +59 -0
  957. synapse/storage/schema/main/delta/92/04_thread_subscriptions_seq.sql.postgres +19 -0
  958. synapse/storage/schema/main/delta/92/05_fixup_max_depth_cap.sql +17 -0
  959. synapse/storage/schema/main/delta/92/05_thread_subscriptions_comments.sql.postgres +18 -0
  960. synapse/storage/schema/main/delta/92/06_device_federation_inbox_index.sql +16 -0
  961. synapse/storage/schema/main/delta/92/06_threads_last_sent_stream_ordering_comments.sql.postgres +24 -0
  962. synapse/storage/schema/main/delta/92/07_add_user_reports.sql +22 -0
  963. synapse/storage/schema/main/delta/92/07_event_txn_id_device_id_txn_id2.sql +15 -0
  964. synapse/storage/schema/main/delta/92/08_room_ban_redactions.sql +21 -0
  965. synapse/storage/schema/main/delta/92/08_thread_subscriptions_seq_fixup.sql.postgres +19 -0
  966. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql +20 -0
  967. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql.postgres +18 -0
  968. synapse/storage/schema/main/delta/93/01_add_delayed_events.sql +15 -0
  969. synapse/storage/schema/main/full_schemas/72/full.sql.postgres +1344 -0
  970. synapse/storage/schema/main/full_schemas/72/full.sql.sqlite +646 -0
  971. synapse/storage/schema/state/delta/23/drop_state_index.sql +35 -0
  972. synapse/storage/schema/state/delta/32/remove_state_indices.sql +38 -0
  973. synapse/storage/schema/state/delta/35/add_state_index.sql +36 -0
  974. synapse/storage/schema/state/delta/35/state.sql +41 -0
  975. synapse/storage/schema/state/delta/35/state_dedupe.sql +36 -0
  976. synapse/storage/schema/state/delta/47/state_group_seq.py +38 -0
  977. synapse/storage/schema/state/delta/56/state_group_room_idx.sql +36 -0
  978. synapse/storage/schema/state/delta/61/02state_groups_state_n_distinct.sql.postgres +34 -0
  979. synapse/storage/schema/state/delta/70/08_state_group_edges_unique.sql +36 -0
  980. synapse/storage/schema/state/delta/89/01_state_groups_deletion.sql +39 -0
  981. synapse/storage/schema/state/delta/90/02_delete_unreferenced_state_groups.sql +16 -0
  982. synapse/storage/schema/state/delta/90/03_remove_old_deletion_bg_update.sql +15 -0
  983. synapse/storage/schema/state/full_schemas/72/full.sql.postgres +30 -0
  984. synapse/storage/schema/state/full_schemas/72/full.sql.sqlite +20 -0
  985. synapse/storage/types.py +183 -0
  986. synapse/storage/util/__init__.py +20 -0
  987. synapse/storage/util/id_generators.py +928 -0
  988. synapse/storage/util/partial_state_events_tracker.py +194 -0
  989. synapse/storage/util/sequence.py +315 -0
  990. synapse/streams/__init__.py +43 -0
  991. synapse/streams/config.py +91 -0
  992. synapse/streams/events.py +203 -0
  993. synapse/synapse_rust/__init__.pyi +3 -0
  994. synapse/synapse_rust/acl.pyi +20 -0
  995. synapse/synapse_rust/events.pyi +136 -0
  996. synapse/synapse_rust/http_client.pyi +32 -0
  997. synapse/synapse_rust/push.pyi +86 -0
  998. synapse/synapse_rust/rendezvous.pyi +30 -0
  999. synapse/synapse_rust/segmenter.pyi +1 -0
  1000. synapse/synapse_rust.abi3.so +0 -0
  1001. synapse/types/__init__.py +1600 -0
  1002. synapse/types/handlers/__init__.py +93 -0
  1003. synapse/types/handlers/policy_server.py +16 -0
  1004. synapse/types/handlers/sliding_sync.py +908 -0
  1005. synapse/types/rest/__init__.py +25 -0
  1006. synapse/types/rest/client/__init__.py +413 -0
  1007. synapse/types/state.py +634 -0
  1008. synapse/types/storage/__init__.py +66 -0
  1009. synapse/util/__init__.py +169 -0
  1010. synapse/util/async_helpers.py +1045 -0
  1011. synapse/util/background_queue.py +142 -0
  1012. synapse/util/batching_queue.py +202 -0
  1013. synapse/util/caches/__init__.py +300 -0
  1014. synapse/util/caches/cached_call.py +143 -0
  1015. synapse/util/caches/deferred_cache.py +530 -0
  1016. synapse/util/caches/descriptors.py +692 -0
  1017. synapse/util/caches/dictionary_cache.py +346 -0
  1018. synapse/util/caches/expiringcache.py +249 -0
  1019. synapse/util/caches/lrucache.py +975 -0
  1020. synapse/util/caches/response_cache.py +322 -0
  1021. synapse/util/caches/stream_change_cache.py +370 -0
  1022. synapse/util/caches/treecache.py +189 -0
  1023. synapse/util/caches/ttlcache.py +197 -0
  1024. synapse/util/cancellation.py +63 -0
  1025. synapse/util/check_dependencies.py +335 -0
  1026. synapse/util/clock.py +567 -0
  1027. synapse/util/constants.py +22 -0
  1028. synapse/util/daemonize.py +165 -0
  1029. synapse/util/distributor.py +157 -0
  1030. synapse/util/events.py +134 -0
  1031. synapse/util/file_consumer.py +164 -0
  1032. synapse/util/frozenutils.py +57 -0
  1033. synapse/util/gai_resolver.py +178 -0
  1034. synapse/util/hash.py +38 -0
  1035. synapse/util/httpresourcetree.py +108 -0
  1036. synapse/util/iterutils.py +189 -0
  1037. synapse/util/json.py +56 -0
  1038. synapse/util/linked_list.py +156 -0
  1039. synapse/util/logcontext.py +46 -0
  1040. synapse/util/logformatter.py +28 -0
  1041. synapse/util/macaroons.py +325 -0
  1042. synapse/util/manhole.py +191 -0
  1043. synapse/util/metrics.py +339 -0
  1044. synapse/util/module_loader.py +116 -0
  1045. synapse/util/msisdn.py +51 -0
  1046. synapse/util/patch_inline_callbacks.py +250 -0
  1047. synapse/util/pydantic_models.py +63 -0
  1048. synapse/util/ratelimitutils.py +419 -0
  1049. synapse/util/retryutils.py +339 -0
  1050. synapse/util/rlimit.py +42 -0
  1051. synapse/util/rust.py +133 -0
  1052. synapse/util/sentinel.py +21 -0
  1053. synapse/util/stringutils.py +293 -0
  1054. synapse/util/task_scheduler.py +493 -0
  1055. synapse/util/templates.py +126 -0
  1056. synapse/util/threepids.py +123 -0
  1057. synapse/util/wheel_timer.py +112 -0
  1058. synapse/visibility.py +835 -0
@@ -0,0 +1,1834 @@
1
+ #
2
+ # This file is licensed under the Affero General Public License (AGPL) version 3.
3
+ #
4
+ # Copyright 2019 The Matrix.org Foundation C.I.C.
5
+ # Copyright 2016 OpenMarket Ltd
6
+ # Copyright (C) 2023 New Vector, Ltd
7
+ #
8
+ # This program is free software: you can redistribute it and/or modify
9
+ # it under the terms of the GNU Affero General Public License as
10
+ # published by the Free Software Foundation, either version 3 of the
11
+ # License, or (at your option) any later version.
12
+ #
13
+ # See the GNU Affero General Public License for more details:
14
+ # <https://www.gnu.org/licenses/agpl-3.0.html>.
15
+ #
16
+ # Originally licensed under the Apache License, Version 2.0:
17
+ # <http://www.apache.org/licenses/LICENSE-2.0>.
18
+ #
19
+ # [This file includes modifications made by New Vector Limited]
20
+ #
21
+ #
22
+ import logging
23
+ from typing import TYPE_CHECKING, Iterable, Mapping
24
+
25
+ import attr
26
+ from canonicaljson import encode_canonical_json
27
+ from signedjson.key import VerifyKey, decode_verify_key_bytes
28
+ from signedjson.sign import SignatureVerifyException, verify_signed_json
29
+ from unpaddedbase64 import decode_base64
30
+
31
+ from twisted.internet import defer
32
+
33
+ from synapse.api.constants import EduTypes
34
+ from synapse.api.errors import CodeMessageException, Codes, NotFoundError, SynapseError
35
+ from synapse.handlers.device import DeviceWriterHandler
36
+ from synapse.logging.context import make_deferred_yieldable, run_in_background
37
+ from synapse.logging.opentracing import log_kv, set_tag, tag_args, trace
38
+ from synapse.types import (
39
+ JsonDict,
40
+ JsonMapping,
41
+ ScheduledTask,
42
+ TaskStatus,
43
+ UserID,
44
+ get_domain_from_id,
45
+ get_verify_key_from_cross_signing_key,
46
+ )
47
+ from synapse.util.async_helpers import Linearizer, concurrently_execute
48
+ from synapse.util.cancellation import cancellable
49
+ from synapse.util.json import json_decoder
50
+ from synapse.util.retryutils import (
51
+ NotRetryingDestination,
52
+ filter_destinations_by_retry_limiter,
53
+ )
54
+
55
+ if TYPE_CHECKING:
56
+ from synapse.server import HomeServer
57
+
58
+ logger = logging.getLogger(__name__)
59
+
60
+ ONE_TIME_KEY_UPLOAD = "one_time_key_upload_lock"
61
+
62
+
63
+ class E2eKeysHandler:
64
+ def __init__(self, hs: "HomeServer"):
65
+ self.config = hs.config
66
+ self.store = hs.get_datastores().main
67
+ self.federation = hs.get_federation_client()
68
+ self.device_handler = hs.get_device_handler()
69
+ self._appservice_handler = hs.get_application_service_handler()
70
+ self.is_mine = hs.is_mine
71
+ self.clock = hs.get_clock()
72
+ self._worker_lock_handler = hs.get_worker_locks_handler()
73
+ self._task_scheduler = hs.get_task_scheduler()
74
+
75
+ federation_registry = hs.get_federation_registry()
76
+
77
+ # Only the first writer in the list should handle EDUs for signing key
78
+ # updates, so that we can use an in-memory linearizer instead of worker locks.
79
+ edu_writer = hs.config.worker.writers.device_lists[0]
80
+ if hs.get_instance_name() == edu_writer:
81
+ edu_updater = SigningKeyEduUpdater(hs)
82
+
83
+ # Only register this edu handler on master as it requires writing
84
+ # device updates to the db
85
+ federation_registry.register_edu_handler(
86
+ EduTypes.SIGNING_KEY_UPDATE,
87
+ edu_updater.incoming_signing_key_update,
88
+ )
89
+ # also handle the unstable version
90
+ # FIXME: remove this when enough servers have upgraded
91
+ federation_registry.register_edu_handler(
92
+ EduTypes.UNSTABLE_SIGNING_KEY_UPDATE,
93
+ edu_updater.incoming_signing_key_update,
94
+ )
95
+ else:
96
+ federation_registry.register_instances_for_edu(
97
+ EduTypes.SIGNING_KEY_UPDATE,
98
+ [edu_writer],
99
+ )
100
+ federation_registry.register_instances_for_edu(
101
+ EduTypes.UNSTABLE_SIGNING_KEY_UPDATE,
102
+ [edu_writer],
103
+ )
104
+
105
+ # doesn't really work as part of the generic query API, because the
106
+ # query request requires an object POST, but we abuse the
107
+ # "query handler" interface.
108
+ federation_registry.register_query_handler(
109
+ "client_keys", self.on_federation_query_client_keys
110
+ )
111
+
112
+ # Limit the number of in-flight requests from a single device.
113
+ self._query_devices_linearizer = Linearizer(
114
+ name="query_devices", max_count=10, clock=hs.get_clock()
115
+ )
116
+
117
+ self._query_appservices_for_otks = (
118
+ hs.config.experimental.msc3983_appservice_otk_claims
119
+ )
120
+ self._query_appservices_for_keys = (
121
+ hs.config.experimental.msc3984_appservice_key_query
122
+ )
123
+
124
+ self._task_scheduler.register_action(
125
+ self._delete_old_one_time_keys_task, "delete_old_otks"
126
+ )
127
+
128
+ @trace
129
+ @cancellable
130
+ async def query_devices(
131
+ self,
132
+ query_body: JsonDict,
133
+ timeout: int,
134
+ from_user_id: str,
135
+ from_device_id: str | None,
136
+ ) -> JsonDict:
137
+ """Handle a device key query from a client
138
+
139
+ {
140
+ "device_keys": {
141
+ "<user_id>": ["<device_id>"]
142
+ }
143
+ }
144
+ ->
145
+ {
146
+ "device_keys": {
147
+ "<user_id>": {
148
+ "<device_id>": {
149
+ ...
150
+ }
151
+ }
152
+ }
153
+ }
154
+
155
+ Args:
156
+ from_user_id: the user making the query. This is used when
157
+ adding cross-signing signatures to limit what signatures users
158
+ can see.
159
+ from_device_id: the device making the query. This is used to limit
160
+ the number of in-flight queries at a time.
161
+ """
162
+ async with self._query_devices_linearizer.queue((from_user_id, from_device_id)):
163
+
164
+ async def filter_device_key_query(
165
+ query: dict[str, list[str]],
166
+ ) -> dict[str, list[str]]:
167
+ if not self.config.experimental.msc4263_limit_key_queries_to_users_who_share_rooms:
168
+ # Only ignore invalid user IDs, which is the same behaviour as if
169
+ # the user existed but had no keys.
170
+ return {
171
+ user_id: v
172
+ for user_id, v in query.items()
173
+ if UserID.is_valid(user_id)
174
+ }
175
+
176
+ # Strip invalid user IDs and user IDs the requesting user does not share rooms with.
177
+ valid_user_ids = [
178
+ user_id for user_id in query.keys() if UserID.is_valid(user_id)
179
+ ]
180
+ allowed_user_ids = set(
181
+ await self.store.do_users_share_a_room_joined_or_invited(
182
+ from_user_id, valid_user_ids
183
+ )
184
+ )
185
+ return {
186
+ user_id: v
187
+ for user_id, v in query.items()
188
+ if user_id in allowed_user_ids
189
+ }
190
+
191
+ device_keys_query: dict[str, list[str]] = await filter_device_key_query(
192
+ query_body.get("device_keys", {})
193
+ )
194
+
195
+ # separate users by domain.
196
+ # make a map from domain to user_id to device_ids
197
+ local_query = {}
198
+ remote_queries = {}
199
+
200
+ for user_id, device_ids in device_keys_query.items():
201
+ # we use UserID.from_string to catch invalid user ids
202
+ if self.is_mine(UserID.from_string(user_id)):
203
+ local_query[user_id] = device_ids
204
+ else:
205
+ remote_queries[user_id] = device_ids
206
+
207
+ set_tag("local_key_query", str(local_query))
208
+ set_tag("remote_key_query", str(remote_queries))
209
+
210
+ # First get local devices.
211
+ # A map of destination -> failure response.
212
+ failures: dict[str, JsonDict] = {}
213
+ results = {}
214
+ if local_query:
215
+ local_result = await self.query_local_devices(local_query)
216
+ for user_id, keys in local_result.items():
217
+ if user_id in local_query:
218
+ results[user_id] = keys
219
+
220
+ # Get cached cross-signing keys
221
+ cross_signing_keys = await self.get_cross_signing_keys_from_cache(
222
+ device_keys_query, from_user_id
223
+ )
224
+
225
+ # Now attempt to get any remote devices from our local cache.
226
+ # A map of destination -> user ID -> device IDs.
227
+ remote_queries_not_in_cache: dict[str, dict[str, Iterable[str]]] = {}
228
+ if remote_queries:
229
+ user_ids = set()
230
+ user_and_device_ids: list[tuple[str, str]] = []
231
+ for user_id, device_ids in remote_queries.items():
232
+ if device_ids:
233
+ user_and_device_ids.extend(
234
+ (user_id, device_id) for device_id in device_ids
235
+ )
236
+ else:
237
+ user_ids.add(user_id)
238
+
239
+ (
240
+ user_ids_not_in_cache,
241
+ remote_results,
242
+ ) = await self.store.get_user_devices_from_cache(
243
+ user_ids, user_and_device_ids
244
+ )
245
+
246
+ # Check that the homeserver still shares a room with all cached users.
247
+ # Note that this check may be slightly racy when a remote user leaves a
248
+ # room after we have fetched their cached device list. In the worst case
249
+ # we will do extra federation queries for devices that we had cached.
250
+ cached_users = set(remote_results.keys())
251
+ valid_cached_users = (
252
+ await self.store.get_users_server_still_shares_room_with(
253
+ remote_results.keys()
254
+ )
255
+ )
256
+ invalid_cached_users = cached_users - valid_cached_users
257
+ if invalid_cached_users:
258
+ # Fix up results. If we get here, it means there was either a bug in
259
+ # device list tracking, or we hit the race mentioned above.
260
+ # TODO: In practice, this path is hit fairly often in existing
261
+ # deployments when clients query the keys of departed remote
262
+ # users. A background update to mark the appropriate device
263
+ # lists as unsubscribed is needed.
264
+ # https://github.com/matrix-org/synapse/issues/13651
265
+ # Note that this currently introduces a failure mode when clients
266
+ # are trying to decrypt old messages from a remote user whose
267
+ # homeserver is no longer available. We may want to consider falling
268
+ # back to the cached data when we fail to retrieve a device list
269
+ # over federation for such remote users.
270
+ user_ids_not_in_cache.update(invalid_cached_users)
271
+ for invalid_user_id in invalid_cached_users:
272
+ remote_results.pop(invalid_user_id)
273
+
274
+ for user_id, devices in remote_results.items():
275
+ user_devices = results.setdefault(user_id, {})
276
+ for device_id, device in devices.items():
277
+ keys = device.get("keys", None)
278
+ device_display_name = device.get("device_display_name", None)
279
+ if keys:
280
+ result = dict(keys)
281
+ unsigned = result.setdefault("unsigned", {})
282
+ if device_display_name:
283
+ unsigned["device_display_name"] = device_display_name
284
+ user_devices[device_id] = result
285
+
286
+ # check for missing cross-signing keys.
287
+ for user_id in remote_queries.keys():
288
+ cached_cross_master = user_id in cross_signing_keys["master_keys"]
289
+ cached_cross_selfsigning = (
290
+ user_id in cross_signing_keys["self_signing_keys"]
291
+ )
292
+
293
+ # check if we are missing only one of cross-signing master or
294
+ # self-signing key, but the other one is cached.
295
+ # as we need both, this will issue a federation request.
296
+ # if we don't have any of the keys, either the user doesn't have
297
+ # cross-signing set up, or the cached device list
298
+ # is not (yet) updated.
299
+ if cached_cross_master ^ cached_cross_selfsigning:
300
+ user_ids_not_in_cache.add(user_id)
301
+
302
+ # add those users to the list to fetch over federation.
303
+ for user_id in user_ids_not_in_cache:
304
+ domain = get_domain_from_id(user_id)
305
+ r = remote_queries_not_in_cache.setdefault(domain, {})
306
+ r[user_id] = remote_queries[user_id]
307
+
308
+ # Now fetch any devices that we don't have in our cache
309
+ # TODO It might make sense to propagate cancellations into the
310
+ # deferreds which are querying remote homeservers.
311
+ logger.debug(
312
+ "%d destinations to query devices for", len(remote_queries_not_in_cache)
313
+ )
314
+
315
+ async def _query(destination: str) -> None:
316
+ queries = remote_queries_not_in_cache[destination]
317
+ return await self._query_devices_for_destination(
318
+ results,
319
+ cross_signing_keys,
320
+ failures,
321
+ destination,
322
+ queries,
323
+ timeout,
324
+ )
325
+
326
+ # Only try and fetch keys for destinations that are not marked as
327
+ # down.
328
+ unfiltered_destinations = remote_queries_not_in_cache.keys()
329
+ filtered_destinations = set(
330
+ await filter_destinations_by_retry_limiter(
331
+ unfiltered_destinations,
332
+ self.clock,
333
+ self.store,
334
+ # Let's give an arbitrary grace period for those hosts that are
335
+ # only recently down
336
+ retry_due_within_ms=60 * 1000,
337
+ )
338
+ )
339
+ failures.update(
340
+ (dest, _NOT_READY_FOR_RETRY_FAILURE)
341
+ for dest in (unfiltered_destinations - filtered_destinations)
342
+ )
343
+
344
+ await concurrently_execute(
345
+ _query,
346
+ filtered_destinations,
347
+ 10,
348
+ delay_cancellation=True,
349
+ )
350
+
351
+ return {"device_keys": results, "failures": failures, **cross_signing_keys}
352
+
353
+ @trace
354
+ async def _query_devices_for_destination(
355
+ self,
356
+ results: JsonDict,
357
+ cross_signing_keys: JsonDict,
358
+ failures: dict[str, JsonDict],
359
+ destination: str,
360
+ destination_query: dict[str, Iterable[str]],
361
+ timeout: int,
362
+ ) -> None:
363
+ """This is called when we are querying the device list of a user on
364
+ a remote homeserver and their device list is not in the device list
365
+ cache. If we share a room with this user and we're not querying for
366
+ specific user we will update the cache with their device list.
367
+
368
+ Args:
369
+ results: A map from user ID to their device keys, which gets
370
+ updated with the newly fetched keys.
371
+ cross_signing_keys: Map from user ID to their cross signing keys,
372
+ which gets updated with the newly fetched keys.
373
+ failures: Map of destinations to failures that have occurred while
374
+ attempting to fetch keys.
375
+ destination: The remote server to query
376
+ destination_query: The query dict of devices to query the remote
377
+ server for.
378
+ timeout: The timeout for remote HTTP requests.
379
+ """
380
+
381
+ # We first consider whether we wish to update the device list cache with
382
+ # the users device list. We want to track a user's devices when the
383
+ # authenticated user shares a room with the queried user and the query
384
+ # has not specified a particular device.
385
+ # If we update the cache for the queried user we remove them from further
386
+ # queries. We use the more efficient batched query_client_keys for all
387
+ # remaining users
388
+ user_ids_updated = []
389
+
390
+ # Perform a user device resync for each user only once and only as long as:
391
+ # - they have an empty device_list
392
+ # - they are in some rooms that this server can see
393
+ users_to_resync_devices = {
394
+ user_id
395
+ for (user_id, device_list) in destination_query.items()
396
+ if (not device_list) and (await self.store.get_rooms_for_user(user_id))
397
+ }
398
+
399
+ logger.debug(
400
+ "%d users to resync devices for from destination %s",
401
+ len(users_to_resync_devices),
402
+ destination,
403
+ )
404
+
405
+ try:
406
+ user_resync_results = (
407
+ await self.device_handler.device_list_updater.multi_user_device_resync(
408
+ list(users_to_resync_devices)
409
+ )
410
+ )
411
+ for user_id in users_to_resync_devices:
412
+ resync_results = user_resync_results[user_id]
413
+
414
+ if resync_results is None:
415
+ # TODO: It's weird that we'll store a failure against a
416
+ # destination, yet continue processing users from that
417
+ # destination.
418
+ # We might want to consider changing this, but for now
419
+ # I'm leaving it as I found it.
420
+ failures[destination] = _exception_to_failure(
421
+ ValueError(f"Device resync failed for {user_id!r}")
422
+ )
423
+ continue
424
+
425
+ # Add the device keys to the results.
426
+ user_devices = resync_results["devices"]
427
+ user_results = results.setdefault(user_id, {})
428
+ for device in user_devices:
429
+ user_results[device["device_id"]] = device["keys"]
430
+ user_ids_updated.append(user_id)
431
+
432
+ # Add any cross signing keys to the results.
433
+ master_key = resync_results.get("master_key")
434
+ self_signing_key = resync_results.get("self_signing_key")
435
+
436
+ if master_key:
437
+ cross_signing_keys["master_keys"][user_id] = master_key
438
+
439
+ if self_signing_key:
440
+ cross_signing_keys["self_signing_keys"][user_id] = self_signing_key
441
+ except Exception as e:
442
+ failures[destination] = _exception_to_failure(e)
443
+
444
+ if len(destination_query) == len(user_ids_updated):
445
+ # We've updated all the users in the query and we do not need to
446
+ # make any further remote calls.
447
+ return
448
+
449
+ # Remove all the users from the query which we have updated
450
+ for user_id in user_ids_updated:
451
+ destination_query.pop(user_id)
452
+
453
+ try:
454
+ remote_result = await self.federation.query_client_keys(
455
+ destination, {"device_keys": destination_query}, timeout=timeout
456
+ )
457
+
458
+ for user_id, keys in remote_result["device_keys"].items():
459
+ if user_id in destination_query:
460
+ results[user_id] = keys
461
+
462
+ if "master_keys" in remote_result:
463
+ for user_id, key in remote_result["master_keys"].items():
464
+ if user_id in destination_query:
465
+ cross_signing_keys["master_keys"][user_id] = key
466
+
467
+ if "self_signing_keys" in remote_result:
468
+ for user_id, key in remote_result["self_signing_keys"].items():
469
+ if user_id in destination_query:
470
+ cross_signing_keys["self_signing_keys"][user_id] = key
471
+
472
+ except Exception as e:
473
+ failure = _exception_to_failure(e)
474
+ failures[destination] = failure
475
+ set_tag("error", True)
476
+ set_tag("reason", str(failure))
477
+
478
+ return
479
+
480
+ @cancellable
481
+ async def get_cross_signing_keys_from_cache(
482
+ self, query: Iterable[str], from_user_id: str | None
483
+ ) -> dict[str, dict[str, JsonMapping]]:
484
+ """Get cross-signing keys for users from the database
485
+
486
+ Args:
487
+ query: an iterable of user IDs. A dict whose keys
488
+ are user IDs satisfies this, so the query format used for
489
+ query_devices can be used here.
490
+ from_user_id: the user making the query. This is used when
491
+ adding cross-signing signatures to limit what signatures users
492
+ can see.
493
+
494
+ Returns:
495
+ A map from (master_keys|self_signing_keys|user_signing_keys) -> user_id -> key
496
+ """
497
+ master_keys = {}
498
+ self_signing_keys = {}
499
+ user_signing_keys = {}
500
+
501
+ user_ids = list(query)
502
+
503
+ keys = await self.store.get_e2e_cross_signing_keys_bulk(user_ids, from_user_id)
504
+
505
+ for user_id, user_info in keys.items():
506
+ if user_info is None:
507
+ continue
508
+ if "master" in user_info:
509
+ master_keys[user_id] = user_info["master"]
510
+ if "self_signing" in user_info:
511
+ self_signing_keys[user_id] = user_info["self_signing"]
512
+
513
+ # users can see other users' master and self-signing keys, but can
514
+ # only see their own user-signing keys
515
+ if from_user_id:
516
+ from_user_key = keys.get(from_user_id)
517
+ if from_user_key and "user_signing" in from_user_key:
518
+ user_signing_keys[from_user_id] = from_user_key["user_signing"]
519
+
520
+ return {
521
+ "master_keys": master_keys,
522
+ "self_signing_keys": self_signing_keys,
523
+ "user_signing_keys": user_signing_keys,
524
+ }
525
+
526
+ @trace
527
+ @cancellable
528
+ async def query_local_devices(
529
+ self,
530
+ query: Mapping[str, list[str] | None],
531
+ include_displaynames: bool = True,
532
+ ) -> dict[str, dict[str, dict]]:
533
+ """Get E2E device keys for local users
534
+
535
+ Args:
536
+ query: map from user_id to a list
537
+ of devices to query (None for all devices)
538
+ include_displaynames: Whether to include device displaynames in the returned
539
+ device details.
540
+
541
+ Returns:
542
+ A map from user_id -> device_id -> device details
543
+ """
544
+ set_tag("local_query", str(query))
545
+ local_query: list[tuple[str, str | None]] = []
546
+
547
+ result_dict: dict[str, dict[str, dict]] = {}
548
+ for user_id, device_ids in query.items():
549
+ # we use UserID.from_string to catch invalid user ids
550
+ if not self.is_mine(UserID.from_string(user_id)):
551
+ logger.warning("Request for keys for non-local user %s", user_id)
552
+ log_kv(
553
+ {
554
+ "message": "Requested a local key for a user which"
555
+ " was not local to the homeserver",
556
+ "user_id": user_id,
557
+ }
558
+ )
559
+ set_tag("error", True)
560
+ raise SynapseError(400, "Not a user here")
561
+
562
+ if not device_ids:
563
+ local_query.append((user_id, None))
564
+ else:
565
+ for device_id in device_ids:
566
+ local_query.append((user_id, device_id))
567
+
568
+ # make sure that each queried user appears in the result dict
569
+ result_dict[user_id] = {}
570
+
571
+ results = await self.store.get_e2e_device_keys_for_cs_api(
572
+ local_query, include_displaynames
573
+ )
574
+
575
+ # Check if the application services have any additional results.
576
+ if self._query_appservices_for_keys:
577
+ # Query the appservices for any keys.
578
+ appservice_results = await self._appservice_handler.query_keys(query)
579
+
580
+ # Merge results, overriding with what the appservice returned.
581
+ for user_id, devices in appservice_results.get("device_keys", {}).items():
582
+ # Copy the appservice device info over the homeserver device info, but
583
+ # don't completely overwrite it.
584
+ results.setdefault(user_id, {}).update(devices)
585
+
586
+ # TODO Handle cross-signing keys.
587
+
588
+ # Build the result structure
589
+ for user_id, device_keys in results.items():
590
+ for device_id, device_info in device_keys.items():
591
+ result_dict[user_id][device_id] = device_info
592
+
593
+ log_kv(results)
594
+ return result_dict
595
+
596
+ async def on_federation_query_client_keys(
597
+ self, query_body: dict[str, dict[str, list[str] | None]]
598
+ ) -> JsonDict:
599
+ """Handle a device key query from a federated server:
600
+
601
+ Handles the path: GET /_matrix/federation/v1/users/keys/query
602
+
603
+ Args:
604
+ query_body: The body of the query request. Should contain a key
605
+ "device_keys" that map to a dictionary of user ID's -> list of
606
+ device IDs. If the list of device IDs is empty, all devices of
607
+ that user will be queried.
608
+
609
+ Returns:
610
+ A json dictionary containing the following:
611
+ - device_keys: A dictionary containing the requested device information.
612
+ - master_keys: An optional dictionary of user ID -> master cross-signing
613
+ key info.
614
+ - self_signing_key: An optional dictionary of user ID -> self-signing
615
+ key info.
616
+ """
617
+ device_keys_query: dict[str, list[str] | None] = query_body.get(
618
+ "device_keys", {}
619
+ )
620
+ if any(
621
+ not self.is_mine(UserID.from_string(user_id))
622
+ for user_id in device_keys_query
623
+ ):
624
+ raise SynapseError(400, "User is not hosted on this homeserver")
625
+
626
+ res = await self.query_local_devices(
627
+ device_keys_query,
628
+ include_displaynames=(
629
+ self.config.federation.allow_device_name_lookup_over_federation
630
+ ),
631
+ )
632
+
633
+ # add in the cross-signing keys
634
+ cross_signing_keys = await self.get_cross_signing_keys_from_cache(
635
+ device_keys_query, None
636
+ )
637
+
638
+ return {"device_keys": res, **cross_signing_keys}
639
+
640
+ async def claim_local_one_time_keys(
641
+ self,
642
+ local_query: list[tuple[str, str, str, int]],
643
+ always_include_fallback_keys: bool,
644
+ ) -> Iterable[dict[str, dict[str, dict[str, JsonDict]]]]:
645
+ """Claim one time keys for local users.
646
+
647
+ 1. Attempt to claim OTKs from the database.
648
+ 2. Ask application services if they provide OTKs.
649
+ 3. Attempt to fetch fallback keys from the database.
650
+
651
+ Args:
652
+ local_query: An iterable of tuples of (user ID, device ID, algorithm, number of keys).
653
+ always_include_fallback_keys: True to always include fallback keys.
654
+
655
+ Returns:
656
+ An iterable of maps of user ID -> a map device ID -> a map of key ID -> JSON bytes.
657
+ """
658
+
659
+ # Cap the number of OTKs that can be claimed at once to avoid abuse.
660
+ local_query = [
661
+ (user_id, device_id, algorithm, min(count, 5))
662
+ for user_id, device_id, algorithm, count in local_query
663
+ ]
664
+
665
+ otk_results, not_found = await self.store.claim_e2e_one_time_keys(local_query)
666
+
667
+ # If the application services have not provided any keys via the C-S
668
+ # API, query it directly for one-time keys.
669
+ if self._query_appservices_for_otks:
670
+ # TODO Should this query for fallback keys of uploaded OTKs if
671
+ # always_include_fallback_keys is True? The MSC is ambiguous.
672
+ (
673
+ appservice_results,
674
+ not_found,
675
+ ) = await self._appservice_handler.claim_e2e_one_time_keys(not_found)
676
+ else:
677
+ appservice_results = {}
678
+
679
+ # Calculate which user ID / device ID / algorithm tuples to get fallback
680
+ # keys for. This can be either only missing results *or* all results
681
+ # (which don't already have a fallback key).
682
+ if always_include_fallback_keys:
683
+ # Build the fallback query as any part of the original query where
684
+ # the appservice didn't respond with a fallback key.
685
+ fallback_query = []
686
+
687
+ # Iterate each item in the original query and search the results
688
+ # from the appservice for that user ID / device ID. If it is found,
689
+ # check if any of the keys match the requested algorithm & are a
690
+ # fallback key.
691
+ for user_id, device_id, algorithm, _count in local_query:
692
+ # Check if the appservice responded for this query.
693
+ as_result = appservice_results.get(user_id, {}).get(device_id, {})
694
+ found_otk = False
695
+ for key_id, key_json in as_result.items():
696
+ if key_id.startswith(f"{algorithm}:"):
697
+ # A OTK or fallback key was found for this query.
698
+ found_otk = True
699
+ # A fallback key was found for this query, no need to
700
+ # query further.
701
+ if key_json.get("fallback", False):
702
+ break
703
+
704
+ else:
705
+ # No fallback key was found from appservices, query for it.
706
+ # Only mark the fallback key as used if no OTK was found
707
+ # (from either the database or appservices).
708
+ mark_as_used = not found_otk and not any(
709
+ key_id.startswith(f"{algorithm}:")
710
+ for key_id in otk_results.get(user_id, {})
711
+ .get(device_id, {})
712
+ .keys()
713
+ )
714
+ # Note that it doesn't make sense to request more than 1 fallback key
715
+ # per (user_id, device_id, algorithm).
716
+ fallback_query.append((user_id, device_id, algorithm, mark_as_used))
717
+
718
+ else:
719
+ # All fallback keys get marked as used.
720
+ fallback_query = [
721
+ # Note that it doesn't make sense to request more than 1 fallback key
722
+ # per (user_id, device_id, algorithm).
723
+ (user_id, device_id, algorithm, True)
724
+ for user_id, device_id, algorithm, count in not_found
725
+ ]
726
+
727
+ # For each user that does not have a one-time keys available, see if
728
+ # there is a fallback key.
729
+ fallback_results = await self.store.claim_e2e_fallback_keys(fallback_query)
730
+
731
+ # Return the results in order, each item from the input query should
732
+ # only appear once in the combined list.
733
+ return (otk_results, appservice_results, fallback_results)
734
+
735
+ @trace
736
+ async def claim_one_time_keys(
737
+ self,
738
+ query: dict[str, dict[str, dict[str, int]]],
739
+ user: UserID,
740
+ timeout: int | None,
741
+ always_include_fallback_keys: bool,
742
+ ) -> JsonDict:
743
+ """
744
+ Args:
745
+ query: A chain of maps from (user_id, device_id, algorithm) to the requested
746
+ number of keys to claim.
747
+ user: The user who is claiming these keys.
748
+ timeout: How long to wait for any federation key claim requests before
749
+ giving up.
750
+ always_include_fallback_keys: always include a fallback key for local users'
751
+ devices, even if we managed to claim a one-time-key.
752
+
753
+ Returns: a heterogeneous dict with two keys:
754
+ one_time_keys: chain of maps user ID -> device ID -> key ID -> key.
755
+ failures: map from remote destination to a JsonDict describing the error.
756
+ """
757
+ local_query: list[tuple[str, str, str, int]] = []
758
+ remote_queries: dict[str, dict[str, dict[str, dict[str, int]]]] = {}
759
+
760
+ for user_id, one_time_keys in query.items():
761
+ # we use UserID.from_string to catch invalid user ids
762
+ if self.is_mine(UserID.from_string(user_id)):
763
+ for device_id, algorithms in one_time_keys.items():
764
+ for algorithm, count in algorithms.items():
765
+ local_query.append((user_id, device_id, algorithm, count))
766
+ else:
767
+ domain = get_domain_from_id(user_id)
768
+ remote_queries.setdefault(domain, {})[user_id] = one_time_keys
769
+
770
+ set_tag("local_key_query", str(local_query))
771
+ set_tag("remote_key_query", str(remote_queries))
772
+
773
+ results = await self.claim_local_one_time_keys(
774
+ local_query, always_include_fallback_keys
775
+ )
776
+
777
+ # A map of user ID -> device ID -> key ID -> key.
778
+ json_result: dict[str, dict[str, dict[str, JsonDict]]] = {}
779
+ for result in results:
780
+ for user_id, device_keys in result.items():
781
+ for device_id, keys in device_keys.items():
782
+ for key_id, key in keys.items():
783
+ json_result.setdefault(user_id, {}).setdefault(
784
+ device_id, {}
785
+ ).update({key_id: key})
786
+
787
+ # Remote failures.
788
+ failures: dict[str, JsonDict] = {}
789
+
790
+ @trace
791
+ async def claim_client_keys(destination: str) -> None:
792
+ set_tag("destination", destination)
793
+ device_keys = remote_queries[destination]
794
+ try:
795
+ remote_result = await self.federation.claim_client_keys(
796
+ user, destination, device_keys, timeout=timeout
797
+ )
798
+ for user_id, keys in remote_result["one_time_keys"].items():
799
+ if user_id in device_keys:
800
+ json_result[user_id] = keys
801
+
802
+ except Exception as e:
803
+ failure = _exception_to_failure(e)
804
+ failures[destination] = failure
805
+ set_tag("error", True)
806
+ set_tag("reason", str(failure))
807
+
808
+ await make_deferred_yieldable(
809
+ defer.gatherResults(
810
+ [
811
+ run_in_background(claim_client_keys, destination)
812
+ for destination in remote_queries
813
+ ],
814
+ consumeErrors=True,
815
+ )
816
+ )
817
+
818
+ logger.info(
819
+ "Claimed one-time-keys: %s",
820
+ ",".join(
821
+ (
822
+ "%s for %s:%s" % (key_id, user_id, device_id)
823
+ for user_id, user_keys in json_result.items()
824
+ for device_id, device_keys in user_keys.items()
825
+ for key_id, _ in device_keys.items()
826
+ )
827
+ ),
828
+ )
829
+
830
+ log_kv({"one_time_keys": json_result, "failures": failures})
831
+ return {"one_time_keys": json_result, "failures": failures}
832
+
833
+ @tag_args
834
+ async def upload_keys_for_user(
835
+ self, user_id: str, device_id: str, keys: JsonDict
836
+ ) -> JsonDict:
837
+ """
838
+ Args:
839
+ user_id: user whose keys are being uploaded.
840
+ device_id: device whose keys are being uploaded.
841
+ keys: the body of a /keys/upload request.
842
+
843
+ Returns a dictionary with one field:
844
+ "one_time_keys": A mapping from algorithm to number of keys for that
845
+ algorithm, including those previously persisted.
846
+ """
847
+ time_now = self.clock.time_msec()
848
+
849
+ device_keys = keys.get("device_keys", None)
850
+ if device_keys:
851
+ log_kv(
852
+ {
853
+ "message": "Updating device_keys for user.",
854
+ "user_id": user_id,
855
+ "device_id": device_id,
856
+ }
857
+ )
858
+ await self.upload_device_keys_for_user(
859
+ user_id=user_id,
860
+ device_id=device_id,
861
+ keys={"device_keys": device_keys},
862
+ )
863
+ else:
864
+ log_kv({"message": "Did not update device_keys", "reason": "not a dict"})
865
+
866
+ one_time_keys = keys.get("one_time_keys", None)
867
+ if one_time_keys:
868
+ log_kv(
869
+ {
870
+ "message": "Updating one_time_keys for device.",
871
+ "user_id": user_id,
872
+ "device_id": device_id,
873
+ }
874
+ )
875
+ await self._upload_one_time_keys_for_user(
876
+ user_id, device_id, time_now, one_time_keys
877
+ )
878
+ else:
879
+ log_kv(
880
+ {"message": "Did not update one_time_keys", "reason": "no keys given"}
881
+ )
882
+
883
+ fallback_keys = keys.get("fallback_keys")
884
+ if fallback_keys:
885
+ log_kv(
886
+ {
887
+ "message": "Updating fallback_keys for device.",
888
+ "user_id": user_id,
889
+ "device_id": device_id,
890
+ }
891
+ )
892
+ await self.store.set_e2e_fallback_keys(user_id, device_id, fallback_keys)
893
+ else:
894
+ log_kv(
895
+ {"message": "Did not update fallback_keys", "reason": "no keys given"}
896
+ )
897
+
898
+ result = await self.store.count_e2e_one_time_keys(user_id, device_id)
899
+
900
+ set_tag("one_time_key_counts", str(result))
901
+ return {"one_time_key_counts": result}
902
+
903
+ @tag_args
904
+ async def upload_device_keys_for_user(
905
+ self, user_id: str, device_id: str, keys: JsonDict
906
+ ) -> None:
907
+ """
908
+ Args:
909
+ user_id: user whose keys are being uploaded.
910
+ device_id: device whose keys are being uploaded.
911
+ device_keys: the `device_keys` of an /keys/upload request.
912
+
913
+ """
914
+ time_now = self.clock.time_msec()
915
+
916
+ device_keys = keys["device_keys"]
917
+ logger.info(
918
+ "Updating device_keys for device %r for user %s at %d",
919
+ device_id,
920
+ user_id,
921
+ time_now,
922
+ )
923
+ log_kv(
924
+ {
925
+ "message": "Updating device_keys for user.",
926
+ "user_id": user_id,
927
+ "device_id": device_id,
928
+ }
929
+ )
930
+ # TODO: Sign the JSON with the server key
931
+ changed = await self.store.set_e2e_device_keys(
932
+ user_id, device_id, time_now, device_keys
933
+ )
934
+ if changed:
935
+ # Only notify about device updates *if* the keys actually changed
936
+ await self.device_handler.notify_device_update(user_id, [device_id])
937
+
938
+ # the device should have been registered already, but it may have been
939
+ # deleted due to a race with a DELETE request. Or we may be using an
940
+ # old access_token without an associated device_id. Either way, we
941
+ # need to double-check the device is registered to avoid ending up with
942
+ # keys without a corresponding device.
943
+ await self.device_handler.check_device_registered(user_id, device_id)
944
+
945
+ async def _upload_one_time_keys_for_user(
946
+ self, user_id: str, device_id: str, time_now: int, one_time_keys: JsonDict
947
+ ) -> None:
948
+ # We take out a lock so that we don't have to worry about a client
949
+ # sending duplicate requests.
950
+ lock_key = f"{user_id}_{device_id}"
951
+ async with self._worker_lock_handler.acquire_lock(
952
+ ONE_TIME_KEY_UPLOAD, lock_key
953
+ ):
954
+ logger.info(
955
+ "Adding one_time_keys %r for device %r for user %r at %d",
956
+ one_time_keys.keys(),
957
+ device_id,
958
+ user_id,
959
+ time_now,
960
+ )
961
+
962
+ # make a list of (alg, id, key) tuples
963
+ key_list = []
964
+ for key_id, key_obj in one_time_keys.items():
965
+ algorithm, key_id = key_id.split(":")
966
+ key_list.append((algorithm, key_id, key_obj))
967
+
968
+ # First we check if we have already persisted any of the keys.
969
+ existing_key_map = await self.store.get_e2e_one_time_keys(
970
+ user_id, device_id, [k_id for _, k_id, _ in key_list]
971
+ )
972
+
973
+ new_keys = [] # Keys that we need to insert. (alg, id, json) tuples.
974
+ for algorithm, key_id, key in key_list:
975
+ ex_json = existing_key_map.get((algorithm, key_id), None)
976
+ if ex_json:
977
+ if not _one_time_keys_match(ex_json, key):
978
+ raise SynapseError(
979
+ 400,
980
+ (
981
+ "One time key %s:%s already exists. "
982
+ "Old key: %s; new key: %r"
983
+ )
984
+ % (algorithm, key_id, ex_json, key),
985
+ )
986
+ else:
987
+ new_keys.append(
988
+ (algorithm, key_id, encode_canonical_json(key).decode("ascii"))
989
+ )
990
+
991
+ log_kv({"message": "Inserting new one_time_keys.", "keys": new_keys})
992
+ await self.store.add_e2e_one_time_keys(
993
+ user_id, device_id, time_now, new_keys
994
+ )
995
+
996
+ async def upload_signing_keys_for_user(
997
+ self, user_id: str, keys: JsonDict
998
+ ) -> JsonDict:
999
+ """Upload signing keys for cross-signing
1000
+
1001
+ Args:
1002
+ user_id: the user uploading the keys
1003
+ keys: the signing keys
1004
+ """
1005
+ # if a master key is uploaded, then check it. Otherwise, load the
1006
+ # stored master key, to check signatures on other keys
1007
+ if "master_key" in keys:
1008
+ master_key = keys["master_key"]
1009
+
1010
+ _check_cross_signing_key(master_key, user_id, "master")
1011
+ else:
1012
+ master_key = await self.store.get_e2e_cross_signing_key(user_id, "master")
1013
+
1014
+ # if there is no master key, then we can't do anything, because all the
1015
+ # other cross-signing keys need to be signed by the master key
1016
+ if not master_key:
1017
+ raise SynapseError(400, "No master key available", Codes.MISSING_PARAM)
1018
+
1019
+ try:
1020
+ master_key_id, master_verify_key = get_verify_key_from_cross_signing_key(
1021
+ master_key
1022
+ )
1023
+ except ValueError:
1024
+ if "master_key" in keys:
1025
+ # the invalid key came from the request
1026
+ raise SynapseError(400, "Invalid master key", Codes.INVALID_PARAM)
1027
+ else:
1028
+ # the invalid key came from the database
1029
+ logger.error("Invalid master key found for user %s", user_id)
1030
+ raise SynapseError(500, "Invalid master key")
1031
+
1032
+ # for the other cross-signing keys, make sure that they have valid
1033
+ # signatures from the master key
1034
+ if "self_signing_key" in keys:
1035
+ self_signing_key = keys["self_signing_key"]
1036
+
1037
+ _check_cross_signing_key(
1038
+ self_signing_key, user_id, "self_signing", master_verify_key
1039
+ )
1040
+
1041
+ if "user_signing_key" in keys:
1042
+ user_signing_key = keys["user_signing_key"]
1043
+
1044
+ _check_cross_signing_key(
1045
+ user_signing_key, user_id, "user_signing", master_verify_key
1046
+ )
1047
+
1048
+ # if everything checks out, then store the keys and send notifications
1049
+ deviceids = []
1050
+ if "master_key" in keys:
1051
+ await self.store.set_e2e_cross_signing_key(user_id, "master", master_key)
1052
+ deviceids.append(master_verify_key.version)
1053
+ if "self_signing_key" in keys:
1054
+ await self.store.set_e2e_cross_signing_key(
1055
+ user_id, "self_signing", self_signing_key
1056
+ )
1057
+ try:
1058
+ deviceids.append(
1059
+ get_verify_key_from_cross_signing_key(self_signing_key)[1].version
1060
+ )
1061
+ except ValueError:
1062
+ raise SynapseError(400, "Invalid self-signing key", Codes.INVALID_PARAM)
1063
+ if "user_signing_key" in keys:
1064
+ await self.store.set_e2e_cross_signing_key(
1065
+ user_id, "user_signing", user_signing_key
1066
+ )
1067
+ # the signature stream matches the semantics that we want for
1068
+ # user-signing key updates: only the user themselves is notified of
1069
+ # their own user-signing key updates
1070
+ await self.device_handler.notify_user_signature_update(user_id, [user_id])
1071
+
1072
+ # master key and self-signing key updates match the semantics of device
1073
+ # list updates: all users who share an encrypted room are notified
1074
+ if len(deviceids):
1075
+ await self.device_handler.notify_device_update(user_id, deviceids)
1076
+
1077
+ return {}
1078
+
1079
+ async def upload_signatures_for_device_keys(
1080
+ self, user_id: str, signatures: JsonDict
1081
+ ) -> JsonDict:
1082
+ """Upload device signatures for cross-signing
1083
+
1084
+ Args:
1085
+ user_id: the user uploading the signatures
1086
+ signatures: map of users to devices to signed keys. This is the submission
1087
+ from the user; an exception will be raised if it is malformed.
1088
+ Returns:
1089
+ The response to be sent back to the client. The response will have
1090
+ a "failures" key, which will be a dict mapping users to devices
1091
+ to errors for the signatures that failed.
1092
+ Raises:
1093
+ SynapseError: if the signatures dict is not valid.
1094
+ """
1095
+ failures = {}
1096
+
1097
+ # signatures to be stored. Each item will be a SignatureListItem
1098
+ signature_list = []
1099
+
1100
+ # split between checking signatures for own user and signatures for
1101
+ # other users, since we verify them with different keys
1102
+ self_signatures = signatures.get(user_id, {})
1103
+ other_signatures = {k: v for k, v in signatures.items() if k != user_id}
1104
+
1105
+ self_signature_list, self_failures = await self._process_self_signatures(
1106
+ user_id, self_signatures
1107
+ )
1108
+ signature_list.extend(self_signature_list)
1109
+ failures.update(self_failures)
1110
+
1111
+ other_signature_list, other_failures = await self._process_other_signatures(
1112
+ user_id, other_signatures
1113
+ )
1114
+ signature_list.extend(other_signature_list)
1115
+ failures.update(other_failures)
1116
+
1117
+ # store the signature, and send the appropriate notifications for sync
1118
+ logger.debug("upload signature failures: %r", failures)
1119
+ await self.store.store_e2e_cross_signing_signatures(user_id, signature_list)
1120
+
1121
+ self_device_ids = [item.target_device_id for item in self_signature_list]
1122
+ if self_device_ids:
1123
+ await self.device_handler.notify_device_update(user_id, self_device_ids)
1124
+ signed_users = [item.target_user_id for item in other_signature_list]
1125
+ if signed_users:
1126
+ await self.device_handler.notify_user_signature_update(
1127
+ user_id, signed_users
1128
+ )
1129
+
1130
+ return {"failures": failures}
1131
+
1132
+ async def _process_self_signatures(
1133
+ self, user_id: str, signatures: JsonDict
1134
+ ) -> tuple[list["SignatureListItem"], dict[str, dict[str, dict]]]:
1135
+ """Process uploaded signatures of the user's own keys.
1136
+
1137
+ Signatures of the user's own keys from this API come in two forms:
1138
+ - signatures of the user's devices by the user's self-signing key,
1139
+ - signatures of the user's master key by the user's devices.
1140
+
1141
+ Args:
1142
+ user_id: the user uploading the keys
1143
+ signatures (dict[string, dict]): map of devices to signed keys
1144
+
1145
+ Returns:
1146
+ A tuple of a list of signatures to store, and a map of users to
1147
+ devices to failure reasons
1148
+
1149
+ Raises:
1150
+ SynapseError: if the input is malformed
1151
+ """
1152
+ signature_list: list["SignatureListItem"] = []
1153
+ failures: dict[str, dict[str, JsonDict]] = {}
1154
+ if not signatures:
1155
+ return signature_list, failures
1156
+
1157
+ if not isinstance(signatures, dict):
1158
+ raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
1159
+
1160
+ try:
1161
+ # get our self-signing key to verify the signatures
1162
+ (
1163
+ _,
1164
+ self_signing_key_id,
1165
+ self_signing_verify_key,
1166
+ ) = await self._get_e2e_cross_signing_verify_key(user_id, "self_signing")
1167
+
1168
+ # get our master key, since we may have received a signature of it.
1169
+ # We need to fetch it here so that we know what its key ID is, so
1170
+ # that we can check if a signature that was sent is a signature of
1171
+ # the master key or of a device
1172
+ (
1173
+ master_key,
1174
+ _,
1175
+ master_verify_key,
1176
+ ) = await self._get_e2e_cross_signing_verify_key(user_id, "master")
1177
+
1178
+ # fetch our stored devices. This is used to 1. verify
1179
+ # signatures on the master key, and 2. to compare with what
1180
+ # was sent if the device was signed
1181
+ devices = await self.store.get_e2e_device_keys_for_cs_api([(user_id, None)])
1182
+
1183
+ if user_id not in devices:
1184
+ raise NotFoundError("No device keys found")
1185
+
1186
+ devices = devices[user_id]
1187
+ except SynapseError as e:
1188
+ failure = _exception_to_failure(e)
1189
+ failures[user_id] = dict.fromkeys(signatures.keys(), failure)
1190
+ return signature_list, failures
1191
+
1192
+ for device_id, device in signatures.items():
1193
+ # make sure submitted data is in the right form
1194
+ if not isinstance(device, dict):
1195
+ raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
1196
+
1197
+ try:
1198
+ if "signatures" not in device or user_id not in device["signatures"]:
1199
+ # no signature was sent
1200
+ raise SynapseError(
1201
+ 400, "Invalid signature", Codes.INVALID_SIGNATURE
1202
+ )
1203
+
1204
+ if device_id == master_verify_key.version:
1205
+ # The signature is of the master key. This needs to be
1206
+ # handled differently from signatures of normal devices.
1207
+ master_key_signature_list = self._check_master_key_signature(
1208
+ user_id, device_id, device, master_key, devices
1209
+ )
1210
+ signature_list.extend(master_key_signature_list)
1211
+ continue
1212
+
1213
+ # at this point, we have a device that should be signed
1214
+ # by the self-signing key
1215
+ if self_signing_key_id not in device["signatures"][user_id]:
1216
+ # no signature was sent
1217
+ raise SynapseError(
1218
+ 400, "Invalid signature", Codes.INVALID_SIGNATURE
1219
+ )
1220
+
1221
+ try:
1222
+ stored_device = devices[device_id]
1223
+ except KeyError:
1224
+ raise NotFoundError("Unknown device")
1225
+ if self_signing_key_id in stored_device.get("signatures", {}).get(
1226
+ user_id, {}
1227
+ ):
1228
+ # we already have a signature on this device, so we
1229
+ # can skip it, since it should be exactly the same
1230
+ continue
1231
+
1232
+ _check_device_signature(
1233
+ user_id, self_signing_verify_key, device, stored_device
1234
+ )
1235
+
1236
+ signature = device["signatures"][user_id][self_signing_key_id]
1237
+ signature_list.append(
1238
+ SignatureListItem(
1239
+ self_signing_key_id, user_id, device_id, signature
1240
+ )
1241
+ )
1242
+ except SynapseError as e:
1243
+ failures.setdefault(user_id, {})[device_id] = _exception_to_failure(e)
1244
+
1245
+ return signature_list, failures
1246
+
1247
+ def _check_master_key_signature(
1248
+ self,
1249
+ user_id: str,
1250
+ master_key_id: str,
1251
+ signed_master_key: JsonDict,
1252
+ stored_master_key: JsonMapping,
1253
+ devices: dict[str, dict[str, JsonDict]],
1254
+ ) -> list["SignatureListItem"]:
1255
+ """Check signatures of a user's master key made by their devices.
1256
+
1257
+ Args:
1258
+ user_id: the user whose master key is being checked
1259
+ master_key_id: the ID of the user's master key
1260
+ signed_master_key: the user's signed master key that was uploaded
1261
+ stored_master_key: our previously-stored copy of the user's master key
1262
+ devices: the user's devices
1263
+
1264
+ Returns:
1265
+ A list of signatures to store
1266
+
1267
+ Raises:
1268
+ SynapseError: if a signature is invalid
1269
+ """
1270
+ # for each device that signed the master key, check the signature.
1271
+ master_key_signature_list = []
1272
+ sigs = signed_master_key["signatures"]
1273
+ for signing_key_id, signature in sigs[user_id].items():
1274
+ _, signing_device_id = signing_key_id.split(":", 1)
1275
+ if (
1276
+ signing_device_id not in devices
1277
+ or signing_key_id not in devices[signing_device_id]["keys"]
1278
+ ):
1279
+ # signed by an unknown device, or the
1280
+ # device does not have the key
1281
+ raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
1282
+
1283
+ # get the key and check the signature
1284
+ pubkey = devices[signing_device_id]["keys"][signing_key_id]
1285
+ verify_key = decode_verify_key_bytes(signing_key_id, decode_base64(pubkey))
1286
+ _check_device_signature(
1287
+ user_id, verify_key, signed_master_key, stored_master_key
1288
+ )
1289
+
1290
+ master_key_signature_list.append(
1291
+ SignatureListItem(signing_key_id, user_id, master_key_id, signature)
1292
+ )
1293
+
1294
+ return master_key_signature_list
1295
+
1296
+ async def _process_other_signatures(
1297
+ self, user_id: str, signatures: dict[str, dict]
1298
+ ) -> tuple[list["SignatureListItem"], dict[str, dict[str, dict]]]:
1299
+ """Process uploaded signatures of other users' keys. These will be the
1300
+ target user's master keys, signed by the uploading user's user-signing
1301
+ key.
1302
+
1303
+ Args:
1304
+ user_id: the user uploading the keys
1305
+ signatures: map of users to devices to signed keys
1306
+
1307
+ Returns:
1308
+ A list of signatures to store, and a map of users to devices to failure
1309
+ reasons
1310
+
1311
+ Raises:
1312
+ SynapseError: if the input is malformed
1313
+ """
1314
+ signature_list: list["SignatureListItem"] = []
1315
+ failures: dict[str, dict[str, JsonDict]] = {}
1316
+ if not signatures:
1317
+ return signature_list, failures
1318
+
1319
+ try:
1320
+ # get our user-signing key to verify the signatures
1321
+ (
1322
+ user_signing_key,
1323
+ user_signing_key_id,
1324
+ user_signing_verify_key,
1325
+ ) = await self._get_e2e_cross_signing_verify_key(user_id, "user_signing")
1326
+ except SynapseError as e:
1327
+ failure = _exception_to_failure(e)
1328
+ for user, devicemap in signatures.items():
1329
+ failures[user] = dict.fromkeys(devicemap.keys(), failure)
1330
+ return signature_list, failures
1331
+
1332
+ for target_user, devicemap in signatures.items():
1333
+ # make sure submitted data is in the right form
1334
+ if not isinstance(devicemap, dict):
1335
+ raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
1336
+ for device in devicemap.values():
1337
+ if not isinstance(device, dict):
1338
+ raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
1339
+
1340
+ device_id = None
1341
+ try:
1342
+ # get the target user's master key, to make sure it matches
1343
+ # what was sent
1344
+ (
1345
+ master_key,
1346
+ master_key_id,
1347
+ _,
1348
+ ) = await self._get_e2e_cross_signing_verify_key(
1349
+ target_user, "master", user_id
1350
+ )
1351
+
1352
+ # make sure that the target user's master key is the one that
1353
+ # was signed (and no others)
1354
+ device_id = master_key_id.split(":", 1)[1]
1355
+ if device_id not in devicemap:
1356
+ logger.debug(
1357
+ "upload signature: could not find signature for device %s",
1358
+ device_id,
1359
+ )
1360
+ # set device to None so that the failure gets
1361
+ # marked on all the signatures
1362
+ device_id = None
1363
+ raise NotFoundError("Unknown device")
1364
+ key = devicemap[device_id]
1365
+ other_devices = [k for k in devicemap.keys() if k != device_id]
1366
+ if other_devices:
1367
+ # other devices were signed -- mark those as failures
1368
+ logger.debug("upload signature: too many devices specified")
1369
+ failure = _exception_to_failure(NotFoundError("Unknown device"))
1370
+ failures[target_user] = dict.fromkeys(other_devices, failure)
1371
+
1372
+ if user_signing_key_id in master_key.get("signatures", {}).get(
1373
+ user_id, {}
1374
+ ):
1375
+ # we already have the signature, so we can skip it
1376
+ continue
1377
+
1378
+ _check_device_signature(
1379
+ user_id, user_signing_verify_key, key, master_key
1380
+ )
1381
+
1382
+ signature = key["signatures"][user_id][user_signing_key_id]
1383
+ signature_list.append(
1384
+ SignatureListItem(
1385
+ user_signing_key_id, target_user, device_id, signature
1386
+ )
1387
+ )
1388
+ except SynapseError as e:
1389
+ failure = _exception_to_failure(e)
1390
+ if device_id is None:
1391
+ failures[target_user] = dict.fromkeys(devicemap.keys(), failure)
1392
+ else:
1393
+ failures.setdefault(target_user, {})[device_id] = failure
1394
+
1395
+ return signature_list, failures
1396
+
1397
+ async def _get_e2e_cross_signing_verify_key(
1398
+ self, user_id: str, key_type: str, from_user_id: str | None = None
1399
+ ) -> tuple[JsonMapping, str, VerifyKey]:
1400
+ """Fetch locally or remotely query for a cross-signing public key.
1401
+
1402
+ First, attempt to fetch the cross-signing public key from storage.
1403
+ If that fails, query the keys from the homeserver they belong to
1404
+ and update our local copy.
1405
+
1406
+ Args:
1407
+ user_id: the user whose key should be fetched
1408
+ key_type: the type of key to fetch
1409
+ from_user_id: the user that we are fetching the keys for.
1410
+ This affects what signatures are fetched.
1411
+
1412
+ Returns:
1413
+ The raw key data, the key ID, and the signedjson verify key
1414
+
1415
+ Raises:
1416
+ NotFoundError: if the key is not found
1417
+ SynapseError: if `user_id` is invalid
1418
+ """
1419
+ user = UserID.from_string(user_id)
1420
+ key = await self.store.get_e2e_cross_signing_key(
1421
+ user_id, key_type, from_user_id
1422
+ )
1423
+
1424
+ if key:
1425
+ # We found a copy of this key in our database. Decode and return it
1426
+ key_id, verify_key = get_verify_key_from_cross_signing_key(key)
1427
+ return key, key_id, verify_key
1428
+
1429
+ # If we couldn't find the key locally, and we're looking for keys of
1430
+ # another user then attempt to fetch the missing key from the remote
1431
+ # user's server.
1432
+ #
1433
+ # We may run into this in possible edge cases where a user tries to
1434
+ # cross-sign a remote user, but does not share any rooms with them yet.
1435
+ # Thus, we would not have their key list yet. We instead fetch the key,
1436
+ # store it and notify clients of new, associated device IDs.
1437
+ if self.is_mine(user) or key_type not in ["master", "self_signing"]:
1438
+ # Note that master and self_signing keys are the only cross-signing keys we
1439
+ # can request over federation
1440
+ raise NotFoundError("No %s key found for %s" % (key_type, user_id))
1441
+
1442
+ cross_signing_keys = await self._retrieve_cross_signing_keys_for_remote_user(
1443
+ user, key_type
1444
+ )
1445
+ if cross_signing_keys is None:
1446
+ raise NotFoundError("No %s key found for %s" % (key_type, user_id))
1447
+
1448
+ return cross_signing_keys
1449
+
1450
+ async def _retrieve_cross_signing_keys_for_remote_user(
1451
+ self,
1452
+ user: UserID,
1453
+ desired_key_type: str,
1454
+ ) -> tuple[JsonMapping, str, VerifyKey] | None:
1455
+ """Queries cross-signing keys for a remote user and saves them to the database
1456
+
1457
+ Only the key specified by `key_type` will be returned, while all retrieved keys
1458
+ will be saved regardless
1459
+
1460
+ Args:
1461
+ user: The user to query remote keys for
1462
+ desired_key_type: The type of key to receive. One of "master", "self_signing"
1463
+
1464
+ Returns:
1465
+ A tuple of the retrieved key content, the key's ID and the matching VerifyKey.
1466
+ If the key cannot be retrieved, all values in the tuple will instead be None.
1467
+ """
1468
+ try:
1469
+ remote_result = await self.federation.query_user_devices(
1470
+ user.domain, user.to_string()
1471
+ )
1472
+ except Exception as e:
1473
+ logger.warning(
1474
+ "Unable to query %s for cross-signing keys of user %s: %s %s",
1475
+ user.domain,
1476
+ user.to_string(),
1477
+ type(e),
1478
+ e,
1479
+ )
1480
+ return None
1481
+
1482
+ # Process each of the retrieved cross-signing keys
1483
+ desired_key_data = None
1484
+ retrieved_device_ids = []
1485
+ for key_type in ["master", "self_signing"]:
1486
+ key_content = remote_result.get(key_type + "_key")
1487
+ if not key_content:
1488
+ continue
1489
+
1490
+ # Ensure these keys belong to the correct user
1491
+ if "user_id" not in key_content:
1492
+ logger.warning(
1493
+ "Invalid %s key retrieved, missing user_id field: %s",
1494
+ key_type,
1495
+ key_content,
1496
+ )
1497
+ continue
1498
+ if user.to_string() != key_content["user_id"]:
1499
+ logger.warning(
1500
+ "Found %s key of user %s when querying for keys of user %s",
1501
+ key_type,
1502
+ key_content["user_id"],
1503
+ user.to_string(),
1504
+ )
1505
+ continue
1506
+
1507
+ # Validate the key contents
1508
+ try:
1509
+ # verify_key is a VerifyKey from signedjson, which uses
1510
+ # .version to denote the portion of the key ID after the
1511
+ # algorithm and colon, which is the device ID
1512
+ key_id, verify_key = get_verify_key_from_cross_signing_key(key_content)
1513
+ except ValueError as e:
1514
+ logger.warning(
1515
+ "Invalid %s key retrieved: %s - %s %s",
1516
+ key_type,
1517
+ key_content,
1518
+ type(e),
1519
+ e,
1520
+ )
1521
+ continue
1522
+
1523
+ # Note down the device ID attached to this key
1524
+ retrieved_device_ids.append(verify_key.version)
1525
+
1526
+ # If this is the desired key type, save it and its ID/VerifyKey
1527
+ if key_type == desired_key_type:
1528
+ desired_key_data = key_content, key_id, verify_key
1529
+
1530
+ # At the same time, store this key in the db for subsequent queries
1531
+ await self.store.set_e2e_cross_signing_key(
1532
+ user.to_string(), key_type, key_content
1533
+ )
1534
+
1535
+ # Notify clients that new devices for this user have been discovered
1536
+ if retrieved_device_ids:
1537
+ # XXX is this necessary?
1538
+ await self.device_handler.notify_device_update(
1539
+ user.to_string(), retrieved_device_ids
1540
+ )
1541
+
1542
+ return desired_key_data
1543
+
1544
+ async def check_cross_signing_setup(self, user_id: str) -> tuple[bool, bool]:
1545
+ """Checks if the user has cross-signing set up
1546
+
1547
+ Args:
1548
+ user_id: The user to check
1549
+
1550
+ Returns: a 2-tuple of booleans
1551
+ - whether the user has cross-signing set up, and
1552
+ - whether the user's master cross-signing key may be replaced without UIA.
1553
+ """
1554
+ (
1555
+ exists,
1556
+ ts_replacable_without_uia_before,
1557
+ ) = await self.store.get_master_cross_signing_key_updatable_before(user_id)
1558
+
1559
+ if ts_replacable_without_uia_before is None:
1560
+ return exists, False
1561
+ else:
1562
+ return exists, self.clock.time_msec() < ts_replacable_without_uia_before
1563
+
1564
+ async def has_different_keys(self, user_id: str, body: JsonDict) -> bool:
1565
+ """
1566
+ Check if a key provided in `body` differs from the same key stored in the DB. Returns
1567
+ true on the first difference. If a key exists in `body` but does not exist in the DB,
1568
+ returns True. If `body` has no keys, this always returns False.
1569
+ Note by 'key' we mean Matrix key rather than JSON key.
1570
+
1571
+ The purpose of this function is to detect whether or not we need to apply UIA checks.
1572
+ We must apply UIA checks if any key in the database is being overwritten. If a key is
1573
+ being inserted for the first time, or if the key exactly matches what is in the database,
1574
+ then no UIA check needs to be performed.
1575
+
1576
+ Args:
1577
+ user_id: The user who sent the `body`.
1578
+ body: The JSON request body from POST /keys/device_signing/upload
1579
+ Returns:
1580
+ True if any key in `body` has a different value in the database.
1581
+ """
1582
+ # Ensure that each key provided in the request body exactly matches the one we have stored.
1583
+ # The first time we see the DB having a different key to the matching request key, bail.
1584
+ # Note: we do not care if the DB has a key which the request does not specify, as we only
1585
+ # care about *replacements* or *insertions* (i.e UPSERT)
1586
+ req_body_key_to_db_key = {
1587
+ "master_key": "master",
1588
+ "self_signing_key": "self_signing",
1589
+ "user_signing_key": "user_signing",
1590
+ }
1591
+ for req_body_key, db_key in req_body_key_to_db_key.items():
1592
+ if req_body_key in body:
1593
+ existing_key = await self.store.get_e2e_cross_signing_key(
1594
+ user_id, db_key
1595
+ )
1596
+ if existing_key != body[req_body_key]:
1597
+ return True
1598
+ return False
1599
+
1600
+ async def _delete_old_one_time_keys_task(
1601
+ self, task: ScheduledTask
1602
+ ) -> tuple[TaskStatus, JsonMapping | None, str | None]:
1603
+ """Scheduler task to delete old one time keys.
1604
+
1605
+ Until Synapse 1.119, Synapse used to issue one-time-keys in a random order, leading to the possibility
1606
+ that it could still have old OTKs that the client has dropped. This task is scheduled exactly once
1607
+ by a database schema delta file, and it clears out old one-time-keys that look like they came from libolm.
1608
+ """
1609
+ last_user = task.result.get("from_user", "") if task.result else ""
1610
+ while True:
1611
+ # We process users in batches of 100
1612
+ users, rowcount = await self.store.delete_old_otks_for_next_user_batch(
1613
+ last_user, 100
1614
+ )
1615
+ if len(users) == 0:
1616
+ # We're done!
1617
+ return TaskStatus.COMPLETE, None, None
1618
+
1619
+ logger.debug(
1620
+ "Deleted %i old one-time-keys for users '%s'..'%s'",
1621
+ rowcount,
1622
+ users[0],
1623
+ users[-1],
1624
+ )
1625
+ last_user = users[-1]
1626
+
1627
+ # Store our progress
1628
+ await self._task_scheduler.update_task(
1629
+ task.id, result={"from_user": last_user}
1630
+ )
1631
+
1632
+ # Sleep a little before doing the next user.
1633
+ #
1634
+ # matrix.org has about 15M users in the e2e_one_time_keys_json table
1635
+ # (comprising 20M devices). We want this to take about a week, so we need
1636
+ # to do about one batch of 100 users every 4 seconds.
1637
+ await self.clock.sleep(4)
1638
+
1639
+
1640
+ def _check_cross_signing_key(
1641
+ key: JsonDict, user_id: str, key_type: str, signing_key: VerifyKey | None = None
1642
+ ) -> None:
1643
+ """Check a cross-signing key uploaded by a user. Performs some basic sanity
1644
+ checking, and ensures that it is signed, if a signature is required.
1645
+
1646
+ Args:
1647
+ key: the key data to verify
1648
+ user_id: the user whose key is being checked
1649
+ key_type: the type of key that the key should be
1650
+ signing_key: the signing key that the key should be signed with. If
1651
+ omitted, signatures will not be checked.
1652
+ """
1653
+ if (
1654
+ key.get("user_id") != user_id
1655
+ or key_type not in key.get("usage", [])
1656
+ or len(key.get("keys", {})) != 1
1657
+ ):
1658
+ raise SynapseError(400, ("Invalid %s key" % (key_type,)), Codes.INVALID_PARAM)
1659
+
1660
+ if signing_key:
1661
+ try:
1662
+ verify_signed_json(key, user_id, signing_key)
1663
+ except SignatureVerifyException:
1664
+ raise SynapseError(
1665
+ 400, ("Invalid signature on %s key" % key_type), Codes.INVALID_SIGNATURE
1666
+ )
1667
+
1668
+
1669
+ def _check_device_signature(
1670
+ user_id: str,
1671
+ verify_key: VerifyKey,
1672
+ signed_device: JsonDict,
1673
+ stored_device: JsonMapping,
1674
+ ) -> None:
1675
+ """Check that a signature on a device or cross-signing key is correct and
1676
+ matches the copy of the device/key that we have stored. Throws an
1677
+ exception if an error is detected.
1678
+
1679
+ Args:
1680
+ user_id: the user ID whose signature is being checked
1681
+ verify_key: the key to verify the device with
1682
+ signed_device: the uploaded signed device data
1683
+ stored_device: our previously stored copy of the device
1684
+
1685
+ Raises:
1686
+ SynapseError: if the signature was invalid or the sent device is not the
1687
+ same as the stored device
1688
+
1689
+ """
1690
+
1691
+ # make sure that the device submitted matches what we have stored
1692
+ stripped_signed_device = {
1693
+ k: v for k, v in signed_device.items() if k not in ["signatures", "unsigned"]
1694
+ }
1695
+ stripped_stored_device = {
1696
+ k: v for k, v in stored_device.items() if k not in ["signatures", "unsigned"]
1697
+ }
1698
+ if stripped_signed_device != stripped_stored_device:
1699
+ logger.debug(
1700
+ "upload signatures: key does not match %s vs %s",
1701
+ signed_device,
1702
+ stored_device,
1703
+ )
1704
+ raise SynapseError(400, "Key does not match")
1705
+
1706
+ try:
1707
+ verify_signed_json(signed_device, user_id, verify_key)
1708
+ except SignatureVerifyException:
1709
+ logger.debug("invalid signature on key")
1710
+ raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
1711
+
1712
+
1713
+ _NOT_READY_FOR_RETRY_FAILURE = {"status": 503, "message": "Not ready for retry"}
1714
+
1715
+
1716
+ def _exception_to_failure(e: Exception) -> JsonDict:
1717
+ if isinstance(e, SynapseError):
1718
+ return {"status": e.code, "errcode": e.errcode, "message": str(e)}
1719
+
1720
+ if isinstance(e, CodeMessageException):
1721
+ return {"status": e.code, "message": str(e)}
1722
+
1723
+ if isinstance(e, NotRetryingDestination):
1724
+ return _NOT_READY_FOR_RETRY_FAILURE
1725
+
1726
+ # include ConnectionRefused and other errors
1727
+ #
1728
+ # Note that some Exceptions (notably twisted's ResponseFailed etc) don't
1729
+ # give a string for e.message, which json then fails to serialize.
1730
+ return {"status": 503, "message": str(e)}
1731
+
1732
+
1733
+ def _one_time_keys_match(old_key_json: str, new_key: JsonDict) -> bool:
1734
+ old_key = json_decoder.decode(old_key_json)
1735
+
1736
+ # if either is a string rather than an object, they must match exactly
1737
+ if not isinstance(old_key, dict) or not isinstance(new_key, dict):
1738
+ return old_key == new_key
1739
+
1740
+ # otherwise, we strip off the 'signatures' if any, because it's legitimate
1741
+ # for different upload attempts to have different signatures.
1742
+ old_key.pop("signatures", None)
1743
+ new_key_copy = dict(new_key)
1744
+ new_key_copy.pop("signatures", None)
1745
+
1746
+ return old_key == new_key_copy
1747
+
1748
+
1749
+ @attr.s(slots=True, auto_attribs=True)
1750
+ class SignatureListItem:
1751
+ """An item in the signature list as used by upload_signatures_for_device_keys."""
1752
+
1753
+ signing_key_id: str
1754
+ target_user_id: str
1755
+ target_device_id: str
1756
+ signature: JsonDict
1757
+
1758
+
1759
+ class SigningKeyEduUpdater:
1760
+ """Handles incoming signing key updates from federation and updates the DB"""
1761
+
1762
+ def __init__(self, hs: "HomeServer"):
1763
+ self.store = hs.get_datastores().main
1764
+ self.federation = hs.get_federation_client()
1765
+ self.clock = hs.get_clock()
1766
+
1767
+ device_handler = hs.get_device_handler()
1768
+ assert isinstance(device_handler, DeviceWriterHandler)
1769
+ self._device_handler = device_handler
1770
+
1771
+ self._remote_edu_linearizer = Linearizer(
1772
+ name="remote_signing_key", clock=self.clock
1773
+ )
1774
+
1775
+ # user_id -> list of updates waiting to be handled.
1776
+ self._pending_updates: dict[str, list[tuple[JsonDict, JsonDict]]] = {}
1777
+
1778
+ async def incoming_signing_key_update(
1779
+ self, origin: str, edu_content: JsonDict
1780
+ ) -> None:
1781
+ """Called on incoming signing key update from federation. Responsible for
1782
+ parsing the EDU and adding to pending updates list.
1783
+
1784
+ Args:
1785
+ origin: the server that sent the EDU
1786
+ edu_content: the contents of the EDU
1787
+ """
1788
+
1789
+ user_id = edu_content.pop("user_id")
1790
+ master_key = edu_content.pop("master_key", None)
1791
+ self_signing_key = edu_content.pop("self_signing_key", None)
1792
+
1793
+ if get_domain_from_id(user_id) != origin:
1794
+ logger.warning("Got signing key update edu for %r from %r", user_id, origin)
1795
+ return
1796
+
1797
+ room_ids = await self.store.get_rooms_for_user(user_id)
1798
+ if not room_ids:
1799
+ # We don't share any rooms with this user. Ignore update, as we
1800
+ # probably won't get any further updates.
1801
+ return
1802
+
1803
+ self._pending_updates.setdefault(user_id, []).append(
1804
+ (master_key, self_signing_key)
1805
+ )
1806
+
1807
+ await self._handle_signing_key_updates(user_id)
1808
+
1809
+ async def _handle_signing_key_updates(self, user_id: str) -> None:
1810
+ """Actually handle pending updates.
1811
+
1812
+ Args:
1813
+ user_id: the user whose updates we are processing
1814
+ """
1815
+
1816
+ async with self._remote_edu_linearizer.queue(user_id):
1817
+ pending_updates = self._pending_updates.pop(user_id, [])
1818
+ if not pending_updates:
1819
+ # This can happen since we batch updates
1820
+ return
1821
+
1822
+ device_ids: list[str] = []
1823
+
1824
+ logger.info("pending updates: %r", pending_updates)
1825
+
1826
+ for master_key, self_signing_key in pending_updates:
1827
+ new_device_ids = await self._device_handler.device_list_updater.process_cross_signing_key_update(
1828
+ user_id,
1829
+ master_key,
1830
+ self_signing_key,
1831
+ )
1832
+ device_ids = device_ids + new_device_ids
1833
+
1834
+ await self._device_handler.notify_device_update(user_id, device_ids)