matrix-synapse 1.142.0rc3__cp314-abi3-musllinux_1_2_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.

Potentially problematic release.


This version of matrix-synapse might be problematic. Click here for more details.

Files changed (1057) hide show
  1. matrix_synapse-1.142.0rc3.dist-info/AUTHORS.rst +51 -0
  2. matrix_synapse-1.142.0rc3.dist-info/LICENSE-AGPL-3.0 +661 -0
  3. matrix_synapse-1.142.0rc3.dist-info/LICENSE-COMMERCIAL +6 -0
  4. matrix_synapse-1.142.0rc3.dist-info/METADATA +375 -0
  5. matrix_synapse-1.142.0rc3.dist-info/RECORD +1057 -0
  6. matrix_synapse-1.142.0rc3.dist-info/WHEEL +4 -0
  7. matrix_synapse-1.142.0rc3.dist-info/entry_points.txt +14 -0
  8. matrix_synapse.libs/libgcc_s-2d945d6c.so.1 +0 -0
  9. synapse/__init__.py +97 -0
  10. synapse/_scripts/__init__.py +0 -0
  11. synapse/_scripts/export_signing_key.py +109 -0
  12. synapse/_scripts/generate_config.py +83 -0
  13. synapse/_scripts/generate_log_config.py +56 -0
  14. synapse/_scripts/generate_signing_key.py +55 -0
  15. synapse/_scripts/generate_workers_map.py +318 -0
  16. synapse/_scripts/hash_password.py +95 -0
  17. synapse/_scripts/move_remote_media_to_new_store.py +128 -0
  18. synapse/_scripts/register_new_matrix_user.py +374 -0
  19. synapse/_scripts/review_recent_signups.py +212 -0
  20. synapse/_scripts/synapse_port_db.py +1603 -0
  21. synapse/_scripts/synctl.py +365 -0
  22. synapse/_scripts/update_synapse_database.py +130 -0
  23. synapse/api/__init__.py +20 -0
  24. synapse/api/auth/__init__.py +207 -0
  25. synapse/api/auth/base.py +406 -0
  26. synapse/api/auth/internal.py +299 -0
  27. synapse/api/auth/mas.py +457 -0
  28. synapse/api/auth/msc3861_delegated.py +617 -0
  29. synapse/api/auth_blocking.py +144 -0
  30. synapse/api/constants.py +362 -0
  31. synapse/api/errors.py +907 -0
  32. synapse/api/filtering.py +539 -0
  33. synapse/api/presence.py +104 -0
  34. synapse/api/ratelimiting.py +482 -0
  35. synapse/api/room_versions.py +535 -0
  36. synapse/api/urls.py +119 -0
  37. synapse/app/__init__.py +60 -0
  38. synapse/app/_base.py +866 -0
  39. synapse/app/admin_cmd.py +388 -0
  40. synapse/app/appservice.py +30 -0
  41. synapse/app/client_reader.py +30 -0
  42. synapse/app/complement_fork_starter.py +206 -0
  43. synapse/app/event_creator.py +29 -0
  44. synapse/app/federation_reader.py +30 -0
  45. synapse/app/federation_sender.py +30 -0
  46. synapse/app/frontend_proxy.py +30 -0
  47. synapse/app/generic_worker.py +475 -0
  48. synapse/app/homeserver.py +504 -0
  49. synapse/app/media_repository.py +30 -0
  50. synapse/app/phone_stats_home.py +296 -0
  51. synapse/app/pusher.py +30 -0
  52. synapse/app/synchrotron.py +30 -0
  53. synapse/app/user_dir.py +31 -0
  54. synapse/appservice/__init__.py +461 -0
  55. synapse/appservice/api.py +569 -0
  56. synapse/appservice/scheduler.py +567 -0
  57. synapse/config/__init__.py +27 -0
  58. synapse/config/__main__.py +62 -0
  59. synapse/config/_base.py +1108 -0
  60. synapse/config/_base.pyi +217 -0
  61. synapse/config/_util.py +99 -0
  62. synapse/config/account_validity.py +116 -0
  63. synapse/config/api.py +141 -0
  64. synapse/config/appservice.py +210 -0
  65. synapse/config/auth.py +80 -0
  66. synapse/config/auto_accept_invites.py +43 -0
  67. synapse/config/background_updates.py +44 -0
  68. synapse/config/cache.py +231 -0
  69. synapse/config/captcha.py +90 -0
  70. synapse/config/cas.py +116 -0
  71. synapse/config/consent.py +73 -0
  72. synapse/config/database.py +184 -0
  73. synapse/config/emailconfig.py +367 -0
  74. synapse/config/experimental.py +595 -0
  75. synapse/config/federation.py +114 -0
  76. synapse/config/homeserver.py +141 -0
  77. synapse/config/jwt.py +55 -0
  78. synapse/config/key.py +447 -0
  79. synapse/config/logger.py +390 -0
  80. synapse/config/mas.py +191 -0
  81. synapse/config/matrixrtc.py +66 -0
  82. synapse/config/metrics.py +84 -0
  83. synapse/config/modules.py +40 -0
  84. synapse/config/oembed.py +185 -0
  85. synapse/config/oidc.py +509 -0
  86. synapse/config/password_auth_providers.py +82 -0
  87. synapse/config/push.py +64 -0
  88. synapse/config/ratelimiting.py +254 -0
  89. synapse/config/redis.py +74 -0
  90. synapse/config/registration.py +296 -0
  91. synapse/config/repository.py +311 -0
  92. synapse/config/retention.py +162 -0
  93. synapse/config/room.py +88 -0
  94. synapse/config/room_directory.py +165 -0
  95. synapse/config/saml2.py +251 -0
  96. synapse/config/server.py +1170 -0
  97. synapse/config/server_notices.py +84 -0
  98. synapse/config/spam_checker.py +66 -0
  99. synapse/config/sso.py +121 -0
  100. synapse/config/stats.py +54 -0
  101. synapse/config/third_party_event_rules.py +40 -0
  102. synapse/config/tls.py +192 -0
  103. synapse/config/tracer.py +71 -0
  104. synapse/config/user_directory.py +47 -0
  105. synapse/config/user_types.py +44 -0
  106. synapse/config/voip.py +59 -0
  107. synapse/config/workers.py +642 -0
  108. synapse/crypto/__init__.py +20 -0
  109. synapse/crypto/context_factory.py +278 -0
  110. synapse/crypto/event_signing.py +194 -0
  111. synapse/crypto/keyring.py +931 -0
  112. synapse/event_auth.py +1266 -0
  113. synapse/events/__init__.py +668 -0
  114. synapse/events/auto_accept_invites.py +216 -0
  115. synapse/events/builder.py +387 -0
  116. synapse/events/presence_router.py +245 -0
  117. synapse/events/snapshot.py +559 -0
  118. synapse/events/utils.py +928 -0
  119. synapse/events/validator.py +305 -0
  120. synapse/federation/__init__.py +22 -0
  121. synapse/federation/federation_base.py +383 -0
  122. synapse/federation/federation_client.py +2134 -0
  123. synapse/federation/federation_server.py +1544 -0
  124. synapse/federation/persistence.py +71 -0
  125. synapse/federation/send_queue.py +532 -0
  126. synapse/federation/sender/__init__.py +1165 -0
  127. synapse/federation/sender/per_destination_queue.py +884 -0
  128. synapse/federation/sender/transaction_manager.py +210 -0
  129. synapse/federation/transport/__init__.py +28 -0
  130. synapse/federation/transport/client.py +1201 -0
  131. synapse/federation/transport/server/__init__.py +334 -0
  132. synapse/federation/transport/server/_base.py +429 -0
  133. synapse/federation/transport/server/federation.py +912 -0
  134. synapse/federation/units.py +133 -0
  135. synapse/handlers/__init__.py +20 -0
  136. synapse/handlers/account.py +162 -0
  137. synapse/handlers/account_data.py +362 -0
  138. synapse/handlers/account_validity.py +361 -0
  139. synapse/handlers/admin.py +618 -0
  140. synapse/handlers/appservice.py +991 -0
  141. synapse/handlers/auth.py +2494 -0
  142. synapse/handlers/cas.py +413 -0
  143. synapse/handlers/deactivate_account.py +363 -0
  144. synapse/handlers/delayed_events.py +635 -0
  145. synapse/handlers/device.py +1873 -0
  146. synapse/handlers/devicemessage.py +399 -0
  147. synapse/handlers/directory.py +554 -0
  148. synapse/handlers/e2e_keys.py +1834 -0
  149. synapse/handlers/e2e_room_keys.py +455 -0
  150. synapse/handlers/event_auth.py +390 -0
  151. synapse/handlers/events.py +201 -0
  152. synapse/handlers/federation.py +2043 -0
  153. synapse/handlers/federation_event.py +2420 -0
  154. synapse/handlers/identity.py +812 -0
  155. synapse/handlers/initial_sync.py +528 -0
  156. synapse/handlers/jwt.py +120 -0
  157. synapse/handlers/message.py +2347 -0
  158. synapse/handlers/oidc.py +1803 -0
  159. synapse/handlers/pagination.py +768 -0
  160. synapse/handlers/password_policy.py +102 -0
  161. synapse/handlers/presence.py +2638 -0
  162. synapse/handlers/profile.py +655 -0
  163. synapse/handlers/push_rules.py +164 -0
  164. synapse/handlers/read_marker.py +79 -0
  165. synapse/handlers/receipts.py +351 -0
  166. synapse/handlers/register.py +1060 -0
  167. synapse/handlers/relations.py +624 -0
  168. synapse/handlers/reports.py +98 -0
  169. synapse/handlers/room.py +2447 -0
  170. synapse/handlers/room_list.py +632 -0
  171. synapse/handlers/room_member.py +2365 -0
  172. synapse/handlers/room_member_worker.py +146 -0
  173. synapse/handlers/room_policy.py +186 -0
  174. synapse/handlers/room_summary.py +1057 -0
  175. synapse/handlers/saml.py +524 -0
  176. synapse/handlers/search.py +723 -0
  177. synapse/handlers/send_email.py +209 -0
  178. synapse/handlers/set_password.py +71 -0
  179. synapse/handlers/sliding_sync/__init__.py +1701 -0
  180. synapse/handlers/sliding_sync/extensions.py +970 -0
  181. synapse/handlers/sliding_sync/room_lists.py +2266 -0
  182. synapse/handlers/sliding_sync/store.py +128 -0
  183. synapse/handlers/sso.py +1292 -0
  184. synapse/handlers/state_deltas.py +82 -0
  185. synapse/handlers/stats.py +322 -0
  186. synapse/handlers/sync.py +3109 -0
  187. synapse/handlers/thread_subscriptions.py +190 -0
  188. synapse/handlers/typing.py +606 -0
  189. synapse/handlers/ui_auth/__init__.py +48 -0
  190. synapse/handlers/ui_auth/checkers.py +332 -0
  191. synapse/handlers/user_directory.py +783 -0
  192. synapse/handlers/worker_lock.py +365 -0
  193. synapse/http/__init__.py +106 -0
  194. synapse/http/additional_resource.py +62 -0
  195. synapse/http/client.py +1360 -0
  196. synapse/http/connectproxyclient.py +309 -0
  197. synapse/http/federation/__init__.py +19 -0
  198. synapse/http/federation/matrix_federation_agent.py +490 -0
  199. synapse/http/federation/srv_resolver.py +196 -0
  200. synapse/http/federation/well_known_resolver.py +367 -0
  201. synapse/http/matrixfederationclient.py +1875 -0
  202. synapse/http/proxy.py +290 -0
  203. synapse/http/proxyagent.py +497 -0
  204. synapse/http/replicationagent.py +203 -0
  205. synapse/http/request_metrics.py +309 -0
  206. synapse/http/server.py +1114 -0
  207. synapse/http/servlet.py +1019 -0
  208. synapse/http/site.py +825 -0
  209. synapse/http/types.py +27 -0
  210. synapse/logging/__init__.py +31 -0
  211. synapse/logging/_remote.py +261 -0
  212. synapse/logging/_terse_json.py +95 -0
  213. synapse/logging/context.py +1211 -0
  214. synapse/logging/formatter.py +63 -0
  215. synapse/logging/handlers.py +99 -0
  216. synapse/logging/loggers.py +25 -0
  217. synapse/logging/opentracing.py +1132 -0
  218. synapse/logging/scopecontextmanager.py +161 -0
  219. synapse/media/_base.py +827 -0
  220. synapse/media/filepath.py +417 -0
  221. synapse/media/media_repository.py +1580 -0
  222. synapse/media/media_storage.py +704 -0
  223. synapse/media/oembed.py +277 -0
  224. synapse/media/preview_html.py +559 -0
  225. synapse/media/storage_provider.py +195 -0
  226. synapse/media/thumbnailer.py +833 -0
  227. synapse/media/url_previewer.py +875 -0
  228. synapse/metrics/__init__.py +754 -0
  229. synapse/metrics/_gc.py +219 -0
  230. synapse/metrics/_reactor_metrics.py +171 -0
  231. synapse/metrics/_types.py +38 -0
  232. synapse/metrics/background_process_metrics.py +556 -0
  233. synapse/metrics/common_usage_metrics.py +94 -0
  234. synapse/metrics/jemalloc.py +248 -0
  235. synapse/module_api/__init__.py +2154 -0
  236. synapse/module_api/callbacks/__init__.py +50 -0
  237. synapse/module_api/callbacks/account_validity_callbacks.py +106 -0
  238. synapse/module_api/callbacks/media_repository_callbacks.py +160 -0
  239. synapse/module_api/callbacks/ratelimit_callbacks.py +79 -0
  240. synapse/module_api/callbacks/spamchecker_callbacks.py +1113 -0
  241. synapse/module_api/callbacks/third_party_event_rules_callbacks.py +599 -0
  242. synapse/module_api/errors.py +42 -0
  243. synapse/notifier.py +972 -0
  244. synapse/push/__init__.py +212 -0
  245. synapse/push/bulk_push_rule_evaluator.py +637 -0
  246. synapse/push/clientformat.py +126 -0
  247. synapse/push/emailpusher.py +333 -0
  248. synapse/push/httppusher.py +564 -0
  249. synapse/push/mailer.py +1012 -0
  250. synapse/push/presentable_names.py +216 -0
  251. synapse/push/push_tools.py +114 -0
  252. synapse/push/push_types.py +141 -0
  253. synapse/push/pusher.py +87 -0
  254. synapse/push/pusherpool.py +501 -0
  255. synapse/push/rulekinds.py +33 -0
  256. synapse/py.typed +0 -0
  257. synapse/replication/__init__.py +20 -0
  258. synapse/replication/http/__init__.py +68 -0
  259. synapse/replication/http/_base.py +468 -0
  260. synapse/replication/http/account_data.py +297 -0
  261. synapse/replication/http/deactivate_account.py +81 -0
  262. synapse/replication/http/delayed_events.py +62 -0
  263. synapse/replication/http/devices.py +254 -0
  264. synapse/replication/http/federation.py +334 -0
  265. synapse/replication/http/login.py +106 -0
  266. synapse/replication/http/membership.py +364 -0
  267. synapse/replication/http/presence.py +133 -0
  268. synapse/replication/http/push.py +156 -0
  269. synapse/replication/http/register.py +172 -0
  270. synapse/replication/http/send_events.py +182 -0
  271. synapse/replication/http/state.py +82 -0
  272. synapse/replication/http/streams.py +101 -0
  273. synapse/replication/tcp/__init__.py +56 -0
  274. synapse/replication/tcp/client.py +552 -0
  275. synapse/replication/tcp/commands.py +569 -0
  276. synapse/replication/tcp/context.py +41 -0
  277. synapse/replication/tcp/external_cache.py +156 -0
  278. synapse/replication/tcp/handler.py +942 -0
  279. synapse/replication/tcp/protocol.py +608 -0
  280. synapse/replication/tcp/redis.py +509 -0
  281. synapse/replication/tcp/resource.py +348 -0
  282. synapse/replication/tcp/streams/__init__.py +96 -0
  283. synapse/replication/tcp/streams/_base.py +766 -0
  284. synapse/replication/tcp/streams/events.py +287 -0
  285. synapse/replication/tcp/streams/federation.py +92 -0
  286. synapse/replication/tcp/streams/partial_state.py +80 -0
  287. synapse/res/providers.json +29 -0
  288. synapse/res/templates/_base.html +29 -0
  289. synapse/res/templates/account_previously_renewed.html +6 -0
  290. synapse/res/templates/account_renewed.html +6 -0
  291. synapse/res/templates/add_threepid.html +8 -0
  292. synapse/res/templates/add_threepid.txt +6 -0
  293. synapse/res/templates/add_threepid_failure.html +7 -0
  294. synapse/res/templates/add_threepid_success.html +6 -0
  295. synapse/res/templates/already_in_use.html +12 -0
  296. synapse/res/templates/already_in_use.txt +10 -0
  297. synapse/res/templates/auth_success.html +21 -0
  298. synapse/res/templates/invalid_token.html +6 -0
  299. synapse/res/templates/mail-Element.css +7 -0
  300. synapse/res/templates/mail-Vector.css +7 -0
  301. synapse/res/templates/mail-expiry.css +4 -0
  302. synapse/res/templates/mail.css +156 -0
  303. synapse/res/templates/notice_expiry.html +46 -0
  304. synapse/res/templates/notice_expiry.txt +7 -0
  305. synapse/res/templates/notif.html +51 -0
  306. synapse/res/templates/notif.txt +22 -0
  307. synapse/res/templates/notif_mail.html +59 -0
  308. synapse/res/templates/notif_mail.txt +10 -0
  309. synapse/res/templates/password_reset.html +10 -0
  310. synapse/res/templates/password_reset.txt +7 -0
  311. synapse/res/templates/password_reset_confirmation.html +15 -0
  312. synapse/res/templates/password_reset_failure.html +7 -0
  313. synapse/res/templates/password_reset_success.html +6 -0
  314. synapse/res/templates/recaptcha.html +42 -0
  315. synapse/res/templates/registration.html +12 -0
  316. synapse/res/templates/registration.txt +10 -0
  317. synapse/res/templates/registration_failure.html +6 -0
  318. synapse/res/templates/registration_success.html +6 -0
  319. synapse/res/templates/registration_token.html +18 -0
  320. synapse/res/templates/room.html +33 -0
  321. synapse/res/templates/room.txt +9 -0
  322. synapse/res/templates/sso.css +129 -0
  323. synapse/res/templates/sso_account_deactivated.html +25 -0
  324. synapse/res/templates/sso_auth_account_details.html +186 -0
  325. synapse/res/templates/sso_auth_account_details.js +116 -0
  326. synapse/res/templates/sso_auth_bad_user.html +26 -0
  327. synapse/res/templates/sso_auth_confirm.html +27 -0
  328. synapse/res/templates/sso_auth_success.html +26 -0
  329. synapse/res/templates/sso_error.html +71 -0
  330. synapse/res/templates/sso_footer.html +19 -0
  331. synapse/res/templates/sso_login_idp_picker.html +60 -0
  332. synapse/res/templates/sso_new_user_consent.html +30 -0
  333. synapse/res/templates/sso_partial_profile.html +19 -0
  334. synapse/res/templates/sso_redirect_confirm.html +39 -0
  335. synapse/res/templates/style.css +33 -0
  336. synapse/res/templates/terms.html +27 -0
  337. synapse/rest/__init__.py +197 -0
  338. synapse/rest/admin/__init__.py +390 -0
  339. synapse/rest/admin/_base.py +72 -0
  340. synapse/rest/admin/background_updates.py +171 -0
  341. synapse/rest/admin/devices.py +221 -0
  342. synapse/rest/admin/event_reports.py +173 -0
  343. synapse/rest/admin/events.py +69 -0
  344. synapse/rest/admin/experimental_features.py +137 -0
  345. synapse/rest/admin/federation.py +243 -0
  346. synapse/rest/admin/media.py +540 -0
  347. synapse/rest/admin/registration_tokens.py +358 -0
  348. synapse/rest/admin/rooms.py +1061 -0
  349. synapse/rest/admin/scheduled_tasks.py +70 -0
  350. synapse/rest/admin/server_notice_servlet.py +132 -0
  351. synapse/rest/admin/statistics.py +132 -0
  352. synapse/rest/admin/username_available.py +58 -0
  353. synapse/rest/admin/users.py +1608 -0
  354. synapse/rest/client/__init__.py +20 -0
  355. synapse/rest/client/_base.py +113 -0
  356. synapse/rest/client/account.py +930 -0
  357. synapse/rest/client/account_data.py +319 -0
  358. synapse/rest/client/account_validity.py +103 -0
  359. synapse/rest/client/appservice_ping.py +125 -0
  360. synapse/rest/client/auth.py +218 -0
  361. synapse/rest/client/auth_metadata.py +122 -0
  362. synapse/rest/client/capabilities.py +121 -0
  363. synapse/rest/client/delayed_events.py +111 -0
  364. synapse/rest/client/devices.py +587 -0
  365. synapse/rest/client/directory.py +211 -0
  366. synapse/rest/client/events.py +116 -0
  367. synapse/rest/client/filter.py +112 -0
  368. synapse/rest/client/initial_sync.py +65 -0
  369. synapse/rest/client/keys.py +678 -0
  370. synapse/rest/client/knock.py +104 -0
  371. synapse/rest/client/login.py +754 -0
  372. synapse/rest/client/login_token_request.py +127 -0
  373. synapse/rest/client/logout.py +93 -0
  374. synapse/rest/client/matrixrtc.py +52 -0
  375. synapse/rest/client/media.py +286 -0
  376. synapse/rest/client/mutual_rooms.py +93 -0
  377. synapse/rest/client/notifications.py +137 -0
  378. synapse/rest/client/openid.py +109 -0
  379. synapse/rest/client/password_policy.py +69 -0
  380. synapse/rest/client/presence.py +131 -0
  381. synapse/rest/client/profile.py +291 -0
  382. synapse/rest/client/push_rule.py +331 -0
  383. synapse/rest/client/pusher.py +181 -0
  384. synapse/rest/client/read_marker.py +104 -0
  385. synapse/rest/client/receipts.py +165 -0
  386. synapse/rest/client/register.py +1067 -0
  387. synapse/rest/client/relations.py +138 -0
  388. synapse/rest/client/rendezvous.py +76 -0
  389. synapse/rest/client/reporting.py +207 -0
  390. synapse/rest/client/room.py +1669 -0
  391. synapse/rest/client/room_keys.py +426 -0
  392. synapse/rest/client/room_upgrade_rest_servlet.py +112 -0
  393. synapse/rest/client/sendtodevice.py +85 -0
  394. synapse/rest/client/sync.py +1131 -0
  395. synapse/rest/client/tags.py +129 -0
  396. synapse/rest/client/thirdparty.py +130 -0
  397. synapse/rest/client/thread_subscriptions.py +247 -0
  398. synapse/rest/client/tokenrefresh.py +52 -0
  399. synapse/rest/client/transactions.py +149 -0
  400. synapse/rest/client/user_directory.py +90 -0
  401. synapse/rest/client/versions.py +191 -0
  402. synapse/rest/client/voip.py +88 -0
  403. synapse/rest/consent/__init__.py +0 -0
  404. synapse/rest/consent/consent_resource.py +210 -0
  405. synapse/rest/health.py +38 -0
  406. synapse/rest/key/__init__.py +20 -0
  407. synapse/rest/key/v2/__init__.py +40 -0
  408. synapse/rest/key/v2/local_key_resource.py +125 -0
  409. synapse/rest/key/v2/remote_key_resource.py +302 -0
  410. synapse/rest/media/__init__.py +0 -0
  411. synapse/rest/media/config_resource.py +53 -0
  412. synapse/rest/media/create_resource.py +90 -0
  413. synapse/rest/media/download_resource.py +110 -0
  414. synapse/rest/media/media_repository_resource.py +113 -0
  415. synapse/rest/media/preview_url_resource.py +77 -0
  416. synapse/rest/media/thumbnail_resource.py +142 -0
  417. synapse/rest/media/upload_resource.py +187 -0
  418. synapse/rest/media/v1/__init__.py +39 -0
  419. synapse/rest/media/v1/_base.py +23 -0
  420. synapse/rest/media/v1/media_storage.py +23 -0
  421. synapse/rest/media/v1/storage_provider.py +23 -0
  422. synapse/rest/synapse/__init__.py +20 -0
  423. synapse/rest/synapse/client/__init__.py +93 -0
  424. synapse/rest/synapse/client/federation_whitelist.py +66 -0
  425. synapse/rest/synapse/client/jwks.py +77 -0
  426. synapse/rest/synapse/client/new_user_consent.py +115 -0
  427. synapse/rest/synapse/client/oidc/__init__.py +45 -0
  428. synapse/rest/synapse/client/oidc/backchannel_logout_resource.py +42 -0
  429. synapse/rest/synapse/client/oidc/callback_resource.py +48 -0
  430. synapse/rest/synapse/client/password_reset.py +129 -0
  431. synapse/rest/synapse/client/pick_idp.py +107 -0
  432. synapse/rest/synapse/client/pick_username.py +153 -0
  433. synapse/rest/synapse/client/rendezvous.py +58 -0
  434. synapse/rest/synapse/client/saml2/__init__.py +42 -0
  435. synapse/rest/synapse/client/saml2/metadata_resource.py +46 -0
  436. synapse/rest/synapse/client/saml2/response_resource.py +52 -0
  437. synapse/rest/synapse/client/sso_register.py +56 -0
  438. synapse/rest/synapse/client/unsubscribe.py +88 -0
  439. synapse/rest/synapse/mas/__init__.py +71 -0
  440. synapse/rest/synapse/mas/_base.py +55 -0
  441. synapse/rest/synapse/mas/devices.py +239 -0
  442. synapse/rest/synapse/mas/users.py +469 -0
  443. synapse/rest/well_known.py +148 -0
  444. synapse/server.py +1258 -0
  445. synapse/server_notices/__init__.py +0 -0
  446. synapse/server_notices/consent_server_notices.py +136 -0
  447. synapse/server_notices/resource_limits_server_notices.py +215 -0
  448. synapse/server_notices/server_notices_manager.py +388 -0
  449. synapse/server_notices/server_notices_sender.py +67 -0
  450. synapse/server_notices/worker_server_notices_sender.py +46 -0
  451. synapse/spam_checker_api/__init__.py +31 -0
  452. synapse/state/__init__.py +1022 -0
  453. synapse/state/v1.py +370 -0
  454. synapse/state/v2.py +985 -0
  455. synapse/static/client/login/index.html +47 -0
  456. synapse/static/client/login/js/jquery-3.4.1.min.js +2 -0
  457. synapse/static/client/login/js/login.js +291 -0
  458. synapse/static/client/login/spinner.gif +0 -0
  459. synapse/static/client/login/style.css +79 -0
  460. synapse/static/index.html +63 -0
  461. synapse/storage/__init__.py +43 -0
  462. synapse/storage/_base.py +245 -0
  463. synapse/storage/admin_client_config.py +26 -0
  464. synapse/storage/background_updates.py +1189 -0
  465. synapse/storage/controllers/__init__.py +57 -0
  466. synapse/storage/controllers/persist_events.py +1239 -0
  467. synapse/storage/controllers/purge_events.py +456 -0
  468. synapse/storage/controllers/state.py +954 -0
  469. synapse/storage/controllers/stats.py +119 -0
  470. synapse/storage/database.py +2720 -0
  471. synapse/storage/databases/__init__.py +175 -0
  472. synapse/storage/databases/main/__init__.py +424 -0
  473. synapse/storage/databases/main/account_data.py +1060 -0
  474. synapse/storage/databases/main/appservice.py +473 -0
  475. synapse/storage/databases/main/cache.py +911 -0
  476. synapse/storage/databases/main/censor_events.py +225 -0
  477. synapse/storage/databases/main/client_ips.py +817 -0
  478. synapse/storage/databases/main/delayed_events.py +560 -0
  479. synapse/storage/databases/main/deviceinbox.py +1272 -0
  480. synapse/storage/databases/main/devices.py +2581 -0
  481. synapse/storage/databases/main/directory.py +212 -0
  482. synapse/storage/databases/main/e2e_room_keys.py +690 -0
  483. synapse/storage/databases/main/end_to_end_keys.py +1896 -0
  484. synapse/storage/databases/main/event_federation.py +2509 -0
  485. synapse/storage/databases/main/event_push_actions.py +1937 -0
  486. synapse/storage/databases/main/events.py +3746 -0
  487. synapse/storage/databases/main/events_bg_updates.py +2910 -0
  488. synapse/storage/databases/main/events_forward_extremities.py +126 -0
  489. synapse/storage/databases/main/events_worker.py +2784 -0
  490. synapse/storage/databases/main/experimental_features.py +130 -0
  491. synapse/storage/databases/main/filtering.py +231 -0
  492. synapse/storage/databases/main/keys.py +291 -0
  493. synapse/storage/databases/main/lock.py +553 -0
  494. synapse/storage/databases/main/media_repository.py +1070 -0
  495. synapse/storage/databases/main/metrics.py +460 -0
  496. synapse/storage/databases/main/monthly_active_users.py +443 -0
  497. synapse/storage/databases/main/openid.py +61 -0
  498. synapse/storage/databases/main/presence.py +511 -0
  499. synapse/storage/databases/main/profile.py +541 -0
  500. synapse/storage/databases/main/purge_events.py +511 -0
  501. synapse/storage/databases/main/push_rule.py +972 -0
  502. synapse/storage/databases/main/pusher.py +794 -0
  503. synapse/storage/databases/main/receipts.py +1342 -0
  504. synapse/storage/databases/main/registration.py +3076 -0
  505. synapse/storage/databases/main/rejections.py +38 -0
  506. synapse/storage/databases/main/relations.py +1118 -0
  507. synapse/storage/databases/main/room.py +2781 -0
  508. synapse/storage/databases/main/roommember.py +2112 -0
  509. synapse/storage/databases/main/search.py +941 -0
  510. synapse/storage/databases/main/session.py +151 -0
  511. synapse/storage/databases/main/signatures.py +94 -0
  512. synapse/storage/databases/main/sliding_sync.py +603 -0
  513. synapse/storage/databases/main/state.py +1006 -0
  514. synapse/storage/databases/main/state_deltas.py +329 -0
  515. synapse/storage/databases/main/stats.py +791 -0
  516. synapse/storage/databases/main/stream.py +2580 -0
  517. synapse/storage/databases/main/tags.py +360 -0
  518. synapse/storage/databases/main/task_scheduler.py +225 -0
  519. synapse/storage/databases/main/thread_subscriptions.py +591 -0
  520. synapse/storage/databases/main/transactions.py +681 -0
  521. synapse/storage/databases/main/ui_auth.py +420 -0
  522. synapse/storage/databases/main/user_directory.py +1331 -0
  523. synapse/storage/databases/main/user_erasure_store.py +117 -0
  524. synapse/storage/databases/state/__init__.py +22 -0
  525. synapse/storage/databases/state/bg_updates.py +499 -0
  526. synapse/storage/databases/state/deletion.py +558 -0
  527. synapse/storage/databases/state/store.py +949 -0
  528. synapse/storage/engines/__init__.py +70 -0
  529. synapse/storage/engines/_base.py +154 -0
  530. synapse/storage/engines/postgres.py +261 -0
  531. synapse/storage/engines/sqlite.py +199 -0
  532. synapse/storage/invite_rule.py +112 -0
  533. synapse/storage/keys.py +40 -0
  534. synapse/storage/prepare_database.py +731 -0
  535. synapse/storage/push_rule.py +28 -0
  536. synapse/storage/roommember.py +89 -0
  537. synapse/storage/schema/README.md +4 -0
  538. synapse/storage/schema/__init__.py +182 -0
  539. synapse/storage/schema/common/delta/25/00background_updates.sql +40 -0
  540. synapse/storage/schema/common/delta/35/00background_updates_add_col.sql +36 -0
  541. synapse/storage/schema/common/delta/58/00background_update_ordering.sql +38 -0
  542. synapse/storage/schema/common/full_schemas/72/full.sql.postgres +8 -0
  543. synapse/storage/schema/common/full_schemas/72/full.sql.sqlite +6 -0
  544. synapse/storage/schema/common/schema_version.sql +60 -0
  545. synapse/storage/schema/main/delta/12/v12.sql +82 -0
  546. synapse/storage/schema/main/delta/13/v13.sql +38 -0
  547. synapse/storage/schema/main/delta/14/v14.sql +42 -0
  548. synapse/storage/schema/main/delta/15/appservice_txns.sql +50 -0
  549. synapse/storage/schema/main/delta/15/presence_indices.sql +2 -0
  550. synapse/storage/schema/main/delta/15/v15.sql +24 -0
  551. synapse/storage/schema/main/delta/16/events_order_index.sql +4 -0
  552. synapse/storage/schema/main/delta/16/remote_media_cache_index.sql +2 -0
  553. synapse/storage/schema/main/delta/16/remove_duplicates.sql +9 -0
  554. synapse/storage/schema/main/delta/16/room_alias_index.sql +3 -0
  555. synapse/storage/schema/main/delta/16/unique_constraints.sql +72 -0
  556. synapse/storage/schema/main/delta/16/users.sql +56 -0
  557. synapse/storage/schema/main/delta/17/drop_indexes.sql +37 -0
  558. synapse/storage/schema/main/delta/17/server_keys.sql +43 -0
  559. synapse/storage/schema/main/delta/17/user_threepids.sql +9 -0
  560. synapse/storage/schema/main/delta/18/server_keys_bigger_ints.sql +51 -0
  561. synapse/storage/schema/main/delta/19/event_index.sql +38 -0
  562. synapse/storage/schema/main/delta/20/dummy.sql +1 -0
  563. synapse/storage/schema/main/delta/20/pushers.py +93 -0
  564. synapse/storage/schema/main/delta/21/end_to_end_keys.sql +53 -0
  565. synapse/storage/schema/main/delta/21/receipts.sql +57 -0
  566. synapse/storage/schema/main/delta/22/receipts_index.sql +41 -0
  567. synapse/storage/schema/main/delta/22/user_threepids_unique.sql +19 -0
  568. synapse/storage/schema/main/delta/24/stats_reporting.sql +37 -0
  569. synapse/storage/schema/main/delta/25/fts.py +81 -0
  570. synapse/storage/schema/main/delta/25/guest_access.sql +44 -0
  571. synapse/storage/schema/main/delta/25/history_visibility.sql +44 -0
  572. synapse/storage/schema/main/delta/25/tags.sql +57 -0
  573. synapse/storage/schema/main/delta/26/account_data.sql +36 -0
  574. synapse/storage/schema/main/delta/27/account_data.sql +55 -0
  575. synapse/storage/schema/main/delta/27/forgotten_memberships.sql +45 -0
  576. synapse/storage/schema/main/delta/27/ts.py +61 -0
  577. synapse/storage/schema/main/delta/28/event_push_actions.sql +46 -0
  578. synapse/storage/schema/main/delta/28/events_room_stream.sql +39 -0
  579. synapse/storage/schema/main/delta/28/public_roms_index.sql +39 -0
  580. synapse/storage/schema/main/delta/28/receipts_user_id_index.sql +41 -0
  581. synapse/storage/schema/main/delta/28/upgrade_times.sql +40 -0
  582. synapse/storage/schema/main/delta/28/users_is_guest.sql +41 -0
  583. synapse/storage/schema/main/delta/29/push_actions.sql +54 -0
  584. synapse/storage/schema/main/delta/30/alias_creator.sql +35 -0
  585. synapse/storage/schema/main/delta/30/as_users.py +82 -0
  586. synapse/storage/schema/main/delta/30/deleted_pushers.sql +44 -0
  587. synapse/storage/schema/main/delta/30/presence_stream.sql +49 -0
  588. synapse/storage/schema/main/delta/30/public_rooms.sql +42 -0
  589. synapse/storage/schema/main/delta/30/push_rule_stream.sql +57 -0
  590. synapse/storage/schema/main/delta/30/threepid_guest_access_tokens.sql +43 -0
  591. synapse/storage/schema/main/delta/31/invites.sql +61 -0
  592. synapse/storage/schema/main/delta/31/local_media_repository_url_cache.sql +46 -0
  593. synapse/storage/schema/main/delta/31/pushers_0.py +92 -0
  594. synapse/storage/schema/main/delta/31/pushers_index.sql +41 -0
  595. synapse/storage/schema/main/delta/31/search_update.py +65 -0
  596. synapse/storage/schema/main/delta/32/events.sql +35 -0
  597. synapse/storage/schema/main/delta/32/openid.sql +9 -0
  598. synapse/storage/schema/main/delta/32/pusher_throttle.sql +42 -0
  599. synapse/storage/schema/main/delta/32/remove_indices.sql +52 -0
  600. synapse/storage/schema/main/delta/32/reports.sql +44 -0
  601. synapse/storage/schema/main/delta/33/access_tokens_device_index.sql +36 -0
  602. synapse/storage/schema/main/delta/33/devices.sql +40 -0
  603. synapse/storage/schema/main/delta/33/devices_for_e2e_keys.sql +38 -0
  604. synapse/storage/schema/main/delta/33/devices_for_e2e_keys_clear_unknown_device.sql +39 -0
  605. synapse/storage/schema/main/delta/33/event_fields.py +61 -0
  606. synapse/storage/schema/main/delta/33/remote_media_ts.py +43 -0
  607. synapse/storage/schema/main/delta/33/user_ips_index.sql +36 -0
  608. synapse/storage/schema/main/delta/34/appservice_stream.sql +42 -0
  609. synapse/storage/schema/main/delta/34/cache_stream.py +50 -0
  610. synapse/storage/schema/main/delta/34/device_inbox.sql +43 -0
  611. synapse/storage/schema/main/delta/34/push_display_name_rename.sql +39 -0
  612. synapse/storage/schema/main/delta/34/received_txn_purge.py +36 -0
  613. synapse/storage/schema/main/delta/35/contains_url.sql +36 -0
  614. synapse/storage/schema/main/delta/35/device_outbox.sql +58 -0
  615. synapse/storage/schema/main/delta/35/device_stream_id.sql +40 -0
  616. synapse/storage/schema/main/delta/35/event_push_actions_index.sql +36 -0
  617. synapse/storage/schema/main/delta/35/public_room_list_change_stream.sql +52 -0
  618. synapse/storage/schema/main/delta/35/stream_order_to_extrem.sql +56 -0
  619. synapse/storage/schema/main/delta/36/readd_public_rooms.sql +45 -0
  620. synapse/storage/schema/main/delta/37/remove_auth_idx.py +89 -0
  621. synapse/storage/schema/main/delta/37/user_threepids.sql +71 -0
  622. synapse/storage/schema/main/delta/38/postgres_fts_gist.sql +38 -0
  623. synapse/storage/schema/main/delta/39/appservice_room_list.sql +48 -0
  624. synapse/storage/schema/main/delta/39/device_federation_stream_idx.sql +35 -0
  625. synapse/storage/schema/main/delta/39/event_push_index.sql +36 -0
  626. synapse/storage/schema/main/delta/39/federation_out_position.sql +41 -0
  627. synapse/storage/schema/main/delta/39/membership_profile.sql +39 -0
  628. synapse/storage/schema/main/delta/40/current_state_idx.sql +36 -0
  629. synapse/storage/schema/main/delta/40/device_inbox.sql +40 -0
  630. synapse/storage/schema/main/delta/40/device_list_streams.sql +79 -0
  631. synapse/storage/schema/main/delta/40/event_push_summary.sql +57 -0
  632. synapse/storage/schema/main/delta/40/pushers.sql +58 -0
  633. synapse/storage/schema/main/delta/41/device_list_stream_idx.sql +36 -0
  634. synapse/storage/schema/main/delta/41/device_outbound_index.sql +35 -0
  635. synapse/storage/schema/main/delta/41/event_search_event_id_idx.sql +36 -0
  636. synapse/storage/schema/main/delta/41/ratelimit.sql +41 -0
  637. synapse/storage/schema/main/delta/42/current_state_delta.sql +48 -0
  638. synapse/storage/schema/main/delta/42/device_list_last_id.sql +52 -0
  639. synapse/storage/schema/main/delta/42/event_auth_state_only.sql +36 -0
  640. synapse/storage/schema/main/delta/42/user_dir.py +88 -0
  641. synapse/storage/schema/main/delta/43/blocked_rooms.sql +40 -0
  642. synapse/storage/schema/main/delta/43/quarantine_media.sql +36 -0
  643. synapse/storage/schema/main/delta/43/url_cache.sql +35 -0
  644. synapse/storage/schema/main/delta/43/user_share.sql +52 -0
  645. synapse/storage/schema/main/delta/44/expire_url_cache.sql +60 -0
  646. synapse/storage/schema/main/delta/45/group_server.sql +186 -0
  647. synapse/storage/schema/main/delta/45/profile_cache.sql +47 -0
  648. synapse/storage/schema/main/delta/46/drop_refresh_tokens.sql +36 -0
  649. synapse/storage/schema/main/delta/46/drop_unique_deleted_pushers.sql +54 -0
  650. synapse/storage/schema/main/delta/46/group_server.sql +51 -0
  651. synapse/storage/schema/main/delta/46/local_media_repository_url_idx.sql +43 -0
  652. synapse/storage/schema/main/delta/46/user_dir_null_room_ids.sql +54 -0
  653. synapse/storage/schema/main/delta/46/user_dir_typos.sql +43 -0
  654. synapse/storage/schema/main/delta/47/last_access_media.sql +35 -0
  655. synapse/storage/schema/main/delta/47/postgres_fts_gin.sql +36 -0
  656. synapse/storage/schema/main/delta/47/push_actions_staging.sql +47 -0
  657. synapse/storage/schema/main/delta/48/add_user_consent.sql +37 -0
  658. synapse/storage/schema/main/delta/48/add_user_ips_last_seen_index.sql +36 -0
  659. synapse/storage/schema/main/delta/48/deactivated_users.sql +44 -0
  660. synapse/storage/schema/main/delta/48/group_unique_indexes.py +67 -0
  661. synapse/storage/schema/main/delta/48/groups_joinable.sql +41 -0
  662. synapse/storage/schema/main/delta/49/add_user_consent_server_notice_sent.sql +39 -0
  663. synapse/storage/schema/main/delta/49/add_user_daily_visits.sql +40 -0
  664. synapse/storage/schema/main/delta/49/add_user_ips_last_seen_only_index.sql +36 -0
  665. synapse/storage/schema/main/delta/50/add_creation_ts_users_index.sql +38 -0
  666. synapse/storage/schema/main/delta/50/erasure_store.sql +40 -0
  667. synapse/storage/schema/main/delta/50/make_event_content_nullable.py +102 -0
  668. synapse/storage/schema/main/delta/51/e2e_room_keys.sql +58 -0
  669. synapse/storage/schema/main/delta/51/monthly_active_users.sql +46 -0
  670. synapse/storage/schema/main/delta/52/add_event_to_state_group_index.sql +38 -0
  671. synapse/storage/schema/main/delta/52/device_list_streams_unique_idx.sql +55 -0
  672. synapse/storage/schema/main/delta/52/e2e_room_keys.sql +72 -0
  673. synapse/storage/schema/main/delta/53/add_user_type_to_users.sql +38 -0
  674. synapse/storage/schema/main/delta/53/drop_sent_transactions.sql +35 -0
  675. synapse/storage/schema/main/delta/53/event_format_version.sql +35 -0
  676. synapse/storage/schema/main/delta/53/user_dir_populate.sql +49 -0
  677. synapse/storage/schema/main/delta/53/user_ips_index.sql +49 -0
  678. synapse/storage/schema/main/delta/53/user_share.sql +63 -0
  679. synapse/storage/schema/main/delta/53/user_threepid_id.sql +48 -0
  680. synapse/storage/schema/main/delta/53/users_in_public_rooms.sql +47 -0
  681. synapse/storage/schema/main/delta/54/account_validity_with_renewal.sql +49 -0
  682. synapse/storage/schema/main/delta/54/add_validity_to_server_keys.sql +42 -0
  683. synapse/storage/schema/main/delta/54/delete_forward_extremities.sql +42 -0
  684. synapse/storage/schema/main/delta/54/drop_legacy_tables.sql +49 -0
  685. synapse/storage/schema/main/delta/54/drop_presence_list.sql +35 -0
  686. synapse/storage/schema/main/delta/54/relations.sql +46 -0
  687. synapse/storage/schema/main/delta/54/stats.sql +99 -0
  688. synapse/storage/schema/main/delta/54/stats2.sql +47 -0
  689. synapse/storage/schema/main/delta/55/access_token_expiry.sql +37 -0
  690. synapse/storage/schema/main/delta/55/track_threepid_validations.sql +50 -0
  691. synapse/storage/schema/main/delta/55/users_alter_deactivated.sql +38 -0
  692. synapse/storage/schema/main/delta/56/add_spans_to_device_lists.sql +39 -0
  693. synapse/storage/schema/main/delta/56/current_state_events_membership.sql +41 -0
  694. synapse/storage/schema/main/delta/56/current_state_events_membership_mk2.sql +43 -0
  695. synapse/storage/schema/main/delta/56/delete_keys_from_deleted_backups.sql +44 -0
  696. synapse/storage/schema/main/delta/56/destinations_failure_ts.sql +44 -0
  697. synapse/storage/schema/main/delta/56/destinations_retry_interval_type.sql.postgres +18 -0
  698. synapse/storage/schema/main/delta/56/device_stream_id_insert.sql +39 -0
  699. synapse/storage/schema/main/delta/56/devices_last_seen.sql +43 -0
  700. synapse/storage/schema/main/delta/56/drop_unused_event_tables.sql +39 -0
  701. synapse/storage/schema/main/delta/56/event_expiry.sql +40 -0
  702. synapse/storage/schema/main/delta/56/event_labels.sql +49 -0
  703. synapse/storage/schema/main/delta/56/event_labels_background_update.sql +36 -0
  704. synapse/storage/schema/main/delta/56/fix_room_keys_index.sql +37 -0
  705. synapse/storage/schema/main/delta/56/hidden_devices.sql +37 -0
  706. synapse/storage/schema/main/delta/56/hidden_devices_fix.sql.sqlite +42 -0
  707. synapse/storage/schema/main/delta/56/nuke_empty_communities_from_db.sql +48 -0
  708. synapse/storage/schema/main/delta/56/public_room_list_idx.sql +35 -0
  709. synapse/storage/schema/main/delta/56/redaction_censor.sql +35 -0
  710. synapse/storage/schema/main/delta/56/redaction_censor2.sql +41 -0
  711. synapse/storage/schema/main/delta/56/redaction_censor3_fix_update.sql.postgres +25 -0
  712. synapse/storage/schema/main/delta/56/redaction_censor4.sql +35 -0
  713. synapse/storage/schema/main/delta/56/remove_tombstoned_rooms_from_directory.sql +38 -0
  714. synapse/storage/schema/main/delta/56/room_key_etag.sql +36 -0
  715. synapse/storage/schema/main/delta/56/room_membership_idx.sql +37 -0
  716. synapse/storage/schema/main/delta/56/room_retention.sql +52 -0
  717. synapse/storage/schema/main/delta/56/signing_keys.sql +75 -0
  718. synapse/storage/schema/main/delta/56/signing_keys_nonunique_signatures.sql +41 -0
  719. synapse/storage/schema/main/delta/56/stats_separated.sql +175 -0
  720. synapse/storage/schema/main/delta/56/unique_user_filter_index.py +46 -0
  721. synapse/storage/schema/main/delta/56/user_external_ids.sql +43 -0
  722. synapse/storage/schema/main/delta/56/users_in_public_rooms_idx.sql +36 -0
  723. synapse/storage/schema/main/delta/57/delete_old_current_state_events.sql +41 -0
  724. synapse/storage/schema/main/delta/57/device_list_remote_cache_stale.sql +44 -0
  725. synapse/storage/schema/main/delta/57/local_current_membership.py +111 -0
  726. synapse/storage/schema/main/delta/57/remove_sent_outbound_pokes.sql +40 -0
  727. synapse/storage/schema/main/delta/57/rooms_version_column.sql +43 -0
  728. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.postgres +35 -0
  729. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.sqlite +22 -0
  730. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.postgres +39 -0
  731. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.sqlite +23 -0
  732. synapse/storage/schema/main/delta/58/02remove_dup_outbound_pokes.sql +41 -0
  733. synapse/storage/schema/main/delta/58/03persist_ui_auth.sql +55 -0
  734. synapse/storage/schema/main/delta/58/05cache_instance.sql.postgres +30 -0
  735. synapse/storage/schema/main/delta/58/06dlols_unique_idx.py +83 -0
  736. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.postgres +33 -0
  737. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.sqlite +44 -0
  738. synapse/storage/schema/main/delta/58/07persist_ui_auth_ips.sql +44 -0
  739. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.postgres +18 -0
  740. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.sqlite +18 -0
  741. synapse/storage/schema/main/delta/58/09shadow_ban.sql +37 -0
  742. synapse/storage/schema/main/delta/58/10_pushrules_enabled_delete_obsolete.sql +47 -0
  743. synapse/storage/schema/main/delta/58/10drop_local_rejections_stream.sql +41 -0
  744. synapse/storage/schema/main/delta/58/10federation_pos_instance_name.sql +41 -0
  745. synapse/storage/schema/main/delta/58/11dehydration.sql +39 -0
  746. synapse/storage/schema/main/delta/58/11fallback.sql +43 -0
  747. synapse/storage/schema/main/delta/58/11user_id_seq.py +38 -0
  748. synapse/storage/schema/main/delta/58/12room_stats.sql +51 -0
  749. synapse/storage/schema/main/delta/58/13remove_presence_allow_inbound.sql +36 -0
  750. synapse/storage/schema/main/delta/58/14events_instance_name.sql +35 -0
  751. synapse/storage/schema/main/delta/58/14events_instance_name.sql.postgres +28 -0
  752. synapse/storage/schema/main/delta/58/15_catchup_destination_rooms.sql +61 -0
  753. synapse/storage/schema/main/delta/58/15unread_count.sql +45 -0
  754. synapse/storage/schema/main/delta/58/16populate_stats_process_rooms_fix.sql +41 -0
  755. synapse/storage/schema/main/delta/58/17_catchup_last_successful.sql +40 -0
  756. synapse/storage/schema/main/delta/58/18stream_positions.sql +41 -0
  757. synapse/storage/schema/main/delta/58/19instance_map.sql.postgres +25 -0
  758. synapse/storage/schema/main/delta/58/19txn_id.sql +59 -0
  759. synapse/storage/schema/main/delta/58/20instance_name_event_tables.sql +36 -0
  760. synapse/storage/schema/main/delta/58/20user_daily_visits.sql +37 -0
  761. synapse/storage/schema/main/delta/58/21as_device_stream.sql +36 -0
  762. synapse/storage/schema/main/delta/58/21drop_device_max_stream_id.sql +1 -0
  763. synapse/storage/schema/main/delta/58/22puppet_token.sql +36 -0
  764. synapse/storage/schema/main/delta/58/22users_have_local_media.sql +2 -0
  765. synapse/storage/schema/main/delta/58/23e2e_cross_signing_keys_idx.sql +36 -0
  766. synapse/storage/schema/main/delta/58/24drop_event_json_index.sql +38 -0
  767. synapse/storage/schema/main/delta/58/25user_external_ids_user_id_idx.sql +36 -0
  768. synapse/storage/schema/main/delta/58/26access_token_last_validated.sql +37 -0
  769. synapse/storage/schema/main/delta/58/27local_invites.sql +37 -0
  770. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.postgres +16 -0
  771. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.sqlite +62 -0
  772. synapse/storage/schema/main/delta/59/01ignored_user.py +85 -0
  773. synapse/storage/schema/main/delta/59/02shard_send_to_device.sql +37 -0
  774. synapse/storage/schema/main/delta/59/03shard_send_to_device_sequence.sql.postgres +25 -0
  775. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql +71 -0
  776. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql.postgres +16 -0
  777. synapse/storage/schema/main/delta/59/04drop_account_data.sql +36 -0
  778. synapse/storage/schema/main/delta/59/05cache_invalidation.sql +36 -0
  779. synapse/storage/schema/main/delta/59/06chain_cover_index.sql +36 -0
  780. synapse/storage/schema/main/delta/59/06shard_account_data.sql +39 -0
  781. synapse/storage/schema/main/delta/59/06shard_account_data.sql.postgres +32 -0
  782. synapse/storage/schema/main/delta/59/07shard_account_data_fix.sql +37 -0
  783. synapse/storage/schema/main/delta/59/08delete_pushers_for_deactivated_accounts.sql +39 -0
  784. synapse/storage/schema/main/delta/59/08delete_stale_pushers.sql +39 -0
  785. synapse/storage/schema/main/delta/59/09rejected_events_metadata.sql +45 -0
  786. synapse/storage/schema/main/delta/59/10delete_purged_chain_cover.sql +36 -0
  787. synapse/storage/schema/main/delta/59/11add_knock_members_to_stats.sql +39 -0
  788. synapse/storage/schema/main/delta/59/11drop_thumbnail_constraint.sql.postgres +22 -0
  789. synapse/storage/schema/main/delta/59/12account_validity_token_used_ts_ms.sql +37 -0
  790. synapse/storage/schema/main/delta/59/12presence_stream_instance.sql +37 -0
  791. synapse/storage/schema/main/delta/59/12presence_stream_instance_seq.sql.postgres +20 -0
  792. synapse/storage/schema/main/delta/59/13users_to_send_full_presence_to.sql +53 -0
  793. synapse/storage/schema/main/delta/59/14refresh_tokens.sql +53 -0
  794. synapse/storage/schema/main/delta/59/15locks.sql +56 -0
  795. synapse/storage/schema/main/delta/59/16federation_inbound_staging.sql +51 -0
  796. synapse/storage/schema/main/delta/60/01recreate_stream_ordering.sql.postgres +45 -0
  797. synapse/storage/schema/main/delta/60/02change_stream_ordering_columns.sql.postgres +30 -0
  798. synapse/storage/schema/main/delta/61/01change_appservices_txns.sql.postgres +23 -0
  799. synapse/storage/schema/main/delta/61/01insertion_event_lookups.sql +68 -0
  800. synapse/storage/schema/main/delta/61/02drop_redundant_room_depth_index.sql +37 -0
  801. synapse/storage/schema/main/delta/61/03recreate_min_depth.py +74 -0
  802. synapse/storage/schema/main/delta/62/01insertion_event_extremities.sql +43 -0
  803. synapse/storage/schema/main/delta/63/01create_registration_tokens.sql +42 -0
  804. synapse/storage/schema/main/delta/63/02delete_unlinked_email_pushers.sql +39 -0
  805. synapse/storage/schema/main/delta/63/02populate-rooms-creator.sql +36 -0
  806. synapse/storage/schema/main/delta/63/03session_store.sql +42 -0
  807. synapse/storage/schema/main/delta/63/04add_presence_stream_not_offline_index.sql +37 -0
  808. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.postgres +23 -0
  809. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.sqlite +37 -0
  810. synapse/storage/schema/main/delta/65/01msc2716_insertion_event_edges.sql +38 -0
  811. synapse/storage/schema/main/delta/65/03remove_hidden_devices_from_device_inbox.sql +41 -0
  812. synapse/storage/schema/main/delta/65/04_local_group_updates.sql +37 -0
  813. synapse/storage/schema/main/delta/65/05_remove_room_stats_historical_and_user_stats_historical.sql +38 -0
  814. synapse/storage/schema/main/delta/65/06remove_deleted_devices_from_device_inbox.sql +53 -0
  815. synapse/storage/schema/main/delta/65/07_arbitrary_relations.sql +37 -0
  816. synapse/storage/schema/main/delta/65/08_device_inbox_background_updates.sql +37 -0
  817. synapse/storage/schema/main/delta/65/10_expirable_refresh_tokens.sql +47 -0
  818. synapse/storage/schema/main/delta/65/11_devices_auth_provider_session.sql +46 -0
  819. synapse/storage/schema/main/delta/67/01drop_public_room_list_stream.sql +37 -0
  820. synapse/storage/schema/main/delta/68/01event_columns.sql +45 -0
  821. synapse/storage/schema/main/delta/68/02_msc2409_add_device_id_appservice_stream_type.sql +40 -0
  822. synapse/storage/schema/main/delta/68/03_delete_account_data_for_deactivated_accounts.sql +39 -0
  823. synapse/storage/schema/main/delta/68/04_refresh_tokens_index_next_token_id.sql +47 -0
  824. synapse/storage/schema/main/delta/68/04partial_state_rooms.sql +60 -0
  825. synapse/storage/schema/main/delta/68/05_delete_non_strings_from_event_search.sql.sqlite +22 -0
  826. synapse/storage/schema/main/delta/68/05partial_state_rooms_triggers.py +80 -0
  827. synapse/storage/schema/main/delta/68/06_msc3202_add_device_list_appservice_stream_type.sql +42 -0
  828. synapse/storage/schema/main/delta/69/01as_txn_seq.py +54 -0
  829. synapse/storage/schema/main/delta/69/01device_list_oubound_by_room.sql +57 -0
  830. synapse/storage/schema/main/delta/69/02cache_invalidation_index.sql +37 -0
  831. synapse/storage/schema/main/delta/70/01clean_table_purged_rooms.sql +39 -0
  832. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.postgres +43 -0
  833. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.sqlite +47 -0
  834. synapse/storage/schema/main/delta/71/01remove_noop_background_updates.sql +80 -0
  835. synapse/storage/schema/main/delta/71/02event_push_summary_unique.sql +37 -0
  836. synapse/storage/schema/main/delta/72/01add_room_type_to_state_stats.sql +38 -0
  837. synapse/storage/schema/main/delta/72/01event_push_summary_receipt.sql +54 -0
  838. synapse/storage/schema/main/delta/72/02event_push_actions_index.sql +38 -0
  839. synapse/storage/schema/main/delta/72/03bg_populate_events_columns.py +57 -0
  840. synapse/storage/schema/main/delta/72/03drop_event_reference_hashes.sql +36 -0
  841. synapse/storage/schema/main/delta/72/03remove_groups.sql +50 -0
  842. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.postgres +17 -0
  843. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.sqlite +40 -0
  844. synapse/storage/schema/main/delta/72/05receipts_event_stream_ordering.sql +38 -0
  845. synapse/storage/schema/main/delta/72/05remove_unstable_private_read_receipts.sql +38 -0
  846. synapse/storage/schema/main/delta/72/06add_consent_ts_to_users.sql +35 -0
  847. synapse/storage/schema/main/delta/72/06thread_notifications.sql +49 -0
  848. synapse/storage/schema/main/delta/72/07force_update_current_state_events_membership.py +67 -0
  849. synapse/storage/schema/main/delta/72/07thread_receipts.sql.postgres +30 -0
  850. synapse/storage/schema/main/delta/72/07thread_receipts.sql.sqlite +70 -0
  851. synapse/storage/schema/main/delta/72/08begin_cache_invalidation_seq_at_2.sql.postgres +23 -0
  852. synapse/storage/schema/main/delta/72/08thread_receipts.sql +39 -0
  853. synapse/storage/schema/main/delta/72/09partial_indices.sql.sqlite +56 -0
  854. synapse/storage/schema/main/delta/73/01event_failed_pull_attempts.sql +48 -0
  855. synapse/storage/schema/main/delta/73/02add_pusher_enabled.sql +35 -0
  856. synapse/storage/schema/main/delta/73/02room_id_indexes_for_purging.sql +41 -0
  857. synapse/storage/schema/main/delta/73/03pusher_device_id.sql +39 -0
  858. synapse/storage/schema/main/delta/73/03users_approved_column.sql +39 -0
  859. synapse/storage/schema/main/delta/73/04partial_join_details.sql +42 -0
  860. synapse/storage/schema/main/delta/73/04pending_device_list_updates.sql +47 -0
  861. synapse/storage/schema/main/delta/73/05old_push_actions.sql.postgres +22 -0
  862. synapse/storage/schema/main/delta/73/05old_push_actions.sql.sqlite +24 -0
  863. synapse/storage/schema/main/delta/73/06thread_notifications_thread_id_idx.sql +42 -0
  864. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.postgres +23 -0
  865. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.sqlite +76 -0
  866. synapse/storage/schema/main/delta/73/09partial_joined_via_destination.sql +37 -0
  867. synapse/storage/schema/main/delta/73/09threads_table.sql +49 -0
  868. synapse/storage/schema/main/delta/73/10_update_sqlite_fts4_tokenizer.py +71 -0
  869. synapse/storage/schema/main/delta/73/10login_tokens.sql +54 -0
  870. synapse/storage/schema/main/delta/73/11event_search_room_id_n_distinct.sql.postgres +33 -0
  871. synapse/storage/schema/main/delta/73/12refactor_device_list_outbound_pokes.sql +72 -0
  872. synapse/storage/schema/main/delta/73/13add_device_lists_index.sql +39 -0
  873. synapse/storage/schema/main/delta/73/20_un_partial_stated_room_stream.sql +51 -0
  874. synapse/storage/schema/main/delta/73/21_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  875. synapse/storage/schema/main/delta/73/22_rebuild_user_dir_stats.sql +48 -0
  876. synapse/storage/schema/main/delta/73/22_un_partial_stated_event_stream.sql +53 -0
  877. synapse/storage/schema/main/delta/73/23_fix_thread_index.sql +52 -0
  878. synapse/storage/schema/main/delta/73/23_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  879. synapse/storage/schema/main/delta/73/24_events_jump_to_date_index.sql +36 -0
  880. synapse/storage/schema/main/delta/73/25drop_presence.sql +36 -0
  881. synapse/storage/schema/main/delta/74/01_user_directory_stale_remote_users.sql +58 -0
  882. synapse/storage/schema/main/delta/74/02_set_device_id_for_pushers_bg_update.sql +38 -0
  883. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.postgres +29 -0
  884. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.sqlite +23 -0
  885. synapse/storage/schema/main/delta/74/03_room_membership_index.sql +38 -0
  886. synapse/storage/schema/main/delta/74/04_delete_e2e_backup_keys_for_deactivated_users.sql +36 -0
  887. synapse/storage/schema/main/delta/74/04_membership_tables_event_stream_ordering_triggers.py +87 -0
  888. synapse/storage/schema/main/delta/74/05_events_txn_id_device_id.sql +72 -0
  889. synapse/storage/schema/main/delta/74/90COMMENTS_destinations.sql.postgres +52 -0
  890. synapse/storage/schema/main/delta/76/01_add_profiles_full_user_id_column.sql +39 -0
  891. synapse/storage/schema/main/delta/76/02_add_user_filters_full_user_id_column.sql +39 -0
  892. synapse/storage/schema/main/delta/76/03_per_user_experimental_features.sql +46 -0
  893. synapse/storage/schema/main/delta/76/04_add_room_forgetter.sql +43 -0
  894. synapse/storage/schema/main/delta/77/01_add_profiles_not_valid_check.sql.postgres +16 -0
  895. synapse/storage/schema/main/delta/77/02_add_user_filters_not_valid_check.sql.postgres +16 -0
  896. synapse/storage/schema/main/delta/77/03bg_populate_full_user_id_profiles.sql +35 -0
  897. synapse/storage/schema/main/delta/77/04bg_populate_full_user_id_user_filters.sql +35 -0
  898. synapse/storage/schema/main/delta/77/05thread_notifications_backfill.sql +67 -0
  899. synapse/storage/schema/main/delta/77/06thread_notifications_not_null.sql.sqlite +102 -0
  900. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions.sql.postgres +27 -0
  901. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions_staging.sql.postgres +27 -0
  902. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_summary.sql.postgres +29 -0
  903. synapse/storage/schema/main/delta/77/14bg_indices_event_stream_ordering.sql +39 -0
  904. synapse/storage/schema/main/delta/78/01_validate_and_update_profiles.py +99 -0
  905. synapse/storage/schema/main/delta/78/02_validate_and_update_user_filters.py +100 -0
  906. synapse/storage/schema/main/delta/78/03_remove_unused_indexes_user_filters.py +72 -0
  907. synapse/storage/schema/main/delta/78/03event_extremities_constraints.py +65 -0
  908. synapse/storage/schema/main/delta/78/04_add_full_user_id_index_user_filters.py +32 -0
  909. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.postgres +102 -0
  910. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.sqlite +72 -0
  911. synapse/storage/schema/main/delta/79/04_mitigate_stream_ordering_update_race.py +70 -0
  912. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.postgres +69 -0
  913. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.sqlite +65 -0
  914. synapse/storage/schema/main/delta/80/01_users_alter_locked.sql +35 -0
  915. synapse/storage/schema/main/delta/80/02_read_write_locks_unlogged.sql.postgres +30 -0
  916. synapse/storage/schema/main/delta/80/02_scheduled_tasks.sql +47 -0
  917. synapse/storage/schema/main/delta/80/03_read_write_locks_triggers.sql.postgres +37 -0
  918. synapse/storage/schema/main/delta/80/04_read_write_locks_deadlock.sql.postgres +71 -0
  919. synapse/storage/schema/main/delta/82/02_scheduled_tasks_index.sql +35 -0
  920. synapse/storage/schema/main/delta/82/04_add_indices_for_purging_rooms.sql +39 -0
  921. synapse/storage/schema/main/delta/82/05gaps.sql +44 -0
  922. synapse/storage/schema/main/delta/83/01_drop_old_tables.sql +43 -0
  923. synapse/storage/schema/main/delta/83/03_instance_name_receipts.sql.sqlite +17 -0
  924. synapse/storage/schema/main/delta/83/05_cross_signing_key_update_grant.sql +34 -0
  925. synapse/storage/schema/main/delta/83/06_event_push_summary_room.sql +36 -0
  926. synapse/storage/schema/main/delta/84/01_auth_links_stats.sql.postgres +20 -0
  927. synapse/storage/schema/main/delta/84/02_auth_links_index.sql +16 -0
  928. synapse/storage/schema/main/delta/84/03_auth_links_analyze.sql.postgres +16 -0
  929. synapse/storage/schema/main/delta/84/04_access_token_index.sql +15 -0
  930. synapse/storage/schema/main/delta/85/01_add_suspended.sql +14 -0
  931. synapse/storage/schema/main/delta/85/02_add_instance_names.sql +27 -0
  932. synapse/storage/schema/main/delta/85/03_new_sequences.sql.postgres +54 -0
  933. synapse/storage/schema/main/delta/85/04_cleanup_device_federation_outbox.sql +15 -0
  934. synapse/storage/schema/main/delta/85/05_add_instance_names_converted_pos.sql +16 -0
  935. synapse/storage/schema/main/delta/85/06_add_room_reports.sql +20 -0
  936. synapse/storage/schema/main/delta/86/01_authenticate_media.sql +15 -0
  937. synapse/storage/schema/main/delta/86/02_receipts_event_id_index.sql +15 -0
  938. synapse/storage/schema/main/delta/87/01_sliding_sync_memberships.sql +169 -0
  939. synapse/storage/schema/main/delta/87/02_per_connection_state.sql +81 -0
  940. synapse/storage/schema/main/delta/87/03_current_state_index.sql +19 -0
  941. synapse/storage/schema/main/delta/88/01_add_delayed_events.sql +43 -0
  942. synapse/storage/schema/main/delta/88/01_custom_profile_fields.sql +15 -0
  943. synapse/storage/schema/main/delta/88/02_fix_sliding_sync_membership_snapshots_forgotten_column.sql +21 -0
  944. synapse/storage/schema/main/delta/88/03_add_otk_ts_added_index.sql +18 -0
  945. synapse/storage/schema/main/delta/88/04_current_state_delta_index.sql +18 -0
  946. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.postgres +19 -0
  947. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.sqlite +19 -0
  948. synapse/storage/schema/main/delta/88/05_sliding_sync_room_config_index.sql +20 -0
  949. synapse/storage/schema/main/delta/88/06_events_received_ts_index.sql +17 -0
  950. synapse/storage/schema/main/delta/89/01_sliding_sync_membership_snapshot_index.sql +15 -0
  951. synapse/storage/schema/main/delta/90/01_add_column_participant_room_memberships_table.sql +16 -0
  952. synapse/storage/schema/main/delta/91/01_media_hash.sql +28 -0
  953. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.postgres +16 -0
  954. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.sqlite +16 -0
  955. synapse/storage/schema/main/delta/92/02_remove_populate_participant_bg_update.sql +17 -0
  956. synapse/storage/schema/main/delta/92/04_ss_membership_snapshot_idx.sql +16 -0
  957. synapse/storage/schema/main/delta/92/04_thread_subscriptions.sql +59 -0
  958. synapse/storage/schema/main/delta/92/04_thread_subscriptions_seq.sql.postgres +19 -0
  959. synapse/storage/schema/main/delta/92/05_fixup_max_depth_cap.sql +17 -0
  960. synapse/storage/schema/main/delta/92/05_thread_subscriptions_comments.sql.postgres +18 -0
  961. synapse/storage/schema/main/delta/92/06_device_federation_inbox_index.sql +16 -0
  962. synapse/storage/schema/main/delta/92/06_threads_last_sent_stream_ordering_comments.sql.postgres +24 -0
  963. synapse/storage/schema/main/delta/92/07_add_user_reports.sql +22 -0
  964. synapse/storage/schema/main/delta/92/07_event_txn_id_device_id_txn_id2.sql +15 -0
  965. synapse/storage/schema/main/delta/92/08_room_ban_redactions.sql +21 -0
  966. synapse/storage/schema/main/delta/92/08_thread_subscriptions_seq_fixup.sql.postgres +19 -0
  967. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql +20 -0
  968. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql.postgres +18 -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 +185 -0
  986. synapse/storage/util/__init__.py +20 -0
  987. synapse/storage/util/id_generators.py +909 -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 +92 -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 +909 -0
  1005. synapse/types/rest/__init__.py +25 -0
  1006. synapse/types/rest/client/__init__.py +415 -0
  1007. synapse/types/state.py +635 -0
  1008. synapse/types/storage/__init__.py +66 -0
  1009. synapse/util/__init__.py +170 -0
  1010. synapse/util/async_helpers.py +1067 -0
  1011. synapse/util/batching_queue.py +202 -0
  1012. synapse/util/caches/__init__.py +300 -0
  1013. synapse/util/caches/cached_call.py +143 -0
  1014. synapse/util/caches/deferred_cache.py +530 -0
  1015. synapse/util/caches/descriptors.py +694 -0
  1016. synapse/util/caches/dictionary_cache.py +350 -0
  1017. synapse/util/caches/expiringcache.py +251 -0
  1018. synapse/util/caches/lrucache.py +977 -0
  1019. synapse/util/caches/response_cache.py +323 -0
  1020. synapse/util/caches/stream_change_cache.py +370 -0
  1021. synapse/util/caches/treecache.py +189 -0
  1022. synapse/util/caches/ttlcache.py +197 -0
  1023. synapse/util/cancellation.py +63 -0
  1024. synapse/util/check_dependencies.py +335 -0
  1025. synapse/util/clock.py +500 -0
  1026. synapse/util/constants.py +22 -0
  1027. synapse/util/daemonize.py +165 -0
  1028. synapse/util/distributor.py +159 -0
  1029. synapse/util/events.py +134 -0
  1030. synapse/util/file_consumer.py +164 -0
  1031. synapse/util/frozenutils.py +57 -0
  1032. synapse/util/gai_resolver.py +180 -0
  1033. synapse/util/hash.py +38 -0
  1034. synapse/util/httpresourcetree.py +108 -0
  1035. synapse/util/iterutils.py +189 -0
  1036. synapse/util/json.py +56 -0
  1037. synapse/util/linked_list.py +156 -0
  1038. synapse/util/logcontext.py +46 -0
  1039. synapse/util/logformatter.py +28 -0
  1040. synapse/util/macaroons.py +325 -0
  1041. synapse/util/manhole.py +191 -0
  1042. synapse/util/metrics.py +340 -0
  1043. synapse/util/module_loader.py +116 -0
  1044. synapse/util/msisdn.py +51 -0
  1045. synapse/util/patch_inline_callbacks.py +250 -0
  1046. synapse/util/pydantic_models.py +56 -0
  1047. synapse/util/ratelimitutils.py +420 -0
  1048. synapse/util/retryutils.py +339 -0
  1049. synapse/util/rlimit.py +42 -0
  1050. synapse/util/rust.py +134 -0
  1051. synapse/util/sentinel.py +21 -0
  1052. synapse/util/stringutils.py +293 -0
  1053. synapse/util/task_scheduler.py +493 -0
  1054. synapse/util/templates.py +126 -0
  1055. synapse/util/threepids.py +123 -0
  1056. synapse/util/wheel_timer.py +112 -0
  1057. synapse/visibility.py +836 -0
