matrix-synapse 1.145.0rc2__cp310-abi3-manylinux_2_28_x86_64.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 (1636) hide show
  1. AUTHORS.rst +51 -0
  2. CHANGES.md +1732 -0
  3. CONTRIBUTING.md +3 -0
  4. Cargo.lock +1923 -0
  5. Cargo.toml +6 -0
  6. INSTALL.md +7 -0
  7. LICENSE-AGPL-3.0 +661 -0
  8. LICENSE-COMMERCIAL +6 -0
  9. UPGRADE.rst +7 -0
  10. book.toml +47 -0
  11. changelog.d/.gitignore +1 -0
  12. demo/.gitignore +4 -0
  13. demo/clean.sh +22 -0
  14. demo/start.sh +173 -0
  15. demo/stop.sh +14 -0
  16. docs/.sample_config_header.yaml +12 -0
  17. docs/CAPTCHA_SETUP.md +37 -0
  18. docs/README.md +86 -0
  19. docs/SUMMARY.md +126 -0
  20. docs/admin_api/README.rst +13 -0
  21. docs/admin_api/account_validity.md +47 -0
  22. docs/admin_api/client_server_api_extensions.md +67 -0
  23. docs/admin_api/event_reports.md +185 -0
  24. docs/admin_api/experimental_features.md +52 -0
  25. docs/admin_api/fetch_event.md +53 -0
  26. docs/admin_api/media_admin_api.md +372 -0
  27. docs/admin_api/purge_history_api.md +77 -0
  28. docs/admin_api/register_api.md +92 -0
  29. docs/admin_api/room_membership.md +35 -0
  30. docs/admin_api/rooms.md +1190 -0
  31. docs/admin_api/scheduled_tasks.md +54 -0
  32. docs/admin_api/server_notices.md +48 -0
  33. docs/admin_api/statistics.md +132 -0
  34. docs/admin_api/user_admin_api.md +1602 -0
  35. docs/admin_api/version_api.md +23 -0
  36. docs/ancient_architecture_notes.md +81 -0
  37. docs/application_services.md +36 -0
  38. docs/architecture.md +65 -0
  39. docs/auth_chain_diff.dot +32 -0
  40. docs/auth_chain_diff.dot.png +0 -0
  41. docs/auth_chain_difference_algorithm.md +141 -0
  42. docs/changelogs/CHANGES-2019.md +1039 -0
  43. docs/changelogs/CHANGES-2020.md +2145 -0
  44. docs/changelogs/CHANGES-2021.md +2573 -0
  45. docs/changelogs/CHANGES-2022.md +2766 -0
  46. docs/changelogs/CHANGES-2023.md +2202 -0
  47. docs/changelogs/CHANGES-2024.md +1586 -0
  48. docs/changelogs/CHANGES-pre-1.0.md +3641 -0
  49. docs/changelogs/README.md +1 -0
  50. docs/code_style.md +119 -0
  51. docs/consent_tracking.md +197 -0
  52. docs/delegate.md +111 -0
  53. docs/deprecation_policy.md +89 -0
  54. docs/development/cas.md +64 -0
  55. docs/development/contributing_guide.md +554 -0
  56. docs/development/database_schema.md +404 -0
  57. docs/development/demo.md +42 -0
  58. docs/development/dependencies.md +326 -0
  59. docs/development/experimental_features.md +37 -0
  60. docs/development/git.md +148 -0
  61. docs/development/img/git/branches.jpg +0 -0
  62. docs/development/img/git/clean.png +0 -0
  63. docs/development/img/git/squash.png +0 -0
  64. docs/development/internal_documentation/README.md +12 -0
  65. docs/development/internal_documentation/release_notes_review_checklist.md +12 -0
  66. docs/development/releases.md +37 -0
  67. docs/development/reviews.md +41 -0
  68. docs/development/room-dag-concepts.md +115 -0
  69. docs/development/saml.md +40 -0
  70. docs/development/synapse_architecture/cancellation.md +392 -0
  71. docs/development/synapse_architecture/faster_joins.md +375 -0
  72. docs/development/synapse_architecture/streams.md +198 -0
  73. docs/element_logo_white_bg.svg +94 -0
  74. docs/favicon.png +0 -0
  75. docs/favicon.svg +58 -0
  76. docs/federate.md +67 -0
  77. docs/jwt.md +105 -0
  78. docs/log_contexts.md +566 -0
  79. docs/manhole.md +101 -0
  80. docs/media_repository.md +78 -0
  81. docs/message_retention_policies.md +207 -0
  82. docs/metrics-howto.md +315 -0
  83. docs/modules/account_data_callbacks.md +106 -0
  84. docs/modules/account_validity_callbacks.md +57 -0
  85. docs/modules/add_extra_fields_to_client_events_unsigned.md +32 -0
  86. docs/modules/background_update_controller_callbacks.md +71 -0
  87. docs/modules/index.md +53 -0
  88. docs/modules/media_repository_callbacks.md +131 -0
  89. docs/modules/password_auth_provider_callbacks.md +270 -0
  90. docs/modules/porting_legacy_module.md +20 -0
  91. docs/modules/presence_router_callbacks.md +112 -0
  92. docs/modules/ratelimit_callbacks.md +43 -0
  93. docs/modules/spam_checker_callbacks.md +517 -0
  94. docs/modules/third_party_rules_callbacks.md +350 -0
  95. docs/modules/writing_a_module.md +141 -0
  96. docs/openid.md +783 -0
  97. docs/opentracing.md +99 -0
  98. docs/other/running_synapse_on_single_board_computers.md +75 -0
  99. docs/password_auth_providers.md +129 -0
  100. docs/postgres.md +269 -0
  101. docs/presence_router_module.md +247 -0
  102. docs/privacy_policy_templates/en/1.0.html +26 -0
  103. docs/privacy_policy_templates/en/success.html +11 -0
  104. docs/replication.md +36 -0
  105. docs/reverse_proxy.md +327 -0
  106. docs/room_and_user_statistics.md +22 -0
  107. docs/sample_config.yaml +47 -0
  108. docs/sample_log_config.yaml +75 -0
  109. docs/server_notices.md +66 -0
  110. docs/setup/forward_proxy.md +89 -0
  111. docs/setup/installation.md +656 -0
  112. docs/setup/security.md +41 -0
  113. docs/setup/turn/coturn.md +197 -0
  114. docs/setup/turn/eturnal.md +170 -0
  115. docs/spam_checker.md +122 -0
  116. docs/sso_mapping_providers.md +208 -0
  117. docs/structured_logging.md +80 -0
  118. docs/synctl_workers.md +36 -0
  119. docs/systemd-with-workers/README.md +101 -0
  120. docs/systemd-with-workers/system/matrix-synapse-worker@.service +26 -0
  121. docs/systemd-with-workers/system/matrix-synapse.service +23 -0
  122. docs/systemd-with-workers/system/matrix-synapse.target +6 -0
  123. docs/systemd-with-workers/workers/background_worker.yaml +4 -0
  124. docs/systemd-with-workers/workers/event_persister.yaml +20 -0
  125. docs/systemd-with-workers/workers/federation_sender.yaml +4 -0
  126. docs/systemd-with-workers/workers/generic_worker.yaml +11 -0
  127. docs/systemd-with-workers/workers/media_worker.yaml +11 -0
  128. docs/systemd-with-workers/workers/pusher_worker.yaml +4 -0
  129. docs/tcp_replication.md +258 -0
  130. docs/templates.md +254 -0
  131. docs/turn-howto.md +168 -0
  132. docs/upgrade.md +2876 -0
  133. docs/usage/administration/README.md +7 -0
  134. docs/usage/administration/admin_api/README.md +47 -0
  135. docs/usage/administration/admin_api/background_updates.md +109 -0
  136. docs/usage/administration/admin_api/federation.md +212 -0
  137. docs/usage/administration/admin_api/registration_tokens.md +298 -0
  138. docs/usage/administration/admin_faq.md +294 -0
  139. docs/usage/administration/backups.md +125 -0
  140. docs/usage/administration/database_maintenance_tools.md +18 -0
  141. docs/usage/administration/monitoring/reporting_homeserver_usage_statistics.md +77 -0
  142. docs/usage/administration/monthly_active_users.md +84 -0
  143. docs/usage/administration/request_log.md +44 -0
  144. docs/usage/administration/state_groups.md +25 -0
  145. docs/usage/administration/understanding_synapse_through_grafana_graphs.md +83 -0
  146. docs/usage/administration/useful_sql_for_admins.md +216 -0
  147. docs/usage/configuration/README.md +4 -0
  148. docs/usage/configuration/config_documentation.md +4768 -0
  149. docs/usage/configuration/homeserver_sample_config.md +17 -0
  150. docs/usage/configuration/logging_sample_config.md +19 -0
  151. docs/usage/configuration/user_authentication/README.md +15 -0
  152. docs/usage/configuration/user_authentication/refresh_tokens.md +139 -0
  153. docs/usage/configuration/user_authentication/single_sign_on/README.md +5 -0
  154. docs/usage/configuration/user_authentication/single_sign_on/cas.md +8 -0
  155. docs/usage/configuration/user_authentication/single_sign_on/saml.md +8 -0
  156. docs/user_directory.md +130 -0
  157. docs/website_files/README.md +35 -0
  158. docs/website_files/indent-section-headers.css +7 -0
  159. docs/website_files/remove-nav-buttons.css +8 -0
  160. docs/website_files/table-of-contents.css +47 -0
  161. docs/website_files/table-of-contents.js +148 -0
  162. docs/website_files/theme/index.hbs +324 -0
  163. docs/website_files/version-picker.css +78 -0
  164. docs/website_files/version-picker.js +147 -0
  165. docs/website_files/version.js +1 -0
  166. docs/welcome_and_overview.md +67 -0
  167. docs/workers.md +897 -0
  168. matrix_synapse-1.145.0rc2.dist-info/METADATA +260 -0
  169. matrix_synapse-1.145.0rc2.dist-info/RECORD +1636 -0
  170. matrix_synapse-1.145.0rc2.dist-info/WHEEL +5 -0
  171. matrix_synapse-1.145.0rc2.dist-info/entry_points.txt +13 -0
  172. matrix_synapse-1.145.0rc2.dist-info/licenses/AUTHORS.rst +51 -0
  173. matrix_synapse-1.145.0rc2.dist-info/licenses/LICENSE-AGPL-3.0 +661 -0
  174. matrix_synapse-1.145.0rc2.dist-info/licenses/LICENSE-COMMERCIAL +6 -0
  175. mypy.ini +115 -0
  176. rust/Cargo.toml +63 -0
  177. rust/build.rs +45 -0
  178. scripts-dev/build_debian_packages.py +228 -0
  179. scripts-dev/check-newsfragment.sh +62 -0
  180. scripts-dev/check_line_terminators.sh +29 -0
  181. scripts-dev/check_locked_deps_have_sdists.py +64 -0
  182. scripts-dev/check_schema_delta.py +240 -0
  183. scripts-dev/complement.sh +332 -0
  184. scripts-dev/config-lint.sh +15 -0
  185. scripts-dev/database-save.sh +15 -0
  186. scripts-dev/docker_update_debian_changelog.sh +70 -0
  187. scripts-dev/dump_macaroon.py +25 -0
  188. scripts-dev/federation_client.py +428 -0
  189. scripts-dev/gen_config_documentation.py +510 -0
  190. scripts-dev/generate_sample_config.sh +28 -0
  191. scripts-dev/lint.sh +141 -0
  192. scripts-dev/make_full_schema.sh +310 -0
  193. scripts-dev/mypy_synapse_plugin.py +918 -0
  194. scripts-dev/next_github_number.sh +9 -0
  195. scripts-dev/release.py +986 -0
  196. scripts-dev/schema_versions.py +182 -0
  197. scripts-dev/sign_json.py +172 -0
  198. synapse/__init__.py +97 -0
  199. synapse/_scripts/__init__.py +0 -0
  200. synapse/_scripts/export_signing_key.py +109 -0
  201. synapse/_scripts/generate_config.py +83 -0
  202. synapse/_scripts/generate_log_config.py +56 -0
  203. synapse/_scripts/generate_signing_key.py +55 -0
  204. synapse/_scripts/generate_workers_map.py +318 -0
  205. synapse/_scripts/hash_password.py +95 -0
  206. synapse/_scripts/move_remote_media_to_new_store.py +128 -0
  207. synapse/_scripts/register_new_matrix_user.py +402 -0
  208. synapse/_scripts/review_recent_signups.py +212 -0
  209. synapse/_scripts/synapse_port_db.py +1604 -0
  210. synapse/_scripts/synctl.py +365 -0
  211. synapse/_scripts/update_synapse_database.py +130 -0
  212. synapse/api/__init__.py +20 -0
  213. synapse/api/auth/__init__.py +207 -0
  214. synapse/api/auth/base.py +406 -0
  215. synapse/api/auth/internal.py +299 -0
  216. synapse/api/auth/mas.py +436 -0
  217. synapse/api/auth/msc3861_delegated.py +617 -0
  218. synapse/api/auth_blocking.py +144 -0
  219. synapse/api/constants.py +379 -0
  220. synapse/api/errors.py +913 -0
  221. synapse/api/filtering.py +537 -0
  222. synapse/api/presence.py +102 -0
  223. synapse/api/ratelimiting.py +481 -0
  224. synapse/api/room_versions.py +535 -0
  225. synapse/api/urls.py +118 -0
  226. synapse/app/__init__.py +62 -0
  227. synapse/app/_base.py +906 -0
  228. synapse/app/admin_cmd.py +388 -0
  229. synapse/app/appservice.py +30 -0
  230. synapse/app/client_reader.py +30 -0
  231. synapse/app/complement_fork_starter.py +206 -0
  232. synapse/app/event_creator.py +29 -0
  233. synapse/app/federation_reader.py +30 -0
  234. synapse/app/federation_sender.py +30 -0
  235. synapse/app/frontend_proxy.py +30 -0
  236. synapse/app/generic_worker.py +475 -0
  237. synapse/app/homeserver.py +505 -0
  238. synapse/app/media_repository.py +30 -0
  239. synapse/app/phone_stats_home.py +292 -0
  240. synapse/app/pusher.py +30 -0
  241. synapse/app/synchrotron.py +30 -0
  242. synapse/app/user_dir.py +31 -0
  243. synapse/appservice/__init__.py +458 -0
  244. synapse/appservice/api.py +567 -0
  245. synapse/appservice/scheduler.py +565 -0
  246. synapse/config/__init__.py +27 -0
  247. synapse/config/__main__.py +62 -0
  248. synapse/config/_base.py +1154 -0
  249. synapse/config/_base.pyi +216 -0
  250. synapse/config/_util.py +99 -0
  251. synapse/config/account_validity.py +116 -0
  252. synapse/config/api.py +141 -0
  253. synapse/config/appservice.py +210 -0
  254. synapse/config/auth.py +80 -0
  255. synapse/config/auto_accept_invites.py +43 -0
  256. synapse/config/background_updates.py +44 -0
  257. synapse/config/cache.py +231 -0
  258. synapse/config/captcha.py +90 -0
  259. synapse/config/cas.py +116 -0
  260. synapse/config/consent.py +73 -0
  261. synapse/config/database.py +184 -0
  262. synapse/config/emailconfig.py +367 -0
  263. synapse/config/experimental.py +601 -0
  264. synapse/config/federation.py +114 -0
  265. synapse/config/homeserver.py +141 -0
  266. synapse/config/jwt.py +55 -0
  267. synapse/config/key.py +447 -0
  268. synapse/config/logger.py +390 -0
  269. synapse/config/mas.py +192 -0
  270. synapse/config/matrixrtc.py +66 -0
  271. synapse/config/metrics.py +93 -0
  272. synapse/config/modules.py +40 -0
  273. synapse/config/oembed.py +185 -0
  274. synapse/config/oidc.py +509 -0
  275. synapse/config/password_auth_providers.py +82 -0
  276. synapse/config/push.py +64 -0
  277. synapse/config/ratelimiting.py +260 -0
  278. synapse/config/redis.py +74 -0
  279. synapse/config/registration.py +296 -0
  280. synapse/config/repository.py +311 -0
  281. synapse/config/retention.py +162 -0
  282. synapse/config/room.py +88 -0
  283. synapse/config/room_directory.py +165 -0
  284. synapse/config/saml2.py +251 -0
  285. synapse/config/server.py +1139 -0
  286. synapse/config/server_notices.py +84 -0
  287. synapse/config/spam_checker.py +66 -0
  288. synapse/config/sso.py +121 -0
  289. synapse/config/stats.py +54 -0
  290. synapse/config/third_party_event_rules.py +40 -0
  291. synapse/config/tls.py +192 -0
  292. synapse/config/tracer.py +71 -0
  293. synapse/config/user_directory.py +47 -0
  294. synapse/config/user_types.py +42 -0
  295. synapse/config/voip.py +59 -0
  296. synapse/config/workers.py +642 -0
  297. synapse/crypto/__init__.py +20 -0
  298. synapse/crypto/context_factory.py +278 -0
  299. synapse/crypto/event_signing.py +194 -0
  300. synapse/crypto/keyring.py +980 -0
  301. synapse/event_auth.py +1266 -0
  302. synapse/events/__init__.py +667 -0
  303. synapse/events/auto_accept_invites.py +216 -0
  304. synapse/events/builder.py +387 -0
  305. synapse/events/presence_router.py +243 -0
  306. synapse/events/snapshot.py +559 -0
  307. synapse/events/utils.py +924 -0
  308. synapse/events/validator.py +305 -0
  309. synapse/federation/__init__.py +22 -0
  310. synapse/federation/federation_base.py +382 -0
  311. synapse/federation/federation_client.py +2133 -0
  312. synapse/federation/federation_server.py +1543 -0
  313. synapse/federation/persistence.py +70 -0
  314. synapse/federation/send_queue.py +532 -0
  315. synapse/federation/sender/__init__.py +1165 -0
  316. synapse/federation/sender/per_destination_queue.py +886 -0
  317. synapse/federation/sender/transaction_manager.py +210 -0
  318. synapse/federation/transport/__init__.py +28 -0
  319. synapse/federation/transport/client.py +1199 -0
  320. synapse/federation/transport/server/__init__.py +334 -0
  321. synapse/federation/transport/server/_base.py +429 -0
  322. synapse/federation/transport/server/federation.py +910 -0
  323. synapse/federation/units.py +133 -0
  324. synapse/handlers/__init__.py +20 -0
  325. synapse/handlers/account.py +162 -0
  326. synapse/handlers/account_data.py +360 -0
  327. synapse/handlers/account_validity.py +362 -0
  328. synapse/handlers/admin.py +615 -0
  329. synapse/handlers/appservice.py +989 -0
  330. synapse/handlers/auth.py +2482 -0
  331. synapse/handlers/cas.py +413 -0
  332. synapse/handlers/deactivate_account.py +363 -0
  333. synapse/handlers/delayed_events.py +607 -0
  334. synapse/handlers/device.py +1869 -0
  335. synapse/handlers/devicemessage.py +399 -0
  336. synapse/handlers/directory.py +545 -0
  337. synapse/handlers/e2e_keys.py +1835 -0
  338. synapse/handlers/e2e_room_keys.py +455 -0
  339. synapse/handlers/event_auth.py +390 -0
  340. synapse/handlers/events.py +203 -0
  341. synapse/handlers/federation.py +2042 -0
  342. synapse/handlers/federation_event.py +2420 -0
  343. synapse/handlers/identity.py +812 -0
  344. synapse/handlers/initial_sync.py +528 -0
  345. synapse/handlers/jwt.py +120 -0
  346. synapse/handlers/message.py +2357 -0
  347. synapse/handlers/oidc.py +1801 -0
  348. synapse/handlers/pagination.py +811 -0
  349. synapse/handlers/password_policy.py +102 -0
  350. synapse/handlers/presence.py +2634 -0
  351. synapse/handlers/profile.py +656 -0
  352. synapse/handlers/push_rules.py +164 -0
  353. synapse/handlers/read_marker.py +79 -0
  354. synapse/handlers/receipts.py +351 -0
  355. synapse/handlers/register.py +1059 -0
  356. synapse/handlers/relations.py +623 -0
  357. synapse/handlers/reports.py +98 -0
  358. synapse/handlers/room.py +2449 -0
  359. synapse/handlers/room_list.py +632 -0
  360. synapse/handlers/room_member.py +2366 -0
  361. synapse/handlers/room_member_worker.py +146 -0
  362. synapse/handlers/room_policy.py +186 -0
  363. synapse/handlers/room_summary.py +1057 -0
  364. synapse/handlers/saml.py +524 -0
  365. synapse/handlers/search.py +723 -0
  366. synapse/handlers/send_email.py +209 -0
  367. synapse/handlers/set_password.py +71 -0
  368. synapse/handlers/sliding_sync/__init__.py +1961 -0
  369. synapse/handlers/sliding_sync/extensions.py +969 -0
  370. synapse/handlers/sliding_sync/room_lists.py +2317 -0
  371. synapse/handlers/sliding_sync/store.py +126 -0
  372. synapse/handlers/sso.py +1291 -0
  373. synapse/handlers/state_deltas.py +82 -0
  374. synapse/handlers/stats.py +322 -0
  375. synapse/handlers/sync.py +3096 -0
  376. synapse/handlers/thread_subscriptions.py +190 -0
  377. synapse/handlers/typing.py +612 -0
  378. synapse/handlers/ui_auth/__init__.py +48 -0
  379. synapse/handlers/ui_auth/checkers.py +332 -0
  380. synapse/handlers/user_directory.py +786 -0
  381. synapse/handlers/worker_lock.py +371 -0
  382. synapse/http/__init__.py +105 -0
  383. synapse/http/additional_resource.py +62 -0
  384. synapse/http/client.py +1377 -0
  385. synapse/http/connectproxyclient.py +316 -0
  386. synapse/http/federation/__init__.py +19 -0
  387. synapse/http/federation/matrix_federation_agent.py +490 -0
  388. synapse/http/federation/srv_resolver.py +196 -0
  389. synapse/http/federation/well_known_resolver.py +368 -0
  390. synapse/http/matrixfederationclient.py +1874 -0
  391. synapse/http/proxy.py +290 -0
  392. synapse/http/proxyagent.py +497 -0
  393. synapse/http/replicationagent.py +203 -0
  394. synapse/http/request_metrics.py +309 -0
  395. synapse/http/server.py +1111 -0
  396. synapse/http/servlet.py +1018 -0
  397. synapse/http/site.py +952 -0
  398. synapse/http/types.py +27 -0
  399. synapse/logging/__init__.py +31 -0
  400. synapse/logging/_remote.py +261 -0
  401. synapse/logging/_terse_json.py +95 -0
  402. synapse/logging/context.py +1209 -0
  403. synapse/logging/formatter.py +62 -0
  404. synapse/logging/handlers.py +99 -0
  405. synapse/logging/loggers.py +25 -0
  406. synapse/logging/opentracing.py +1132 -0
  407. synapse/logging/scopecontextmanager.py +160 -0
  408. synapse/media/_base.py +831 -0
  409. synapse/media/filepath.py +417 -0
  410. synapse/media/media_repository.py +1595 -0
  411. synapse/media/media_storage.py +703 -0
  412. synapse/media/oembed.py +277 -0
  413. synapse/media/preview_html.py +556 -0
  414. synapse/media/storage_provider.py +195 -0
  415. synapse/media/thumbnailer.py +833 -0
  416. synapse/media/url_previewer.py +884 -0
  417. synapse/metrics/__init__.py +748 -0
  418. synapse/metrics/_gc.py +219 -0
  419. synapse/metrics/_reactor_metrics.py +171 -0
  420. synapse/metrics/_types.py +38 -0
  421. synapse/metrics/background_process_metrics.py +555 -0
  422. synapse/metrics/common_usage_metrics.py +95 -0
  423. synapse/metrics/jemalloc.py +248 -0
  424. synapse/module_api/__init__.py +2131 -0
  425. synapse/module_api/callbacks/__init__.py +50 -0
  426. synapse/module_api/callbacks/account_validity_callbacks.py +106 -0
  427. synapse/module_api/callbacks/media_repository_callbacks.py +157 -0
  428. synapse/module_api/callbacks/ratelimit_callbacks.py +78 -0
  429. synapse/module_api/callbacks/spamchecker_callbacks.py +991 -0
  430. synapse/module_api/callbacks/third_party_event_rules_callbacks.py +592 -0
  431. synapse/module_api/errors.py +42 -0
  432. synapse/notifier.py +969 -0
  433. synapse/push/__init__.py +212 -0
  434. synapse/push/bulk_push_rule_evaluator.py +635 -0
  435. synapse/push/clientformat.py +126 -0
  436. synapse/push/emailpusher.py +334 -0
  437. synapse/push/httppusher.py +565 -0
  438. synapse/push/mailer.py +1009 -0
  439. synapse/push/presentable_names.py +216 -0
  440. synapse/push/push_tools.py +114 -0
  441. synapse/push/push_types.py +141 -0
  442. synapse/push/pusher.py +87 -0
  443. synapse/push/pusherpool.py +501 -0
  444. synapse/push/rulekinds.py +33 -0
  445. synapse/py.typed +0 -0
  446. synapse/replication/__init__.py +20 -0
  447. synapse/replication/http/__init__.py +68 -0
  448. synapse/replication/http/_base.py +469 -0
  449. synapse/replication/http/account_data.py +297 -0
  450. synapse/replication/http/deactivate_account.py +81 -0
  451. synapse/replication/http/delayed_events.py +62 -0
  452. synapse/replication/http/devices.py +254 -0
  453. synapse/replication/http/federation.py +334 -0
  454. synapse/replication/http/login.py +106 -0
  455. synapse/replication/http/membership.py +364 -0
  456. synapse/replication/http/presence.py +133 -0
  457. synapse/replication/http/push.py +156 -0
  458. synapse/replication/http/register.py +172 -0
  459. synapse/replication/http/send_events.py +182 -0
  460. synapse/replication/http/state.py +82 -0
  461. synapse/replication/http/streams.py +101 -0
  462. synapse/replication/tcp/__init__.py +56 -0
  463. synapse/replication/tcp/client.py +553 -0
  464. synapse/replication/tcp/commands.py +569 -0
  465. synapse/replication/tcp/context.py +41 -0
  466. synapse/replication/tcp/external_cache.py +156 -0
  467. synapse/replication/tcp/handler.py +922 -0
  468. synapse/replication/tcp/protocol.py +611 -0
  469. synapse/replication/tcp/redis.py +510 -0
  470. synapse/replication/tcp/resource.py +349 -0
  471. synapse/replication/tcp/streams/__init__.py +96 -0
  472. synapse/replication/tcp/streams/_base.py +765 -0
  473. synapse/replication/tcp/streams/events.py +287 -0
  474. synapse/replication/tcp/streams/federation.py +92 -0
  475. synapse/replication/tcp/streams/partial_state.py +80 -0
  476. synapse/res/providers.json +29 -0
  477. synapse/res/templates/_base.html +29 -0
  478. synapse/res/templates/account_previously_renewed.html +6 -0
  479. synapse/res/templates/account_renewed.html +6 -0
  480. synapse/res/templates/add_threepid.html +8 -0
  481. synapse/res/templates/add_threepid.txt +6 -0
  482. synapse/res/templates/add_threepid_failure.html +7 -0
  483. synapse/res/templates/add_threepid_success.html +6 -0
  484. synapse/res/templates/already_in_use.html +12 -0
  485. synapse/res/templates/already_in_use.txt +10 -0
  486. synapse/res/templates/auth_success.html +21 -0
  487. synapse/res/templates/invalid_token.html +6 -0
  488. synapse/res/templates/mail-Element.css +7 -0
  489. synapse/res/templates/mail-Vector.css +7 -0
  490. synapse/res/templates/mail-expiry.css +4 -0
  491. synapse/res/templates/mail.css +156 -0
  492. synapse/res/templates/notice_expiry.html +46 -0
  493. synapse/res/templates/notice_expiry.txt +7 -0
  494. synapse/res/templates/notif.html +51 -0
  495. synapse/res/templates/notif.txt +22 -0
  496. synapse/res/templates/notif_mail.html +59 -0
  497. synapse/res/templates/notif_mail.txt +10 -0
  498. synapse/res/templates/password_reset.html +10 -0
  499. synapse/res/templates/password_reset.txt +7 -0
  500. synapse/res/templates/password_reset_confirmation.html +15 -0
  501. synapse/res/templates/password_reset_failure.html +7 -0
  502. synapse/res/templates/password_reset_success.html +6 -0
  503. synapse/res/templates/recaptcha.html +42 -0
  504. synapse/res/templates/registration.html +12 -0
  505. synapse/res/templates/registration.txt +10 -0
  506. synapse/res/templates/registration_failure.html +6 -0
  507. synapse/res/templates/registration_success.html +6 -0
  508. synapse/res/templates/registration_token.html +18 -0
  509. synapse/res/templates/room.html +33 -0
  510. synapse/res/templates/room.txt +9 -0
  511. synapse/res/templates/sso.css +129 -0
  512. synapse/res/templates/sso_account_deactivated.html +25 -0
  513. synapse/res/templates/sso_auth_account_details.html +186 -0
  514. synapse/res/templates/sso_auth_account_details.js +116 -0
  515. synapse/res/templates/sso_auth_bad_user.html +26 -0
  516. synapse/res/templates/sso_auth_confirm.html +27 -0
  517. synapse/res/templates/sso_auth_success.html +26 -0
  518. synapse/res/templates/sso_error.html +71 -0
  519. synapse/res/templates/sso_footer.html +19 -0
  520. synapse/res/templates/sso_login_idp_picker.html +60 -0
  521. synapse/res/templates/sso_new_user_consent.html +30 -0
  522. synapse/res/templates/sso_partial_profile.html +19 -0
  523. synapse/res/templates/sso_redirect_confirm.html +39 -0
  524. synapse/res/templates/style.css +33 -0
  525. synapse/res/templates/terms.html +27 -0
  526. synapse/rest/__init__.py +197 -0
  527. synapse/rest/admin/__init__.py +395 -0
  528. synapse/rest/admin/_base.py +72 -0
  529. synapse/rest/admin/background_updates.py +171 -0
  530. synapse/rest/admin/devices.py +221 -0
  531. synapse/rest/admin/event_reports.py +173 -0
  532. synapse/rest/admin/events.py +69 -0
  533. synapse/rest/admin/experimental_features.py +137 -0
  534. synapse/rest/admin/federation.py +243 -0
  535. synapse/rest/admin/media.py +540 -0
  536. synapse/rest/admin/registration_tokens.py +358 -0
  537. synapse/rest/admin/rooms.py +1092 -0
  538. synapse/rest/admin/scheduled_tasks.py +70 -0
  539. synapse/rest/admin/server_notice_servlet.py +132 -0
  540. synapse/rest/admin/statistics.py +132 -0
  541. synapse/rest/admin/username_available.py +58 -0
  542. synapse/rest/admin/users.py +1634 -0
  543. synapse/rest/client/__init__.py +20 -0
  544. synapse/rest/client/_base.py +113 -0
  545. synapse/rest/client/account.py +937 -0
  546. synapse/rest/client/account_data.py +319 -0
  547. synapse/rest/client/account_validity.py +103 -0
  548. synapse/rest/client/appservice_ping.py +125 -0
  549. synapse/rest/client/auth.py +218 -0
  550. synapse/rest/client/auth_metadata.py +122 -0
  551. synapse/rest/client/capabilities.py +121 -0
  552. synapse/rest/client/delayed_events.py +165 -0
  553. synapse/rest/client/devices.py +587 -0
  554. synapse/rest/client/directory.py +211 -0
  555. synapse/rest/client/events.py +116 -0
  556. synapse/rest/client/filter.py +112 -0
  557. synapse/rest/client/initial_sync.py +65 -0
  558. synapse/rest/client/keys.py +678 -0
  559. synapse/rest/client/knock.py +104 -0
  560. synapse/rest/client/login.py +750 -0
  561. synapse/rest/client/login_token_request.py +127 -0
  562. synapse/rest/client/logout.py +93 -0
  563. synapse/rest/client/matrixrtc.py +52 -0
  564. synapse/rest/client/media.py +307 -0
  565. synapse/rest/client/mutual_rooms.py +145 -0
  566. synapse/rest/client/notifications.py +137 -0
  567. synapse/rest/client/openid.py +109 -0
  568. synapse/rest/client/password_policy.py +69 -0
  569. synapse/rest/client/presence.py +131 -0
  570. synapse/rest/client/profile.py +291 -0
  571. synapse/rest/client/push_rule.py +331 -0
  572. synapse/rest/client/pusher.py +181 -0
  573. synapse/rest/client/read_marker.py +104 -0
  574. synapse/rest/client/receipts.py +165 -0
  575. synapse/rest/client/register.py +1072 -0
  576. synapse/rest/client/relations.py +138 -0
  577. synapse/rest/client/rendezvous.py +76 -0
  578. synapse/rest/client/reporting.py +207 -0
  579. synapse/rest/client/room.py +1763 -0
  580. synapse/rest/client/room_keys.py +426 -0
  581. synapse/rest/client/room_upgrade_rest_servlet.py +112 -0
  582. synapse/rest/client/sendtodevice.py +85 -0
  583. synapse/rest/client/sync.py +1131 -0
  584. synapse/rest/client/tags.py +129 -0
  585. synapse/rest/client/thirdparty.py +130 -0
  586. synapse/rest/client/thread_subscriptions.py +247 -0
  587. synapse/rest/client/tokenrefresh.py +52 -0
  588. synapse/rest/client/transactions.py +150 -0
  589. synapse/rest/client/user_directory.py +99 -0
  590. synapse/rest/client/versions.py +193 -0
  591. synapse/rest/client/voip.py +88 -0
  592. synapse/rest/consent/__init__.py +0 -0
  593. synapse/rest/consent/consent_resource.py +210 -0
  594. synapse/rest/health.py +38 -0
  595. synapse/rest/key/__init__.py +20 -0
  596. synapse/rest/key/v2/__init__.py +40 -0
  597. synapse/rest/key/v2/local_key_resource.py +125 -0
  598. synapse/rest/key/v2/remote_key_resource.py +302 -0
  599. synapse/rest/media/__init__.py +0 -0
  600. synapse/rest/media/config_resource.py +53 -0
  601. synapse/rest/media/create_resource.py +90 -0
  602. synapse/rest/media/download_resource.py +110 -0
  603. synapse/rest/media/media_repository_resource.py +113 -0
  604. synapse/rest/media/preview_url_resource.py +77 -0
  605. synapse/rest/media/thumbnail_resource.py +142 -0
  606. synapse/rest/media/upload_resource.py +187 -0
  607. synapse/rest/media/v1/__init__.py +39 -0
  608. synapse/rest/media/v1/_base.py +23 -0
  609. synapse/rest/media/v1/media_storage.py +23 -0
  610. synapse/rest/media/v1/storage_provider.py +23 -0
  611. synapse/rest/synapse/__init__.py +20 -0
  612. synapse/rest/synapse/client/__init__.py +93 -0
  613. synapse/rest/synapse/client/federation_whitelist.py +66 -0
  614. synapse/rest/synapse/client/jwks.py +77 -0
  615. synapse/rest/synapse/client/new_user_consent.py +115 -0
  616. synapse/rest/synapse/client/oidc/__init__.py +45 -0
  617. synapse/rest/synapse/client/oidc/backchannel_logout_resource.py +42 -0
  618. synapse/rest/synapse/client/oidc/callback_resource.py +48 -0
  619. synapse/rest/synapse/client/password_reset.py +129 -0
  620. synapse/rest/synapse/client/pick_idp.py +107 -0
  621. synapse/rest/synapse/client/pick_username.py +153 -0
  622. synapse/rest/synapse/client/rendezvous.py +58 -0
  623. synapse/rest/synapse/client/saml2/__init__.py +42 -0
  624. synapse/rest/synapse/client/saml2/metadata_resource.py +46 -0
  625. synapse/rest/synapse/client/saml2/response_resource.py +52 -0
  626. synapse/rest/synapse/client/sso_register.py +56 -0
  627. synapse/rest/synapse/client/unsubscribe.py +88 -0
  628. synapse/rest/synapse/mas/__init__.py +71 -0
  629. synapse/rest/synapse/mas/_base.py +55 -0
  630. synapse/rest/synapse/mas/devices.py +239 -0
  631. synapse/rest/synapse/mas/users.py +469 -0
  632. synapse/rest/well_known.py +148 -0
  633. synapse/server.py +1279 -0
  634. synapse/server_notices/__init__.py +0 -0
  635. synapse/server_notices/consent_server_notices.py +136 -0
  636. synapse/server_notices/resource_limits_server_notices.py +215 -0
  637. synapse/server_notices/server_notices_manager.py +388 -0
  638. synapse/server_notices/server_notices_sender.py +67 -0
  639. synapse/server_notices/worker_server_notices_sender.py +46 -0
  640. synapse/spam_checker_api/__init__.py +31 -0
  641. synapse/state/__init__.py +1023 -0
  642. synapse/state/v1.py +369 -0
  643. synapse/state/v2.py +985 -0
  644. synapse/static/client/login/index.html +47 -0
  645. synapse/static/client/login/js/jquery-3.4.1.min.js +2 -0
  646. synapse/static/client/login/js/login.js +291 -0
  647. synapse/static/client/login/spinner.gif +0 -0
  648. synapse/static/client/login/style.css +79 -0
  649. synapse/static/index.html +63 -0
  650. synapse/storage/__init__.py +43 -0
  651. synapse/storage/_base.py +245 -0
  652. synapse/storage/admin_client_config.py +25 -0
  653. synapse/storage/background_updates.py +1189 -0
  654. synapse/storage/controllers/__init__.py +57 -0
  655. synapse/storage/controllers/persist_events.py +1237 -0
  656. synapse/storage/controllers/purge_events.py +456 -0
  657. synapse/storage/controllers/state.py +950 -0
  658. synapse/storage/controllers/stats.py +119 -0
  659. synapse/storage/database.py +2720 -0
  660. synapse/storage/databases/__init__.py +175 -0
  661. synapse/storage/databases/main/__init__.py +420 -0
  662. synapse/storage/databases/main/account_data.py +1073 -0
  663. synapse/storage/databases/main/appservice.py +473 -0
  664. synapse/storage/databases/main/cache.py +912 -0
  665. synapse/storage/databases/main/censor_events.py +226 -0
  666. synapse/storage/databases/main/client_ips.py +816 -0
  667. synapse/storage/databases/main/delayed_events.py +577 -0
  668. synapse/storage/databases/main/deviceinbox.py +1272 -0
  669. synapse/storage/databases/main/devices.py +2579 -0
  670. synapse/storage/databases/main/directory.py +212 -0
  671. synapse/storage/databases/main/e2e_room_keys.py +689 -0
  672. synapse/storage/databases/main/end_to_end_keys.py +1894 -0
  673. synapse/storage/databases/main/event_federation.py +2511 -0
  674. synapse/storage/databases/main/event_push_actions.py +1936 -0
  675. synapse/storage/databases/main/events.py +3765 -0
  676. synapse/storage/databases/main/events_bg_updates.py +2910 -0
  677. synapse/storage/databases/main/events_forward_extremities.py +126 -0
  678. synapse/storage/databases/main/events_worker.py +2787 -0
  679. synapse/storage/databases/main/experimental_features.py +130 -0
  680. synapse/storage/databases/main/filtering.py +231 -0
  681. synapse/storage/databases/main/keys.py +291 -0
  682. synapse/storage/databases/main/lock.py +554 -0
  683. synapse/storage/databases/main/media_repository.py +1068 -0
  684. synapse/storage/databases/main/metrics.py +461 -0
  685. synapse/storage/databases/main/monthly_active_users.py +443 -0
  686. synapse/storage/databases/main/openid.py +60 -0
  687. synapse/storage/databases/main/presence.py +509 -0
  688. synapse/storage/databases/main/profile.py +539 -0
  689. synapse/storage/databases/main/purge_events.py +521 -0
  690. synapse/storage/databases/main/push_rule.py +970 -0
  691. synapse/storage/databases/main/pusher.py +793 -0
  692. synapse/storage/databases/main/receipts.py +1341 -0
  693. synapse/storage/databases/main/registration.py +3071 -0
  694. synapse/storage/databases/main/rejections.py +37 -0
  695. synapse/storage/databases/main/relations.py +1116 -0
  696. synapse/storage/databases/main/room.py +2779 -0
  697. synapse/storage/databases/main/roommember.py +2132 -0
  698. synapse/storage/databases/main/search.py +939 -0
  699. synapse/storage/databases/main/session.py +152 -0
  700. synapse/storage/databases/main/signatures.py +94 -0
  701. synapse/storage/databases/main/sliding_sync.py +842 -0
  702. synapse/storage/databases/main/state.py +1002 -0
  703. synapse/storage/databases/main/state_deltas.py +360 -0
  704. synapse/storage/databases/main/stats.py +789 -0
  705. synapse/storage/databases/main/stream.py +2589 -0
  706. synapse/storage/databases/main/tags.py +360 -0
  707. synapse/storage/databases/main/task_scheduler.py +225 -0
  708. synapse/storage/databases/main/thread_subscriptions.py +589 -0
  709. synapse/storage/databases/main/transactions.py +676 -0
  710. synapse/storage/databases/main/ui_auth.py +420 -0
  711. synapse/storage/databases/main/user_directory.py +1330 -0
  712. synapse/storage/databases/main/user_erasure_store.py +117 -0
  713. synapse/storage/databases/state/__init__.py +22 -0
  714. synapse/storage/databases/state/bg_updates.py +497 -0
  715. synapse/storage/databases/state/deletion.py +557 -0
  716. synapse/storage/databases/state/store.py +948 -0
  717. synapse/storage/engines/__init__.py +70 -0
  718. synapse/storage/engines/_base.py +154 -0
  719. synapse/storage/engines/postgres.py +261 -0
  720. synapse/storage/engines/sqlite.py +199 -0
  721. synapse/storage/invite_rule.py +152 -0
  722. synapse/storage/keys.py +40 -0
  723. synapse/storage/prepare_database.py +730 -0
  724. synapse/storage/push_rule.py +28 -0
  725. synapse/storage/roommember.py +88 -0
  726. synapse/storage/schema/README.md +4 -0
  727. synapse/storage/schema/__init__.py +186 -0
  728. synapse/storage/schema/common/delta/25/00background_updates.sql +40 -0
  729. synapse/storage/schema/common/delta/35/00background_updates_add_col.sql +36 -0
  730. synapse/storage/schema/common/delta/58/00background_update_ordering.sql +38 -0
  731. synapse/storage/schema/common/full_schemas/72/full.sql.postgres +8 -0
  732. synapse/storage/schema/common/full_schemas/72/full.sql.sqlite +6 -0
  733. synapse/storage/schema/common/schema_version.sql +60 -0
  734. synapse/storage/schema/main/delta/12/v12.sql +82 -0
  735. synapse/storage/schema/main/delta/13/v13.sql +38 -0
  736. synapse/storage/schema/main/delta/14/v14.sql +42 -0
  737. synapse/storage/schema/main/delta/15/appservice_txns.sql +50 -0
  738. synapse/storage/schema/main/delta/15/presence_indices.sql +2 -0
  739. synapse/storage/schema/main/delta/15/v15.sql +24 -0
  740. synapse/storage/schema/main/delta/16/events_order_index.sql +4 -0
  741. synapse/storage/schema/main/delta/16/remote_media_cache_index.sql +2 -0
  742. synapse/storage/schema/main/delta/16/remove_duplicates.sql +9 -0
  743. synapse/storage/schema/main/delta/16/room_alias_index.sql +3 -0
  744. synapse/storage/schema/main/delta/16/unique_constraints.sql +72 -0
  745. synapse/storage/schema/main/delta/16/users.sql +56 -0
  746. synapse/storage/schema/main/delta/17/drop_indexes.sql +37 -0
  747. synapse/storage/schema/main/delta/17/server_keys.sql +43 -0
  748. synapse/storage/schema/main/delta/17/user_threepids.sql +9 -0
  749. synapse/storage/schema/main/delta/18/server_keys_bigger_ints.sql +51 -0
  750. synapse/storage/schema/main/delta/19/event_index.sql +38 -0
  751. synapse/storage/schema/main/delta/20/dummy.sql +1 -0
  752. synapse/storage/schema/main/delta/20/pushers.py +93 -0
  753. synapse/storage/schema/main/delta/21/end_to_end_keys.sql +53 -0
  754. synapse/storage/schema/main/delta/21/receipts.sql +57 -0
  755. synapse/storage/schema/main/delta/22/receipts_index.sql +41 -0
  756. synapse/storage/schema/main/delta/22/user_threepids_unique.sql +19 -0
  757. synapse/storage/schema/main/delta/24/stats_reporting.sql +37 -0
  758. synapse/storage/schema/main/delta/25/fts.py +81 -0
  759. synapse/storage/schema/main/delta/25/guest_access.sql +44 -0
  760. synapse/storage/schema/main/delta/25/history_visibility.sql +44 -0
  761. synapse/storage/schema/main/delta/25/tags.sql +57 -0
  762. synapse/storage/schema/main/delta/26/account_data.sql +36 -0
  763. synapse/storage/schema/main/delta/27/account_data.sql +55 -0
  764. synapse/storage/schema/main/delta/27/forgotten_memberships.sql +45 -0
  765. synapse/storage/schema/main/delta/27/ts.py +61 -0
  766. synapse/storage/schema/main/delta/28/event_push_actions.sql +46 -0
  767. synapse/storage/schema/main/delta/28/events_room_stream.sql +39 -0
  768. synapse/storage/schema/main/delta/28/public_roms_index.sql +39 -0
  769. synapse/storage/schema/main/delta/28/receipts_user_id_index.sql +41 -0
  770. synapse/storage/schema/main/delta/28/upgrade_times.sql +40 -0
  771. synapse/storage/schema/main/delta/28/users_is_guest.sql +41 -0
  772. synapse/storage/schema/main/delta/29/push_actions.sql +54 -0
  773. synapse/storage/schema/main/delta/30/alias_creator.sql +35 -0
  774. synapse/storage/schema/main/delta/30/as_users.py +82 -0
  775. synapse/storage/schema/main/delta/30/deleted_pushers.sql +44 -0
  776. synapse/storage/schema/main/delta/30/presence_stream.sql +49 -0
  777. synapse/storage/schema/main/delta/30/public_rooms.sql +42 -0
  778. synapse/storage/schema/main/delta/30/push_rule_stream.sql +57 -0
  779. synapse/storage/schema/main/delta/30/threepid_guest_access_tokens.sql +43 -0
  780. synapse/storage/schema/main/delta/31/invites.sql +61 -0
  781. synapse/storage/schema/main/delta/31/local_media_repository_url_cache.sql +46 -0
  782. synapse/storage/schema/main/delta/31/pushers_0.py +92 -0
  783. synapse/storage/schema/main/delta/31/pushers_index.sql +41 -0
  784. synapse/storage/schema/main/delta/31/search_update.py +65 -0
  785. synapse/storage/schema/main/delta/32/events.sql +35 -0
  786. synapse/storage/schema/main/delta/32/openid.sql +9 -0
  787. synapse/storage/schema/main/delta/32/pusher_throttle.sql +42 -0
  788. synapse/storage/schema/main/delta/32/remove_indices.sql +52 -0
  789. synapse/storage/schema/main/delta/32/reports.sql +44 -0
  790. synapse/storage/schema/main/delta/33/access_tokens_device_index.sql +36 -0
  791. synapse/storage/schema/main/delta/33/devices.sql +40 -0
  792. synapse/storage/schema/main/delta/33/devices_for_e2e_keys.sql +38 -0
  793. synapse/storage/schema/main/delta/33/devices_for_e2e_keys_clear_unknown_device.sql +39 -0
  794. synapse/storage/schema/main/delta/33/event_fields.py +61 -0
  795. synapse/storage/schema/main/delta/33/remote_media_ts.py +43 -0
  796. synapse/storage/schema/main/delta/33/user_ips_index.sql +36 -0
  797. synapse/storage/schema/main/delta/34/appservice_stream.sql +42 -0
  798. synapse/storage/schema/main/delta/34/cache_stream.py +50 -0
  799. synapse/storage/schema/main/delta/34/device_inbox.sql +43 -0
  800. synapse/storage/schema/main/delta/34/push_display_name_rename.sql +39 -0
  801. synapse/storage/schema/main/delta/34/received_txn_purge.py +36 -0
  802. synapse/storage/schema/main/delta/35/contains_url.sql +36 -0
  803. synapse/storage/schema/main/delta/35/device_outbox.sql +58 -0
  804. synapse/storage/schema/main/delta/35/device_stream_id.sql +40 -0
  805. synapse/storage/schema/main/delta/35/event_push_actions_index.sql +36 -0
  806. synapse/storage/schema/main/delta/35/public_room_list_change_stream.sql +52 -0
  807. synapse/storage/schema/main/delta/35/stream_order_to_extrem.sql +56 -0
  808. synapse/storage/schema/main/delta/36/readd_public_rooms.sql +45 -0
  809. synapse/storage/schema/main/delta/37/remove_auth_idx.py +89 -0
  810. synapse/storage/schema/main/delta/37/user_threepids.sql +71 -0
  811. synapse/storage/schema/main/delta/38/postgres_fts_gist.sql +38 -0
  812. synapse/storage/schema/main/delta/39/appservice_room_list.sql +48 -0
  813. synapse/storage/schema/main/delta/39/device_federation_stream_idx.sql +35 -0
  814. synapse/storage/schema/main/delta/39/event_push_index.sql +36 -0
  815. synapse/storage/schema/main/delta/39/federation_out_position.sql +41 -0
  816. synapse/storage/schema/main/delta/39/membership_profile.sql +39 -0
  817. synapse/storage/schema/main/delta/40/current_state_idx.sql +36 -0
  818. synapse/storage/schema/main/delta/40/device_inbox.sql +40 -0
  819. synapse/storage/schema/main/delta/40/device_list_streams.sql +79 -0
  820. synapse/storage/schema/main/delta/40/event_push_summary.sql +57 -0
  821. synapse/storage/schema/main/delta/40/pushers.sql +58 -0
  822. synapse/storage/schema/main/delta/41/device_list_stream_idx.sql +36 -0
  823. synapse/storage/schema/main/delta/41/device_outbound_index.sql +35 -0
  824. synapse/storage/schema/main/delta/41/event_search_event_id_idx.sql +36 -0
  825. synapse/storage/schema/main/delta/41/ratelimit.sql +41 -0
  826. synapse/storage/schema/main/delta/42/current_state_delta.sql +48 -0
  827. synapse/storage/schema/main/delta/42/device_list_last_id.sql +52 -0
  828. synapse/storage/schema/main/delta/42/event_auth_state_only.sql +36 -0
  829. synapse/storage/schema/main/delta/42/user_dir.py +88 -0
  830. synapse/storage/schema/main/delta/43/blocked_rooms.sql +40 -0
  831. synapse/storage/schema/main/delta/43/quarantine_media.sql +36 -0
  832. synapse/storage/schema/main/delta/43/url_cache.sql +35 -0
  833. synapse/storage/schema/main/delta/43/user_share.sql +52 -0
  834. synapse/storage/schema/main/delta/44/expire_url_cache.sql +60 -0
  835. synapse/storage/schema/main/delta/45/group_server.sql +186 -0
  836. synapse/storage/schema/main/delta/45/profile_cache.sql +47 -0
  837. synapse/storage/schema/main/delta/46/drop_refresh_tokens.sql +36 -0
  838. synapse/storage/schema/main/delta/46/drop_unique_deleted_pushers.sql +54 -0
  839. synapse/storage/schema/main/delta/46/group_server.sql +51 -0
  840. synapse/storage/schema/main/delta/46/local_media_repository_url_idx.sql +43 -0
  841. synapse/storage/schema/main/delta/46/user_dir_null_room_ids.sql +54 -0
  842. synapse/storage/schema/main/delta/46/user_dir_typos.sql +43 -0
  843. synapse/storage/schema/main/delta/47/last_access_media.sql +35 -0
  844. synapse/storage/schema/main/delta/47/postgres_fts_gin.sql +36 -0
  845. synapse/storage/schema/main/delta/47/push_actions_staging.sql +47 -0
  846. synapse/storage/schema/main/delta/48/add_user_consent.sql +37 -0
  847. synapse/storage/schema/main/delta/48/add_user_ips_last_seen_index.sql +36 -0
  848. synapse/storage/schema/main/delta/48/deactivated_users.sql +44 -0
  849. synapse/storage/schema/main/delta/48/group_unique_indexes.py +67 -0
  850. synapse/storage/schema/main/delta/48/groups_joinable.sql +41 -0
  851. synapse/storage/schema/main/delta/49/add_user_consent_server_notice_sent.sql +39 -0
  852. synapse/storage/schema/main/delta/49/add_user_daily_visits.sql +40 -0
  853. synapse/storage/schema/main/delta/49/add_user_ips_last_seen_only_index.sql +36 -0
  854. synapse/storage/schema/main/delta/50/add_creation_ts_users_index.sql +38 -0
  855. synapse/storage/schema/main/delta/50/erasure_store.sql +40 -0
  856. synapse/storage/schema/main/delta/50/make_event_content_nullable.py +102 -0
  857. synapse/storage/schema/main/delta/51/e2e_room_keys.sql +58 -0
  858. synapse/storage/schema/main/delta/51/monthly_active_users.sql +46 -0
  859. synapse/storage/schema/main/delta/52/add_event_to_state_group_index.sql +38 -0
  860. synapse/storage/schema/main/delta/52/device_list_streams_unique_idx.sql +55 -0
  861. synapse/storage/schema/main/delta/52/e2e_room_keys.sql +72 -0
  862. synapse/storage/schema/main/delta/53/add_user_type_to_users.sql +38 -0
  863. synapse/storage/schema/main/delta/53/drop_sent_transactions.sql +35 -0
  864. synapse/storage/schema/main/delta/53/event_format_version.sql +35 -0
  865. synapse/storage/schema/main/delta/53/user_dir_populate.sql +49 -0
  866. synapse/storage/schema/main/delta/53/user_ips_index.sql +49 -0
  867. synapse/storage/schema/main/delta/53/user_share.sql +63 -0
  868. synapse/storage/schema/main/delta/53/user_threepid_id.sql +48 -0
  869. synapse/storage/schema/main/delta/53/users_in_public_rooms.sql +47 -0
  870. synapse/storage/schema/main/delta/54/account_validity_with_renewal.sql +49 -0
  871. synapse/storage/schema/main/delta/54/add_validity_to_server_keys.sql +42 -0
  872. synapse/storage/schema/main/delta/54/delete_forward_extremities.sql +42 -0
  873. synapse/storage/schema/main/delta/54/drop_legacy_tables.sql +49 -0
  874. synapse/storage/schema/main/delta/54/drop_presence_list.sql +35 -0
  875. synapse/storage/schema/main/delta/54/relations.sql +46 -0
  876. synapse/storage/schema/main/delta/54/stats.sql +99 -0
  877. synapse/storage/schema/main/delta/54/stats2.sql +47 -0
  878. synapse/storage/schema/main/delta/55/access_token_expiry.sql +37 -0
  879. synapse/storage/schema/main/delta/55/track_threepid_validations.sql +50 -0
  880. synapse/storage/schema/main/delta/55/users_alter_deactivated.sql +38 -0
  881. synapse/storage/schema/main/delta/56/add_spans_to_device_lists.sql +39 -0
  882. synapse/storage/schema/main/delta/56/current_state_events_membership.sql +41 -0
  883. synapse/storage/schema/main/delta/56/current_state_events_membership_mk2.sql +43 -0
  884. synapse/storage/schema/main/delta/56/delete_keys_from_deleted_backups.sql +44 -0
  885. synapse/storage/schema/main/delta/56/destinations_failure_ts.sql +44 -0
  886. synapse/storage/schema/main/delta/56/destinations_retry_interval_type.sql.postgres +18 -0
  887. synapse/storage/schema/main/delta/56/device_stream_id_insert.sql +39 -0
  888. synapse/storage/schema/main/delta/56/devices_last_seen.sql +43 -0
  889. synapse/storage/schema/main/delta/56/drop_unused_event_tables.sql +39 -0
  890. synapse/storage/schema/main/delta/56/event_expiry.sql +40 -0
  891. synapse/storage/schema/main/delta/56/event_labels.sql +49 -0
  892. synapse/storage/schema/main/delta/56/event_labels_background_update.sql +36 -0
  893. synapse/storage/schema/main/delta/56/fix_room_keys_index.sql +37 -0
  894. synapse/storage/schema/main/delta/56/hidden_devices.sql +37 -0
  895. synapse/storage/schema/main/delta/56/hidden_devices_fix.sql.sqlite +42 -0
  896. synapse/storage/schema/main/delta/56/nuke_empty_communities_from_db.sql +48 -0
  897. synapse/storage/schema/main/delta/56/public_room_list_idx.sql +35 -0
  898. synapse/storage/schema/main/delta/56/redaction_censor.sql +35 -0
  899. synapse/storage/schema/main/delta/56/redaction_censor2.sql +41 -0
  900. synapse/storage/schema/main/delta/56/redaction_censor3_fix_update.sql.postgres +25 -0
  901. synapse/storage/schema/main/delta/56/redaction_censor4.sql +35 -0
  902. synapse/storage/schema/main/delta/56/remove_tombstoned_rooms_from_directory.sql +38 -0
  903. synapse/storage/schema/main/delta/56/room_key_etag.sql +36 -0
  904. synapse/storage/schema/main/delta/56/room_membership_idx.sql +37 -0
  905. synapse/storage/schema/main/delta/56/room_retention.sql +52 -0
  906. synapse/storage/schema/main/delta/56/signing_keys.sql +75 -0
  907. synapse/storage/schema/main/delta/56/signing_keys_nonunique_signatures.sql +41 -0
  908. synapse/storage/schema/main/delta/56/stats_separated.sql +175 -0
  909. synapse/storage/schema/main/delta/56/unique_user_filter_index.py +46 -0
  910. synapse/storage/schema/main/delta/56/user_external_ids.sql +43 -0
  911. synapse/storage/schema/main/delta/56/users_in_public_rooms_idx.sql +36 -0
  912. synapse/storage/schema/main/delta/57/delete_old_current_state_events.sql +41 -0
  913. synapse/storage/schema/main/delta/57/device_list_remote_cache_stale.sql +44 -0
  914. synapse/storage/schema/main/delta/57/local_current_membership.py +111 -0
  915. synapse/storage/schema/main/delta/57/remove_sent_outbound_pokes.sql +40 -0
  916. synapse/storage/schema/main/delta/57/rooms_version_column.sql +43 -0
  917. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.postgres +35 -0
  918. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.sqlite +22 -0
  919. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.postgres +39 -0
  920. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.sqlite +23 -0
  921. synapse/storage/schema/main/delta/58/02remove_dup_outbound_pokes.sql +41 -0
  922. synapse/storage/schema/main/delta/58/03persist_ui_auth.sql +55 -0
  923. synapse/storage/schema/main/delta/58/05cache_instance.sql.postgres +30 -0
  924. synapse/storage/schema/main/delta/58/06dlols_unique_idx.py +83 -0
  925. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.postgres +33 -0
  926. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.sqlite +44 -0
  927. synapse/storage/schema/main/delta/58/07persist_ui_auth_ips.sql +44 -0
  928. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.postgres +18 -0
  929. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.sqlite +18 -0
  930. synapse/storage/schema/main/delta/58/09shadow_ban.sql +37 -0
  931. synapse/storage/schema/main/delta/58/10_pushrules_enabled_delete_obsolete.sql +47 -0
  932. synapse/storage/schema/main/delta/58/10drop_local_rejections_stream.sql +41 -0
  933. synapse/storage/schema/main/delta/58/10federation_pos_instance_name.sql +41 -0
  934. synapse/storage/schema/main/delta/58/11dehydration.sql +39 -0
  935. synapse/storage/schema/main/delta/58/11fallback.sql +43 -0
  936. synapse/storage/schema/main/delta/58/11user_id_seq.py +38 -0
  937. synapse/storage/schema/main/delta/58/12room_stats.sql +51 -0
  938. synapse/storage/schema/main/delta/58/13remove_presence_allow_inbound.sql +36 -0
  939. synapse/storage/schema/main/delta/58/14events_instance_name.sql +35 -0
  940. synapse/storage/schema/main/delta/58/14events_instance_name.sql.postgres +28 -0
  941. synapse/storage/schema/main/delta/58/15_catchup_destination_rooms.sql +61 -0
  942. synapse/storage/schema/main/delta/58/15unread_count.sql +45 -0
  943. synapse/storage/schema/main/delta/58/16populate_stats_process_rooms_fix.sql +41 -0
  944. synapse/storage/schema/main/delta/58/17_catchup_last_successful.sql +40 -0
  945. synapse/storage/schema/main/delta/58/18stream_positions.sql +41 -0
  946. synapse/storage/schema/main/delta/58/19instance_map.sql.postgres +25 -0
  947. synapse/storage/schema/main/delta/58/19txn_id.sql +59 -0
  948. synapse/storage/schema/main/delta/58/20instance_name_event_tables.sql +36 -0
  949. synapse/storage/schema/main/delta/58/20user_daily_visits.sql +37 -0
  950. synapse/storage/schema/main/delta/58/21as_device_stream.sql +36 -0
  951. synapse/storage/schema/main/delta/58/21drop_device_max_stream_id.sql +1 -0
  952. synapse/storage/schema/main/delta/58/22puppet_token.sql +36 -0
  953. synapse/storage/schema/main/delta/58/22users_have_local_media.sql +2 -0
  954. synapse/storage/schema/main/delta/58/23e2e_cross_signing_keys_idx.sql +36 -0
  955. synapse/storage/schema/main/delta/58/24drop_event_json_index.sql +38 -0
  956. synapse/storage/schema/main/delta/58/25user_external_ids_user_id_idx.sql +36 -0
  957. synapse/storage/schema/main/delta/58/26access_token_last_validated.sql +37 -0
  958. synapse/storage/schema/main/delta/58/27local_invites.sql +37 -0
  959. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.postgres +16 -0
  960. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.sqlite +62 -0
  961. synapse/storage/schema/main/delta/59/01ignored_user.py +85 -0
  962. synapse/storage/schema/main/delta/59/02shard_send_to_device.sql +37 -0
  963. synapse/storage/schema/main/delta/59/03shard_send_to_device_sequence.sql.postgres +25 -0
  964. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql +71 -0
  965. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql.postgres +16 -0
  966. synapse/storage/schema/main/delta/59/04drop_account_data.sql +36 -0
  967. synapse/storage/schema/main/delta/59/05cache_invalidation.sql +36 -0
  968. synapse/storage/schema/main/delta/59/06chain_cover_index.sql +36 -0
  969. synapse/storage/schema/main/delta/59/06shard_account_data.sql +39 -0
  970. synapse/storage/schema/main/delta/59/06shard_account_data.sql.postgres +32 -0
  971. synapse/storage/schema/main/delta/59/07shard_account_data_fix.sql +37 -0
  972. synapse/storage/schema/main/delta/59/08delete_pushers_for_deactivated_accounts.sql +39 -0
  973. synapse/storage/schema/main/delta/59/08delete_stale_pushers.sql +39 -0
  974. synapse/storage/schema/main/delta/59/09rejected_events_metadata.sql +45 -0
  975. synapse/storage/schema/main/delta/59/10delete_purged_chain_cover.sql +36 -0
  976. synapse/storage/schema/main/delta/59/11add_knock_members_to_stats.sql +39 -0
  977. synapse/storage/schema/main/delta/59/11drop_thumbnail_constraint.sql.postgres +22 -0
  978. synapse/storage/schema/main/delta/59/12account_validity_token_used_ts_ms.sql +37 -0
  979. synapse/storage/schema/main/delta/59/12presence_stream_instance.sql +37 -0
  980. synapse/storage/schema/main/delta/59/12presence_stream_instance_seq.sql.postgres +20 -0
  981. synapse/storage/schema/main/delta/59/13users_to_send_full_presence_to.sql +53 -0
  982. synapse/storage/schema/main/delta/59/14refresh_tokens.sql +53 -0
  983. synapse/storage/schema/main/delta/59/15locks.sql +56 -0
  984. synapse/storage/schema/main/delta/59/16federation_inbound_staging.sql +51 -0
  985. synapse/storage/schema/main/delta/60/01recreate_stream_ordering.sql.postgres +45 -0
  986. synapse/storage/schema/main/delta/60/02change_stream_ordering_columns.sql.postgres +30 -0
  987. synapse/storage/schema/main/delta/61/01change_appservices_txns.sql.postgres +23 -0
  988. synapse/storage/schema/main/delta/61/01insertion_event_lookups.sql +68 -0
  989. synapse/storage/schema/main/delta/61/02drop_redundant_room_depth_index.sql +37 -0
  990. synapse/storage/schema/main/delta/61/03recreate_min_depth.py +74 -0
  991. synapse/storage/schema/main/delta/62/01insertion_event_extremities.sql +43 -0
  992. synapse/storage/schema/main/delta/63/01create_registration_tokens.sql +42 -0
  993. synapse/storage/schema/main/delta/63/02delete_unlinked_email_pushers.sql +39 -0
  994. synapse/storage/schema/main/delta/63/02populate-rooms-creator.sql +36 -0
  995. synapse/storage/schema/main/delta/63/03session_store.sql +42 -0
  996. synapse/storage/schema/main/delta/63/04add_presence_stream_not_offline_index.sql +37 -0
  997. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.postgres +23 -0
  998. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.sqlite +37 -0
  999. synapse/storage/schema/main/delta/65/01msc2716_insertion_event_edges.sql +38 -0
  1000. synapse/storage/schema/main/delta/65/03remove_hidden_devices_from_device_inbox.sql +41 -0
  1001. synapse/storage/schema/main/delta/65/04_local_group_updates.sql +37 -0
  1002. synapse/storage/schema/main/delta/65/05_remove_room_stats_historical_and_user_stats_historical.sql +38 -0
  1003. synapse/storage/schema/main/delta/65/06remove_deleted_devices_from_device_inbox.sql +53 -0
  1004. synapse/storage/schema/main/delta/65/07_arbitrary_relations.sql +37 -0
  1005. synapse/storage/schema/main/delta/65/08_device_inbox_background_updates.sql +37 -0
  1006. synapse/storage/schema/main/delta/65/10_expirable_refresh_tokens.sql +47 -0
  1007. synapse/storage/schema/main/delta/65/11_devices_auth_provider_session.sql +46 -0
  1008. synapse/storage/schema/main/delta/67/01drop_public_room_list_stream.sql +37 -0
  1009. synapse/storage/schema/main/delta/68/01event_columns.sql +45 -0
  1010. synapse/storage/schema/main/delta/68/02_msc2409_add_device_id_appservice_stream_type.sql +40 -0
  1011. synapse/storage/schema/main/delta/68/03_delete_account_data_for_deactivated_accounts.sql +39 -0
  1012. synapse/storage/schema/main/delta/68/04_refresh_tokens_index_next_token_id.sql +47 -0
  1013. synapse/storage/schema/main/delta/68/04partial_state_rooms.sql +60 -0
  1014. synapse/storage/schema/main/delta/68/05_delete_non_strings_from_event_search.sql.sqlite +22 -0
  1015. synapse/storage/schema/main/delta/68/05partial_state_rooms_triggers.py +80 -0
  1016. synapse/storage/schema/main/delta/68/06_msc3202_add_device_list_appservice_stream_type.sql +42 -0
  1017. synapse/storage/schema/main/delta/69/01as_txn_seq.py +54 -0
  1018. synapse/storage/schema/main/delta/69/01device_list_oubound_by_room.sql +57 -0
  1019. synapse/storage/schema/main/delta/69/02cache_invalidation_index.sql +37 -0
  1020. synapse/storage/schema/main/delta/70/01clean_table_purged_rooms.sql +39 -0
  1021. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.postgres +43 -0
  1022. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.sqlite +47 -0
  1023. synapse/storage/schema/main/delta/71/01remove_noop_background_updates.sql +80 -0
  1024. synapse/storage/schema/main/delta/71/02event_push_summary_unique.sql +37 -0
  1025. synapse/storage/schema/main/delta/72/01add_room_type_to_state_stats.sql +38 -0
  1026. synapse/storage/schema/main/delta/72/01event_push_summary_receipt.sql +54 -0
  1027. synapse/storage/schema/main/delta/72/02event_push_actions_index.sql +38 -0
  1028. synapse/storage/schema/main/delta/72/03bg_populate_events_columns.py +57 -0
  1029. synapse/storage/schema/main/delta/72/03drop_event_reference_hashes.sql +36 -0
  1030. synapse/storage/schema/main/delta/72/03remove_groups.sql +50 -0
  1031. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.postgres +17 -0
  1032. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.sqlite +40 -0
  1033. synapse/storage/schema/main/delta/72/05receipts_event_stream_ordering.sql +38 -0
  1034. synapse/storage/schema/main/delta/72/05remove_unstable_private_read_receipts.sql +38 -0
  1035. synapse/storage/schema/main/delta/72/06add_consent_ts_to_users.sql +35 -0
  1036. synapse/storage/schema/main/delta/72/06thread_notifications.sql +49 -0
  1037. synapse/storage/schema/main/delta/72/07force_update_current_state_events_membership.py +67 -0
  1038. synapse/storage/schema/main/delta/72/07thread_receipts.sql.postgres +30 -0
  1039. synapse/storage/schema/main/delta/72/07thread_receipts.sql.sqlite +70 -0
  1040. synapse/storage/schema/main/delta/72/08begin_cache_invalidation_seq_at_2.sql.postgres +23 -0
  1041. synapse/storage/schema/main/delta/72/08thread_receipts.sql +39 -0
  1042. synapse/storage/schema/main/delta/72/09partial_indices.sql.sqlite +56 -0
  1043. synapse/storage/schema/main/delta/73/01event_failed_pull_attempts.sql +48 -0
  1044. synapse/storage/schema/main/delta/73/02add_pusher_enabled.sql +35 -0
  1045. synapse/storage/schema/main/delta/73/02room_id_indexes_for_purging.sql +41 -0
  1046. synapse/storage/schema/main/delta/73/03pusher_device_id.sql +39 -0
  1047. synapse/storage/schema/main/delta/73/03users_approved_column.sql +39 -0
  1048. synapse/storage/schema/main/delta/73/04partial_join_details.sql +42 -0
  1049. synapse/storage/schema/main/delta/73/04pending_device_list_updates.sql +47 -0
  1050. synapse/storage/schema/main/delta/73/05old_push_actions.sql.postgres +22 -0
  1051. synapse/storage/schema/main/delta/73/05old_push_actions.sql.sqlite +24 -0
  1052. synapse/storage/schema/main/delta/73/06thread_notifications_thread_id_idx.sql +42 -0
  1053. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.postgres +23 -0
  1054. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.sqlite +76 -0
  1055. synapse/storage/schema/main/delta/73/09partial_joined_via_destination.sql +37 -0
  1056. synapse/storage/schema/main/delta/73/09threads_table.sql +49 -0
  1057. synapse/storage/schema/main/delta/73/10_update_sqlite_fts4_tokenizer.py +71 -0
  1058. synapse/storage/schema/main/delta/73/10login_tokens.sql +54 -0
  1059. synapse/storage/schema/main/delta/73/11event_search_room_id_n_distinct.sql.postgres +33 -0
  1060. synapse/storage/schema/main/delta/73/12refactor_device_list_outbound_pokes.sql +72 -0
  1061. synapse/storage/schema/main/delta/73/13add_device_lists_index.sql +39 -0
  1062. synapse/storage/schema/main/delta/73/20_un_partial_stated_room_stream.sql +51 -0
  1063. synapse/storage/schema/main/delta/73/21_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  1064. synapse/storage/schema/main/delta/73/22_rebuild_user_dir_stats.sql +48 -0
  1065. synapse/storage/schema/main/delta/73/22_un_partial_stated_event_stream.sql +53 -0
  1066. synapse/storage/schema/main/delta/73/23_fix_thread_index.sql +52 -0
  1067. synapse/storage/schema/main/delta/73/23_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  1068. synapse/storage/schema/main/delta/73/24_events_jump_to_date_index.sql +36 -0
  1069. synapse/storage/schema/main/delta/73/25drop_presence.sql +36 -0
  1070. synapse/storage/schema/main/delta/74/01_user_directory_stale_remote_users.sql +58 -0
  1071. synapse/storage/schema/main/delta/74/02_set_device_id_for_pushers_bg_update.sql +38 -0
  1072. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.postgres +29 -0
  1073. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.sqlite +23 -0
  1074. synapse/storage/schema/main/delta/74/03_room_membership_index.sql +38 -0
  1075. synapse/storage/schema/main/delta/74/04_delete_e2e_backup_keys_for_deactivated_users.sql +36 -0
  1076. synapse/storage/schema/main/delta/74/04_membership_tables_event_stream_ordering_triggers.py +87 -0
  1077. synapse/storage/schema/main/delta/74/05_events_txn_id_device_id.sql +72 -0
  1078. synapse/storage/schema/main/delta/74/90COMMENTS_destinations.sql.postgres +52 -0
  1079. synapse/storage/schema/main/delta/76/01_add_profiles_full_user_id_column.sql +39 -0
  1080. synapse/storage/schema/main/delta/76/02_add_user_filters_full_user_id_column.sql +39 -0
  1081. synapse/storage/schema/main/delta/76/03_per_user_experimental_features.sql +46 -0
  1082. synapse/storage/schema/main/delta/76/04_add_room_forgetter.sql +43 -0
  1083. synapse/storage/schema/main/delta/77/01_add_profiles_not_valid_check.sql.postgres +16 -0
  1084. synapse/storage/schema/main/delta/77/02_add_user_filters_not_valid_check.sql.postgres +16 -0
  1085. synapse/storage/schema/main/delta/77/03bg_populate_full_user_id_profiles.sql +35 -0
  1086. synapse/storage/schema/main/delta/77/04bg_populate_full_user_id_user_filters.sql +35 -0
  1087. synapse/storage/schema/main/delta/77/05thread_notifications_backfill.sql +67 -0
  1088. synapse/storage/schema/main/delta/77/06thread_notifications_not_null.sql.sqlite +102 -0
  1089. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions.sql.postgres +27 -0
  1090. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions_staging.sql.postgres +27 -0
  1091. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_summary.sql.postgres +29 -0
  1092. synapse/storage/schema/main/delta/77/14bg_indices_event_stream_ordering.sql +39 -0
  1093. synapse/storage/schema/main/delta/78/01_validate_and_update_profiles.py +99 -0
  1094. synapse/storage/schema/main/delta/78/02_validate_and_update_user_filters.py +100 -0
  1095. synapse/storage/schema/main/delta/78/03_remove_unused_indexes_user_filters.py +72 -0
  1096. synapse/storage/schema/main/delta/78/03event_extremities_constraints.py +65 -0
  1097. synapse/storage/schema/main/delta/78/04_add_full_user_id_index_user_filters.py +32 -0
  1098. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.postgres +102 -0
  1099. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.sqlite +72 -0
  1100. synapse/storage/schema/main/delta/79/04_mitigate_stream_ordering_update_race.py +70 -0
  1101. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.postgres +69 -0
  1102. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.sqlite +65 -0
  1103. synapse/storage/schema/main/delta/80/01_users_alter_locked.sql +35 -0
  1104. synapse/storage/schema/main/delta/80/02_read_write_locks_unlogged.sql.postgres +30 -0
  1105. synapse/storage/schema/main/delta/80/02_scheduled_tasks.sql +47 -0
  1106. synapse/storage/schema/main/delta/80/03_read_write_locks_triggers.sql.postgres +37 -0
  1107. synapse/storage/schema/main/delta/80/04_read_write_locks_deadlock.sql.postgres +71 -0
  1108. synapse/storage/schema/main/delta/82/02_scheduled_tasks_index.sql +35 -0
  1109. synapse/storage/schema/main/delta/82/04_add_indices_for_purging_rooms.sql +39 -0
  1110. synapse/storage/schema/main/delta/82/05gaps.sql +44 -0
  1111. synapse/storage/schema/main/delta/83/01_drop_old_tables.sql +43 -0
  1112. synapse/storage/schema/main/delta/83/03_instance_name_receipts.sql.sqlite +17 -0
  1113. synapse/storage/schema/main/delta/83/05_cross_signing_key_update_grant.sql +34 -0
  1114. synapse/storage/schema/main/delta/83/06_event_push_summary_room.sql +36 -0
  1115. synapse/storage/schema/main/delta/84/01_auth_links_stats.sql.postgres +20 -0
  1116. synapse/storage/schema/main/delta/84/02_auth_links_index.sql +16 -0
  1117. synapse/storage/schema/main/delta/84/03_auth_links_analyze.sql.postgres +16 -0
  1118. synapse/storage/schema/main/delta/84/04_access_token_index.sql +15 -0
  1119. synapse/storage/schema/main/delta/85/01_add_suspended.sql +14 -0
  1120. synapse/storage/schema/main/delta/85/02_add_instance_names.sql +27 -0
  1121. synapse/storage/schema/main/delta/85/03_new_sequences.sql.postgres +54 -0
  1122. synapse/storage/schema/main/delta/85/04_cleanup_device_federation_outbox.sql +15 -0
  1123. synapse/storage/schema/main/delta/85/05_add_instance_names_converted_pos.sql +16 -0
  1124. synapse/storage/schema/main/delta/85/06_add_room_reports.sql +20 -0
  1125. synapse/storage/schema/main/delta/86/01_authenticate_media.sql +15 -0
  1126. synapse/storage/schema/main/delta/86/02_receipts_event_id_index.sql +15 -0
  1127. synapse/storage/schema/main/delta/87/01_sliding_sync_memberships.sql +169 -0
  1128. synapse/storage/schema/main/delta/87/02_per_connection_state.sql +81 -0
  1129. synapse/storage/schema/main/delta/87/03_current_state_index.sql +19 -0
  1130. synapse/storage/schema/main/delta/88/01_add_delayed_events.sql +43 -0
  1131. synapse/storage/schema/main/delta/88/01_custom_profile_fields.sql +15 -0
  1132. synapse/storage/schema/main/delta/88/02_fix_sliding_sync_membership_snapshots_forgotten_column.sql +21 -0
  1133. synapse/storage/schema/main/delta/88/03_add_otk_ts_added_index.sql +18 -0
  1134. synapse/storage/schema/main/delta/88/04_current_state_delta_index.sql +18 -0
  1135. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.postgres +19 -0
  1136. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.sqlite +19 -0
  1137. synapse/storage/schema/main/delta/88/05_sliding_sync_room_config_index.sql +20 -0
  1138. synapse/storage/schema/main/delta/88/06_events_received_ts_index.sql +17 -0
  1139. synapse/storage/schema/main/delta/89/01_sliding_sync_membership_snapshot_index.sql +15 -0
  1140. synapse/storage/schema/main/delta/90/01_add_column_participant_room_memberships_table.sql +16 -0
  1141. synapse/storage/schema/main/delta/91/01_media_hash.sql +28 -0
  1142. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.postgres +16 -0
  1143. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.sqlite +16 -0
  1144. synapse/storage/schema/main/delta/92/02_remove_populate_participant_bg_update.sql +17 -0
  1145. synapse/storage/schema/main/delta/92/04_ss_membership_snapshot_idx.sql +16 -0
  1146. synapse/storage/schema/main/delta/92/04_thread_subscriptions.sql +59 -0
  1147. synapse/storage/schema/main/delta/92/04_thread_subscriptions_seq.sql.postgres +19 -0
  1148. synapse/storage/schema/main/delta/92/05_fixup_max_depth_cap.sql +17 -0
  1149. synapse/storage/schema/main/delta/92/05_thread_subscriptions_comments.sql.postgres +18 -0
  1150. synapse/storage/schema/main/delta/92/06_device_federation_inbox_index.sql +16 -0
  1151. synapse/storage/schema/main/delta/92/06_threads_last_sent_stream_ordering_comments.sql.postgres +24 -0
  1152. synapse/storage/schema/main/delta/92/07_add_user_reports.sql +22 -0
  1153. synapse/storage/schema/main/delta/92/07_event_txn_id_device_id_txn_id2.sql +15 -0
  1154. synapse/storage/schema/main/delta/92/08_room_ban_redactions.sql +21 -0
  1155. synapse/storage/schema/main/delta/92/08_thread_subscriptions_seq_fixup.sql.postgres +19 -0
  1156. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql +20 -0
  1157. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql.postgres +18 -0
  1158. synapse/storage/schema/main/delta/93/01_add_delayed_events.sql +15 -0
  1159. synapse/storage/schema/main/delta/93/02_sliding_sync_members.sql +60 -0
  1160. synapse/storage/schema/main/delta/93/03_sss_pos_last_used.sql +27 -0
  1161. synapse/storage/schema/main/full_schemas/72/full.sql.postgres +1344 -0
  1162. synapse/storage/schema/main/full_schemas/72/full.sql.sqlite +646 -0
  1163. synapse/storage/schema/state/delta/23/drop_state_index.sql +35 -0
  1164. synapse/storage/schema/state/delta/32/remove_state_indices.sql +38 -0
  1165. synapse/storage/schema/state/delta/35/add_state_index.sql +36 -0
  1166. synapse/storage/schema/state/delta/35/state.sql +41 -0
  1167. synapse/storage/schema/state/delta/35/state_dedupe.sql +36 -0
  1168. synapse/storage/schema/state/delta/47/state_group_seq.py +38 -0
  1169. synapse/storage/schema/state/delta/56/state_group_room_idx.sql +36 -0
  1170. synapse/storage/schema/state/delta/61/02state_groups_state_n_distinct.sql.postgres +34 -0
  1171. synapse/storage/schema/state/delta/70/08_state_group_edges_unique.sql +36 -0
  1172. synapse/storage/schema/state/delta/89/01_state_groups_deletion.sql +39 -0
  1173. synapse/storage/schema/state/delta/90/02_delete_unreferenced_state_groups.sql +16 -0
  1174. synapse/storage/schema/state/delta/90/03_remove_old_deletion_bg_update.sql +15 -0
  1175. synapse/storage/schema/state/full_schemas/72/full.sql.postgres +30 -0
  1176. synapse/storage/schema/state/full_schemas/72/full.sql.sqlite +20 -0
  1177. synapse/storage/types.py +183 -0
  1178. synapse/storage/util/__init__.py +20 -0
  1179. synapse/storage/util/id_generators.py +928 -0
  1180. synapse/storage/util/partial_state_events_tracker.py +194 -0
  1181. synapse/storage/util/sequence.py +315 -0
  1182. synapse/streams/__init__.py +43 -0
  1183. synapse/streams/config.py +91 -0
  1184. synapse/streams/events.py +203 -0
  1185. synapse/synapse_rust/__init__.pyi +3 -0
  1186. synapse/synapse_rust/acl.pyi +20 -0
  1187. synapse/synapse_rust/events.pyi +136 -0
  1188. synapse/synapse_rust/http_client.pyi +32 -0
  1189. synapse/synapse_rust/push.pyi +86 -0
  1190. synapse/synapse_rust/rendezvous.pyi +30 -0
  1191. synapse/synapse_rust/segmenter.pyi +1 -0
  1192. synapse/synapse_rust.abi3.so +0 -0
  1193. synapse/types/__init__.py +1600 -0
  1194. synapse/types/handlers/__init__.py +93 -0
  1195. synapse/types/handlers/policy_server.py +16 -0
  1196. synapse/types/handlers/sliding_sync.py +1004 -0
  1197. synapse/types/rest/__init__.py +25 -0
  1198. synapse/types/rest/client/__init__.py +413 -0
  1199. synapse/types/state.py +634 -0
  1200. synapse/types/storage/__init__.py +66 -0
  1201. synapse/util/__init__.py +160 -0
  1202. synapse/util/async_helpers.py +1048 -0
  1203. synapse/util/background_queue.py +142 -0
  1204. synapse/util/batching_queue.py +203 -0
  1205. synapse/util/caches/__init__.py +300 -0
  1206. synapse/util/caches/cached_call.py +143 -0
  1207. synapse/util/caches/deferred_cache.py +530 -0
  1208. synapse/util/caches/descriptors.py +692 -0
  1209. synapse/util/caches/dictionary_cache.py +346 -0
  1210. synapse/util/caches/expiringcache.py +250 -0
  1211. synapse/util/caches/lrucache.py +976 -0
  1212. synapse/util/caches/response_cache.py +323 -0
  1213. synapse/util/caches/stream_change_cache.py +370 -0
  1214. synapse/util/caches/treecache.py +189 -0
  1215. synapse/util/caches/ttlcache.py +197 -0
  1216. synapse/util/cancellation.py +63 -0
  1217. synapse/util/check_dependencies.py +335 -0
  1218. synapse/util/clock.py +592 -0
  1219. synapse/util/daemonize.py +165 -0
  1220. synapse/util/distributor.py +157 -0
  1221. synapse/util/duration.py +117 -0
  1222. synapse/util/events.py +134 -0
  1223. synapse/util/file_consumer.py +164 -0
  1224. synapse/util/frozenutils.py +57 -0
  1225. synapse/util/gai_resolver.py +178 -0
  1226. synapse/util/hash.py +38 -0
  1227. synapse/util/httpresourcetree.py +108 -0
  1228. synapse/util/iterutils.py +190 -0
  1229. synapse/util/json.py +56 -0
  1230. synapse/util/linked_list.py +156 -0
  1231. synapse/util/logcontext.py +46 -0
  1232. synapse/util/logformatter.py +28 -0
  1233. synapse/util/macaroons.py +325 -0
  1234. synapse/util/manhole.py +191 -0
  1235. synapse/util/metrics.py +339 -0
  1236. synapse/util/module_loader.py +116 -0
  1237. synapse/util/msisdn.py +51 -0
  1238. synapse/util/patch_inline_callbacks.py +250 -0
  1239. synapse/util/pydantic_models.py +63 -0
  1240. synapse/util/ratelimitutils.py +422 -0
  1241. synapse/util/retryutils.py +339 -0
  1242. synapse/util/rlimit.py +42 -0
  1243. synapse/util/rust.py +164 -0
  1244. synapse/util/sentinel.py +21 -0
  1245. synapse/util/stringutils.py +293 -0
  1246. synapse/util/task_scheduler.py +494 -0
  1247. synapse/util/templates.py +126 -0
  1248. synapse/util/threepids.py +123 -0
  1249. synapse/util/wheel_timer.py +112 -0
  1250. synapse/visibility.py +869 -0
  1251. synmark/__init__.py +47 -0
  1252. synmark/__main__.py +128 -0
  1253. synmark/suites/__init__.py +9 -0
  1254. synmark/suites/logging.py +154 -0
  1255. synmark/suites/lrucache.py +48 -0
  1256. synmark/suites/lrucache_evict.py +49 -0
  1257. sytest-blacklist +33 -0
  1258. tests/__init__.py +29 -0
  1259. tests/api/__init__.py +0 -0
  1260. tests/api/test_auth.py +548 -0
  1261. tests/api/test_errors.py +46 -0
  1262. tests/api/test_filtering.py +622 -0
  1263. tests/api/test_ratelimiting.py +505 -0
  1264. tests/api/test_urls.py +81 -0
  1265. tests/app/__init__.py +0 -0
  1266. tests/app/test_homeserver_shutdown.py +271 -0
  1267. tests/app/test_homeserver_start.py +49 -0
  1268. tests/app/test_openid_listener.py +139 -0
  1269. tests/app/test_phone_stats_home.py +248 -0
  1270. tests/appservice/__init__.py +20 -0
  1271. tests/appservice/test_api.py +253 -0
  1272. tests/appservice/test_appservice.py +259 -0
  1273. tests/appservice/test_scheduler.py +477 -0
  1274. tests/config/__init__.py +20 -0
  1275. tests/config/test___main__.py +38 -0
  1276. tests/config/test_api.py +146 -0
  1277. tests/config/test_appservice.py +48 -0
  1278. tests/config/test_background_update.py +65 -0
  1279. tests/config/test_base.py +151 -0
  1280. tests/config/test_cache.py +193 -0
  1281. tests/config/test_database.py +42 -0
  1282. tests/config/test_generate.py +72 -0
  1283. tests/config/test_load.py +322 -0
  1284. tests/config/test_oauth_delegation.py +454 -0
  1285. tests/config/test_ratelimiting.py +77 -0
  1286. tests/config/test_registration_config.py +203 -0
  1287. tests/config/test_room_directory.py +203 -0
  1288. tests/config/test_server.py +248 -0
  1289. tests/config/test_tls.py +209 -0
  1290. tests/config/test_util.py +59 -0
  1291. tests/config/test_workers.py +332 -0
  1292. tests/config/utils.py +66 -0
  1293. tests/crypto/__init__.py +20 -0
  1294. tests/crypto/test_event_signing.py +109 -0
  1295. tests/crypto/test_keyring.py +737 -0
  1296. tests/events/__init__.py +0 -0
  1297. tests/events/test_auto_accept_invites.py +827 -0
  1298. tests/events/test_presence_router.py +540 -0
  1299. tests/events/test_snapshot.py +121 -0
  1300. tests/events/test_utils.py +986 -0
  1301. tests/federation/__init__.py +0 -0
  1302. tests/federation/test_complexity.py +257 -0
  1303. tests/federation/test_federation_catch_up.py +585 -0
  1304. tests/federation/test_federation_client.py +316 -0
  1305. tests/federation/test_federation_devices.py +161 -0
  1306. tests/federation/test_federation_media.py +295 -0
  1307. tests/federation/test_federation_out_of_band_membership.py +671 -0
  1308. tests/federation/test_federation_sender.py +956 -0
  1309. tests/federation/test_federation_server.py +631 -0
  1310. tests/federation/transport/__init__.py +0 -0
  1311. tests/federation/transport/server/__init__.py +20 -0
  1312. tests/federation/transport/server/test__base.py +156 -0
  1313. tests/federation/transport/test_client.py +157 -0
  1314. tests/federation/transport/test_knocking.py +323 -0
  1315. tests/federation/transport/test_server.py +74 -0
  1316. tests/handlers/__init__.py +0 -0
  1317. tests/handlers/oidc_test_key.p8 +5 -0
  1318. tests/handlers/oidc_test_key.pub.pem +4 -0
  1319. tests/handlers/test_admin.py +361 -0
  1320. tests/handlers/test_appservice.py +1336 -0
  1321. tests/handlers/test_auth.py +248 -0
  1322. tests/handlers/test_cas.py +239 -0
  1323. tests/handlers/test_deactivate_account.py +485 -0
  1324. tests/handlers/test_device.py +665 -0
  1325. tests/handlers/test_directory.py +613 -0
  1326. tests/handlers/test_e2e_keys.py +2025 -0
  1327. tests/handlers/test_e2e_room_keys.py +569 -0
  1328. tests/handlers/test_federation.py +794 -0
  1329. tests/handlers/test_federation_event.py +1181 -0
  1330. tests/handlers/test_message.py +322 -0
  1331. tests/handlers/test_oauth_delegation.py +1314 -0
  1332. tests/handlers/test_oidc.py +1688 -0
  1333. tests/handlers/test_password_providers.py +987 -0
  1334. tests/handlers/test_presence.py +2144 -0
  1335. tests/handlers/test_profile.py +401 -0
  1336. tests/handlers/test_receipts.py +342 -0
  1337. tests/handlers/test_register.py +880 -0
  1338. tests/handlers/test_room.py +108 -0
  1339. tests/handlers/test_room_list.py +93 -0
  1340. tests/handlers/test_room_member.py +764 -0
  1341. tests/handlers/test_room_policy.py +468 -0
  1342. tests/handlers/test_room_summary.py +1248 -0
  1343. tests/handlers/test_saml.py +427 -0
  1344. tests/handlers/test_send_email.py +230 -0
  1345. tests/handlers/test_sliding_sync.py +5065 -0
  1346. tests/handlers/test_sso.py +152 -0
  1347. tests/handlers/test_stats.py +594 -0
  1348. tests/handlers/test_sync.py +1275 -0
  1349. tests/handlers/test_typing.py +557 -0
  1350. tests/handlers/test_user_directory.py +1435 -0
  1351. tests/handlers/test_worker_lock.py +126 -0
  1352. tests/http/__init__.py +196 -0
  1353. tests/http/ca.crt +19 -0
  1354. tests/http/ca.key +27 -0
  1355. tests/http/federation/__init__.py +19 -0
  1356. tests/http/federation/test_matrix_federation_agent.py +1855 -0
  1357. tests/http/federation/test_srv_resolver.py +220 -0
  1358. tests/http/server/__init__.py +20 -0
  1359. tests/http/server/_base.py +621 -0
  1360. tests/http/server.key +27 -0
  1361. tests/http/test_additional_resource.py +76 -0
  1362. tests/http/test_client.py +422 -0
  1363. tests/http/test_endpoint.py +62 -0
  1364. tests/http/test_matrixfederationclient.py +1092 -0
  1365. tests/http/test_proxy.py +75 -0
  1366. tests/http/test_proxyagent.py +1008 -0
  1367. tests/http/test_servlet.py +145 -0
  1368. tests/http/test_simple_client.py +188 -0
  1369. tests/http/test_site.py +247 -0
  1370. tests/logging/__init__.py +42 -0
  1371. tests/logging/test_loggers.py +127 -0
  1372. tests/logging/test_opentracing.py +524 -0
  1373. tests/logging/test_remote_handler.py +184 -0
  1374. tests/logging/test_terse_json.py +253 -0
  1375. tests/media/__init__.py +20 -0
  1376. tests/media/test_base.py +88 -0
  1377. tests/media/test_filepath.py +602 -0
  1378. tests/media/test_html_preview.py +565 -0
  1379. tests/media/test_media_retention.py +299 -0
  1380. tests/media/test_media_storage.py +1401 -0
  1381. tests/media/test_oembed.py +172 -0
  1382. tests/media/test_url_previewer.py +120 -0
  1383. tests/metrics/__init__.py +0 -0
  1384. tests/metrics/test_background_process_metrics.py +21 -0
  1385. tests/metrics/test_metrics.py +407 -0
  1386. tests/metrics/test_phone_home_stats.py +263 -0
  1387. tests/module_api/__init__.py +0 -0
  1388. tests/module_api/test_account_data_manager.py +171 -0
  1389. tests/module_api/test_api.py +1035 -0
  1390. tests/module_api/test_event_unsigned_addition.py +66 -0
  1391. tests/module_api/test_spamchecker.py +286 -0
  1392. tests/push/__init__.py +0 -0
  1393. tests/push/test_bulk_push_rule_evaluator.py +652 -0
  1394. tests/push/test_email.py +570 -0
  1395. tests/push/test_http.py +1247 -0
  1396. tests/push/test_presentable_names.py +238 -0
  1397. tests/push/test_push_rule_evaluator.py +1069 -0
  1398. tests/replication/__init__.py +20 -0
  1399. tests/replication/_base.py +619 -0
  1400. tests/replication/http/__init__.py +20 -0
  1401. tests/replication/http/test__base.py +113 -0
  1402. tests/replication/storage/__init__.py +20 -0
  1403. tests/replication/storage/_base.py +85 -0
  1404. tests/replication/storage/test_events.py +299 -0
  1405. tests/replication/tcp/__init__.py +19 -0
  1406. tests/replication/tcp/streams/__init__.py +19 -0
  1407. tests/replication/tcp/streams/test_account_data.py +133 -0
  1408. tests/replication/tcp/streams/test_events.py +565 -0
  1409. tests/replication/tcp/streams/test_federation.py +117 -0
  1410. tests/replication/tcp/streams/test_partial_state.py +72 -0
  1411. tests/replication/tcp/streams/test_receipts.py +110 -0
  1412. tests/replication/tcp/streams/test_thread_subscriptions.py +157 -0
  1413. tests/replication/tcp/streams/test_to_device.py +112 -0
  1414. tests/replication/tcp/streams/test_typing.py +223 -0
  1415. tests/replication/tcp/test_commands.py +50 -0
  1416. tests/replication/tcp/test_handler.py +211 -0
  1417. tests/replication/test_auth.py +120 -0
  1418. tests/replication/test_client_reader_shard.py +101 -0
  1419. tests/replication/test_federation_ack.py +88 -0
  1420. tests/replication/test_federation_sender_shard.py +352 -0
  1421. tests/replication/test_module_cache_invalidation.py +89 -0
  1422. tests/replication/test_multi_media_repo.py +496 -0
  1423. tests/replication/test_pusher_shard.py +192 -0
  1424. tests/replication/test_sharded_event_persister.py +332 -0
  1425. tests/replication/test_sharded_receipts.py +250 -0
  1426. tests/rest/__init__.py +20 -0
  1427. tests/rest/admin/__init__.py +19 -0
  1428. tests/rest/admin/test_admin.py +614 -0
  1429. tests/rest/admin/test_background_updates.py +375 -0
  1430. tests/rest/admin/test_device.py +600 -0
  1431. tests/rest/admin/test_event.py +74 -0
  1432. tests/rest/admin/test_event_reports.py +781 -0
  1433. tests/rest/admin/test_federation.py +863 -0
  1434. tests/rest/admin/test_jwks.py +106 -0
  1435. tests/rest/admin/test_media.py +1091 -0
  1436. tests/rest/admin/test_registration_tokens.py +729 -0
  1437. tests/rest/admin/test_room.py +3626 -0
  1438. tests/rest/admin/test_scheduled_tasks.py +192 -0
  1439. tests/rest/admin/test_server_notice.py +753 -0
  1440. tests/rest/admin/test_statistics.py +523 -0
  1441. tests/rest/admin/test_user.py +6061 -0
  1442. tests/rest/admin/test_username_available.py +82 -0
  1443. tests/rest/client/__init__.py +20 -0
  1444. tests/rest/client/sliding_sync/__init__.py +13 -0
  1445. tests/rest/client/sliding_sync/test_connection_tracking.py +505 -0
  1446. tests/rest/client/sliding_sync/test_extension_account_data.py +1056 -0
  1447. tests/rest/client/sliding_sync/test_extension_e2ee.py +459 -0
  1448. tests/rest/client/sliding_sync/test_extension_receipts.py +934 -0
  1449. tests/rest/client/sliding_sync/test_extension_thread_subscriptions.py +497 -0
  1450. tests/rest/client/sliding_sync/test_extension_to_device.py +294 -0
  1451. tests/rest/client/sliding_sync/test_extension_typing.py +500 -0
  1452. tests/rest/client/sliding_sync/test_extensions.py +306 -0
  1453. tests/rest/client/sliding_sync/test_lists_filters.py +1975 -0
  1454. tests/rest/client/sliding_sync/test_room_subscriptions.py +303 -0
  1455. tests/rest/client/sliding_sync/test_rooms_invites.py +528 -0
  1456. tests/rest/client/sliding_sync/test_rooms_meta.py +1338 -0
  1457. tests/rest/client/sliding_sync/test_rooms_required_state.py +2247 -0
  1458. tests/rest/client/sliding_sync/test_rooms_timeline.py +718 -0
  1459. tests/rest/client/sliding_sync/test_sliding_sync.py +1688 -0
  1460. tests/rest/client/test_account.py +1543 -0
  1461. tests/rest/client/test_account_data.py +81 -0
  1462. tests/rest/client/test_auth.py +1508 -0
  1463. tests/rest/client/test_auth_metadata.py +145 -0
  1464. tests/rest/client/test_capabilities.py +318 -0
  1465. tests/rest/client/test_consent.py +138 -0
  1466. tests/rest/client/test_delayed_events.py +553 -0
  1467. tests/rest/client/test_devices.py +634 -0
  1468. tests/rest/client/test_directory.py +249 -0
  1469. tests/rest/client/test_ephemeral_message.py +113 -0
  1470. tests/rest/client/test_events.py +165 -0
  1471. tests/rest/client/test_filter.py +124 -0
  1472. tests/rest/client/test_identity.py +67 -0
  1473. tests/rest/client/test_keys.py +516 -0
  1474. tests/rest/client/test_login.py +1881 -0
  1475. tests/rest/client/test_login_token_request.py +175 -0
  1476. tests/rest/client/test_matrixrtc.py +105 -0
  1477. tests/rest/client/test_media.py +3156 -0
  1478. tests/rest/client/test_models.py +83 -0
  1479. tests/rest/client/test_mutual_rooms.py +235 -0
  1480. tests/rest/client/test_notifications.py +231 -0
  1481. tests/rest/client/test_owned_state.py +308 -0
  1482. tests/rest/client/test_password_policy.py +186 -0
  1483. tests/rest/client/test_power_levels.py +295 -0
  1484. tests/rest/client/test_presence.py +149 -0
  1485. tests/rest/client/test_profile.py +925 -0
  1486. tests/rest/client/test_push_rule_attrs.py +510 -0
  1487. tests/rest/client/test_read_marker.py +151 -0
  1488. tests/rest/client/test_receipts.py +287 -0
  1489. tests/rest/client/test_redactions.py +657 -0
  1490. tests/rest/client/test_register.py +1314 -0
  1491. tests/rest/client/test_relations.py +1954 -0
  1492. tests/rest/client/test_rendezvous.py +468 -0
  1493. tests/rest/client/test_reporting.py +324 -0
  1494. tests/rest/client/test_retention.py +389 -0
  1495. tests/rest/client/test_rooms.py +5486 -0
  1496. tests/rest/client/test_sendtodevice.py +271 -0
  1497. tests/rest/client/test_shadow_banned.py +335 -0
  1498. tests/rest/client/test_sync.py +1147 -0
  1499. tests/rest/client/test_tags.py +161 -0
  1500. tests/rest/client/test_third_party_rules.py +1076 -0
  1501. tests/rest/client/test_thread_subscriptions.py +351 -0
  1502. tests/rest/client/test_transactions.py +204 -0
  1503. tests/rest/client/test_typing.py +114 -0
  1504. tests/rest/client/test_upgrade_room.py +433 -0
  1505. tests/rest/client/utils.py +985 -0
  1506. tests/rest/key/__init__.py +0 -0
  1507. tests/rest/key/v2/__init__.py +0 -0
  1508. tests/rest/key/v2/test_remote_key_resource.py +282 -0
  1509. tests/rest/media/__init__.py +19 -0
  1510. tests/rest/media/test_domain_blocking.py +148 -0
  1511. tests/rest/media/test_url_preview.py +1445 -0
  1512. tests/rest/synapse/__init__.py +12 -0
  1513. tests/rest/synapse/client/__init__.py +12 -0
  1514. tests/rest/synapse/client/test_federation_whitelist.py +118 -0
  1515. tests/rest/synapse/mas/__init__.py +12 -0
  1516. tests/rest/synapse/mas/_base.py +43 -0
  1517. tests/rest/synapse/mas/test_devices.py +693 -0
  1518. tests/rest/synapse/mas/test_users.py +1399 -0
  1519. tests/rest/test_health.py +35 -0
  1520. tests/rest/test_well_known.py +155 -0
  1521. tests/scripts/__init__.py +0 -0
  1522. tests/scripts/test_new_matrix_user.py +172 -0
  1523. tests/server.py +1374 -0
  1524. tests/server_notices/__init__.py +241 -0
  1525. tests/server_notices/test_consent.py +111 -0
  1526. tests/server_notices/test_resource_limits_server_notices.py +409 -0
  1527. tests/state/__init__.py +0 -0
  1528. tests/state/test_v2.py +1096 -0
  1529. tests/state/test_v21.py +506 -0
  1530. tests/storage/__init__.py +0 -0
  1531. tests/storage/databases/__init__.py +20 -0
  1532. tests/storage/databases/main/__init__.py +20 -0
  1533. tests/storage/databases/main/test_cache.py +124 -0
  1534. tests/storage/databases/main/test_deviceinbox.py +323 -0
  1535. tests/storage/databases/main/test_end_to_end_keys.py +127 -0
  1536. tests/storage/databases/main/test_events_worker.py +594 -0
  1537. tests/storage/databases/main/test_lock.py +499 -0
  1538. tests/storage/databases/main/test_metrics.py +88 -0
  1539. tests/storage/databases/main/test_receipts.py +218 -0
  1540. tests/storage/databases/main/test_room.py +192 -0
  1541. tests/storage/test__base.py +178 -0
  1542. tests/storage/test_account_data.py +186 -0
  1543. tests/storage/test_appservice.py +568 -0
  1544. tests/storage/test_background_update.py +671 -0
  1545. tests/storage/test_base.py +813 -0
  1546. tests/storage/test_cleanup_extrems.py +396 -0
  1547. tests/storage/test_client_ips.py +788 -0
  1548. tests/storage/test_database.py +288 -0
  1549. tests/storage/test_devices.py +353 -0
  1550. tests/storage/test_directory.py +74 -0
  1551. tests/storage/test_e2e_room_keys.py +87 -0
  1552. tests/storage/test_end_to_end_keys.py +120 -0
  1553. tests/storage/test_event_chain.py +826 -0
  1554. tests/storage/test_event_federation.py +1433 -0
  1555. tests/storage/test_event_push_actions.py +809 -0
  1556. tests/storage/test_events.py +591 -0
  1557. tests/storage/test_events_bg_updates.py +156 -0
  1558. tests/storage/test_id_generators.py +791 -0
  1559. tests/storage/test_invite_rule.py +171 -0
  1560. tests/storage/test_main.py +56 -0
  1561. tests/storage/test_monthly_active_users.py +500 -0
  1562. tests/storage/test_profile.py +134 -0
  1563. tests/storage/test_purge.py +459 -0
  1564. tests/storage/test_receipts.py +309 -0
  1565. tests/storage/test_redaction.py +462 -0
  1566. tests/storage/test_registration.py +277 -0
  1567. tests/storage/test_relations.py +118 -0
  1568. tests/storage/test_rollback_worker.py +132 -0
  1569. tests/storage/test_room.py +69 -0
  1570. tests/storage/test_room_search.py +383 -0
  1571. tests/storage/test_roommember.py +812 -0
  1572. tests/storage/test_sliding_sync_tables.py +5187 -0
  1573. tests/storage/test_state.py +959 -0
  1574. tests/storage/test_state_deletion.py +475 -0
  1575. tests/storage/test_stream.py +1533 -0
  1576. tests/storage/test_thread_subscriptions.py +369 -0
  1577. tests/storage/test_transactions.py +77 -0
  1578. tests/storage/test_txn_limit.py +49 -0
  1579. tests/storage/test_unsafe_locale.py +67 -0
  1580. tests/storage/test_user_directory.py +691 -0
  1581. tests/storage/test_user_filters.py +101 -0
  1582. tests/storage/util/__init__.py +20 -0
  1583. tests/storage/util/test_partial_state_events_tracker.py +181 -0
  1584. tests/synapse_rust/__init__.py +11 -0
  1585. tests/synapse_rust/test_http_client.py +225 -0
  1586. tests/test_distributor.py +74 -0
  1587. tests/test_event_auth.py +921 -0
  1588. tests/test_mau.py +347 -0
  1589. tests/test_phone_home.py +102 -0
  1590. tests/test_rust.py +11 -0
  1591. tests/test_server.py +557 -0
  1592. tests/test_state.py +902 -0
  1593. tests/test_terms_auth.py +128 -0
  1594. tests/test_types.py +201 -0
  1595. tests/test_utils/__init__.py +161 -0
  1596. tests/test_utils/event_injection.py +150 -0
  1597. tests/test_utils/html_parsers.py +59 -0
  1598. tests/test_utils/logging_setup.py +74 -0
  1599. tests/test_utils/oidc.py +370 -0
  1600. tests/test_visibility.py +712 -0
  1601. tests/types/__init__.py +0 -0
  1602. tests/types/test_init.py +51 -0
  1603. tests/types/test_state.py +627 -0
  1604. tests/unittest.py +1108 -0
  1605. tests/util/__init__.py +20 -0
  1606. tests/util/caches/__init__.py +20 -0
  1607. tests/util/caches/test_cached_call.py +168 -0
  1608. tests/util/caches/test_deferred_cache.py +317 -0
  1609. tests/util/caches/test_descriptors.py +1110 -0
  1610. tests/util/caches/test_response_cache.py +225 -0
  1611. tests/util/caches/test_ttlcache.py +90 -0
  1612. tests/util/test_async_helpers.py +808 -0
  1613. tests/util/test_background_queue.py +117 -0
  1614. tests/util/test_batching_queue.py +252 -0
  1615. tests/util/test_check_dependencies.py +243 -0
  1616. tests/util/test_dict_cache.py +130 -0
  1617. tests/util/test_events.py +118 -0
  1618. tests/util/test_expiring_cache.py +113 -0
  1619. tests/util/test_file_consumer.py +199 -0
  1620. tests/util/test_itertools.py +190 -0
  1621. tests/util/test_linearizer.py +264 -0
  1622. tests/util/test_logcontext.py +715 -0
  1623. tests/util/test_logformatter.py +44 -0
  1624. tests/util/test_lrucache.py +479 -0
  1625. tests/util/test_macaroons.py +126 -0
  1626. tests/util/test_mutable_overlay_mapping.py +189 -0
  1627. tests/util/test_ratelimitutils.py +146 -0
  1628. tests/util/test_retryutils.py +314 -0
  1629. tests/util/test_rwlock.py +401 -0
  1630. tests/util/test_stream_change_cache.py +304 -0
  1631. tests/util/test_stringutils.py +86 -0
  1632. tests/util/test_task_scheduler.py +227 -0
  1633. tests/util/test_threepids.py +55 -0
  1634. tests/util/test_treecache.py +93 -0
  1635. tests/util/test_wheel_timer.py +82 -0
  1636. tests/utils.py +342 -0
@@ -0,0 +1,2420 @@
1
+ #
2
+ # This file is licensed under the Affero General Public License (AGPL) version 3.
3
+ #
4
+ # Copyright 2021 The Matrix.org Foundation C.I.C.
5
+ # Copyright (C) 2023 New Vector, Ltd
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU Affero General Public License as
9
+ # published by the Free Software Foundation, either version 3 of the
10
+ # License, or (at your option) any later version.
11
+ #
12
+ # See the GNU Affero General Public License for more details:
13
+ # <https://www.gnu.org/licenses/agpl-3.0.html>.
14
+ #
15
+ # Originally licensed under the Apache License, Version 2.0:
16
+ # <http://www.apache.org/licenses/LICENSE-2.0>.
17
+ #
18
+ # [This file includes modifications made by New Vector Limited]
19
+ #
20
+ #
21
+
22
+ import collections
23
+ import itertools
24
+ import logging
25
+ from http import HTTPStatus
26
+ from typing import (
27
+ TYPE_CHECKING,
28
+ Collection,
29
+ Container,
30
+ Iterable,
31
+ Sequence,
32
+ )
33
+
34
+ from prometheus_client import Counter, Histogram
35
+
36
+ from synapse import event_auth
37
+ from synapse.api.constants import (
38
+ EventContentFields,
39
+ EventTypes,
40
+ GuestAccess,
41
+ Membership,
42
+ RejectedReason,
43
+ RoomEncryptionAlgorithms,
44
+ )
45
+ from synapse.api.errors import (
46
+ AuthError,
47
+ Codes,
48
+ EventSizeError,
49
+ FederationError,
50
+ FederationPullAttemptBackoffError,
51
+ HttpResponseException,
52
+ PartialStateConflictError,
53
+ RequestSendFailed,
54
+ SynapseError,
55
+ )
56
+ from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion, RoomVersions
57
+ from synapse.event_auth import (
58
+ auth_types_for_event,
59
+ check_state_dependent_auth_rules,
60
+ check_state_independent_auth_rules,
61
+ validate_event_for_room_version,
62
+ )
63
+ from synapse.events import EventBase
64
+ from synapse.events.snapshot import (
65
+ EventContext,
66
+ EventPersistencePair,
67
+ UnpersistedEventContextBase,
68
+ )
69
+ from synapse.federation.federation_client import InvalidResponseError, PulledPduInfo
70
+ from synapse.logging.context import nested_logging_context
71
+ from synapse.logging.opentracing import (
72
+ SynapseTags,
73
+ set_tag,
74
+ start_active_span,
75
+ tag_args,
76
+ trace,
77
+ )
78
+ from synapse.metrics import SERVER_NAME_LABEL
79
+ from synapse.replication.http.federation import (
80
+ ReplicationFederationSendEventsRestServlet,
81
+ )
82
+ from synapse.state import StateResolutionStore
83
+ from synapse.storage.databases.main.events_worker import EventRedactBehaviour
84
+ from synapse.types import (
85
+ PersistedEventPosition,
86
+ RoomStreamToken,
87
+ StateMap,
88
+ StrCollection,
89
+ UserID,
90
+ get_domain_from_id,
91
+ )
92
+ from synapse.types.state import StateFilter
93
+ from synapse.util.async_helpers import Linearizer, concurrently_execute
94
+ from synapse.util.duration import Duration
95
+ from synapse.util.iterutils import batch_iter, partition, sorted_topologically
96
+ from synapse.util.retryutils import NotRetryingDestination
97
+ from synapse.util.stringutils import shortstr
98
+
99
+ if TYPE_CHECKING:
100
+ from synapse.server import HomeServer
101
+
102
+
103
+ logger = logging.getLogger(__name__)
104
+
105
+ soft_failed_event_counter = Counter(
106
+ "synapse_federation_soft_failed_events_total",
107
+ "Events received over federation that we marked as soft_failed",
108
+ labelnames=[SERVER_NAME_LABEL],
109
+ )
110
+
111
+ # Added to debug performance and track progress on optimizations
112
+ backfill_processing_after_timer = Histogram(
113
+ "synapse_federation_backfill_processing_after_time_seconds",
114
+ "sec",
115
+ labelnames=[SERVER_NAME_LABEL],
116
+ buckets=(
117
+ 0.1,
118
+ 0.25,
119
+ 0.5,
120
+ 1.0,
121
+ 2.5,
122
+ 5.0,
123
+ 7.5,
124
+ 10.0,
125
+ 15.0,
126
+ 20.0,
127
+ 25.0,
128
+ 30.0,
129
+ 40.0,
130
+ 50.0,
131
+ 60.0,
132
+ 80.0,
133
+ 100.0,
134
+ 120.0,
135
+ 150.0,
136
+ 180.0,
137
+ "+Inf",
138
+ ),
139
+ )
140
+
141
+
142
+ class FederationEventHandler:
143
+ """Handles events that originated from federation.
144
+
145
+ Responsible for handing incoming events and passing them on to the rest
146
+ of the homeserver (including auth and state conflict resolutions)
147
+ """
148
+
149
+ def __init__(self, hs: "HomeServer"):
150
+ self.server_name = hs.hostname
151
+ self.hs = hs
152
+ self._clock = hs.get_clock()
153
+ self._store = hs.get_datastores().main
154
+ self._state_store = hs.get_datastores().state
155
+ self._state_deletion_store = hs.get_datastores().state_deletion
156
+ self._storage_controllers = hs.get_storage_controllers()
157
+ self._state_storage_controller = self._storage_controllers.state
158
+
159
+ self._state_handler = hs.get_state_handler()
160
+ self._event_creation_handler = hs.get_event_creation_handler()
161
+ self._event_auth_handler = hs.get_event_auth_handler()
162
+ self._message_handler = hs.get_message_handler()
163
+ self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()
164
+ self._state_resolution_handler = hs.get_state_resolution_handler()
165
+ # avoid a circular dependency by deferring execution here
166
+ self._get_room_member_handler = hs.get_room_member_handler
167
+
168
+ self._federation_client = hs.get_federation_client()
169
+ self._third_party_event_rules = (
170
+ hs.get_module_api_callbacks().third_party_event_rules
171
+ )
172
+ self._notifier = hs.get_notifier()
173
+
174
+ self._server_name = hs.hostname
175
+ self._is_mine_id = hs.is_mine_id
176
+ self._is_mine_server_name = hs.is_mine_server_name
177
+ self._instance_name = hs.get_instance_name()
178
+
179
+ self._config = hs.config
180
+ self._ephemeral_messages_enabled = hs.config.server.enable_ephemeral_messages
181
+
182
+ self._send_events = ReplicationFederationSendEventsRestServlet.make_client(hs)
183
+ self._device_list_updater = hs.get_device_handler().device_list_updater
184
+
185
+ # When joining a room we need to queue any events for that room up.
186
+ # For each room, a list of (pdu, origin) tuples.
187
+ # TODO: replace this with something more elegant, probably based around the
188
+ # federation event staging area.
189
+ self.room_queues: dict[str, list[tuple[EventBase, str]]] = {}
190
+
191
+ self._room_pdu_linearizer = Linearizer(name="fed_room_pdu", clock=self._clock)
192
+
193
+ async def on_receive_pdu(self, origin: str, pdu: EventBase) -> None:
194
+ """Process a PDU received via a federation /send/ transaction
195
+
196
+ Args:
197
+ origin: server which initiated the /send/ transaction. Will
198
+ be used to fetch missing events or state.
199
+ pdu: received PDU
200
+ """
201
+
202
+ # We should never see any outliers here.
203
+ assert not pdu.internal_metadata.outlier
204
+
205
+ room_id = pdu.room_id
206
+ event_id = pdu.event_id
207
+
208
+ # We reprocess pdus when we have seen them only as outliers
209
+ existing = await self._store.get_event(
210
+ event_id, allow_none=True, allow_rejected=True
211
+ )
212
+
213
+ # FIXME: Currently we fetch an event again when we already have it
214
+ # if it has been marked as an outlier.
215
+ if existing:
216
+ if not existing.internal_metadata.is_outlier():
217
+ logger.info(
218
+ "Ignoring received event %s which we have already seen", event_id
219
+ )
220
+ return
221
+ if pdu.internal_metadata.is_outlier():
222
+ logger.info(
223
+ "Ignoring received outlier %s which we already have as an outlier",
224
+ event_id,
225
+ )
226
+ return
227
+ logger.info("De-outliering event %s", event_id)
228
+
229
+ # do some initial sanity-checking of the event. In particular, make
230
+ # sure it doesn't have hundreds of prev_events or auth_events, which
231
+ # could cause a huge state resolution or cascade of event fetches.
232
+ try:
233
+ self._sanity_check_event(pdu)
234
+ except SynapseError as err:
235
+ logger.warning("Received event failed sanity checks")
236
+ raise FederationError("ERROR", err.code, err.msg, affected=pdu.event_id)
237
+
238
+ # If we are currently in the process of joining this room, then we
239
+ # queue up events for later processing.
240
+ if room_id in self.room_queues:
241
+ logger.info(
242
+ "Queuing PDU from %s for now: join in progress",
243
+ origin,
244
+ )
245
+ self.room_queues[room_id].append((pdu, origin))
246
+ return
247
+
248
+ # If we're not in the room just ditch the event entirely (and not
249
+ # invited). This is probably an old server that has come back and thinks
250
+ # we're still in the room (or we've been rejoined to the room by a state
251
+ # reset).
252
+ #
253
+ # Note that if we were never in the room then we would have already
254
+ # dropped the event, since we wouldn't know the room version.
255
+ is_in_room = await self._event_auth_handler.is_host_in_room(
256
+ room_id, self.server_name
257
+ )
258
+ if not is_in_room:
259
+ # Check if this is a leave event rescinding an invite
260
+ if (
261
+ pdu.type == EventTypes.Member
262
+ and pdu.membership == Membership.LEAVE
263
+ and pdu.state_key != pdu.sender
264
+ and self._is_mine_id(pdu.state_key)
265
+ ):
266
+ (
267
+ membership,
268
+ membership_event_id,
269
+ ) = await self._store.get_local_current_membership_for_user_in_room(
270
+ pdu.state_key, pdu.room_id
271
+ )
272
+ if (
273
+ membership == Membership.INVITE
274
+ and membership_event_id
275
+ and membership_event_id
276
+ in pdu.auth_event_ids() # The invite should be in the auth events of the rescission.
277
+ ):
278
+ invite_event = await self._store.get_event(
279
+ membership_event_id, allow_none=True
280
+ )
281
+
282
+ # We cannot fully auth the rescission event, but we can
283
+ # check if the sender of the leave event is the same as the
284
+ # invite.
285
+ #
286
+ # Technically, a room admin could rescind the invite, but we
287
+ # have no way of knowing who is and isn't a room admin.
288
+ if invite_event and pdu.sender == invite_event.sender:
289
+ # Handle the rescission event
290
+ pdu.internal_metadata.outlier = True
291
+ pdu.internal_metadata.out_of_band_membership = True
292
+ context = EventContext.for_outlier(self._storage_controllers)
293
+ await self.persist_events_and_notify(room_id, [(pdu, context)])
294
+ return
295
+
296
+ logger.info(
297
+ "Ignoring PDU from %s as we're not in the room",
298
+ origin,
299
+ )
300
+ return None
301
+
302
+ # Try to fetch any missing prev events to fill in gaps in the graph
303
+ prevs = set(pdu.prev_event_ids())
304
+ seen = await self._store.have_events_in_timeline(prevs)
305
+ missing_prevs = prevs - seen
306
+
307
+ if missing_prevs:
308
+ # We only backfill backwards to the min depth.
309
+ min_depth = await self._store.get_min_depth(pdu.room_id)
310
+ logger.debug("min_depth: %d", min_depth)
311
+
312
+ if min_depth is not None and pdu.depth > min_depth:
313
+ # If we're missing stuff, ensure we only fetch stuff one
314
+ # at a time.
315
+ logger.info(
316
+ "Acquiring room lock to fetch %d missing prev_events: %s",
317
+ len(missing_prevs),
318
+ shortstr(missing_prevs),
319
+ )
320
+ async with self._room_pdu_linearizer.queue(pdu.room_id):
321
+ logger.info(
322
+ "Acquired room lock to fetch %d missing prev_events",
323
+ len(missing_prevs),
324
+ )
325
+
326
+ try:
327
+ await self._get_missing_events_for_pdu(
328
+ origin, pdu, prevs, min_depth
329
+ )
330
+ except Exception as e:
331
+ raise Exception(
332
+ "Error fetching missing prev_events for %s: %s"
333
+ % (event_id, e)
334
+ ) from e
335
+
336
+ # Update the set of things we've seen after trying to
337
+ # fetch the missing stuff
338
+ seen = await self._store.have_events_in_timeline(prevs)
339
+ missing_prevs = prevs - seen
340
+
341
+ if not missing_prevs:
342
+ logger.info("Found all missing prev_events")
343
+
344
+ if missing_prevs:
345
+ # since this event was pushed to us, it is possible for it to
346
+ # become the only forward-extremity in the room, and we would then
347
+ # trust its state to be the state for the whole room. This is very
348
+ # bad. Further, if the event was pushed to us, there is no excuse
349
+ # for us not to have all the prev_events. (XXX: apart from
350
+ # min_depth?)
351
+ #
352
+ # We therefore reject any such events.
353
+ logger.warning(
354
+ "Rejecting: failed to fetch %d prev events: %s",
355
+ len(missing_prevs),
356
+ shortstr(missing_prevs),
357
+ )
358
+ raise FederationError(
359
+ "ERROR",
360
+ 403,
361
+ (
362
+ "Your server isn't divulging details about prev_events "
363
+ "referenced in this event."
364
+ ),
365
+ affected=pdu.event_id,
366
+ )
367
+
368
+ try:
369
+ context = await self._state_handler.compute_event_context(pdu)
370
+ await self._process_received_pdu(origin, pdu, context)
371
+ except PartialStateConflictError:
372
+ # The room was un-partial stated while we were processing the PDU.
373
+ # Try once more, with full state this time.
374
+ logger.info(
375
+ "Room %s was un-partial stated while processing the PDU, trying again.",
376
+ room_id,
377
+ )
378
+ context = await self._state_handler.compute_event_context(pdu)
379
+ await self._process_received_pdu(origin, pdu, context)
380
+
381
+ async def on_send_membership_event(
382
+ self, origin: str, event: EventBase
383
+ ) -> EventPersistencePair:
384
+ """
385
+ We have received a join/leave/knock event for a room via send_join/leave/knock.
386
+
387
+ Verify that event and send it into the room on the remote homeserver's behalf.
388
+
389
+ This is quite similar to on_receive_pdu, with the following principal
390
+ differences:
391
+ * only membership events are permitted (and only events with
392
+ sender==state_key -- ie, no kicks or bans)
393
+ * *We* send out the event on behalf of the remote server.
394
+ * We enforce the membership restrictions of restricted rooms.
395
+ * Rejected events result in an exception rather than being stored.
396
+
397
+ There are also other differences, however it is not clear if these are by
398
+ design or omission. In particular, we do not attempt to backfill any missing
399
+ prev_events.
400
+
401
+ Args:
402
+ origin: The homeserver of the remote (joining/invited/knocking) user.
403
+ event: The member event that has been signed by the remote homeserver.
404
+
405
+ Returns:
406
+ The event and context of the event after inserting it into the room graph.
407
+
408
+ Raises:
409
+ RuntimeError if any prev_events are missing
410
+ SynapseError if the event is not accepted into the room
411
+ PartialStateConflictError if the room was un-partial stated in between
412
+ computing the state at the event and persisting it. The caller should
413
+ retry exactly once in this case.
414
+ """
415
+ logger.debug(
416
+ "on_send_membership_event: Got event: %s, signatures: %s",
417
+ event.event_id,
418
+ event.signatures,
419
+ )
420
+
421
+ if get_domain_from_id(event.sender) != origin:
422
+ logger.info(
423
+ "Got send_membership request for user %r from different origin %s",
424
+ event.sender,
425
+ origin,
426
+ )
427
+ raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
428
+
429
+ if event.sender != event.state_key:
430
+ raise SynapseError(400, "state_key and sender must match", Codes.BAD_JSON)
431
+
432
+ assert not event.internal_metadata.outlier
433
+
434
+ # Send this event on behalf of the other server.
435
+ #
436
+ # The remote server isn't a full participant in the room at this point, so
437
+ # may not have an up-to-date list of the other homeservers participating in
438
+ # the room, so we send it on their behalf.
439
+ event.internal_metadata.send_on_behalf_of = origin
440
+
441
+ context = await self._state_handler.compute_event_context(event)
442
+ await self._check_event_auth(origin, event, context)
443
+ if context.rejected:
444
+ raise SynapseError(
445
+ 403, f"{event.membership} event was rejected", Codes.FORBIDDEN
446
+ )
447
+
448
+ # for joins, we need to check the restrictions of restricted rooms
449
+ if event.membership == Membership.JOIN:
450
+ await self.check_join_restrictions(context, event)
451
+
452
+ # for knock events, we run the third-party event rules. It's not entirely clear
453
+ # why we don't do this for other sorts of membership events.
454
+ if event.membership == Membership.KNOCK:
455
+ event_allowed, _ = await self._third_party_event_rules.check_event_allowed(
456
+ event, context
457
+ )
458
+ if not event_allowed:
459
+ logger.info("Sending of knock %s forbidden by third-party rules", event)
460
+ raise SynapseError(
461
+ 403, "This event is not allowed in this context", Codes.FORBIDDEN
462
+ )
463
+
464
+ # all looks good, we can persist the event.
465
+
466
+ # First, precalculate the joined hosts so that the federation sender doesn't
467
+ # need to.
468
+ await self._event_creation_handler.cache_joined_hosts_for_events(
469
+ [(event, context)]
470
+ )
471
+
472
+ await self._check_for_soft_fail(event, context=context, origin=origin)
473
+ await self._run_push_actions_and_persist_event(event, context)
474
+ return event, context
475
+
476
+ async def check_join_restrictions(
477
+ self,
478
+ context: UnpersistedEventContextBase,
479
+ event: EventBase,
480
+ ) -> None:
481
+ """Check that restrictions in restricted join rules are matched
482
+
483
+ Called when we receive a join event via send_join.
484
+
485
+ Raises an auth error if the restrictions are not matched.
486
+ """
487
+ prev_state_ids = await context.get_prev_state_ids()
488
+
489
+ # Check if the user is already in the room or invited to the room.
490
+ user_id = event.state_key
491
+ prev_member_event_id = prev_state_ids.get((EventTypes.Member, user_id), None)
492
+ prev_membership = None
493
+ if prev_member_event_id:
494
+ prev_member_event = await self._store.get_event(prev_member_event_id)
495
+ prev_membership = prev_member_event.membership
496
+
497
+ # Check if the member should be allowed access via membership in a space.
498
+ await self._event_auth_handler.check_restricted_join_rules(
499
+ prev_state_ids,
500
+ event.room_version,
501
+ user_id,
502
+ prev_membership,
503
+ )
504
+
505
+ @trace
506
+ async def process_remote_join(
507
+ self,
508
+ origin: str,
509
+ room_id: str,
510
+ auth_events: list[EventBase],
511
+ state: list[EventBase],
512
+ event: EventBase,
513
+ room_version: RoomVersion,
514
+ partial_state: bool,
515
+ ) -> int:
516
+ """Persists the events returned by a send_join
517
+
518
+ Checks the auth chain is valid (and passes auth checks) for the
519
+ state and event. Then persists all of the events.
520
+ Notifies about the persisted events where appropriate.
521
+
522
+ Args:
523
+ origin: Where the events came from
524
+ room_id:
525
+ auth_events
526
+ state
527
+ event
528
+ room_version: The room version we expect this room to have, and
529
+ will raise if it doesn't match the version in the create event.
530
+ partial_state: True if the state omits non-critical membership events
531
+
532
+ Returns:
533
+ The stream ID after which all events have been persisted.
534
+
535
+ Raises:
536
+ SynapseError if the response is in some way invalid.
537
+ PartialStateConflictError if the homeserver is already in the room and it
538
+ has been un-partial stated.
539
+ """
540
+ create_event = None
541
+ for e in state:
542
+ if (e.type, e.state_key) == (EventTypes.Create, ""):
543
+ create_event = e
544
+ break
545
+
546
+ if create_event is None:
547
+ # If the state doesn't have a create event then the room is
548
+ # invalid, and it would fail auth checks anyway.
549
+ raise SynapseError(400, "No create event in state")
550
+
551
+ room_version_id = create_event.content.get(
552
+ "room_version", RoomVersions.V1.identifier
553
+ )
554
+
555
+ if room_version.identifier != room_version_id:
556
+ raise SynapseError(400, "Room version mismatch")
557
+
558
+ # persist the auth chain and state events.
559
+ #
560
+ # any invalid events here will be marked as rejected, and we'll carry on.
561
+ #
562
+ # any events whose auth events are missing (ie, not in the send_join response,
563
+ # and not already in our db) will just be ignored. This is correct behaviour,
564
+ # because the reason that auth_events are missing might be due to us being
565
+ # unable to validate their signatures. The fact that we can't validate their
566
+ # signatures right now doesn't mean that we will *never* be able to, so it
567
+ # is premature to reject them.
568
+ #
569
+ await self._auth_and_persist_outliers(
570
+ room_id, itertools.chain(auth_events, state)
571
+ )
572
+
573
+ # and now persist the join event itself.
574
+ logger.info(
575
+ "Peristing join-via-remote %s (partial_state: %s)", event, partial_state
576
+ )
577
+ with nested_logging_context(suffix=event.event_id):
578
+ if partial_state:
579
+ # When handling a second partial state join into a partial state room,
580
+ # the returned state will exclude the membership from the first join. To
581
+ # preserve prior memberships, we try to compute the partial state before
582
+ # the event ourselves if we know about any of the prev events.
583
+ #
584
+ # When we don't know about any of the prev events, it's fine to just use
585
+ # the returned state, since the new join will create a new forward
586
+ # extremity, and leave the forward extremity containing our prior
587
+ # memberships alone.
588
+ prev_event_ids = set(event.prev_event_ids())
589
+ seen_event_ids = await self._store.have_events_in_timeline(
590
+ prev_event_ids
591
+ )
592
+ missing_event_ids = prev_event_ids - seen_event_ids
593
+
594
+ state_maps_to_resolve: list[StateMap[str]] = []
595
+
596
+ # Fetch the state after the prev events that we know about.
597
+ state_maps_to_resolve.extend(
598
+ (
599
+ await self._state_storage_controller.get_state_groups_ids(
600
+ room_id, seen_event_ids, await_full_state=False
601
+ )
602
+ ).values()
603
+ )
604
+
605
+ # When there are prev events we do not have the state for, we state
606
+ # resolve with the state returned by the remote homeserver.
607
+ if missing_event_ids or len(state_maps_to_resolve) == 0:
608
+ state_maps_to_resolve.append(
609
+ {(e.type, e.state_key): e.event_id for e in state}
610
+ )
611
+
612
+ state_ids_before_event = (
613
+ await self._state_resolution_handler.resolve_events_with_store(
614
+ event.room_id,
615
+ room_version.identifier,
616
+ state_maps_to_resolve,
617
+ event_map=None,
618
+ state_res_store=StateResolutionStore(
619
+ self._store, self._state_deletion_store
620
+ ),
621
+ )
622
+ )
623
+ else:
624
+ state_ids_before_event = {
625
+ (e.type, e.state_key): e.event_id for e in state
626
+ }
627
+
628
+ context = await self._state_handler.compute_event_context(
629
+ event,
630
+ state_ids_before_event=state_ids_before_event,
631
+ partial_state=partial_state,
632
+ )
633
+
634
+ await self._check_event_auth(origin, event, context)
635
+ if context.rejected:
636
+ raise SynapseError(403, "Join event was rejected")
637
+
638
+ # the remote server is responsible for sending our join event to the rest
639
+ # of the federation. Indeed, attempting to do so will result in problems
640
+ # when we try to look up the state before the join (to get the server list)
641
+ # and discover that we do not have it.
642
+ event.internal_metadata.proactively_send = False
643
+
644
+ stream_id_after_persist = await self.persist_events_and_notify(
645
+ room_id, [(event, context)]
646
+ )
647
+
648
+ return stream_id_after_persist
649
+
650
+ async def update_state_for_partial_state_event(
651
+ self, destination: str, event: EventBase
652
+ ) -> None:
653
+ """Recalculate the state at an event as part of a de-partial-stating process
654
+
655
+ Args:
656
+ destination: server to request full state from
657
+ event: partial-state event to be de-partial-stated
658
+
659
+ Raises:
660
+ FederationPullAttemptBackoffError if we are are deliberately not attempting
661
+ to pull the given event over federation because we've already done so
662
+ recently and are backing off.
663
+ FederationError if we fail to request state from the remote server.
664
+ """
665
+ logger.info("Updating state for %s", event.event_id)
666
+ with nested_logging_context(suffix=event.event_id):
667
+ # if we have all the event's prev_events, then we can work out the
668
+ # state based on their states. Otherwise, we request it from the destination
669
+ # server.
670
+ #
671
+ # This is the same operation as we do when we receive a regular event
672
+ # over federation.
673
+ context = await self._compute_event_context_with_maybe_missing_prevs(
674
+ destination, event
675
+ )
676
+ if context.partial_state:
677
+ # this can happen if some or all of the event's prev_events still have
678
+ # partial state. We were careful to only pick events from the db without
679
+ # partial-state prev events, so that implies that a prev event has
680
+ # been persisted (with partial state) since we did the query.
681
+ #
682
+ # So, let's just ignore `event` for now; when we re-run the db query
683
+ # we should instead get its partial-state prev event, which we will
684
+ # de-partial-state, and then come back to event.
685
+ logger.warning(
686
+ "%s still has prev_events with partial state: can't de-partial-state it yet",
687
+ event.event_id,
688
+ )
689
+ return
690
+
691
+ # since the state at this event has changed, we should now re-evaluate
692
+ # whether it should have been rejected. We must already have all of the
693
+ # auth events (from last time we went round this path), so there is no
694
+ # need to pass the origin.
695
+ await self._check_event_auth(None, event, context)
696
+
697
+ await self._store.update_state_for_partial_state_event(event, context)
698
+ self._state_storage_controller.notify_event_un_partial_stated(
699
+ event.event_id
700
+ )
701
+ # Notify that there's a new row in the un_partial_stated_events stream.
702
+ self._notifier.notify_replication()
703
+
704
+ @trace
705
+ async def backfill(
706
+ self, dest: str, room_id: str, limit: int, extremities: StrCollection
707
+ ) -> None:
708
+ """Trigger a backfill request to `dest` for the given `room_id`
709
+
710
+ This will attempt to get more events from the remote. If the other side
711
+ has no new events to offer, this will return an empty list.
712
+
713
+ As the events are received, we check their signatures, and also do some
714
+ sanity-checking on them. If any of the backfilled events are invalid,
715
+ this method throws a SynapseError.
716
+
717
+ We might also raise an InvalidResponseError if the response from the remote
718
+ server is just bogus.
719
+
720
+ TODO: make this more useful to distinguish failures of the remote
721
+ server from invalid events (there is probably no point in trying to
722
+ re-fetch invalid events from every other HS in the room.)
723
+ """
724
+ if self._is_mine_server_name(dest):
725
+ raise SynapseError(400, "Can't backfill from self.")
726
+
727
+ events = await self._federation_client.backfill(
728
+ dest, room_id, limit=limit, extremities=extremities
729
+ )
730
+
731
+ if not events:
732
+ return
733
+
734
+ with backfill_processing_after_timer.labels(
735
+ **{SERVER_NAME_LABEL: self.server_name}
736
+ ).time():
737
+ # if there are any events in the wrong room, the remote server is buggy and
738
+ # should not be trusted.
739
+ for ev in events:
740
+ if ev.room_id != room_id:
741
+ raise InvalidResponseError(
742
+ f"Remote server {dest} returned event {ev.event_id} which is in "
743
+ f"room {ev.room_id}, when we were backfilling in {room_id}"
744
+ )
745
+
746
+ await self._process_pulled_events(
747
+ dest,
748
+ events,
749
+ backfilled=True,
750
+ )
751
+
752
+ @trace
753
+ async def _get_missing_events_for_pdu(
754
+ self, origin: str, pdu: EventBase, prevs: set[str], min_depth: int
755
+ ) -> None:
756
+ """
757
+ Args:
758
+ origin: Origin of the pdu. Will be called to get the missing events
759
+ pdu: received pdu
760
+ prevs: List of event ids which we are missing
761
+ min_depth: Minimum depth of events to return.
762
+ """
763
+
764
+ room_id = pdu.room_id
765
+ event_id = pdu.event_id
766
+
767
+ seen = await self._store.have_events_in_timeline(prevs)
768
+
769
+ if not prevs - seen:
770
+ return
771
+
772
+ latest_frozen = await self._store.get_latest_event_ids_in_room(room_id)
773
+
774
+ # We add the prev events that we have seen to the latest
775
+ # list to ensure the remote server doesn't give them to us
776
+ latest = seen | latest_frozen
777
+
778
+ logger.info(
779
+ "Requesting missing events between %s and %s",
780
+ shortstr(latest),
781
+ event_id,
782
+ )
783
+
784
+ # XXX: we set timeout to 10s to help workaround
785
+ # https://github.com/matrix-org/synapse/issues/1733.
786
+ # The reason is to avoid holding the linearizer lock
787
+ # whilst processing inbound /send transactions, causing
788
+ # FDs to stack up and block other inbound transactions
789
+ # which empirically can currently take up to 30 minutes.
790
+ #
791
+ # N.B. this explicitly disables retry attempts.
792
+ #
793
+ # N.B. this also increases our chances of falling back to
794
+ # fetching fresh state for the room if the missing event
795
+ # can't be found, which slightly reduces our security.
796
+ # it may also increase our DAG extremity count for the room,
797
+ # causing additional state resolution? See https://github.com/matrix-org/synapse/issues/1760.
798
+ # However, fetching state doesn't hold the linearizer lock
799
+ # apparently.
800
+ #
801
+ # see https://github.com/matrix-org/synapse/pull/1744
802
+ #
803
+ # ----
804
+ #
805
+ # Update richvdh 2018/09/18: There are a number of problems with timing this
806
+ # request out aggressively on the client side:
807
+ #
808
+ # - it plays badly with the server-side rate-limiter, which starts tarpitting you
809
+ # if you send too many requests at once, so you end up with the server carefully
810
+ # working through the backlog of your requests, which you have already timed
811
+ # out.
812
+ #
813
+ # - for this request in particular, we now (as of
814
+ # https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the
815
+ # server can't produce a plausible-looking set of prev_events - so we becone
816
+ # much more likely to reject the event.
817
+ #
818
+ # - contrary to what it says above, we do *not* fall back to fetching fresh state
819
+ # for the room if get_missing_events times out. Rather, we give up processing
820
+ # the PDU whose prevs we are missing, which then makes it much more likely that
821
+ # we'll end up back here for the *next* PDU in the list, which exacerbates the
822
+ # problem.
823
+ #
824
+ # - the aggressive 10s timeout was introduced to deal with incoming federation
825
+ # requests taking 8 hours to process. It's not entirely clear why that was going
826
+ # on; certainly there were other issues causing traffic storms which are now
827
+ # resolved, and I think in any case we may be more sensible about our locking
828
+ # now. We're *certainly* more sensible about our logging.
829
+ #
830
+ # All that said: Let's try increasing the timeout to 60s and see what happens.
831
+
832
+ try:
833
+ missing_events = await self._federation_client.get_missing_events(
834
+ origin,
835
+ room_id,
836
+ earliest_events_ids=list(latest),
837
+ latest_events=[pdu],
838
+ limit=10,
839
+ min_depth=min_depth,
840
+ timeout=60000,
841
+ )
842
+ except (RequestSendFailed, HttpResponseException, NotRetryingDestination) as e:
843
+ # We failed to get the missing events, but since we need to handle
844
+ # the case of `get_missing_events` not returning the necessary
845
+ # events anyway, it is safe to simply log the error and continue.
846
+ logger.warning("Failed to get prev_events: %s", e)
847
+ return
848
+
849
+ logger.info("Got %d prev_events", len(missing_events))
850
+ await self._process_pulled_events(origin, missing_events, backfilled=False)
851
+
852
+ @trace
853
+ async def _process_pulled_events(
854
+ self, origin: str, events: Collection[EventBase], backfilled: bool
855
+ ) -> None:
856
+ """Process a batch of events we have pulled from a remote server
857
+
858
+ Pulls in any events required to auth the events, persists the received events,
859
+ and notifies clients, if appropriate.
860
+
861
+ Assumes the events have already had their signatures and hashes checked.
862
+
863
+ Params:
864
+ origin: The server we received these events from
865
+ events: The received events.
866
+ backfilled: True if this is part of a historical batch of events (inhibits
867
+ notification to clients, and validation of device keys.)
868
+ """
869
+ set_tag(
870
+ SynapseTags.FUNC_ARG_PREFIX + "event_ids",
871
+ str([event.event_id for event in events]),
872
+ )
873
+ set_tag(
874
+ SynapseTags.FUNC_ARG_PREFIX + "event_ids.length",
875
+ str(len(events)),
876
+ )
877
+ set_tag(SynapseTags.FUNC_ARG_PREFIX + "backfilled", str(backfilled))
878
+ logger.debug(
879
+ "processing pulled backfilled=%s events=%s",
880
+ backfilled,
881
+ [
882
+ "event_id=%s,depth=%d,body=%s,prevs=%s\n"
883
+ % (
884
+ event.event_id,
885
+ event.depth,
886
+ event.content.get("body", event.type),
887
+ event.prev_event_ids(),
888
+ )
889
+ for event in events
890
+ ],
891
+ )
892
+
893
+ # Check if we already any of these have these events.
894
+ # Note: we currently make a lookup in the database directly here rather than
895
+ # checking the event cache, due to:
896
+ # https://github.com/matrix-org/synapse/issues/13476
897
+ existing_events_map = await self._store._get_events_from_db(
898
+ [event.event_id for event in events]
899
+ )
900
+
901
+ new_events: list[EventBase] = []
902
+ for event in events:
903
+ event_id = event.event_id
904
+
905
+ # If we've already seen this event ID...
906
+ if event_id in existing_events_map:
907
+ existing_event = existing_events_map[event_id]
908
+
909
+ # ...and the event itself was not previously stored as an outlier...
910
+ if not existing_event.event.internal_metadata.is_outlier():
911
+ # ...then there's no need to persist it. We have it already.
912
+ logger.info(
913
+ "_process_pulled_event: Ignoring received event %s which we "
914
+ "have already seen",
915
+ event.event_id,
916
+ )
917
+ continue
918
+
919
+ # While we have seen this event before, it was stored as an outlier.
920
+ # We'll now persist it as a non-outlier.
921
+ logger.info("De-outliering event %s", event_id)
922
+
923
+ # Continue on with the events that are new to us.
924
+ new_events.append(event)
925
+
926
+ set_tag(
927
+ SynapseTags.RESULT_PREFIX + "new_events.length",
928
+ str(len(new_events)),
929
+ )
930
+
931
+ @trace
932
+ async def _process_new_pulled_events(new_events: Collection[EventBase]) -> None:
933
+ # We want to sort these by depth so we process them and tell clients about
934
+ # them in order. It's also more efficient to backfill this way (`depth`
935
+ # ascending) because one backfill event is likely to be the `prev_event` of
936
+ # the next event we're going to process.
937
+ sorted_events = sorted(new_events, key=lambda x: x.depth)
938
+ for ev in sorted_events:
939
+ with nested_logging_context(ev.event_id):
940
+ await self._process_pulled_event(origin, ev, backfilled=backfilled)
941
+
942
+ # Check if we've already tried to process these events at some point in the
943
+ # past. We aren't concerned with the expontntial backoff here, just whether it
944
+ # has failed to be processed before.
945
+ event_ids_with_failed_pull_attempts = (
946
+ await self._store.get_event_ids_with_failed_pull_attempts(
947
+ [event.event_id for event in new_events]
948
+ )
949
+ )
950
+
951
+ events_with_failed_pull_attempts, fresh_events = partition(
952
+ new_events, lambda e: e.event_id in event_ids_with_failed_pull_attempts
953
+ )
954
+ set_tag(
955
+ SynapseTags.FUNC_ARG_PREFIX + "events_with_failed_pull_attempts",
956
+ str(event_ids_with_failed_pull_attempts),
957
+ )
958
+ set_tag(
959
+ SynapseTags.RESULT_PREFIX + "events_with_failed_pull_attempts.length",
960
+ str(len(events_with_failed_pull_attempts)),
961
+ )
962
+ set_tag(
963
+ SynapseTags.FUNC_ARG_PREFIX + "fresh_events",
964
+ str([event.event_id for event in fresh_events]),
965
+ )
966
+ set_tag(
967
+ SynapseTags.RESULT_PREFIX + "fresh_events.length",
968
+ str(len(fresh_events)),
969
+ )
970
+
971
+ # Process previously failed backfill events in the background to not waste
972
+ # time on something that is likely to fail again.
973
+ if len(events_with_failed_pull_attempts) > 0:
974
+ self.hs.run_as_background_process(
975
+ "_process_new_pulled_events_with_failed_pull_attempts",
976
+ _process_new_pulled_events,
977
+ events_with_failed_pull_attempts,
978
+ )
979
+
980
+ # We can optimistically try to process and wait for the event to be fully
981
+ # persisted if we've never tried before.
982
+ if len(fresh_events) > 0:
983
+ await _process_new_pulled_events(fresh_events)
984
+
985
+ @trace
986
+ @tag_args
987
+ async def _process_pulled_event(
988
+ self, origin: str, event: EventBase, backfilled: bool
989
+ ) -> None:
990
+ """Process a single event that we have pulled from a remote server
991
+
992
+ Pulls in any events required to auth the event, persists the received event,
993
+ and notifies clients, if appropriate.
994
+
995
+ Assumes the event has already had its signatures and hashes checked.
996
+
997
+ This is somewhat equivalent to on_receive_pdu, but applies somewhat different
998
+ logic in the case that we are missing prev_events (in particular, it just
999
+ requests the state at that point, rather than triggering a get_missing_events) -
1000
+ so is appropriate when we have pulled the event from a remote server, rather
1001
+ than having it pushed to us.
1002
+
1003
+ Params:
1004
+ origin: The server we received this event from
1005
+ events: The received event
1006
+ backfilled: True if this is part of a historical batch of events (inhibits
1007
+ notification to clients, and validation of device keys.)
1008
+ """
1009
+ logger.info("Processing pulled event %s", event)
1010
+
1011
+ # This function should not be used to persist outliers (use something
1012
+ # else) because this does a bunch of operations that aren't necessary
1013
+ # (extra work; in particular, it makes sure we have all the prev_events
1014
+ # and resolves the state across those prev events). If you happen to run
1015
+ # into a situation where the event you're trying to process/backfill is
1016
+ # marked as an `outlier`, then you should update that spot to return an
1017
+ # `EventBase` copy that doesn't have `outlier` flag set.
1018
+ #
1019
+ # `EventBase` is used to represent both an event we have not yet
1020
+ # persisted, and one that we have persisted and now keep in the cache.
1021
+ # In an ideal world this method would only be called with the first type
1022
+ # of event, but it turns out that's not actually the case and for
1023
+ # example, you could get an event from cache that is marked as an
1024
+ # `outlier` (fix up that spot though).
1025
+ assert not event.internal_metadata.is_outlier(), (
1026
+ "Outlier event passed to _process_pulled_event. "
1027
+ "To persist an event as a non-outlier, make sure to pass in a copy without `event.internal_metadata.outlier = true`."
1028
+ )
1029
+
1030
+ event_id = event.event_id
1031
+
1032
+ try:
1033
+ self._sanity_check_event(event)
1034
+ except SynapseError as err:
1035
+ logger.warning("Event %s failed sanity check: %s", event_id, err)
1036
+ await self._store.record_event_failed_pull_attempt(
1037
+ event.room_id, event_id, str(err)
1038
+ )
1039
+ return
1040
+
1041
+ try:
1042
+ try:
1043
+ context = await self._compute_event_context_with_maybe_missing_prevs(
1044
+ origin, event
1045
+ )
1046
+ await self._process_received_pdu(
1047
+ origin,
1048
+ event,
1049
+ context,
1050
+ backfilled=backfilled,
1051
+ )
1052
+ except PartialStateConflictError:
1053
+ # The room was un-partial stated while we were processing the event.
1054
+ # Try once more, with full state this time.
1055
+ context = await self._compute_event_context_with_maybe_missing_prevs(
1056
+ origin, event
1057
+ )
1058
+
1059
+ # We ought to have full state now, barring some unlikely race where we left and
1060
+ # rejoned the room in the background.
1061
+ if context.partial_state:
1062
+ raise AssertionError(
1063
+ f"Event {event.event_id} still has a partial resolved state "
1064
+ f"after room {event.room_id} was un-partial stated"
1065
+ )
1066
+
1067
+ await self._process_received_pdu(
1068
+ origin,
1069
+ event,
1070
+ context,
1071
+ backfilled=backfilled,
1072
+ )
1073
+ except FederationPullAttemptBackoffError as exc:
1074
+ # Log a warning about why we failed to process the event (the error message
1075
+ # for `FederationPullAttemptBackoffError` is pretty good)
1076
+ logger.warning("_process_pulled_event: %s", exc)
1077
+ # We do not record a failed pull attempt when we backoff fetching a missing
1078
+ # `prev_event` because not being able to fetch the `prev_events` just means
1079
+ # we won't be able to de-outlier the pulled event. But we can still use an
1080
+ # `outlier` in the state/auth chain for another event. So we shouldn't stop
1081
+ # a downstream event from trying to pull it.
1082
+ #
1083
+ # This avoids a cascade of backoff for all events in the DAG downstream from
1084
+ # one event backoff upstream.
1085
+ except FederationError as e:
1086
+ await self._store.record_event_failed_pull_attempt(
1087
+ event.room_id, event_id, str(e)
1088
+ )
1089
+
1090
+ if e.code == 403:
1091
+ logger.warning("Pulled event %s failed history check.", event_id)
1092
+ else:
1093
+ raise
1094
+
1095
+ @trace
1096
+ async def _compute_event_context_with_maybe_missing_prevs(
1097
+ self, dest: str, event: EventBase
1098
+ ) -> EventContext:
1099
+ """Build an EventContext structure for a non-outlier event whose prev_events may
1100
+ be missing.
1101
+
1102
+ This is used when we have pulled a batch of events from a remote server, and may
1103
+ not have all the prev_events.
1104
+
1105
+ To build an EventContext, we need to calculate the state before the event. If we
1106
+ already have all the prev_events for `event`, we can simply use the state after
1107
+ the prev_events to calculate the state before `event`.
1108
+
1109
+ Otherwise, the missing prevs become new backwards extremities, and we fall back
1110
+ to asking the remote server for the state after each missing `prev_event`,
1111
+ and resolving across them.
1112
+
1113
+ That's ok provided we then resolve the state against other bits of the DAG
1114
+ before using it - in other words, that the received event `event` is not going
1115
+ to become the only forwards_extremity in the room (which will ensure that you
1116
+ can't just take over a room by sending an event, withholding its prev_events,
1117
+ and declaring yourself to be an admin in the subsequent state request).
1118
+
1119
+ In other words: we should only call this method if `event` has been *pulled*
1120
+ as part of a batch of missing prev events, or similar.
1121
+
1122
+ Params:
1123
+ dest: the remote server to ask for state at the missing prevs. Typically,
1124
+ this will be the server we got `event` from.
1125
+ event: an event to check for missing prevs.
1126
+
1127
+ Returns:
1128
+ The event context.
1129
+
1130
+ Raises:
1131
+ FederationPullAttemptBackoffError if we are are deliberately not attempting
1132
+ to pull one of the given event's `prev_event`s over federation because
1133
+ we've already done so recently and are backing off.
1134
+ FederationError if we fail to get the state from the remote server after any
1135
+ missing `prev_event`s.
1136
+ """
1137
+ room_id = event.room_id
1138
+ event_id = event.event_id
1139
+
1140
+ prevs = set(event.prev_event_ids())
1141
+ seen = await self._store.have_events_in_timeline(prevs)
1142
+ missing_prevs = prevs - seen
1143
+
1144
+ # If we've already recently attempted to pull this missing event, don't
1145
+ # try it again so soon. Since we have to fetch all of the prev_events, we can
1146
+ # bail early here if we find any to ignore.
1147
+ prevs_with_pull_backoff = (
1148
+ await self._store.get_event_ids_to_not_pull_from_backoff(
1149
+ room_id, missing_prevs
1150
+ )
1151
+ )
1152
+ if len(prevs_with_pull_backoff) > 0:
1153
+ raise FederationPullAttemptBackoffError(
1154
+ event_ids=prevs_with_pull_backoff.keys(),
1155
+ message=(
1156
+ f"While computing context for event={event_id}, not attempting to "
1157
+ f"pull missing prev_events={list(prevs_with_pull_backoff.keys())} "
1158
+ "because we already tried to pull recently (backing off)."
1159
+ ),
1160
+ retry_after_ms=(
1161
+ max(prevs_with_pull_backoff.values()) - self._clock.time_msec()
1162
+ ),
1163
+ )
1164
+
1165
+ if not missing_prevs:
1166
+ return await self._state_handler.compute_event_context(event)
1167
+
1168
+ logger.info(
1169
+ "Event %s is missing prev_events %s: calculating state for a "
1170
+ "backwards extremity",
1171
+ event_id,
1172
+ shortstr(missing_prevs),
1173
+ )
1174
+ # Calculate the state after each of the previous events, and
1175
+ # resolve them to find the correct state at the current event.
1176
+
1177
+ try:
1178
+ # Determine whether we may be about to retrieve partial state
1179
+ # Events may be un-partial stated right after we compute the partial state
1180
+ # flag, but that's okay, as long as the flag errs on the conservative side.
1181
+ partial_state_flags = await self._store.get_partial_state_events(seen)
1182
+ partial_state = any(partial_state_flags.values())
1183
+
1184
+ # state_maps is a list of mappings from (type, state_key) to event_id
1185
+ state_maps: list[StateMap[str]] = []
1186
+
1187
+ # Ask the remote server for the states we don't
1188
+ # know about
1189
+ for p in missing_prevs:
1190
+ logger.info("Requesting state after missing prev_event %s", p)
1191
+
1192
+ with nested_logging_context(p):
1193
+ # note that if any of the missing prevs share missing state or
1194
+ # auth events, the requests to fetch those events are deduped
1195
+ # by the get_pdu_cache in federation_client.
1196
+ remote_state_map = (
1197
+ await self._get_state_ids_after_missing_prev_event(
1198
+ dest, room_id, p
1199
+ )
1200
+ )
1201
+
1202
+ state_maps.append(remote_state_map)
1203
+
1204
+ # Get the state of the events we know about. We do this *after*
1205
+ # trying to fetch missing state over federation as that might fail
1206
+ # and then we can skip loading the local state.
1207
+ ours = await self._state_storage_controller.get_state_groups_ids(
1208
+ room_id, seen, await_full_state=False
1209
+ )
1210
+ state_maps.extend(ours.values())
1211
+
1212
+ # we don't need this any more, let's delete it.
1213
+ del ours
1214
+
1215
+ room_version = await self._store.get_room_version_id(room_id)
1216
+ state_map = await self._state_resolution_handler.resolve_events_with_store(
1217
+ room_id,
1218
+ room_version,
1219
+ state_maps,
1220
+ event_map={event_id: event},
1221
+ state_res_store=StateResolutionStore(
1222
+ self._store, self._state_deletion_store
1223
+ ),
1224
+ )
1225
+
1226
+ except Exception as e:
1227
+ logger.warning(
1228
+ "Error attempting to resolve state at missing prev_events: %s", e
1229
+ )
1230
+ raise FederationError(
1231
+ "ERROR",
1232
+ 403,
1233
+ "We can't get valid state history.",
1234
+ affected=event_id,
1235
+ )
1236
+ return await self._state_handler.compute_event_context(
1237
+ event, state_ids_before_event=state_map, partial_state=partial_state
1238
+ )
1239
+
1240
+ @trace
1241
+ @tag_args
1242
+ async def _get_state_ids_after_missing_prev_event(
1243
+ self,
1244
+ destination: str,
1245
+ room_id: str,
1246
+ event_id: str,
1247
+ ) -> StateMap[str]:
1248
+ """Requests all of the room state at a given event from a remote homeserver.
1249
+
1250
+ Args:
1251
+ destination: The remote homeserver to query for the state.
1252
+ room_id: The id of the room we're interested in.
1253
+ event_id: The id of the event we want the state at.
1254
+
1255
+ Returns:
1256
+ The event ids of the state *after* the given event.
1257
+
1258
+ Raises:
1259
+ InvalidResponseError: if the remote homeserver's response contains fields
1260
+ of the wrong type.
1261
+ """
1262
+
1263
+ # It would be better if we could query the difference from our known
1264
+ # state to the given `event_id` so the sending server doesn't have to
1265
+ # send as much and we don't have to process as many events. For example
1266
+ # in a room like #matrix:matrix.org, we get 200k events (77k state_events, 122k
1267
+ # auth_events) from this call.
1268
+ #
1269
+ # Tracked by https://github.com/matrix-org/synapse/issues/13618
1270
+ (
1271
+ state_event_ids,
1272
+ auth_event_ids,
1273
+ ) = await self._federation_client.get_room_state_ids(
1274
+ destination, room_id, event_id=event_id
1275
+ )
1276
+
1277
+ logger.debug(
1278
+ "state_ids returned %i state events, %i auth events",
1279
+ len(state_event_ids),
1280
+ len(auth_event_ids),
1281
+ )
1282
+
1283
+ # Start by checking events we already have in the DB
1284
+ desired_events = set(state_event_ids)
1285
+ desired_events.add(event_id)
1286
+ logger.debug("Fetching %i events from cache/store", len(desired_events))
1287
+ have_events = await self._store.have_seen_events(room_id, desired_events)
1288
+
1289
+ missing_desired_event_ids = desired_events - have_events
1290
+ logger.debug(
1291
+ "We are missing %i events (got %i)",
1292
+ len(missing_desired_event_ids),
1293
+ len(have_events),
1294
+ )
1295
+
1296
+ # We probably won't need most of the auth events, so let's just check which
1297
+ # we have for now, rather than thrashing the event cache with them all
1298
+ # unnecessarily.
1299
+
1300
+ # TODO: we probably won't actually need all of the auth events, since we
1301
+ # already have a bunch of the state events. It would be nice if the
1302
+ # federation api gave us a way of finding out which we actually need.
1303
+
1304
+ missing_auth_event_ids = set(auth_event_ids) - have_events
1305
+ missing_auth_event_ids.difference_update(
1306
+ await self._store.have_seen_events(room_id, missing_auth_event_ids)
1307
+ )
1308
+ logger.debug("We are also missing %i auth events", len(missing_auth_event_ids))
1309
+
1310
+ missing_event_ids = missing_desired_event_ids | missing_auth_event_ids
1311
+
1312
+ set_tag(
1313
+ SynapseTags.RESULT_PREFIX + "missing_auth_event_ids",
1314
+ str(missing_auth_event_ids),
1315
+ )
1316
+ set_tag(
1317
+ SynapseTags.RESULT_PREFIX + "missing_auth_event_ids.length",
1318
+ str(len(missing_auth_event_ids)),
1319
+ )
1320
+ set_tag(
1321
+ SynapseTags.RESULT_PREFIX + "missing_desired_event_ids",
1322
+ str(missing_desired_event_ids),
1323
+ )
1324
+ set_tag(
1325
+ SynapseTags.RESULT_PREFIX + "missing_desired_event_ids.length",
1326
+ str(len(missing_desired_event_ids)),
1327
+ )
1328
+
1329
+ # Making an individual request for each of 1000s of events has a lot of
1330
+ # overhead. On the other hand, we don't really want to fetch all of the events
1331
+ # if we already have most of them.
1332
+ #
1333
+ # As an arbitrary heuristic, if we are missing more than 10% of the events, then
1334
+ # we fetch the whole state.
1335
+ #
1336
+ # TODO: might it be better to have an API which lets us do an aggregate event
1337
+ # request
1338
+ if (len(missing_event_ids) * 10) >= len(auth_event_ids) + len(state_event_ids):
1339
+ logger.debug("Requesting complete state from remote")
1340
+ await self._get_state_and_persist(destination, room_id, event_id)
1341
+ else:
1342
+ logger.debug("Fetching %i events from remote", len(missing_event_ids))
1343
+ await self._get_events_and_persist(
1344
+ destination=destination, room_id=room_id, event_ids=missing_event_ids
1345
+ )
1346
+
1347
+ # We now need to fill out the state map, which involves fetching the
1348
+ # type and state key for each event ID in the state.
1349
+ state_map = {}
1350
+
1351
+ event_metadata = await self._store.get_metadata_for_events(state_event_ids)
1352
+ for state_event_id, metadata in event_metadata.items():
1353
+ if metadata.room_id != room_id:
1354
+ # This is a bogus situation, but since we may only discover it a long time
1355
+ # after it happened, we try our best to carry on, by just omitting the
1356
+ # bad events from the returned state set.
1357
+ #
1358
+ # This can happen if a remote server claims that the state or
1359
+ # auth_events at an event in room A are actually events in room B
1360
+ logger.warning(
1361
+ "Remote server %s claims event %s in room %s is an auth/state "
1362
+ "event in room %s",
1363
+ destination,
1364
+ state_event_id,
1365
+ metadata.room_id,
1366
+ room_id,
1367
+ )
1368
+ continue
1369
+
1370
+ if metadata.state_key is None:
1371
+ logger.warning(
1372
+ "Remote server gave us non-state event in state: %s", state_event_id
1373
+ )
1374
+ continue
1375
+
1376
+ state_map[(metadata.event_type, metadata.state_key)] = state_event_id
1377
+
1378
+ # if we couldn't get the prev event in question, that's a problem.
1379
+ remote_event = await self._store.get_event(
1380
+ event_id,
1381
+ allow_none=True,
1382
+ allow_rejected=True,
1383
+ redact_behaviour=EventRedactBehaviour.as_is,
1384
+ )
1385
+ if not remote_event:
1386
+ raise Exception("Unable to get missing prev_event %s" % (event_id,))
1387
+
1388
+ # missing state at that event is a warning, not a blocker
1389
+ # XXX: this doesn't sound right? it means that we'll end up with incomplete
1390
+ # state.
1391
+ failed_to_fetch = desired_events - event_metadata.keys()
1392
+ # `event_id` could be missing from `event_metadata` because it's not necessarily
1393
+ # a state event. We've already checked that we've fetched it above.
1394
+ failed_to_fetch.discard(event_id)
1395
+ if failed_to_fetch:
1396
+ logger.warning(
1397
+ "Failed to fetch missing state events for %s %s",
1398
+ event_id,
1399
+ failed_to_fetch,
1400
+ )
1401
+ set_tag(
1402
+ SynapseTags.RESULT_PREFIX + "failed_to_fetch",
1403
+ str(failed_to_fetch),
1404
+ )
1405
+ set_tag(
1406
+ SynapseTags.RESULT_PREFIX + "failed_to_fetch.length",
1407
+ str(len(failed_to_fetch)),
1408
+ )
1409
+
1410
+ if remote_event.is_state() and remote_event.rejected_reason is None:
1411
+ state_map[(remote_event.type, remote_event.state_key)] = (
1412
+ remote_event.event_id
1413
+ )
1414
+
1415
+ return state_map
1416
+
1417
+ @trace
1418
+ @tag_args
1419
+ async def _get_state_and_persist(
1420
+ self, destination: str, room_id: str, event_id: str
1421
+ ) -> None:
1422
+ """Get the complete room state at a given event, and persist any new events
1423
+ as outliers"""
1424
+ room_version = await self._store.get_room_version(room_id)
1425
+ auth_events, state_events = await self._federation_client.get_room_state(
1426
+ destination, room_id, event_id=event_id, room_version=room_version
1427
+ )
1428
+ logger.info("/state returned %i events", len(auth_events) + len(state_events))
1429
+
1430
+ await self._auth_and_persist_outliers(
1431
+ room_id, itertools.chain(auth_events, state_events)
1432
+ )
1433
+
1434
+ # we also need the event itself.
1435
+ if not await self._store.have_seen_event(room_id, event_id):
1436
+ await self._get_events_and_persist(
1437
+ destination=destination, room_id=room_id, event_ids=(event_id,)
1438
+ )
1439
+
1440
+ @trace
1441
+ async def _process_received_pdu(
1442
+ self,
1443
+ origin: str,
1444
+ event: EventBase,
1445
+ context: EventContext,
1446
+ backfilled: bool = False,
1447
+ ) -> None:
1448
+ """Called when we have a new non-outlier event.
1449
+
1450
+ This is called when we have a new event to add to the room DAG. This can be
1451
+ due to:
1452
+ * events received directly via a /send request
1453
+ * events retrieved via get_missing_events after a /send request
1454
+ * events backfilled after a client request.
1455
+
1456
+ It's not currently used for events received from incoming send_{join,knock,leave}
1457
+ requests (which go via on_send_membership_event), nor for joins created by a
1458
+ remote join dance (which go via process_remote_join).
1459
+
1460
+ We need to do auth checks and put it through the StateHandler.
1461
+
1462
+ Args:
1463
+ origin: server sending the event
1464
+
1465
+ event: event to be persisted
1466
+
1467
+ context: The `EventContext` to persist the event with.
1468
+
1469
+ backfilled: True if this is part of a historical batch of events (inhibits
1470
+ notification to clients, and validation of device keys.)
1471
+
1472
+ PartialStateConflictError: if the room was un-partial stated in between
1473
+ computing the state at the event and persisting it. The caller should
1474
+ recompute `context` and retry exactly once when this happens.
1475
+ """
1476
+ logger.debug("Processing event: %s", event)
1477
+ assert not event.internal_metadata.outlier
1478
+
1479
+ try:
1480
+ await self._check_event_auth(origin, event, context)
1481
+ except AuthError as e:
1482
+ # This happens only if we couldn't find the auth events. We'll already have
1483
+ # logged a warning, so now we just convert to a FederationError.
1484
+ raise FederationError("ERROR", e.code, e.msg, affected=event.event_id)
1485
+
1486
+ if not backfilled and not context.rejected:
1487
+ # For new (non-backfilled and non-outlier) events we check if the event
1488
+ # passes auth based on the current state. If it doesn't then we
1489
+ # "soft-fail" the event.
1490
+ await self._check_for_soft_fail(event, context=context, origin=origin)
1491
+
1492
+ await self._run_push_actions_and_persist_event(event, context, backfilled)
1493
+
1494
+ if backfilled or context.rejected:
1495
+ return
1496
+
1497
+ await self._maybe_kick_guest_users(event)
1498
+
1499
+ # For encrypted messages we check that we know about the sending device,
1500
+ # if we don't then we mark the device cache for that user as stale.
1501
+ if event.type == EventTypes.Encrypted:
1502
+ device_id = event.content.get("device_id")
1503
+ sender_key = event.content.get("sender_key")
1504
+
1505
+ cached_devices = await self._store.get_cached_devices_for_user(event.sender)
1506
+
1507
+ resync = False # Whether we should resync device lists.
1508
+
1509
+ device = None
1510
+ if device_id is not None:
1511
+ device = cached_devices.get(device_id)
1512
+ if device is None:
1513
+ logger.info(
1514
+ "Received event from remote device not in our cache: %s %s",
1515
+ event.sender,
1516
+ device_id,
1517
+ )
1518
+ resync = True
1519
+
1520
+ # We also check if the `sender_key` matches what we expect.
1521
+ if sender_key is not None:
1522
+ # Figure out what sender key we're expecting. If we know the
1523
+ # device and recognize the algorithm then we can work out the
1524
+ # exact key to expect. Otherwise check it matches any key we
1525
+ # have for that device.
1526
+
1527
+ current_keys: Container[str] = []
1528
+
1529
+ if device:
1530
+ keys = device.get("keys", {}).get("keys", {})
1531
+
1532
+ if (
1533
+ event.content.get("algorithm")
1534
+ == RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2
1535
+ ):
1536
+ # For this algorithm we expect a curve25519 key.
1537
+ key_name = "curve25519:%s" % (device_id,)
1538
+ current_keys = [keys.get(key_name)]
1539
+ else:
1540
+ # We don't know understand the algorithm, so we just
1541
+ # check it matches a key for the device.
1542
+ current_keys = keys.values()
1543
+ elif device_id:
1544
+ # We don't have any keys for the device ID.
1545
+ pass
1546
+ else:
1547
+ # The event didn't include a device ID, so we just look for
1548
+ # keys across all devices.
1549
+ current_keys = [
1550
+ key
1551
+ for device in cached_devices.values()
1552
+ for key in device.get("keys", {}).get("keys", {}).values()
1553
+ ]
1554
+
1555
+ # We now check that the sender key matches (one of) the expected
1556
+ # keys.
1557
+ if sender_key not in current_keys:
1558
+ logger.info(
1559
+ "Received event from remote device with unexpected sender key: %s %s: %s",
1560
+ event.sender,
1561
+ device_id or "<no device_id>",
1562
+ sender_key,
1563
+ )
1564
+ resync = True
1565
+
1566
+ if resync:
1567
+ self.hs.run_as_background_process(
1568
+ "resync_device_due_to_pdu",
1569
+ self._resync_device,
1570
+ event.sender,
1571
+ )
1572
+
1573
+ async def _resync_device(self, sender: str) -> None:
1574
+ """We have detected that the device list for the given user may be out
1575
+ of sync, so we try and resync them.
1576
+ """
1577
+
1578
+ try:
1579
+ await self._store.mark_remote_users_device_caches_as_stale((sender,))
1580
+
1581
+ # Immediately attempt a resync in the background
1582
+ await self._device_list_updater.multi_user_device_resync(user_ids=[sender])
1583
+ except Exception:
1584
+ logger.exception("Failed to resync device for %s", sender)
1585
+
1586
+ async def backfill_event_id(
1587
+ self, destinations: StrCollection, room_id: str, event_id: str
1588
+ ) -> PulledPduInfo:
1589
+ """Backfill a single event and persist it as a non-outlier which means
1590
+ we also pull in all of the state and auth events necessary for it.
1591
+
1592
+ Args:
1593
+ destination: The homeserver to pull the given event_id from.
1594
+ room_id: The room where the event is from.
1595
+ event_id: The event ID to backfill.
1596
+
1597
+ Raises:
1598
+ FederationError if we are unable to find the event from the destination
1599
+ """
1600
+ logger.info("backfill_event_id: event_id=%s", event_id)
1601
+
1602
+ room_version = await self._store.get_room_version(room_id)
1603
+
1604
+ pulled_pdu_info = await self._federation_client.get_pdu(
1605
+ destinations,
1606
+ event_id,
1607
+ room_version,
1608
+ )
1609
+
1610
+ if not pulled_pdu_info:
1611
+ raise FederationError(
1612
+ "ERROR",
1613
+ 404,
1614
+ f"Unable to find event_id={event_id} from remote servers to backfill.",
1615
+ affected=event_id,
1616
+ )
1617
+
1618
+ # Persist the event we just fetched, including pulling all of the state
1619
+ # and auth events to de-outlier it. This also sets up the necessary
1620
+ # `state_groups` for the event.
1621
+ await self._process_pulled_events(
1622
+ pulled_pdu_info.pull_origin,
1623
+ [pulled_pdu_info.pdu],
1624
+ # Prevent notifications going to clients
1625
+ backfilled=True,
1626
+ )
1627
+
1628
+ return pulled_pdu_info
1629
+
1630
+ @trace
1631
+ @tag_args
1632
+ async def _get_events_and_persist(
1633
+ self, destination: str, room_id: str, event_ids: StrCollection
1634
+ ) -> None:
1635
+ """Fetch the given events from a server, and persist them as outliers.
1636
+
1637
+ This function *does not* recursively get missing auth events of the
1638
+ newly fetched events. Callers must include in the `event_ids` argument
1639
+ any missing events from the auth chain.
1640
+
1641
+ Logs a warning if we can't find the given event.
1642
+ """
1643
+
1644
+ room_version = await self._store.get_room_version(room_id)
1645
+
1646
+ events: list[EventBase] = []
1647
+
1648
+ async def get_event(event_id: str) -> None:
1649
+ with nested_logging_context(event_id):
1650
+ try:
1651
+ pulled_pdu_info = await self._federation_client.get_pdu(
1652
+ [destination],
1653
+ event_id,
1654
+ room_version,
1655
+ )
1656
+ if pulled_pdu_info is None:
1657
+ logger.warning(
1658
+ "Server %s didn't return event %s",
1659
+ destination,
1660
+ event_id,
1661
+ )
1662
+ return
1663
+ events.append(pulled_pdu_info.pdu)
1664
+
1665
+ except Exception as e:
1666
+ logger.warning(
1667
+ "Error fetching missing state/auth event %s: %s %s",
1668
+ event_id,
1669
+ type(e),
1670
+ e,
1671
+ )
1672
+
1673
+ await concurrently_execute(get_event, event_ids, 5)
1674
+ logger.info("Fetched %i events of %i requested", len(events), len(event_ids))
1675
+ await self._auth_and_persist_outliers(room_id, events)
1676
+
1677
+ @trace
1678
+ async def _auth_and_persist_outliers(
1679
+ self, room_id: str, events: Iterable[EventBase]
1680
+ ) -> None:
1681
+ """Persist a batch of outlier events fetched from remote servers.
1682
+
1683
+ We first sort the events to make sure that we process each event's auth_events
1684
+ before the event itself.
1685
+
1686
+ We then mark the events as outliers, persist them to the database, and, where
1687
+ appropriate (eg, an invite), awake the notifier.
1688
+
1689
+ Params:
1690
+ room_id: the room that the events are meant to be in (though this has
1691
+ not yet been checked)
1692
+ events: the events that have been fetched
1693
+ """
1694
+ event_map = {event.event_id: event for event in events}
1695
+
1696
+ event_ids = event_map.keys()
1697
+ set_tag(
1698
+ SynapseTags.FUNC_ARG_PREFIX + "event_ids",
1699
+ str(event_ids),
1700
+ )
1701
+ set_tag(
1702
+ SynapseTags.FUNC_ARG_PREFIX + "event_ids.length",
1703
+ str(len(event_ids)),
1704
+ )
1705
+
1706
+ # filter out any events we have already seen. This might happen because
1707
+ # the events were eagerly pushed to us (eg, during a room join), or because
1708
+ # another thread has raced against us since we decided to request the event.
1709
+ #
1710
+ # This is just an optimisation, so it doesn't need to be watertight - the event
1711
+ # persister does another round of deduplication.
1712
+ seen_remotes = await self._store.have_seen_events(room_id, event_map.keys())
1713
+ for s in seen_remotes:
1714
+ event_map.pop(s, None)
1715
+
1716
+ # XXX: it might be possible to kick this process off in parallel with fetching
1717
+ # the events.
1718
+
1719
+ # We need to persist an event's auth events before the event.
1720
+ auth_graph = {
1721
+ ev.event_id: [e_id for e_id in ev.auth_event_ids() if e_id in event_map]
1722
+ for ev in event_map.values()
1723
+ }
1724
+ sorted_auth_event_ids = sorted_topologically(event_map.keys(), auth_graph)
1725
+ sorted_auth_events = [event_map[e_id] for e_id in sorted_auth_event_ids]
1726
+ logger.info(
1727
+ "Persisting %i remaining outliers: %s",
1728
+ len(sorted_auth_events),
1729
+ shortstr(e.event_id for e in sorted_auth_events),
1730
+ )
1731
+
1732
+ # get all the auth events for all the events in this batch. By now, they should
1733
+ # have been persisted.
1734
+ auth_event_ids = {
1735
+ aid for event in sorted_auth_events for aid in event.auth_event_ids()
1736
+ }
1737
+ auth_map = {
1738
+ ev.event_id: ev
1739
+ for ev in sorted_auth_events
1740
+ if ev.event_id in auth_event_ids
1741
+ }
1742
+
1743
+ missing_events = auth_event_ids.difference(auth_map)
1744
+ if missing_events:
1745
+ persisted_events = await self._store.get_events(
1746
+ missing_events,
1747
+ allow_rejected=True,
1748
+ redact_behaviour=EventRedactBehaviour.as_is,
1749
+ )
1750
+ auth_map.update(persisted_events)
1751
+
1752
+ events_and_contexts_to_persist: list[EventPersistencePair] = []
1753
+
1754
+ async def prep(event: EventBase) -> None:
1755
+ with nested_logging_context(suffix=event.event_id):
1756
+ auth = []
1757
+ for auth_event_id in event.auth_event_ids():
1758
+ ae = auth_map.get(auth_event_id)
1759
+ if not ae:
1760
+ # the fact we can't find the auth event doesn't mean it doesn't
1761
+ # exist, which means it is premature to reject `event`. Instead we
1762
+ # just ignore it for now.
1763
+ logger.warning(
1764
+ "Dropping event %s, which relies on auth_event %s, which could not be found",
1765
+ event,
1766
+ auth_event_id,
1767
+ )
1768
+ # Drop the event from the auth_map too, else we may incorrectly persist
1769
+ # events which depend on this dropped event.
1770
+ auth_map.pop(event.event_id, None)
1771
+ return
1772
+ auth.append(ae)
1773
+
1774
+ # we're not bothering about room state, so flag the event as an outlier.
1775
+ event.internal_metadata.outlier = True
1776
+
1777
+ context = EventContext.for_outlier(self._storage_controllers)
1778
+ try:
1779
+ validate_event_for_room_version(event)
1780
+ await check_state_independent_auth_rules(
1781
+ self._store, event, batched_auth_events=auth_map
1782
+ )
1783
+ check_state_dependent_auth_rules(event, auth)
1784
+ except AuthError as e:
1785
+ logger.warning("Rejecting %r because %s", event, e)
1786
+ context.rejected = RejectedReason.AUTH_ERROR
1787
+ except EventSizeError as e:
1788
+ if e.unpersistable:
1789
+ # This event is completely unpersistable.
1790
+ raise e
1791
+ # Otherwise, we are somewhat lenient and just persist the event
1792
+ # as rejected, for moderate compatibility with older Synapse
1793
+ # versions.
1794
+ logger.warning("While validating received event %r: %s", event, e)
1795
+ context.rejected = RejectedReason.OVERSIZED_EVENT
1796
+
1797
+ events_and_contexts_to_persist.append((event, context))
1798
+
1799
+ for i, event in enumerate(sorted_auth_events):
1800
+ await prep(event)
1801
+
1802
+ # The above function is typically not async, and so won't yield to
1803
+ # the reactor. For large rooms let's yield to the reactor
1804
+ # occasionally to ensure we don't block other work.
1805
+ if (i + 1) % 1000 == 0:
1806
+ await self._clock.sleep(Duration(seconds=0))
1807
+
1808
+ # Also persist the new event in batches for similar reasons as above.
1809
+ for batch in batch_iter(events_and_contexts_to_persist, 1000):
1810
+ await self.persist_events_and_notify(
1811
+ room_id,
1812
+ batch,
1813
+ # Mark these events as backfilled as they're historic events that will
1814
+ # eventually be backfilled. For example, missing events we fetch
1815
+ # during backfill should be marked as backfilled as well.
1816
+ backfilled=True,
1817
+ )
1818
+
1819
+ @trace
1820
+ async def _check_event_auth(
1821
+ self, origin: str | None, event: EventBase, context: EventContext
1822
+ ) -> None:
1823
+ """
1824
+ Checks whether an event should be rejected (for failing auth checks).
1825
+
1826
+ Args:
1827
+ origin: The host the event originates from. This is used to fetch
1828
+ any missing auth events. It can be set to None, but only if we are
1829
+ sure that we already have all the auth events.
1830
+ event: The event itself.
1831
+ context:
1832
+ The event context.
1833
+
1834
+ Raises:
1835
+ AuthError if we were unable to find copies of the event's auth events.
1836
+ (Most other failures just cause us to set `context.rejected`.)
1837
+ """
1838
+ # This method should only be used for non-outliers
1839
+ assert not event.internal_metadata.outlier
1840
+
1841
+ # first of all, check that the event itself is valid.
1842
+ try:
1843
+ validate_event_for_room_version(event)
1844
+ except AuthError as e:
1845
+ logger.warning("While validating received event %r: %s", event, e)
1846
+ # TODO: use a different rejected reason here?
1847
+ context.rejected = RejectedReason.AUTH_ERROR
1848
+ return
1849
+ except EventSizeError as e:
1850
+ if e.unpersistable:
1851
+ # This event is completely unpersistable.
1852
+ raise e
1853
+ # Otherwise, we are somewhat lenient and just persist the event
1854
+ # as rejected, for moderate compatibility with older Synapse
1855
+ # versions.
1856
+ logger.warning("While validating received event %r: %s", event, e)
1857
+ context.rejected = RejectedReason.OVERSIZED_EVENT
1858
+ return
1859
+
1860
+ # next, check that we have all of the event's auth events.
1861
+ #
1862
+ # Note that this can raise AuthError, which we want to propagate to the
1863
+ # caller rather than swallow with `context.rejected` (since we cannot be
1864
+ # certain that there is a permanent problem with the event).
1865
+ claimed_auth_events = await self._load_or_fetch_auth_events_for_event(
1866
+ origin, event
1867
+ )
1868
+ set_tag(
1869
+ SynapseTags.RESULT_PREFIX + "claimed_auth_events",
1870
+ str([ev.event_id for ev in claimed_auth_events]),
1871
+ )
1872
+ set_tag(
1873
+ SynapseTags.RESULT_PREFIX + "claimed_auth_events.length",
1874
+ str(len(claimed_auth_events)),
1875
+ )
1876
+
1877
+ # ... and check that the event passes auth at those auth events.
1878
+ # https://spec.matrix.org/v1.3/server-server-api/#checks-performed-on-receipt-of-a-pdu:
1879
+ # 4. Passes authorization rules based on the event’s auth events,
1880
+ # otherwise it is rejected.
1881
+ try:
1882
+ await check_state_independent_auth_rules(self._store, event)
1883
+ check_state_dependent_auth_rules(event, claimed_auth_events)
1884
+ except AuthError as e:
1885
+ logger.warning(
1886
+ "While checking auth of %r against auth_events: %s", event, e
1887
+ )
1888
+ context.rejected = RejectedReason.AUTH_ERROR
1889
+ return
1890
+
1891
+ # now check the auth rules pass against the room state before the event
1892
+ # https://spec.matrix.org/v1.3/server-server-api/#checks-performed-on-receipt-of-a-pdu:
1893
+ # 5. Passes authorization rules based on the state before the event,
1894
+ # otherwise it is rejected.
1895
+ #
1896
+ # ... however, if we only have partial state for the room, then there is a good
1897
+ # chance that we'll be missing some of the state needed to auth the new event.
1898
+ # So, we state-resolve the auth events that we are given against the state that
1899
+ # we know about, which ensures things like bans are applied. (Note that we'll
1900
+ # already have checked we have all the auth events, in
1901
+ # _load_or_fetch_auth_events_for_event above)
1902
+ if context.partial_state:
1903
+ room_version = await self._store.get_room_version_id(event.room_id)
1904
+
1905
+ local_state_id_map = await context.get_prev_state_ids()
1906
+ claimed_auth_events_id_map = {
1907
+ (ev.type, ev.state_key): ev.event_id for ev in claimed_auth_events
1908
+ }
1909
+
1910
+ state_for_auth_id_map = (
1911
+ await self._state_resolution_handler.resolve_events_with_store(
1912
+ event.room_id,
1913
+ room_version,
1914
+ [local_state_id_map, claimed_auth_events_id_map],
1915
+ event_map=None,
1916
+ state_res_store=StateResolutionStore(
1917
+ self._store, self._state_deletion_store
1918
+ ),
1919
+ )
1920
+ )
1921
+ else:
1922
+ event_types = event_auth.auth_types_for_event(event.room_version, event)
1923
+ state_for_auth_id_map = await context.get_prev_state_ids(
1924
+ StateFilter.from_types(event_types)
1925
+ )
1926
+
1927
+ calculated_auth_event_ids = self._event_auth_handler.compute_auth_events(
1928
+ event, state_for_auth_id_map, for_verification=True
1929
+ )
1930
+
1931
+ # if those are the same, we're done here.
1932
+ if collections.Counter(event.auth_event_ids()) == collections.Counter(
1933
+ calculated_auth_event_ids
1934
+ ):
1935
+ return
1936
+
1937
+ # otherwise, re-run the auth checks based on what we calculated.
1938
+ calculated_auth_events = await self._store.get_events_as_list(
1939
+ calculated_auth_event_ids
1940
+ )
1941
+
1942
+ # log the differences
1943
+
1944
+ claimed_auth_event_map = {(e.type, e.state_key): e for e in claimed_auth_events}
1945
+ calculated_auth_event_map = {
1946
+ (e.type, e.state_key): e for e in calculated_auth_events
1947
+ }
1948
+ logger.info(
1949
+ "event's auth_events are different to our calculated auth_events. "
1950
+ "Claimed but not calculated: %s. Calculated but not claimed: %s",
1951
+ [
1952
+ ev
1953
+ for k, ev in claimed_auth_event_map.items()
1954
+ if k not in calculated_auth_event_map
1955
+ or calculated_auth_event_map[k].event_id != ev.event_id
1956
+ ],
1957
+ [
1958
+ ev
1959
+ for k, ev in calculated_auth_event_map.items()
1960
+ if k not in claimed_auth_event_map
1961
+ or claimed_auth_event_map[k].event_id != ev.event_id
1962
+ ],
1963
+ )
1964
+
1965
+ try:
1966
+ check_state_dependent_auth_rules(event, calculated_auth_events)
1967
+ except AuthError as e:
1968
+ logger.warning(
1969
+ "While checking auth of %r against room state before the event: %s",
1970
+ event,
1971
+ e,
1972
+ )
1973
+ context.rejected = RejectedReason.AUTH_ERROR
1974
+
1975
+ @trace
1976
+ async def _maybe_kick_guest_users(self, event: EventBase) -> None:
1977
+ if event.type != EventTypes.GuestAccess:
1978
+ return
1979
+
1980
+ guest_access = event.content.get(EventContentFields.GUEST_ACCESS)
1981
+ if guest_access == GuestAccess.CAN_JOIN:
1982
+ return
1983
+
1984
+ current_state = await self._storage_controllers.state.get_current_state(
1985
+ event.room_id
1986
+ )
1987
+ current_state_list = list(current_state.values())
1988
+ await self._get_room_member_handler().kick_guest_users(current_state_list)
1989
+
1990
+ async def _check_for_soft_fail(
1991
+ self,
1992
+ event: EventBase,
1993
+ context: EventContext,
1994
+ origin: str,
1995
+ ) -> None:
1996
+ """Checks if we should soft fail the event; if so, marks the event as
1997
+ such.
1998
+
1999
+ Does nothing for events in rooms with partial state, since we may not have an
2000
+ accurate membership event for the sender in the current state.
2001
+
2002
+ Args:
2003
+ event
2004
+ context: The `EventContext` which we are about to persist the event with.
2005
+ origin: The host the event originates from.
2006
+ """
2007
+ if await self._store.is_partial_state_room(event.room_id):
2008
+ # We might not know the sender's membership in the current state, so don't
2009
+ # soft fail anything. Even if we do have a membership for the sender in the
2010
+ # current state, it may have been derived from state resolution between
2011
+ # partial and full state and may not be accurate.
2012
+ return
2013
+
2014
+ extrem_ids = await self._store.get_latest_event_ids_in_room(event.room_id)
2015
+ prev_event_ids = set(event.prev_event_ids())
2016
+
2017
+ if extrem_ids == prev_event_ids:
2018
+ # If they're the same then the current state is the same as the
2019
+ # state at the event, so no point rechecking auth for soft fail.
2020
+ return
2021
+
2022
+ room_version = await self._store.get_room_version_id(event.room_id)
2023
+ room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
2024
+
2025
+ # The event types we want to pull from the "current" state.
2026
+ auth_types = auth_types_for_event(room_version_obj, event)
2027
+
2028
+ # Calculate the "current state".
2029
+ seen_event_ids = await self._store.have_events_in_timeline(prev_event_ids)
2030
+ has_missing_prevs = bool(prev_event_ids - seen_event_ids)
2031
+ if has_missing_prevs:
2032
+ # We don't have all the prev_events of this event, which means we have a
2033
+ # gap in the graph, and the new event is going to become a new backwards
2034
+ # extremity.
2035
+ #
2036
+ # In this case we want to be a little careful as we might have been
2037
+ # down for a while and have an incorrect view of the current state,
2038
+ # however we still want to do checks as gaps are easy to
2039
+ # maliciously manufacture.
2040
+ #
2041
+ # So we use a "current state" that is actually a state
2042
+ # resolution across the current forward extremities and the
2043
+ # given state at the event. This should correctly handle cases
2044
+ # like bans, especially with state res v2.
2045
+
2046
+ state_sets_d = await self._state_storage_controller.get_state_groups_ids(
2047
+ event.room_id, extrem_ids
2048
+ )
2049
+ state_sets: list[StateMap[str]] = list(state_sets_d.values())
2050
+ state_ids = await context.get_prev_state_ids()
2051
+ state_sets.append(state_ids)
2052
+ current_state_ids = (
2053
+ await self._state_resolution_handler.resolve_events_with_store(
2054
+ event.room_id,
2055
+ room_version,
2056
+ state_sets,
2057
+ event_map=None,
2058
+ state_res_store=StateResolutionStore(
2059
+ self._store, self._state_deletion_store
2060
+ ),
2061
+ )
2062
+ )
2063
+ else:
2064
+ current_state_ids = (
2065
+ await self._state_storage_controller.get_current_state_ids(
2066
+ event.room_id, StateFilter.from_types(auth_types)
2067
+ )
2068
+ )
2069
+
2070
+ logger.debug(
2071
+ "Doing soft-fail check for %s: state %s",
2072
+ event.event_id,
2073
+ current_state_ids,
2074
+ )
2075
+
2076
+ # Now check if event pass auth against said current state
2077
+ current_state_ids_list = [
2078
+ e for k, e in current_state_ids.items() if k in auth_types
2079
+ ]
2080
+ current_auth_events = await self._store.get_events_as_list(
2081
+ current_state_ids_list
2082
+ )
2083
+
2084
+ try:
2085
+ check_state_dependent_auth_rules(event, current_auth_events)
2086
+ except AuthError as e:
2087
+ logger.warning(
2088
+ "Soft-failing %r (from %s) because %s",
2089
+ event,
2090
+ e,
2091
+ origin,
2092
+ extra={
2093
+ "room_id": event.room_id,
2094
+ "mxid": event.sender,
2095
+ "hs": origin,
2096
+ },
2097
+ )
2098
+ soft_failed_event_counter.labels(
2099
+ **{SERVER_NAME_LABEL: self.server_name}
2100
+ ).inc()
2101
+ event.internal_metadata.soft_failed = True
2102
+
2103
+ async def _load_or_fetch_auth_events_for_event(
2104
+ self, destination: str | None, event: EventBase
2105
+ ) -> Collection[EventBase]:
2106
+ """Fetch this event's auth_events, from database or remote
2107
+
2108
+ Loads any of the auth_events that we already have from the database/cache. If
2109
+ there are any that are missing, calls /event_auth to get the complete auth
2110
+ chain for the event (and then attempts to load the auth_events again).
2111
+
2112
+ If any of the auth_events cannot be found, raises an AuthError. This can happen
2113
+ for a number of reasons; eg: the events don't exist, or we were unable to talk
2114
+ to `destination`, or we couldn't validate the signature on the event (which
2115
+ in turn has multiple potential causes).
2116
+
2117
+ Args:
2118
+ destination: where to send the /event_auth request. Typically the server
2119
+ that sent us `event` in the first place.
2120
+
2121
+ If this is None, no attempt is made to load any missing auth events:
2122
+ rather, an AssertionError is raised if there are any missing events.
2123
+
2124
+ event: the event whose auth_events we want
2125
+
2126
+ Returns:
2127
+ all of the events listed in `event.auth_events_ids`, after deduplication
2128
+
2129
+ Raises:
2130
+ AssertionError if some auth events were missing and no `destination` was
2131
+ supplied.
2132
+
2133
+ AuthError if we were unable to fetch the auth_events for any reason.
2134
+ """
2135
+ event_auth_event_ids = set(event.auth_event_ids())
2136
+ event_auth_events = await self._store.get_events(
2137
+ event_auth_event_ids, allow_rejected=True
2138
+ )
2139
+ missing_auth_event_ids = event_auth_event_ids.difference(
2140
+ event_auth_events.keys()
2141
+ )
2142
+ if not missing_auth_event_ids:
2143
+ return event_auth_events.values()
2144
+ if destination is None:
2145
+ # this shouldn't happen: destination must be set unless we know we have already
2146
+ # persisted the auth events.
2147
+ raise AssertionError(
2148
+ "_load_or_fetch_auth_events_for_event() called with no destination for "
2149
+ "an event with missing auth_events"
2150
+ )
2151
+
2152
+ logger.info(
2153
+ "Event %s refers to unknown auth events %s: fetching auth chain",
2154
+ event,
2155
+ missing_auth_event_ids,
2156
+ )
2157
+ try:
2158
+ await self._get_remote_auth_chain_for_event(
2159
+ destination, event.room_id, event.event_id
2160
+ )
2161
+ except Exception as e:
2162
+ logger.warning("Failed to get auth chain for %s: %s", event, e)
2163
+ # in this case, it's very likely we still won't have all the auth
2164
+ # events - but we pick that up below.
2165
+
2166
+ # try to fetch the auth events we missed list time.
2167
+ extra_auth_events = await self._store.get_events(
2168
+ missing_auth_event_ids, allow_rejected=True
2169
+ )
2170
+ missing_auth_event_ids.difference_update(extra_auth_events.keys())
2171
+ event_auth_events.update(extra_auth_events)
2172
+ if not missing_auth_event_ids:
2173
+ return event_auth_events.values()
2174
+
2175
+ # we still don't have all the auth events.
2176
+ logger.warning(
2177
+ "Missing auth events for %s: %s",
2178
+ event,
2179
+ shortstr(missing_auth_event_ids),
2180
+ )
2181
+ # the fact we can't find the auth event doesn't mean it doesn't
2182
+ # exist, which means it is premature to store `event` as rejected.
2183
+ # instead we raise an AuthError, which will make the caller ignore it.
2184
+ raise AuthError(code=HTTPStatus.FORBIDDEN, msg="Auth events could not be found")
2185
+
2186
+ @trace
2187
+ @tag_args
2188
+ async def _get_remote_auth_chain_for_event(
2189
+ self, destination: str, room_id: str, event_id: str
2190
+ ) -> None:
2191
+ """If we are missing some of an event's auth events, attempt to request them
2192
+
2193
+ Args:
2194
+ destination: where to fetch the auth tree from
2195
+ room_id: the room in which we are lacking auth events
2196
+ event_id: the event for which we are lacking auth events
2197
+ """
2198
+ try:
2199
+ remote_events = await self._federation_client.get_event_auth(
2200
+ destination, room_id, event_id
2201
+ )
2202
+
2203
+ except RequestSendFailed as e1:
2204
+ # The other side isn't around or doesn't implement the
2205
+ # endpoint, so lets just bail out.
2206
+ logger.info("Failed to get event auth from remote: %s", e1)
2207
+ return
2208
+
2209
+ logger.info("/event_auth returned %i events", len(remote_events))
2210
+
2211
+ # `event` may be returned, but we should not yet process it.
2212
+ remote_auth_events = (e for e in remote_events if e.event_id != event_id)
2213
+
2214
+ await self._auth_and_persist_outliers(room_id, remote_auth_events)
2215
+
2216
+ @trace
2217
+ async def _run_push_actions_and_persist_event(
2218
+ self, event: EventBase, context: EventContext, backfilled: bool = False
2219
+ ) -> None:
2220
+ """Run the push actions for a received event, and persist it.
2221
+
2222
+ Args:
2223
+ event: The event itself.
2224
+ context: The event context.
2225
+ backfilled: True if the event was backfilled.
2226
+
2227
+ PartialStateConflictError: if attempting to persist a partial state event in
2228
+ a room that has been un-partial stated.
2229
+ """
2230
+ # this method should not be called on outliers (those code paths call
2231
+ # persist_events_and_notify directly.)
2232
+ assert not event.internal_metadata.outlier
2233
+
2234
+ if not backfilled and not context.rejected:
2235
+ min_depth = await self._store.get_min_depth(event.room_id)
2236
+ if min_depth is None or min_depth > event.depth:
2237
+ # XXX richvdh 2021/10/07: I don't really understand what this
2238
+ # condition is doing. I think it's trying not to send pushes
2239
+ # for events that predate our join - but that's not really what
2240
+ # min_depth means, and anyway ancient events are a more general
2241
+ # problem.
2242
+ #
2243
+ # for now I'm just going to log about it.
2244
+ logger.info(
2245
+ "Skipping push actions for old event with depth %s < %s",
2246
+ event.depth,
2247
+ min_depth,
2248
+ )
2249
+ else:
2250
+ await self._bulk_push_rule_evaluator.action_for_events_by_user(
2251
+ [(event, context)]
2252
+ )
2253
+
2254
+ try:
2255
+ await self.persist_events_and_notify(
2256
+ event.room_id, [(event, context)], backfilled=backfilled
2257
+ )
2258
+ except Exception:
2259
+ await self._store.remove_push_actions_from_staging(event.event_id)
2260
+ raise
2261
+
2262
+ async def persist_events_and_notify(
2263
+ self,
2264
+ room_id: str,
2265
+ event_and_contexts: Sequence[EventPersistencePair],
2266
+ backfilled: bool = False,
2267
+ ) -> int:
2268
+ """Persists events and tells the notifier/pushers about them, if
2269
+ necessary.
2270
+
2271
+ Args:
2272
+ room_id: The room ID of events being persisted.
2273
+ event_and_contexts: Sequence of events with their associated
2274
+ context that should be persisted. All events must belong to
2275
+ the same room.
2276
+ backfilled: Whether these events are a result of
2277
+ backfilling or not
2278
+
2279
+ Returns:
2280
+ The stream ID after which all events have been persisted.
2281
+
2282
+ Raises:
2283
+ PartialStateConflictError: if attempting to persist a partial state event in
2284
+ a room that has been un-partial stated.
2285
+ """
2286
+ if not event_and_contexts:
2287
+ return self._store.get_room_max_stream_ordering()
2288
+
2289
+ instance = self._config.worker.events_shard_config.get_instance(room_id)
2290
+ if instance != self._instance_name:
2291
+ # Limit the number of events sent over replication. We choose 200
2292
+ # here as that is what we default to in `max_request_body_size(..)`
2293
+ result = {}
2294
+ try:
2295
+ for batch in batch_iter(event_and_contexts, 200):
2296
+ result = await self._send_events(
2297
+ instance_name=instance,
2298
+ store=self._store,
2299
+ room_id=room_id,
2300
+ event_and_contexts=batch,
2301
+ backfilled=backfilled,
2302
+ )
2303
+ except SynapseError as e:
2304
+ if e.code == HTTPStatus.CONFLICT:
2305
+ raise PartialStateConflictError()
2306
+ raise
2307
+ return result["max_stream_id"]
2308
+ else:
2309
+ assert self._storage_controllers.persistence
2310
+
2311
+ # Note that this returns the events that were persisted, which may not be
2312
+ # the same as were passed in if some were deduplicated due to transaction IDs.
2313
+ (
2314
+ events,
2315
+ max_stream_token,
2316
+ ) = await self._storage_controllers.persistence.persist_events(
2317
+ event_and_contexts, backfilled=backfilled
2318
+ )
2319
+
2320
+ # After persistence, we never notify clients (wake up `/sync` streams) about
2321
+ # backfilled events but it's important to let all the workers know about any
2322
+ # new event (backfilled or not) because TODO
2323
+ self._notifier.notify_replication()
2324
+
2325
+ if self._ephemeral_messages_enabled:
2326
+ for event in events:
2327
+ # If there's an expiry timestamp on the event, schedule its expiry.
2328
+ self._message_handler.maybe_schedule_expiry(event)
2329
+
2330
+ if not backfilled: # Never notify for backfilled events
2331
+ with start_active_span("notify_persisted_events"):
2332
+ set_tag(
2333
+ SynapseTags.RESULT_PREFIX + "event_ids",
2334
+ str([ev.event_id for ev in events]),
2335
+ )
2336
+ set_tag(
2337
+ SynapseTags.RESULT_PREFIX + "event_ids.length",
2338
+ str(len(events)),
2339
+ )
2340
+ for event in events:
2341
+ await self._notify_persisted_event(event, max_stream_token)
2342
+
2343
+ return max_stream_token.stream
2344
+
2345
+ async def _notify_persisted_event(
2346
+ self, event: EventBase, max_stream_token: RoomStreamToken
2347
+ ) -> None:
2348
+ """Checks to see if notifier/pushers should be notified about the
2349
+ event or not.
2350
+
2351
+ Args:
2352
+ event:
2353
+ max_stream_token: The max_stream_id returned by persist_events
2354
+ """
2355
+
2356
+ extra_users = []
2357
+ if event.type == EventTypes.Member:
2358
+ target_user_id = event.state_key
2359
+
2360
+ # We notify for memberships if its an invite for one of our
2361
+ # users
2362
+ if event.internal_metadata.is_outlier():
2363
+ if event.membership != Membership.INVITE:
2364
+ if not self._is_mine_id(target_user_id):
2365
+ return
2366
+
2367
+ target_user = UserID.from_string(target_user_id)
2368
+ extra_users.append(target_user)
2369
+ elif event.internal_metadata.is_outlier():
2370
+ return
2371
+
2372
+ # the event has been persisted so it should have a stream ordering.
2373
+ assert event.internal_metadata.stream_ordering
2374
+
2375
+ event_pos = PersistedEventPosition(
2376
+ self._instance_name, event.internal_metadata.stream_ordering
2377
+ )
2378
+ await self._notifier.on_new_room_events(
2379
+ [(event, event_pos)], max_stream_token, extra_users=extra_users
2380
+ )
2381
+
2382
+ if event.type == EventTypes.Member and event.membership == Membership.JOIN:
2383
+ # TODO retrieve the previous state, and exclude join -> join transitions
2384
+ self._notifier.notify_user_joined_room(event.event_id, event.room_id)
2385
+
2386
+ # If this is a server ACL event, clear the cache in the storage controller.
2387
+ if event.type == EventTypes.ServerACL:
2388
+ self._state_storage_controller.get_server_acl_for_room.invalidate(
2389
+ (event.room_id,)
2390
+ )
2391
+
2392
+ def _sanity_check_event(self, ev: EventBase) -> None:
2393
+ """
2394
+ Do some early sanity checks of a received event
2395
+
2396
+ In particular, checks it doesn't have an excessive number of
2397
+ prev_events or auth_events, which could cause a huge state resolution
2398
+ or cascade of event fetches.
2399
+
2400
+ Args:
2401
+ ev: event to be checked
2402
+
2403
+ Raises:
2404
+ SynapseError if the event does not pass muster
2405
+ """
2406
+ if len(ev.prev_event_ids()) > 20:
2407
+ logger.warning(
2408
+ "Rejecting event %s which has %i prev_events",
2409
+ ev.event_id,
2410
+ len(ev.prev_event_ids()),
2411
+ )
2412
+ raise SynapseError(HTTPStatus.BAD_REQUEST, "Too many prev_events")
2413
+
2414
+ if len(ev.auth_event_ids()) > 10:
2415
+ logger.warning(
2416
+ "Rejecting event %s which has %i auth_events",
2417
+ ev.event_id,
2418
+ len(ev.auth_event_ids()),
2419
+ )
2420
+ raise SynapseError(HTTPStatus.BAD_REQUEST, "Too many auth_events")