@@ -0,0 +1,1544 @@
1
+ #
2
+ # This file is licensed under the Affero General Public License (AGPL) version 3.
3
+ #
4
+ # Copyright 2019-2021 Matrix.org Federation C.I.C
5
+ # Copyright 2015, 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
+ import random
24
+ from typing import (
25
+ TYPE_CHECKING,
26
+ Any,
27
+ Awaitable,
28
+ Callable,
29
+ Collection,
30
+ Mapping,
31
+ Optional,
32
+ Union,
33
+ )
34
+
35
+ from prometheus_client import Counter, Gauge, Histogram
36
+
37
+ from twisted.python import failure
38
+
39
+ from synapse.api.constants import (
40
+ Direction,
41
+ EduTypes,
42
+ EventContentFields,
43
+ EventTypes,
44
+ Membership,
45
+ )
46
+ from synapse.api.errors import (
47
+ AuthError,
48
+ Codes,
49
+ FederationError,
50
+ IncompatibleRoomVersionError,
51
+ NotFoundError,
52
+ PartialStateConflictError,
53
+ SynapseError,
54
+ UnsupportedRoomVersionError,
55
+ )
56
+ from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
57
+ from synapse.crypto.event_signing import compute_event_signature
58
+ from synapse.events import EventBase
59
+ from synapse.events.snapshot import EventPersistencePair
60
+ from synapse.federation.federation_base import (
61
+ FederationBase,
62
+ InvalidEventSignatureError,
63
+ event_from_pdu_json,
64
+ )
65
+ from synapse.federation.persistence import TransactionActions
66
+ from synapse.federation.units import Edu, Transaction, serialize_and_filter_pdus
67
+ from synapse.handlers.worker_lock import NEW_EVENT_DURING_PURGE_LOCK_NAME
68
+ from synapse.http.servlet import assert_params_in_dict
69
+ from synapse.logging.context import (
70
+ make_deferred_yieldable,
71
+ nested_logging_context,
72
+ run_in_background,
73
+ )
74
+ from synapse.logging.opentracing import (
75
+ SynapseTags,
76
+ log_kv,
77
+ set_tag,
78
+ start_active_span_from_edu,
79
+ tag_args,
80
+ trace,
81
+ )
82
+ from synapse.metrics import SERVER_NAME_LABEL
83
+ from synapse.metrics.background_process_metrics import wrap_as_background_process
84
+ from synapse.replication.http.federation import (
85
+ ReplicationFederationSendEduRestServlet,
86
+ )
87
+ from synapse.storage.databases.main.lock import Lock
88
+ from synapse.storage.databases.main.roommember import extract_heroes_from_room_summary
89
+ from synapse.storage.roommember import MemberSummary
90
+ from synapse.types import JsonDict, StateMap, UserID, get_domain_from_id
91
+ from synapse.util import unwrapFirstError
92
+ from synapse.util.async_helpers import Linearizer, concurrently_execute, gather_results
93
+ from synapse.util.caches.response_cache import ResponseCache
94
+ from synapse.util.stringutils import parse_server_name
95
+
96
+ if TYPE_CHECKING:
97
+ from synapse.server import HomeServer
98
+
99
+ # when processing incoming transactions, we try to handle multiple rooms in
100
+ # parallel, up to this limit.
101
+ TRANSACTION_CONCURRENCY_LIMIT = 10
102
+
103
+ logger = logging.getLogger(__name__)
104
+
105
+ received_pdus_counter = Counter(
106
+ "synapse_federation_server_received_pdus", "", labelnames=[SERVER_NAME_LABEL]
107
+ )
108
+
109
+ received_edus_counter = Counter(
110
+ "synapse_federation_server_received_edus", "", labelnames=[SERVER_NAME_LABEL]
111
+ )
112
+
113
+ received_queries_counter = Counter(
114
+ "synapse_federation_server_received_queries",
115
+ "",
116
+ labelnames=["type", SERVER_NAME_LABEL],
117
+ )
118
+
119
+ pdu_process_time = Histogram(
120
+ "synapse_federation_server_pdu_process_time",
121
+ "Time taken to process an event",
122
+ labelnames=[SERVER_NAME_LABEL],
123
+ )
124
+
125
+ last_pdu_ts_metric = Gauge(
126
+ "synapse_federation_last_received_pdu_time",
127
+ "The timestamp of the last PDU which was successfully received from the given domain",
128
+ labelnames=("origin_server_name", SERVER_NAME_LABEL),
129
+ )
130
+
131
+
132
+ # The name of the lock to use when process events in a room received over
133
+ # federation.
134
+ _INBOUND_EVENT_HANDLING_LOCK_NAME = "federation_inbound_pdu"
135
+
136
+
137
+ class FederationServer(FederationBase):
138
+ def __init__(self, hs: "HomeServer"):
139
+ super().__init__(hs)
140
+
141
+ self.server_name = hs.hostname
142
+ self.handler = hs.get_federation_handler()
143
+ self._spam_checker_module_callbacks = hs.get_module_api_callbacks().spam_checker
144
+ self._federation_event_handler = hs.get_federation_event_handler()
145
+ self.state = hs.get_state_handler()
146
+ self._event_auth_handler = hs.get_event_auth_handler()
147
+ self._room_member_handler = hs.get_room_member_handler()
148
+ self._e2e_keys_handler = hs.get_e2e_keys_handler()
149
+ self._worker_lock_handler = hs.get_worker_locks_handler()
150
+
151
+ self._state_storage_controller = hs.get_storage_controllers().state
152
+
153
+ self.device_handler = hs.get_device_handler()
154
+
155
+ # Ensure the following handlers are loaded since they register callbacks
156
+ # with FederationHandlerRegistry.
157
+ hs.get_directory_handler()
158
+
159
+ self._server_linearizer = Linearizer(name="fed_server", clock=hs.get_clock())
160
+
161
+ # origins that we are currently processing a transaction from.
162
+ # a dict from origin to txn id.
163
+ self._active_transactions: dict[str, str] = {}
164
+
165
+ # We cache results for transaction with the same ID
166
+ self._transaction_resp_cache: ResponseCache[tuple[str, str]] = ResponseCache(
167
+ clock=hs.get_clock(),
168
+ name="fed_txn_handler",
169
+ server_name=self.server_name,
170
+ timeout_ms=30000,
171
+ )
172
+
173
+ self.transaction_actions = TransactionActions(self.store)
174
+
175
+ self.registry = hs.get_federation_registry()
176
+
177
+ # We cache responses to state queries, as they take a while and often
178
+ # come in waves.
179
+ self._state_resp_cache: ResponseCache[tuple[str, Optional[str]]] = (
180
+ ResponseCache(
181
+ clock=hs.get_clock(),
182
+ name="state_resp",
183
+ server_name=self.server_name,
184
+ timeout_ms=30000,
185
+ )
186
+ )
187
+ self._state_ids_resp_cache: ResponseCache[tuple[str, str]] = ResponseCache(
188
+ clock=hs.get_clock(),
189
+ name="state_ids_resp",
190
+ server_name=self.server_name,
191
+ timeout_ms=30000,
192
+ )
193
+
194
+ self._federation_metrics_domains = (
195
+ hs.config.federation.federation_metrics_domains
196
+ )
197
+
198
+ self._room_prejoin_state_types = hs.config.api.room_prejoin_state
199
+
200
+ # Whether we have started handling old events in the staging area.
201
+ self._started_handling_of_staged_events = False
202
+
203
+ @wrap_as_background_process("_handle_old_staged_events")
204
+ async def _handle_old_staged_events(self) -> None:
205
+ """Handle old staged events by fetching all rooms that have staged
206
+ events and start the processing of each of those rooms.
207
+ """
208
+
209
+ # Get all the rooms IDs with staged events.
210
+ room_ids = await self.store.get_all_rooms_with_staged_incoming_events()
211
+
212
+ # We then shuffle them so that if there are multiple instances doing
213
+ # this work they're less likely to collide.
214
+ random.shuffle(room_ids)
215
+
216
+ for room_id in room_ids:
217
+ room_version = await self.store.get_room_version(room_id)
218
+
219
+ # Try and acquire the processing lock for the room, if we get it start a
220
+ # background process for handling the events in the room.
221
+ lock = await self.store.try_acquire_lock(
222
+ _INBOUND_EVENT_HANDLING_LOCK_NAME, room_id
223
+ )
224
+ if lock:
225
+ logger.info("Handling old staged inbound events in %s", room_id)
226
+ self._process_incoming_pdus_in_room_inner(
227
+ room_id,
228
+ room_version,
229
+ lock,
230
+ )
231
+
232
+ # We pause a bit so that we don't start handling all rooms at once.
233
+ await self._clock.sleep(random.uniform(0, 0.1))
234
+
235
+ async def on_backfill_request(
236
+ self, origin: str, room_id: str, versions: list[str], limit: int
237
+ ) -> tuple[int, dict[str, Any]]:
238
+ async with self._server_linearizer.queue((origin, room_id)):
239
+ origin_host, _ = parse_server_name(origin)
240
+ await self.check_server_matches_acl(origin_host, room_id)
241
+
242
+ pdus = await self.handler.on_backfill_request(
243
+ origin, room_id, versions, limit
244
+ )
245
+
246
+ res = self._transaction_dict_from_pdus(pdus)
247
+
248
+ return 200, res
249
+
250
+ async def on_timestamp_to_event_request(
251
+ self, origin: str, room_id: str, timestamp: int, direction: Direction
252
+ ) -> tuple[int, dict[str, Any]]:
253
+ """When we receive a federated `/timestamp_to_event` request,
254
+ handle all of the logic for validating and fetching the event.
255
+
256
+ Args:
257
+ origin: The server we received the event from
258
+ room_id: Room to fetch the event from
259
+ timestamp: The point in time (inclusive) we should navigate from in
260
+ the given direction to find the closest event.
261
+ direction: indicates whether we should navigate forward
262
+ or backward from the given timestamp to find the closest event.
263
+
264
+ Returns:
265
+ Tuple indicating the response status code and dictionary response
266
+ body including `event_id`.
267
+ """
268
+ async with self._server_linearizer.queue((origin, room_id)):
269
+ origin_host, _ = parse_server_name(origin)
270
+ await self.check_server_matches_acl(origin_host, room_id)
271
+
272
+ # We only try to fetch data from the local database
273
+ event_id = await self.store.get_event_id_for_timestamp(
274
+ room_id, timestamp, direction
275
+ )
276
+ if event_id:
277
+ event = await self.store.get_event(
278
+ event_id, allow_none=False, allow_rejected=False
279
+ )
280
+
281
+ return 200, {
282
+ "event_id": event_id,
283
+ "origin_server_ts": event.origin_server_ts,
284
+ }
285
+
286
+ raise SynapseError(
287
+ 404,
288
+ "Unable to find event from %s in direction %s" % (timestamp, direction),
289
+ errcode=Codes.NOT_FOUND,
290
+ )
291
+
292
+ async def on_incoming_transaction(
293
+ self,
294
+ origin: str,
295
+ transaction_id: str,
296
+ destination: str,
297
+ transaction_data: JsonDict,
298
+ ) -> tuple[int, JsonDict]:
299
+ # If we receive a transaction we should make sure that kick off handling
300
+ # any old events in the staging area.
301
+ if not self._started_handling_of_staged_events:
302
+ self._started_handling_of_staged_events = True
303
+ self._handle_old_staged_events()
304
+
305
+ # Start a periodic check for old staged events. This is to handle
306
+ # the case where locks time out, e.g. if another process gets killed
307
+ # without dropping its locks.
308
+ self._clock.looping_call(self._handle_old_staged_events, 60 * 1000)
309
+
310
+ # keep this as early as possible to make the calculated origin ts as
311
+ # accurate as possible.
312
+ request_time = self._clock.time_msec()
313
+
314
+ transaction = Transaction(
315
+ transaction_id=transaction_id,
316
+ destination=destination,
317
+ origin=origin,
318
+ origin_server_ts=transaction_data.get("origin_server_ts"), # type: ignore[arg-type]
319
+ pdus=transaction_data.get("pdus"),
320
+ edus=transaction_data.get("edus"),
321
+ )
322
+
323
+ if not transaction_id:
324
+ raise Exception("Transaction missing transaction_id")
325
+
326
+ logger.debug("[%s] Got transaction", transaction_id)
327
+
328
+ # Reject malformed transactions early: reject if too many PDUs/EDUs
329
+ if len(transaction.pdus) > 50 or len(transaction.edus) > 100:
330
+ logger.info("Transaction PDU or EDU count too large. Returning 400")
331
+ return 400, {}
332
+
333
+ # we only process one transaction from each origin at a time. We need to do
334
+ # this check here, rather than in _on_incoming_transaction_inner so that we
335
+ # don't cache the rejection in _transaction_resp_cache (so that if the txn
336
+ # arrives again later, we can process it).
337
+ current_transaction = self._active_transactions.get(origin)
338
+ if current_transaction and current_transaction != transaction_id:
339
+ logger.warning(
340
+ "Received another txn %s from %s while still processing %s",
341
+ transaction_id,
342
+ origin,
343
+ current_transaction,
344
+ )
345
+ return 429, {
346
+ "errcode": Codes.UNKNOWN,
347
+ "error": "Too many concurrent transactions",
348
+ }
349
+
350
+ # CRITICAL SECTION: we must now not await until we populate _active_transactions
351
+ # in _on_incoming_transaction_inner.
352
+
353
+ # We wrap in a ResponseCache so that we de-duplicate retried
354
+ # transactions.
355
+ return await self._transaction_resp_cache.wrap(
356
+ (origin, transaction_id),
357
+ self._on_incoming_transaction_inner,
358
+ origin,
359
+ transaction,
360
+ request_time,
361
+ )
362
+
363
+ async def _on_incoming_transaction_inner(
364
+ self, origin: str, transaction: Transaction, request_time: int
365
+ ) -> tuple[int, dict[str, Any]]:
366
+ # CRITICAL SECTION: the first thing we must do (before awaiting) is
367
+ # add an entry to _active_transactions.
368
+ assert origin not in self._active_transactions
369
+ self._active_transactions[origin] = transaction.transaction_id
370
+
371
+ try:
372
+ result = await self._handle_incoming_transaction(
373
+ origin, transaction, request_time
374
+ )
375
+ return result
376
+ finally:
377
+ del self._active_transactions[origin]
378
+
379
+ async def _handle_incoming_transaction(
380
+ self, origin: str, transaction: Transaction, request_time: int
381
+ ) -> tuple[int, dict[str, Any]]:
382
+ """Process an incoming transaction and return the HTTP response
383
+
384
+ Args:
385
+ origin: the server making the request
386
+ transaction: incoming transaction
387
+ request_time: timestamp that the HTTP request arrived at
388
+
389
+ Returns:
390
+ HTTP response code and body
391
+ """
392
+ existing_response = await self.transaction_actions.have_responded(
393
+ origin, transaction
394
+ )
395
+
396
+ if existing_response:
397
+ logger.debug(
398
+ "[%s] We've already responded to this request",
399
+ transaction.transaction_id,
400
+ )
401
+ return existing_response
402
+
403
+ logger.debug("[%s] Transaction is new", transaction.transaction_id)
404
+
405
+ # We process PDUs and EDUs in parallel. This is important as we don't
406
+ # want to block things like to device messages from reaching clients
407
+ # behind the potentially expensive handling of PDUs.
408
+ pdu_results, _ = await make_deferred_yieldable(
409
+ gather_results(
410
+ (
411
+ run_in_background(
412
+ self._handle_pdus_in_txn, origin, transaction, request_time
413
+ ),
414
+ run_in_background(self._handle_edus_in_txn, origin, transaction),
415
+ ),
416
+ consumeErrors=True,
417
+ ).addErrback(unwrapFirstError)
418
+ )
419
+
420
+ response = {"pdus": pdu_results}
421
+
422
+ logger.debug("Returning: %s", str(response))
423
+
424
+ await self.transaction_actions.set_response(origin, transaction, 200, response)
425
+ return 200, response
426
+
427
+ async def _handle_pdus_in_txn(
428
+ self, origin: str, transaction: Transaction, request_time: int
429
+ ) -> dict[str, dict]:
430
+ """Process the PDUs in a received transaction.
431
+
432
+ Args:
433
+ origin: the server making the request
434
+ transaction: incoming transaction
435
+ request_time: timestamp that the HTTP request arrived at
436
+
437
+ Returns:
438
+ A map from event ID of a processed PDU to any errors we should
439
+ report back to the sending server.
440
+ """
441
+
442
+ received_pdus_counter.labels(**{SERVER_NAME_LABEL: self.server_name}).inc(
443
+ len(transaction.pdus)
444
+ )
445
+
446
+ origin_host, _ = parse_server_name(origin)
447
+
448
+ pdus_by_room: dict[str, list[EventBase]] = {}
449
+
450
+ newest_pdu_ts = 0
451
+
452
+ for p in transaction.pdus:
453
+ # FIXME (richardv): I don't think this works:
454
+ # https://github.com/matrix-org/synapse/issues/8429
455
+ if "unsigned" in p:
456
+ unsigned = p["unsigned"]
457
+ if "age" in unsigned:
458
+ p["age"] = unsigned["age"]
459
+ if "age" in p:
460
+ p["age_ts"] = request_time - int(p["age"])
461
+ del p["age"]
462
+
463
+ # We try and pull out an event ID so that if later checks fail we
464
+ # can log something sensible. We don't mandate an event ID here in
465
+ # case future event formats get rid of the key.
466
+ possible_event_id = p.get("event_id", "<Unknown>")
467
+
468
+ # Now we get the room ID so that we can check that we know the
469
+ # version of the room.
470
+ room_id = p.get("room_id")
471
+ if not room_id:
472
+ logger.info(
473
+ "Ignoring PDU as does not have a room_id. Event ID: %s",
474
+ possible_event_id,
475
+ )
476
+ continue
477
+
478
+ try:
479
+ room_version = await self.store.get_room_version(room_id)
480
+ except NotFoundError:
481
+ logger.info("Ignoring PDU for unknown room_id: %s", room_id)
482
+ continue
483
+ except UnsupportedRoomVersionError as e:
484
+ # this can happen if support for a given room version is withdrawn,
485
+ # so that we still get events for said room.
486
+ logger.info("Ignoring PDU: %s", e)
487
+ continue
488
+
489
+ try:
490
+ event = event_from_pdu_json(p, room_version)
491
+ except SynapseError as e:
492
+ logger.info("Ignoring PDU for failing to deserialize: %s", e)
493
+ continue
494
+
495
+ pdus_by_room.setdefault(room_id, []).append(event)
496
+
497
+ if event.origin_server_ts > newest_pdu_ts:
498
+ newest_pdu_ts = event.origin_server_ts
499
+
500
+ pdu_results = {}
501
+
502
+ # we can process different rooms in parallel (which is useful if they
503
+ # require callouts to other servers to fetch missing events), but
504
+ # impose a limit to avoid going too crazy with ram/cpu.
505
+
506
+ async def process_pdus_for_room(room_id: str) -> None:
507
+ with nested_logging_context(room_id):
508
+ logger.debug("Processing PDUs for %s", room_id)
509
+
510
+ try:
511
+ await self.check_server_matches_acl(origin_host, room_id)
512
+ except AuthError as e:
513
+ logger.warning(
514
+ "Ignoring PDUs for room %s from banned server", room_id
515
+ )
516
+ for pdu in pdus_by_room[room_id]:
517
+ event_id = pdu.event_id
518
+ pdu_results[event_id] = e.error_dict(self.hs.config)
519
+ return
520
+
521
+ for pdu in pdus_by_room[room_id]:
522
+ pdu_results[pdu.event_id] = await process_pdu(pdu)
523
+
524
+ async def process_pdu(pdu: EventBase) -> JsonDict:
525
+ """
526
+ Processes a pushed PDU sent to us via a `/send` transaction
527
+
528
+ Returns:
529
+ JsonDict representing a "PDU Processing Result" that will be bundled up
530
+ with the other processed PDU's in the `/send` transaction and sent back
531
+ to remote homeserver.
532
+ """
533
+ event_id = pdu.event_id
534
+ with nested_logging_context(event_id):
535
+ try:
536
+ await self._handle_received_pdu(origin, pdu)
537
+ return {}
538
+ except FederationError as e:
539
+ logger.warning("Error handling PDU %s: %s", event_id, e)
540
+ return {"error": str(e)}
541
+ except Exception as e:
542
+ f = failure.Failure()
543
+ logger.error(
544
+ "Failed to handle PDU %s",
545
+ event_id,
546
+ exc_info=(f.type, f.value, f.getTracebackObject()),
547
+ )
548
+ return {"error": str(e)}
549
+
550
+ await concurrently_execute(
551
+ process_pdus_for_room, pdus_by_room.keys(), TRANSACTION_CONCURRENCY_LIMIT
552
+ )
553
+
554
+ if newest_pdu_ts and origin in self._federation_metrics_domains:
555
+ last_pdu_ts_metric.labels(
556
+ origin_server_name=origin, **{SERVER_NAME_LABEL: self.server_name}
557
+ ).set(newest_pdu_ts / 1000)
558
+
559
+ return pdu_results
560
+
561
+ async def _handle_edus_in_txn(self, origin: str, transaction: Transaction) -> None:
562
+ """Process the EDUs in a received transaction."""
563
+
564
+ async def _process_edu(edu_dict: JsonDict) -> None:
565
+ received_edus_counter.labels(**{SERVER_NAME_LABEL: self.server_name}).inc()
566
+
567
+ edu = Edu(
568
+ origin=origin,
569
+ destination=self.server_name,
570
+ edu_type=edu_dict["edu_type"],
571
+ content=edu_dict["content"],
572
+ )
573
+ try:
574
+ await self.registry.on_edu(edu.edu_type, origin, edu.content)
575
+ except Exception:
576
+ # If there was an error handling the EDU, we must reject the
577
+ # transaction.
578
+ #
579
+ # Some EDU types (notably, to-device messages) are, despite their name,
580
+ # expected to be reliable; if we weren't able to do something with it,
581
+ # we have to tell the sender that, and the only way the protocol gives
582
+ # us to do so is by sending an HTTP error back on the transaction.
583
+ #
584
+ # We log the exception now, and then raise a new SynapseError to cause
585
+ # the transaction to be failed.
586
+ logger.exception("Error handling EDU of type %s", edu.edu_type)
587
+ raise SynapseError(500, f"Error handing EDU of type {edu.edu_type}")
588
+
589
+ # TODO: if the first EDU fails, we should probably abort the whole
590
+ # thing rather than carrying on with the rest of them. That would
591
+ # probably be best done inside `concurrently_execute`.
592
+
593
+ await concurrently_execute(
594
+ _process_edu,
595
+ transaction.edus,
596
+ TRANSACTION_CONCURRENCY_LIMIT,
597
+ )
598
+
599
+ async def on_room_state_request(
600
+ self, origin: str, room_id: str, event_id: str
601
+ ) -> tuple[int, JsonDict]:
602
+ await self._event_auth_handler.assert_host_in_room(room_id, origin)
603
+ origin_host, _ = parse_server_name(origin)
604
+ await self.check_server_matches_acl(origin_host, room_id)
605
+
606
+ # we grab the linearizer to protect ourselves from servers which hammer
607
+ # us. In theory we might already have the response to this query
608
+ # in the cache so we could return it without waiting for the linearizer
609
+ # - but that's non-trivial to get right, and anyway somewhat defeats
610
+ # the point of the linearizer.
611
+ async with self._server_linearizer.queue((origin, room_id)):
612
+ resp = await self._state_resp_cache.wrap(
613
+ (room_id, event_id),
614
+ self._on_context_state_request_compute,
615
+ room_id,
616
+ event_id,
617
+ )
618
+
619
+ return 200, resp
620
+
621
+ @trace
622
+ @tag_args
623
+ async def on_state_ids_request(
624
+ self, origin: str, room_id: str, event_id: str
625
+ ) -> tuple[int, JsonDict]:
626
+ if not event_id:
627
+ raise NotImplementedError("Specify an event")
628
+
629
+ await self._event_auth_handler.assert_host_in_room(room_id, origin)
630
+ origin_host, _ = parse_server_name(origin)
631
+ await self.check_server_matches_acl(origin_host, room_id)
632
+
633
+ resp = await self._state_ids_resp_cache.wrap(
634
+ (room_id, event_id),
635
+ self._on_state_ids_request_compute,
636
+ room_id,
637
+ event_id,
638
+ )
639
+
640
+ return 200, resp
641
+
642
+ @trace
643
+ @tag_args
644
+ async def _on_state_ids_request_compute(
645
+ self, room_id: str, event_id: str
646
+ ) -> JsonDict:
647
+ state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
648
+ auth_chain_ids = await self.store.get_auth_chain_ids(room_id, state_ids)
649
+ return {"pdu_ids": state_ids, "auth_chain_ids": list(auth_chain_ids)}
650
+
651
+ async def _on_context_state_request_compute(
652
+ self, room_id: str, event_id: str
653
+ ) -> dict[str, list]:
654
+ pdus: Collection[EventBase]
655
+ event_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
656
+ pdus = await self.store.get_events_as_list(event_ids)
657
+
658
+ auth_chain = await self.store.get_auth_chain(
659
+ room_id, [pdu.event_id for pdu in pdus]
660
+ )
661
+
662
+ return {
663
+ "pdus": serialize_and_filter_pdus(pdus),
664
+ "auth_chain": serialize_and_filter_pdus(auth_chain),
665
+ }
666
+
667
+ async def on_pdu_request(
668
+ self, origin: str, event_id: str
669
+ ) -> tuple[int, Union[JsonDict, str]]:
670
+ pdu = await self.handler.get_persisted_pdu(origin, event_id)
671
+
672
+ if pdu:
673
+ return 200, self._transaction_dict_from_pdus([pdu])
674
+ else:
675
+ return 404, ""
676
+
677
+ async def on_query_request(
678
+ self, query_type: str, args: dict[str, str]
679
+ ) -> tuple[int, dict[str, Any]]:
680
+ received_queries_counter.labels(
681
+ type=query_type,
682
+ **{SERVER_NAME_LABEL: self.server_name},
683
+ ).inc()
684
+ resp = await self.registry.on_query(query_type, args)
685
+ return 200, resp
686
+
687
+ async def on_make_join_request(
688
+ self, origin: str, room_id: str, user_id: str, supported_versions: list[str]
689
+ ) -> dict[str, Any]:
690
+ origin_host, _ = parse_server_name(origin)
691
+ await self.check_server_matches_acl(origin_host, room_id)
692
+
693
+ room_version = await self.store.get_room_version_id(room_id)
694
+ if room_version not in supported_versions:
695
+ logger.warning(
696
+ "Room version %s not in %s", room_version, supported_versions
697
+ )
698
+ raise IncompatibleRoomVersionError(room_version=room_version)
699
+
700
+ # Refuse the request if that room has seen too many joins recently.
701
+ # This is in addition to the HS-level rate limiting applied by
702
+ # BaseFederationServlet.
703
+ # type-ignore: mypy doesn't seem able to deduce the type of the limiter(!?)
704
+ await self._room_member_handler._join_rate_per_room_limiter.ratelimit(
705
+ requester=None,
706
+ key=room_id,
707
+ update=False,
708
+ )
709
+ pdu = await self.handler.on_make_join_request(origin, room_id, user_id)
710
+ return {"event": pdu.get_templated_pdu_json(), "room_version": room_version}
711
+
712
+ async def on_invite_request(
713
+ self, origin: str, content: JsonDict, room_version_id: str
714
+ ) -> dict[str, Any]:
715
+ room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
716
+ if not room_version:
717
+ raise SynapseError(
718
+ 400,
719
+ "Homeserver does not support this room version",
720
+ Codes.UNSUPPORTED_ROOM_VERSION,
721
+ )
722
+
723
+ pdu = event_from_pdu_json(content, room_version)
724
+ origin_host, _ = parse_server_name(origin)
725
+ await self.check_server_matches_acl(origin_host, pdu.room_id)
726
+ if await self._spam_checker_module_callbacks.should_drop_federated_event(pdu):
727
+ logger.info(
728
+ "Federated event contains spam, dropping %s",
729
+ pdu.event_id,
730
+ )
731
+ raise SynapseError(403, Codes.FORBIDDEN)
732
+ try:
733
+ pdu = await self._check_sigs_and_hash(room_version, pdu)
734
+ except InvalidEventSignatureError as e:
735
+ errmsg = f"event id {pdu.event_id}: {e}"
736
+ logger.warning("%s", errmsg)
737
+ raise SynapseError(403, errmsg, Codes.FORBIDDEN)
738
+ ret_pdu = await self.handler.on_invite_request(origin, pdu, room_version)
739
+ time_now = self._clock.time_msec()
740
+ return {"event": ret_pdu.get_pdu_json(time_now)}
741
+
742
+ async def on_send_join_request(
743
+ self,
744
+ origin: str,
745
+ content: JsonDict,
746
+ room_id: str,
747
+ caller_supports_partial_state: bool = False,
748
+ ) -> dict[str, Any]:
749
+ set_tag(
750
+ SynapseTags.SEND_JOIN_RESPONSE_IS_PARTIAL_STATE,
751
+ caller_supports_partial_state,
752
+ )
753
+ await self._room_member_handler._join_rate_per_room_limiter.ratelimit(
754
+ requester=None,
755
+ key=room_id,
756
+ update=False,
757
+ )
758
+
759
+ event, context = await self._on_send_membership_event(
760
+ origin, content, Membership.JOIN, room_id
761
+ )
762
+
763
+ prev_state_ids = await context.get_prev_state_ids()
764
+
765
+ state_event_ids: Collection[str]
766
+ servers_in_room: Optional[Collection[str]]
767
+ if caller_supports_partial_state:
768
+ summary = await self.store.get_room_summary(room_id)
769
+ state_event_ids = _get_event_ids_for_partial_state_join(
770
+ event, prev_state_ids, summary
771
+ )
772
+ servers_in_room = await self.state.get_hosts_in_room_at_events(
773
+ room_id, event_ids=event.prev_event_ids()
774
+ )
775
+ else:
776
+ state_event_ids = prev_state_ids.values()
777
+ servers_in_room = None
778
+
779
+ auth_chain_event_ids = await self.store.get_auth_chain_ids(
780
+ room_id, state_event_ids
781
+ )
782
+
783
+ # if the caller has opted in, we can omit any auth_chain events which are
784
+ # already in state_event_ids
785
+ if caller_supports_partial_state:
786
+ auth_chain_event_ids.difference_update(state_event_ids)
787
+
788
+ auth_chain_events = await self.store.get_events_as_list(auth_chain_event_ids)
789
+ state_events = await self.store.get_events_as_list(state_event_ids)
790
+
791
+ # we try to do all the async stuff before this point, so that time_now is as
792
+ # accurate as possible.
793
+ time_now = self._clock.time_msec()
794
+ event_json = event.get_pdu_json(time_now)
795
+ resp = {
796
+ "event": event_json,
797
+ "state": serialize_and_filter_pdus(state_events, time_now),
798
+ "auth_chain": serialize_and_filter_pdus(auth_chain_events, time_now),
799
+ "members_omitted": caller_supports_partial_state,
800
+ }
801
+
802
+ if servers_in_room is not None:
803
+ resp["servers_in_room"] = list(servers_in_room)
804
+
805
+ return resp
806
+
807
+ async def on_make_leave_request(
808
+ self, origin: str, room_id: str, user_id: str
809
+ ) -> dict[str, Any]:
810
+ origin_host, _ = parse_server_name(origin)
811
+ await self.check_server_matches_acl(origin_host, room_id)
812
+ pdu = await self.handler.on_make_leave_request(origin, room_id, user_id)
813
+
814
+ room_version = await self.store.get_room_version_id(room_id)
815
+
816
+ return {"event": pdu.get_templated_pdu_json(), "room_version": room_version}
817
+
818
+ async def on_send_leave_request(
819
+ self, origin: str, content: JsonDict, room_id: str
820
+ ) -> dict:
821
+ logger.debug("on_send_leave_request: content: %s", content)
822
+ await self._on_send_membership_event(origin, content, Membership.LEAVE, room_id)
823
+ return {}
824
+
825
+ async def on_make_knock_request(
826
+ self, origin: str, room_id: str, user_id: str, supported_versions: list[str]
827
+ ) -> JsonDict:
828
+ """We've received a /make_knock/ request, so we create a partial knock
829
+ event for the room and hand that back, along with the room version, to the knocking
830
+ homeserver. We do *not* persist or process this event until the other server has
831
+ signed it and sent it back.
832
+
833
+ Args:
834
+ origin: The (verified) server name of the requesting server.
835
+ room_id: The room to create the knock event in.
836
+ user_id: The user to create the knock for.
837
+ supported_versions: The room versions supported by the requesting server.
838
+
839
+ Returns:
840
+ The partial knock event.
841
+ """
842
+ origin_host, _ = parse_server_name(origin)
843
+
844
+ if await self.store.is_partial_state_room(room_id):
845
+ # Before we do anything: check if the room is partial-stated.
846
+ # Note that at the time this check was added, `on_make_knock_request` would
847
+ # block due to https://github.com/matrix-org/synapse/issues/12997.
848
+ raise SynapseError(
849
+ 404,
850
+ "Unable to handle /make_knock right now; this server is not fully joined.",
851
+ errcode=Codes.NOT_FOUND,
852
+ )
853
+
854
+ await self.check_server_matches_acl(origin_host, room_id)
855
+
856
+ room_version = await self.store.get_room_version(room_id)
857
+
858
+ # Check that this room version is supported by the remote homeserver
859
+ if room_version.identifier not in supported_versions:
860
+ logger.warning(
861
+ "Room version %s not in %s", room_version.identifier, supported_versions
862
+ )
863
+ raise IncompatibleRoomVersionError(room_version=room_version.identifier)
864
+
865
+ # Check that this room supports knocking as defined by its room version
866
+ if not room_version.knock_join_rule:
867
+ raise SynapseError(
868
+ 403,
869
+ "This room version does not support knocking",
870
+ errcode=Codes.FORBIDDEN,
871
+ )
872
+
873
+ pdu = await self.handler.on_make_knock_request(origin, room_id, user_id)
874
+ return {
875
+ "event": pdu.get_templated_pdu_json(),
876
+ "room_version": room_version.identifier,
877
+ }
878
+
879
+ async def on_send_knock_request(
880
+ self,
881
+ origin: str,
882
+ content: JsonDict,
883
+ room_id: str,
884
+ ) -> dict[str, list[JsonDict]]:
885
+ """
886
+ We have received a knock event for a room. Verify and send the event into the room
887
+ on the knocking homeserver's behalf. Then reply with some stripped state from the
888
+ room for the knockee.
889
+
890
+ Args:
891
+ origin: The remote homeserver of the knocking user.
892
+ content: The content of the request.
893
+ room_id: The ID of the room to knock on.
894
+
895
+ Returns:
896
+ The stripped room state.
897
+ """
898
+ _, context = await self._on_send_membership_event(
899
+ origin, content, Membership.KNOCK, room_id
900
+ )
901
+
902
+ # Retrieve stripped state events from the room and send them back to the remote
903
+ # server. This will allow the remote server's clients to display information
904
+ # related to the room while the knock request is pending.
905
+ stripped_room_state = (
906
+ await self.store.get_stripped_room_state_from_event_context(
907
+ context, self._room_prejoin_state_types
908
+ )
909
+ )
910
+ return {"knock_room_state": stripped_room_state}
911
+
912
+ async def _on_send_membership_event(
913
+ self, origin: str, content: JsonDict, membership_type: str, room_id: str
914
+ ) -> EventPersistencePair:
915
+ """Handle an on_send_{join,leave,knock} request
916
+
917
+ Does some preliminary validation before passing the request on to the
918
+ federation handler.
919
+
920
+ Args:
921
+ origin: The (authenticated) requesting server
922
+ content: The body of the send_* request - a complete membership event
923
+ membership_type: The expected membership type (join or leave, depending
924
+ on the endpoint)
925
+ room_id: The room_id from the request, to be validated against the room_id
926
+ in the event
927
+
928
+ Returns:
929
+ The event and context of the event after inserting it into the room graph.
930
+
931
+ Raises:
932
+ SynapseError if there is a problem with the request, including things like
933
+ the room_id not matching or the event not being authorized.
934
+ """
935
+ assert_params_in_dict(content, ["room_id"])
936
+ if content["room_id"] != room_id:
937
+ raise SynapseError(
938
+ 400,
939
+ "Room ID in body does not match that in request path",
940
+ Codes.BAD_JSON,
941
+ )
942
+
943
+ # Note that get_room_version throws if the room does not exist here.
944
+ room_version = await self.store.get_room_version(room_id)
945
+
946
+ if await self.store.is_partial_state_room(room_id):
947
+ # If our server is still only partially joined, we can't give a complete
948
+ # response to /send_join, /send_knock or /send_leave.
949
+ # This is because we will not be able to provide the server list (for partial
950
+ # joins) or the full state (for full joins).
951
+ # Return a 404 as we would if we weren't in the room at all.
952
+ logger.info(
953
+ "Rejecting /send_%s to %s because it's a partial state room",
954
+ membership_type,
955
+ room_id,
956
+ )
957
+ raise SynapseError(
958
+ 404,
959
+ f"Unable to handle /send_{membership_type} right now; this server is not fully joined.",
960
+ errcode=Codes.NOT_FOUND,
961
+ )
962
+
963
+ if membership_type == Membership.KNOCK and not room_version.knock_join_rule:
964
+ raise SynapseError(
965
+ 403,
966
+ "This room version does not support knocking",
967
+ errcode=Codes.FORBIDDEN,
968
+ )
969
+
970
+ event = event_from_pdu_json(content, room_version)
971
+
972
+ if event.type != EventTypes.Member or not event.is_state():
973
+ raise SynapseError(400, "Not an m.room.member event", Codes.BAD_JSON)
974
+
975
+ if event.content.get("membership") != membership_type:
976
+ raise SynapseError(400, "Not a %s event" % membership_type, Codes.BAD_JSON)
977
+
978
+ origin_host, _ = parse_server_name(origin)
979
+ await self.check_server_matches_acl(origin_host, event.room_id)
980
+
981
+ logger.debug("_on_send_membership_event: pdu sigs: %s", event.signatures)
982
+
983
+ # Sign the event since we're vouching on behalf of the remote server that
984
+ # the event is valid to be sent into the room. Currently this is only done
985
+ # if the user is being joined via restricted join rules.
986
+ if (
987
+ room_version.restricted_join_rule
988
+ and event.membership == Membership.JOIN
989
+ and EventContentFields.AUTHORISING_USER in event.content
990
+ ):
991
+ # We can only authorise our own users.
992
+ authorising_server = get_domain_from_id(
993
+ event.content[EventContentFields.AUTHORISING_USER]
994
+ )
995
+ if not self._is_mine_server_name(authorising_server):
996
+ raise SynapseError(
997
+ 400,
998
+ f"Cannot authorise membership event for {authorising_server}. We can only authorise requests from our own homeserver",
999
+ )
1000
+
1001
+ event.signatures.update(
1002
+ compute_event_signature(
1003
+ room_version,
1004
+ event.get_pdu_json(),
1005
+ self.hs.hostname,
1006
+ self.hs.signing_key,
1007
+ )
1008
+ )
1009
+
1010
+ try:
1011
+ event = await self._check_sigs_and_hash(room_version, event)
1012
+ except InvalidEventSignatureError as e:
1013
+ errmsg = f"event id {event.event_id}: {e}"
1014
+ logger.warning("%s", errmsg)
1015
+ raise SynapseError(403, errmsg, Codes.FORBIDDEN)
1016
+
1017
+ try:
1018
+ return await self._federation_event_handler.on_send_membership_event(
1019
+ origin, event
1020
+ )
1021
+ except PartialStateConflictError:
1022
+ # The room was un-partial stated while we were persisting the event.
1023
+ # Try once more, with full state this time.
1024
+ logger.info(
1025
+ "Room %s was un-partial stated during `on_send_membership_event`, trying again.",
1026
+ room_id,
1027
+ )
1028
+ return await self._federation_event_handler.on_send_membership_event(
1029
+ origin, event
1030
+ )
1031
+
1032
+ async def on_event_auth(
1033
+ self, origin: str, room_id: str, event_id: str
1034
+ ) -> tuple[int, dict[str, Any]]:
1035
+ async with self._server_linearizer.queue((origin, room_id)):
1036
+ await self._event_auth_handler.assert_host_in_room(room_id, origin)
1037
+ origin_host, _ = parse_server_name(origin)
1038
+ await self.check_server_matches_acl(origin_host, room_id)
1039
+
1040
+ time_now = self._clock.time_msec()
1041
+ auth_pdus = await self.handler.on_event_auth(event_id)
1042
+ res = {"auth_chain": serialize_and_filter_pdus(auth_pdus, time_now)}
1043
+ return 200, res
1044
+
1045
+ async def on_query_client_keys(
1046
+ self, origin: str, content: dict[str, str]
1047
+ ) -> tuple[int, dict[str, Any]]:
1048
+ return await self.on_query_request("client_keys", content)
1049
+
1050
+ async def on_query_user_devices(
1051
+ self, origin: str, user_id: str
1052
+ ) -> tuple[int, dict[str, Any]]:
1053
+ keys = await self.device_handler.on_federation_query_user_devices(user_id)
1054
+ return 200, keys
1055
+
1056
+ @trace
1057
+ async def on_claim_client_keys(
1058
+ self, query: list[tuple[str, str, str, int]], always_include_fallback_keys: bool
1059
+ ) -> dict[str, Any]:
1060
+ if any(
1061
+ not self.hs.is_mine(UserID.from_string(user_id))
1062
+ for user_id, _, _, _ in query
1063
+ ):
1064
+ raise SynapseError(400, "User is not hosted on this homeserver")
1065
+
1066
+ log_kv({"message": "Claiming one time keys.", "user, device pairs": query})
1067
+ results = await self._e2e_keys_handler.claim_local_one_time_keys(
1068
+ query, always_include_fallback_keys=always_include_fallback_keys
1069
+ )
1070
+
1071
+ json_result: dict[str, dict[str, dict[str, JsonDict]]] = {}
1072
+ for result in results:
1073
+ for user_id, device_keys in result.items():
1074
+ for device_id, keys in device_keys.items():
1075
+ for key_id, key in keys.items():
1076
+ json_result.setdefault(user_id, {}).setdefault(device_id, {})[
1077
+ key_id
1078
+ ] = key
1079
+
1080
+ logger.info(
1081
+ "Claimed one-time-keys: %s",
1082
+ ",".join(
1083
+ (
1084
+ "%s for %s:%s" % (key_id, user_id, device_id)
1085
+ for user_id, user_keys in json_result.items()
1086
+ for device_id, device_keys in user_keys.items()
1087
+ for key_id, _ in device_keys.items()
1088
+ )
1089
+ ),
1090
+ )
1091
+
1092
+ return {"one_time_keys": json_result}
1093
+
1094
+ async def on_get_missing_events(
1095
+ self,
1096
+ origin: str,
1097
+ room_id: str,
1098
+ earliest_events: list[str],
1099
+ latest_events: list[str],
1100
+ limit: int,
1101
+ ) -> dict[str, list]:
1102
+ async with self._server_linearizer.queue((origin, room_id)):
1103
+ origin_host, _ = parse_server_name(origin)
1104
+ await self.check_server_matches_acl(origin_host, room_id)
1105
+
1106
+ logger.debug(
1107
+ "on_get_missing_events: earliest_events: %r, latest_events: %r,"
1108
+ " limit: %d",
1109
+ earliest_events,
1110
+ latest_events,
1111
+ limit,
1112
+ )
1113
+
1114
+ missing_events = await self.handler.on_get_missing_events(
1115
+ origin, room_id, earliest_events, latest_events, limit
1116
+ )
1117
+
1118
+ if len(missing_events) < 5:
1119
+ logger.debug(
1120
+ "Returning %d events: %r", len(missing_events), missing_events
1121
+ )
1122
+ else:
1123
+ logger.debug("Returning %d events", len(missing_events))
1124
+
1125
+ time_now = self._clock.time_msec()
1126
+
1127
+ return {"events": serialize_and_filter_pdus(missing_events, time_now)}
1128
+
1129
+ async def on_openid_userinfo(self, token: str) -> Optional[str]:
1130
+ ts_now_ms = self._clock.time_msec()
1131
+ return await self.store.get_user_id_for_open_id_token(token, ts_now_ms)
1132
+
1133
+ def _transaction_dict_from_pdus(self, pdu_list: list[EventBase]) -> JsonDict:
1134
+ """Returns a new Transaction containing the given PDUs suitable for
1135
+ transmission.
1136
+ """
1137
+ time_now = self._clock.time_msec()
1138
+ pdus = [p.get_pdu_json(time_now) for p in pdu_list]
1139
+ return Transaction(
1140
+ # Just need a dummy transaction ID and destination since it won't be used.
1141
+ transaction_id="",
1142
+ origin=self.server_name,
1143
+ pdus=pdus,
1144
+ origin_server_ts=int(time_now),
1145
+ destination="",
1146
+ ).get_dict()
1147
+
1148
+ async def _handle_received_pdu(self, origin: str, pdu: EventBase) -> None:
1149
+ """Process a PDU received in a federation /send/ transaction.
1150
+
1151
+ If the event is invalid, then this method throws a FederationError.
1152
+ (The error will then be logged and sent back to the sender (which
1153
+ probably won't do anything with it), and other events in the
1154
+ transaction will be processed as normal).
1155
+
1156
+ It is likely that we'll then receive other events which refer to
1157
+ this rejected_event in their prev_events, etc. When that happens,
1158
+ we'll attempt to fetch the rejected event again, which will presumably
1159
+ fail, so those second-generation events will also get rejected.
1160
+
1161
+ Eventually, we get to the point where there are more than 10 events
1162
+ between any new events and the original rejected event. Since we
1163
+ only try to backfill 10 events deep on received pdu, we then accept the
1164
+ new event, possibly introducing a discontinuity in the DAG, with new
1165
+ forward extremities, so normal service is approximately returned,
1166
+ until we try to backfill across the discontinuity.
1167
+
1168
+ Args:
1169
+ origin: server which sent the pdu
1170
+ pdu: received pdu
1171
+
1172
+ Raises: FederationError if the signatures / hash do not match, or
1173
+ if the event was unacceptable for any other reason (eg, too large,
1174
+ too many prev_events, couldn't find the prev_events)
1175
+ """
1176
+
1177
+ # We've already checked that we know the room version by this point
1178
+ room_version = await self.store.get_room_version(pdu.room_id)
1179
+
1180
+ # Check signature.
1181
+ try:
1182
+ pdu = await self._check_sigs_and_hash(room_version, pdu)
1183
+ except InvalidEventSignatureError as e:
1184
+ logger.warning("event id %s: %s", pdu.event_id, e)
1185
+ raise FederationError("ERROR", 403, str(e), affected=pdu.event_id)
1186
+
1187
+ if await self._spam_checker_module_callbacks.should_drop_federated_event(pdu):
1188
+ logger.warning(
1189
+ "Unstaged federated event contains spam, dropping %s", pdu.event_id
1190
+ )
1191
+ return
1192
+
1193
+ # Add the event to our staging area
1194
+ await self.store.insert_received_event_to_staging(origin, pdu)
1195
+
1196
+ # Try and acquire the processing lock for the room, if we get it start a
1197
+ # background process for handling the events in the room.
1198
+ lock = await self.store.try_acquire_lock(
1199
+ _INBOUND_EVENT_HANDLING_LOCK_NAME, pdu.room_id
1200
+ )
1201
+ if lock:
1202
+ self._process_incoming_pdus_in_room_inner(
1203
+ pdu.room_id, room_version, lock, origin, pdu
1204
+ )
1205
+
1206
+ async def _get_next_nonspam_staged_event_for_room(
1207
+ self, room_id: str, room_version: RoomVersion
1208
+ ) -> Optional[tuple[str, EventBase]]:
1209
+ """Fetch the first non-spam event from staging queue.
1210
+
1211
+ Args:
1212
+ room_id: the room to fetch the first non-spam event in.
1213
+ room_version: the version of the room.
1214
+
1215
+ Returns:
1216
+ The first non-spam event in that room.
1217
+ """
1218
+
1219
+ while True:
1220
+ # We need to do this check outside the lock to avoid a race between
1221
+ # a new event being inserted by another instance and it attempting
1222
+ # to acquire the lock.
1223
+ next = await self.store.get_next_staged_event_for_room(
1224
+ room_id, room_version
1225
+ )
1226
+
1227
+ if next is None:
1228
+ return None
1229
+
1230
+ origin, event = next
1231
+
1232
+ if await self._spam_checker_module_callbacks.should_drop_federated_event(
1233
+ event
1234
+ ):
1235
+ logger.warning(
1236
+ "Staged federated event contains spam, dropping %s",
1237
+ event.event_id,
1238
+ )
1239
+ continue
1240
+
1241
+ return next
1242
+
1243
+ @wrap_as_background_process("_process_incoming_pdus_in_room_inner")
1244
+ async def _process_incoming_pdus_in_room_inner(
1245
+ self,
1246
+ room_id: str,
1247
+ room_version: RoomVersion,
1248
+ lock: Lock,
1249
+ latest_origin: Optional[str] = None,
1250
+ latest_event: Optional[EventBase] = None,
1251
+ ) -> None:
1252
+ """Process events in the staging area for the given room.
1253
+
1254
+ The latest_origin and latest_event args are the latest origin and event
1255
+ received (or None to simply pull the next event from the database).
1256
+ """
1257
+
1258
+ # The common path is for the event we just received be the only event in
1259
+ # the room, so instead of pulling the event out of the DB and parsing
1260
+ # the event we just pull out the next event ID and check if that matches.
1261
+ if latest_event is not None and latest_origin is not None:
1262
+ result = await self.store.get_next_staged_event_id_for_room(room_id)
1263
+ if result is None:
1264
+ latest_origin = None
1265
+ latest_event = None
1266
+ else:
1267
+ next_origin, next_event_id = result
1268
+ if (
1269
+ next_origin != latest_origin
1270
+ or next_event_id != latest_event.event_id
1271
+ ):
1272
+ latest_origin = None
1273
+ latest_event = None
1274
+
1275
+ if latest_origin is None or latest_event is None:
1276
+ next = await self.store.get_next_staged_event_for_room(
1277
+ room_id, room_version
1278
+ )
1279
+ if not next:
1280
+ await lock.release()
1281
+ return
1282
+
1283
+ origin, event = next
1284
+ else:
1285
+ origin = latest_origin
1286
+ event = latest_event
1287
+
1288
+ # We loop round until there are no more events in the room in the
1289
+ # staging area, or we fail to get the lock (which means another process
1290
+ # has started processing).
1291
+ while True:
1292
+ async with lock:
1293
+ logger.info("handling received PDU in room %s: %s", room_id, event)
1294
+ try:
1295
+ with nested_logging_context(event.event_id):
1296
+ # We're taking out a lock within a lock, which could
1297
+ # lead to deadlocks if we're not careful. However, it is
1298
+ # safe on this occasion as we only ever take a write
1299
+ # lock when deleting a room, which we would never do
1300
+ # while holding the `_INBOUND_EVENT_HANDLING_LOCK_NAME`
1301
+ # lock.
1302
+ async with self._worker_lock_handler.acquire_read_write_lock(
1303
+ NEW_EVENT_DURING_PURGE_LOCK_NAME, room_id, write=False
1304
+ ):
1305
+ await self._federation_event_handler.on_receive_pdu(
1306
+ origin, event
1307
+ )
1308
+ except FederationError as e:
1309
+ # XXX: Ideally we'd inform the remote we failed to process
1310
+ # the event, but we can't return an error in the transaction
1311
+ # response (as we've already responded).
1312
+ logger.warning("Error handling PDU %s: %s", event.event_id, e)
1313
+ except Exception:
1314
+ f = failure.Failure()
1315
+ logger.error(
1316
+ "Failed to handle PDU %s",
1317
+ event.event_id,
1318
+ exc_info=(f.type, f.value, f.getTracebackObject()),
1319
+ )
1320
+
1321
+ received_ts = await self.store.remove_received_event_from_staging(
1322
+ origin, event.event_id
1323
+ )
1324
+ if received_ts is not None:
1325
+ pdu_process_time.labels(
1326
+ **{SERVER_NAME_LABEL: self.server_name}
1327
+ ).observe((self._clock.time_msec() - received_ts) / 1000)
1328
+
1329
+ next = await self._get_next_nonspam_staged_event_for_room(
1330
+ room_id, room_version
1331
+ )
1332
+
1333
+ if not next:
1334
+ break
1335
+
1336
+ origin, event = next
1337
+
1338
+ # Prune the event queue if it's getting large.
1339
+ #
1340
+ # We do this *after* handling the first event as the common case is
1341
+ # that the queue is empty (/has the single event in), and so there's
1342
+ # no need to do this check.
1343
+ pruned = await self.store.prune_staged_events_in_room(room_id, room_version)
1344
+ if pruned:
1345
+ # If we have pruned the queue check we need to refetch the next
1346
+ # event to handle.
1347
+ next = await self.store.get_next_staged_event_for_room(
1348
+ room_id, room_version
1349
+ )
1350
+ if not next:
1351
+ break
1352
+
1353
+ origin, event = next
1354
+
1355
+ new_lock = await self.store.try_acquire_lock(
1356
+ _INBOUND_EVENT_HANDLING_LOCK_NAME, room_id
1357
+ )
1358
+ if not new_lock:
1359
+ return
1360
+ lock = new_lock
1361
+
1362
+ async def exchange_third_party_invite(
1363
+ self, sender_user_id: str, target_user_id: str, room_id: str, signed: dict
1364
+ ) -> None:
1365
+ await self.handler.exchange_third_party_invite(
1366
+ sender_user_id, target_user_id, room_id, signed
1367
+ )
1368
+
1369
+ async def on_exchange_third_party_invite_request(self, event_dict: dict) -> None:
1370
+ await self.handler.on_exchange_third_party_invite_request(event_dict)
1371
+
1372
+ async def check_server_matches_acl(self, server_name: str, room_id: str) -> None:
1373
+ """Check if the given server is allowed by the server ACLs in the room
1374
+
1375
+ Args:
1376
+ server_name: name of server, *without any port part*
1377
+ room_id: ID of the room to check
1378
+
1379
+ Raises:
1380
+ AuthError if the server does not match the ACL
1381
+ """
1382
+ server_acl_evaluator = (
1383
+ await self._storage_controllers.state.get_server_acl_for_room(room_id)
1384
+ )
1385
+ if server_acl_evaluator and not server_acl_evaluator.server_matches_acl_event(
1386
+ server_name
1387
+ ):
1388
+ raise AuthError(code=403, msg="Server is banned from room")
1389
+
1390
+
1391
+ class FederationHandlerRegistry:
1392
+ """Allows classes to register themselves as handlers for a given EDU or
1393
+ query type for incoming federation traffic.
1394
+ """
1395
+
1396
+ def __init__(self, hs: "HomeServer"):
1397
+ self.config = hs.config
1398
+ self.clock = hs.get_clock()
1399
+ self._instance_name = hs.get_instance_name()
1400
+
1401
+ # These are safe to load in monolith mode, but will explode if we try
1402
+ # and use them. However we have guards before we use them to ensure that
1403
+ # we don't route to ourselves, and in monolith mode that will always be
1404
+ # the case.
1405
+ self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)
1406
+
1407
+ self.edu_handlers: dict[str, Callable[[str, dict], Awaitable[None]]] = {}
1408
+ self.query_handlers: dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
1409
+
1410
+ # Map from type to instance names that we should route EDU handling to.
1411
+ # We randomly choose one instance from the list to route to for each new
1412
+ # EDU received.
1413
+ self._edu_type_to_instance: dict[str, list[str]] = {}
1414
+
1415
+ def register_edu_handler(
1416
+ self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]
1417
+ ) -> None:
1418
+ """Sets the handler callable that will be used to handle an incoming
1419
+ federation EDU of the given type.
1420
+
1421
+ Args:
1422
+ edu_type: The type of the incoming EDU to register handler for
1423
+ handler: A callable invoked on incoming EDU
1424
+ of the given type. The arguments are the origin server name and
1425
+ the EDU contents.
1426
+ """
1427
+ if edu_type in self.edu_handlers:
1428
+ raise KeyError("Already have an EDU handler for %s" % (edu_type,))
1429
+
1430
+ logger.info("Registering federation EDU handler for %r", edu_type)
1431
+
1432
+ self.edu_handlers[edu_type] = handler
1433
+
1434
+ def register_query_handler(
1435
+ self, query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
1436
+ ) -> None:
1437
+ """Sets the handler callable that will be used to handle an incoming
1438
+ federation query of the given type.
1439
+
1440
+ Args:
1441
+ query_type: Category name of the query, which should match
1442
+ the string used by make_query.
1443
+ handler: Invoked to handle
1444
+ incoming queries of this type. The return will be yielded
1445
+ on and the result used as the response to the query request.
1446
+ """
1447
+ if query_type in self.query_handlers:
1448
+ raise KeyError("Already have a Query handler for %s" % (query_type,))
1449
+
1450
+ logger.info("Registering federation query handler for %r", query_type)
1451
+
1452
+ self.query_handlers[query_type] = handler
1453
+
1454
+ def register_instances_for_edu(
1455
+ self, edu_type: str, instance_names: list[str]
1456
+ ) -> None:
1457
+ """Register that the EDU handler is on multiple instances."""
1458
+ self._edu_type_to_instance[edu_type] = instance_names
1459
+
1460
+ async def on_edu(self, edu_type: str, origin: str, content: dict) -> None:
1461
+ if not self.config.server.track_presence and edu_type == EduTypes.PRESENCE:
1462
+ return
1463
+
1464
+ # Check if we have a handler on this instance
1465
+ handler = self.edu_handlers.get(edu_type)
1466
+ if handler:
1467
+ with start_active_span_from_edu(content, "handle_edu"):
1468
+ await handler(origin, content)
1469
+ return
1470
+
1471
+ # Check if we can route it somewhere else that isn't us
1472
+ instances = self._edu_type_to_instance.get(edu_type, ["master"])
1473
+ if self._instance_name not in instances:
1474
+ # Pick an instance randomly so that we don't overload one.
1475
+ route_to = random.choice(instances)
1476
+
1477
+ await self._send_edu(
1478
+ instance_name=route_to,
1479
+ edu_type=edu_type,
1480
+ origin=origin,
1481
+ content=content,
1482
+ )
1483
+ return
1484
+
1485
+ # Oh well, let's just log and move on.
1486
+ logger.warning("No handler registered for EDU type %s", edu_type)
1487
+
1488
+ async def on_query(self, query_type: str, args: dict) -> JsonDict:
1489
+ handler = self.query_handlers.get(query_type)
1490
+ if handler:
1491
+ return await handler(args)
1492
+
1493
+ # Uh oh, no handler! Let's raise an exception so the request returns an
1494
+ # error.
1495
+ logger.warning("No handler registered for query type %s", query_type)
1496
+ raise NotFoundError("No handler for Query type '%s'" % (query_type,))
1497
+
1498
+
1499
+ def _get_event_ids_for_partial_state_join(
1500
+ join_event: EventBase,
1501
+ prev_state_ids: StateMap[str],
1502
+ summary: Mapping[str, MemberSummary],
1503
+ ) -> Collection[str]:
1504
+ """Calculate state to be returned in a partial_state send_join
1505
+
1506
+ Args:
1507
+ join_event: the join event being send_joined
1508
+ prev_state_ids: the event ids of the state before the join
1509
+
1510
+ Returns:
1511
+ the event ids to be returned
1512
+ """
1513
+
1514
+ # return all non-member events
1515
+ state_event_ids = {
1516
+ event_id
1517
+ for (event_type, state_key), event_id in prev_state_ids.items()
1518
+ if event_type != EventTypes.Member
1519
+ }
1520
+
1521
+ # we also need the current state of the current user (it's going to
1522
+ # be an auth event for the new join, so we may as well return it)
1523
+ current_membership_event_id = prev_state_ids.get(
1524
+ (EventTypes.Member, join_event.state_key)
1525
+ )
1526
+ if current_membership_event_id is not None:
1527
+ state_event_ids.add(current_membership_event_id)
1528
+
1529
+ name_id = prev_state_ids.get((EventTypes.Name, ""))
1530
+ canonical_alias_id = prev_state_ids.get((EventTypes.CanonicalAlias, ""))
1531
+ if not name_id and not canonical_alias_id:
1532
+ # Also include the hero members of the room (for DM rooms without a title).
1533
+ # To do this properly, we should select the correct subset of membership events
1534
+ # from `prev_state_ids`. Instead, we are lazier and use the (cached)
1535
+ # `get_room_summary` function, which is based on the current state of the room.
1536
+ # This introduces races; we choose to ignore them because a) they should be rare
1537
+ # and b) even if it's wrong, joining servers will get the full state eventually.
1538
+ heroes = extract_heroes_from_room_summary(summary, join_event.state_key)
1539
+ for hero in heroes:
1540
+ membership_event_id = prev_state_ids.get((EventTypes.Member, hero))
1541
+ if membership_event_id:
1542
+ state_event_ids.add(membership_event_id)
1543
+
1544
+ return state_event_ids