matrix-synapse 1.143.0rc2__cp310-abi3-manylinux_2_28_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1058) hide show
  1. matrix_synapse-1.143.0rc2.dist-info/AUTHORS.rst +51 -0
  2. matrix_synapse-1.143.0rc2.dist-info/LICENSE-AGPL-3.0 +661 -0
  3. matrix_synapse-1.143.0rc2.dist-info/LICENSE-COMMERCIAL +6 -0
  4. matrix_synapse-1.143.0rc2.dist-info/METADATA +385 -0
  5. matrix_synapse-1.143.0rc2.dist-info/RECORD +1058 -0
  6. matrix_synapse-1.143.0rc2.dist-info/WHEEL +4 -0
  7. matrix_synapse-1.143.0rc2.dist-info/entry_points.txt +14 -0
  8. synapse/__init__.py +97 -0
  9. synapse/_scripts/__init__.py +0 -0
  10. synapse/_scripts/export_signing_key.py +109 -0
  11. synapse/_scripts/generate_config.py +83 -0
  12. synapse/_scripts/generate_log_config.py +56 -0
  13. synapse/_scripts/generate_signing_key.py +55 -0
  14. synapse/_scripts/generate_workers_map.py +318 -0
  15. synapse/_scripts/hash_password.py +95 -0
  16. synapse/_scripts/move_remote_media_to_new_store.py +128 -0
  17. synapse/_scripts/register_new_matrix_user.py +402 -0
  18. synapse/_scripts/review_recent_signups.py +212 -0
  19. synapse/_scripts/synapse_port_db.py +1604 -0
  20. synapse/_scripts/synctl.py +365 -0
  21. synapse/_scripts/update_synapse_database.py +130 -0
  22. synapse/api/__init__.py +20 -0
  23. synapse/api/auth/__init__.py +207 -0
  24. synapse/api/auth/base.py +406 -0
  25. synapse/api/auth/internal.py +299 -0
  26. synapse/api/auth/mas.py +436 -0
  27. synapse/api/auth/msc3861_delegated.py +617 -0
  28. synapse/api/auth_blocking.py +144 -0
  29. synapse/api/constants.py +362 -0
  30. synapse/api/errors.py +907 -0
  31. synapse/api/filtering.py +537 -0
  32. synapse/api/presence.py +102 -0
  33. synapse/api/ratelimiting.py +480 -0
  34. synapse/api/room_versions.py +535 -0
  35. synapse/api/urls.py +118 -0
  36. synapse/app/__init__.py +60 -0
  37. synapse/app/_base.py +862 -0
  38. synapse/app/admin_cmd.py +388 -0
  39. synapse/app/appservice.py +30 -0
  40. synapse/app/client_reader.py +30 -0
  41. synapse/app/complement_fork_starter.py +206 -0
  42. synapse/app/event_creator.py +29 -0
  43. synapse/app/federation_reader.py +30 -0
  44. synapse/app/federation_sender.py +30 -0
  45. synapse/app/frontend_proxy.py +30 -0
  46. synapse/app/generic_worker.py +474 -0
  47. synapse/app/homeserver.py +505 -0
  48. synapse/app/media_repository.py +30 -0
  49. synapse/app/phone_stats_home.py +296 -0
  50. synapse/app/pusher.py +30 -0
  51. synapse/app/synchrotron.py +30 -0
  52. synapse/app/user_dir.py +31 -0
  53. synapse/appservice/__init__.py +458 -0
  54. synapse/appservice/api.py +567 -0
  55. synapse/appservice/scheduler.py +564 -0
  56. synapse/config/__init__.py +27 -0
  57. synapse/config/__main__.py +62 -0
  58. synapse/config/_base.py +1106 -0
  59. synapse/config/_base.pyi +215 -0
  60. synapse/config/_util.py +99 -0
  61. synapse/config/account_validity.py +116 -0
  62. synapse/config/api.py +141 -0
  63. synapse/config/appservice.py +210 -0
  64. synapse/config/auth.py +80 -0
  65. synapse/config/auto_accept_invites.py +43 -0
  66. synapse/config/background_updates.py +44 -0
  67. synapse/config/cache.py +231 -0
  68. synapse/config/captcha.py +90 -0
  69. synapse/config/cas.py +116 -0
  70. synapse/config/consent.py +73 -0
  71. synapse/config/database.py +184 -0
  72. synapse/config/emailconfig.py +367 -0
  73. synapse/config/experimental.py +595 -0
  74. synapse/config/federation.py +114 -0
  75. synapse/config/homeserver.py +141 -0
  76. synapse/config/jwt.py +55 -0
  77. synapse/config/key.py +447 -0
  78. synapse/config/logger.py +390 -0
  79. synapse/config/mas.py +192 -0
  80. synapse/config/matrixrtc.py +66 -0
  81. synapse/config/metrics.py +84 -0
  82. synapse/config/modules.py +40 -0
  83. synapse/config/oembed.py +185 -0
  84. synapse/config/oidc.py +509 -0
  85. synapse/config/password_auth_providers.py +82 -0
  86. synapse/config/push.py +64 -0
  87. synapse/config/ratelimiting.py +254 -0
  88. synapse/config/redis.py +74 -0
  89. synapse/config/registration.py +296 -0
  90. synapse/config/repository.py +311 -0
  91. synapse/config/retention.py +162 -0
  92. synapse/config/room.py +88 -0
  93. synapse/config/room_directory.py +165 -0
  94. synapse/config/saml2.py +251 -0
  95. synapse/config/server.py +1170 -0
  96. synapse/config/server_notices.py +84 -0
  97. synapse/config/spam_checker.py +66 -0
  98. synapse/config/sso.py +121 -0
  99. synapse/config/stats.py +54 -0
  100. synapse/config/third_party_event_rules.py +40 -0
  101. synapse/config/tls.py +192 -0
  102. synapse/config/tracer.py +71 -0
  103. synapse/config/user_directory.py +47 -0
  104. synapse/config/user_types.py +42 -0
  105. synapse/config/voip.py +59 -0
  106. synapse/config/workers.py +642 -0
  107. synapse/crypto/__init__.py +20 -0
  108. synapse/crypto/context_factory.py +278 -0
  109. synapse/crypto/event_signing.py +194 -0
  110. synapse/crypto/keyring.py +931 -0
  111. synapse/event_auth.py +1266 -0
  112. synapse/events/__init__.py +667 -0
  113. synapse/events/auto_accept_invites.py +216 -0
  114. synapse/events/builder.py +387 -0
  115. synapse/events/presence_router.py +243 -0
  116. synapse/events/snapshot.py +559 -0
  117. synapse/events/utils.py +924 -0
  118. synapse/events/validator.py +305 -0
  119. synapse/federation/__init__.py +22 -0
  120. synapse/federation/federation_base.py +382 -0
  121. synapse/federation/federation_client.py +2132 -0
  122. synapse/federation/federation_server.py +1540 -0
  123. synapse/federation/persistence.py +70 -0
  124. synapse/federation/send_queue.py +531 -0
  125. synapse/federation/sender/__init__.py +1164 -0
  126. synapse/federation/sender/per_destination_queue.py +886 -0
  127. synapse/federation/sender/transaction_manager.py +210 -0
  128. synapse/federation/transport/__init__.py +28 -0
  129. synapse/federation/transport/client.py +1199 -0
  130. synapse/federation/transport/server/__init__.py +334 -0
  131. synapse/federation/transport/server/_base.py +429 -0
  132. synapse/federation/transport/server/federation.py +910 -0
  133. synapse/federation/units.py +133 -0
  134. synapse/handlers/__init__.py +20 -0
  135. synapse/handlers/account.py +162 -0
  136. synapse/handlers/account_data.py +360 -0
  137. synapse/handlers/account_validity.py +361 -0
  138. synapse/handlers/admin.py +615 -0
  139. synapse/handlers/appservice.py +989 -0
  140. synapse/handlers/auth.py +2481 -0
  141. synapse/handlers/cas.py +413 -0
  142. synapse/handlers/deactivate_account.py +363 -0
  143. synapse/handlers/delayed_events.py +599 -0
  144. synapse/handlers/device.py +1870 -0
  145. synapse/handlers/devicemessage.py +399 -0
  146. synapse/handlers/directory.py +545 -0
  147. synapse/handlers/e2e_keys.py +1834 -0
  148. synapse/handlers/e2e_room_keys.py +455 -0
  149. synapse/handlers/event_auth.py +390 -0
  150. synapse/handlers/events.py +201 -0
  151. synapse/handlers/federation.py +2039 -0
  152. synapse/handlers/federation_event.py +2419 -0
  153. synapse/handlers/identity.py +812 -0
  154. synapse/handlers/initial_sync.py +528 -0
  155. synapse/handlers/jwt.py +120 -0
  156. synapse/handlers/message.py +2347 -0
  157. synapse/handlers/oidc.py +1801 -0
  158. synapse/handlers/pagination.py +768 -0
  159. synapse/handlers/password_policy.py +102 -0
  160. synapse/handlers/presence.py +2633 -0
  161. synapse/handlers/profile.py +655 -0
  162. synapse/handlers/push_rules.py +164 -0
  163. synapse/handlers/read_marker.py +79 -0
  164. synapse/handlers/receipts.py +351 -0
  165. synapse/handlers/register.py +1059 -0
  166. synapse/handlers/relations.py +623 -0
  167. synapse/handlers/reports.py +98 -0
  168. synapse/handlers/room.py +2448 -0
  169. synapse/handlers/room_list.py +632 -0
  170. synapse/handlers/room_member.py +2365 -0
  171. synapse/handlers/room_member_worker.py +146 -0
  172. synapse/handlers/room_policy.py +186 -0
  173. synapse/handlers/room_summary.py +1057 -0
  174. synapse/handlers/saml.py +524 -0
  175. synapse/handlers/search.py +723 -0
  176. synapse/handlers/send_email.py +209 -0
  177. synapse/handlers/set_password.py +71 -0
  178. synapse/handlers/sliding_sync/__init__.py +1701 -0
  179. synapse/handlers/sliding_sync/extensions.py +969 -0
  180. synapse/handlers/sliding_sync/room_lists.py +2262 -0
  181. synapse/handlers/sliding_sync/store.py +128 -0
  182. synapse/handlers/sso.py +1291 -0
  183. synapse/handlers/state_deltas.py +82 -0
  184. synapse/handlers/stats.py +321 -0
  185. synapse/handlers/sync.py +3106 -0
  186. synapse/handlers/thread_subscriptions.py +190 -0
  187. synapse/handlers/typing.py +606 -0
  188. synapse/handlers/ui_auth/__init__.py +48 -0
  189. synapse/handlers/ui_auth/checkers.py +332 -0
  190. synapse/handlers/user_directory.py +783 -0
  191. synapse/handlers/worker_lock.py +371 -0
  192. synapse/http/__init__.py +105 -0
  193. synapse/http/additional_resource.py +62 -0
  194. synapse/http/client.py +1373 -0
  195. synapse/http/connectproxyclient.py +316 -0
  196. synapse/http/federation/__init__.py +19 -0
  197. synapse/http/federation/matrix_federation_agent.py +490 -0
  198. synapse/http/federation/srv_resolver.py +196 -0
  199. synapse/http/federation/well_known_resolver.py +367 -0
  200. synapse/http/matrixfederationclient.py +1873 -0
  201. synapse/http/proxy.py +290 -0
  202. synapse/http/proxyagent.py +497 -0
  203. synapse/http/replicationagent.py +202 -0
  204. synapse/http/request_metrics.py +309 -0
  205. synapse/http/server.py +1110 -0
  206. synapse/http/servlet.py +1018 -0
  207. synapse/http/site.py +825 -0
  208. synapse/http/types.py +27 -0
  209. synapse/logging/__init__.py +31 -0
  210. synapse/logging/_remote.py +261 -0
  211. synapse/logging/_terse_json.py +95 -0
  212. synapse/logging/context.py +1209 -0
  213. synapse/logging/formatter.py +62 -0
  214. synapse/logging/handlers.py +99 -0
  215. synapse/logging/loggers.py +25 -0
  216. synapse/logging/opentracing.py +1132 -0
  217. synapse/logging/scopecontextmanager.py +160 -0
  218. synapse/media/_base.py +830 -0
  219. synapse/media/filepath.py +417 -0
  220. synapse/media/media_repository.py +1580 -0
  221. synapse/media/media_storage.py +702 -0
  222. synapse/media/oembed.py +277 -0
  223. synapse/media/preview_html.py +556 -0
  224. synapse/media/storage_provider.py +195 -0
  225. synapse/media/thumbnailer.py +833 -0
  226. synapse/media/url_previewer.py +875 -0
  227. synapse/metrics/__init__.py +748 -0
  228. synapse/metrics/_gc.py +219 -0
  229. synapse/metrics/_reactor_metrics.py +171 -0
  230. synapse/metrics/_types.py +38 -0
  231. synapse/metrics/background_process_metrics.py +555 -0
  232. synapse/metrics/common_usage_metrics.py +94 -0
  233. synapse/metrics/jemalloc.py +248 -0
  234. synapse/module_api/__init__.py +2131 -0
  235. synapse/module_api/callbacks/__init__.py +50 -0
  236. synapse/module_api/callbacks/account_validity_callbacks.py +106 -0
  237. synapse/module_api/callbacks/media_repository_callbacks.py +157 -0
  238. synapse/module_api/callbacks/ratelimit_callbacks.py +78 -0
  239. synapse/module_api/callbacks/spamchecker_callbacks.py +991 -0
  240. synapse/module_api/callbacks/third_party_event_rules_callbacks.py +592 -0
  241. synapse/module_api/errors.py +42 -0
  242. synapse/notifier.py +970 -0
  243. synapse/push/__init__.py +212 -0
  244. synapse/push/bulk_push_rule_evaluator.py +635 -0
  245. synapse/push/clientformat.py +126 -0
  246. synapse/push/emailpusher.py +333 -0
  247. synapse/push/httppusher.py +564 -0
  248. synapse/push/mailer.py +1010 -0
  249. synapse/push/presentable_names.py +216 -0
  250. synapse/push/push_tools.py +114 -0
  251. synapse/push/push_types.py +141 -0
  252. synapse/push/pusher.py +87 -0
  253. synapse/push/pusherpool.py +501 -0
  254. synapse/push/rulekinds.py +33 -0
  255. synapse/py.typed +0 -0
  256. synapse/replication/__init__.py +20 -0
  257. synapse/replication/http/__init__.py +68 -0
  258. synapse/replication/http/_base.py +468 -0
  259. synapse/replication/http/account_data.py +297 -0
  260. synapse/replication/http/deactivate_account.py +81 -0
  261. synapse/replication/http/delayed_events.py +62 -0
  262. synapse/replication/http/devices.py +254 -0
  263. synapse/replication/http/federation.py +334 -0
  264. synapse/replication/http/login.py +106 -0
  265. synapse/replication/http/membership.py +364 -0
  266. synapse/replication/http/presence.py +133 -0
  267. synapse/replication/http/push.py +156 -0
  268. synapse/replication/http/register.py +172 -0
  269. synapse/replication/http/send_events.py +182 -0
  270. synapse/replication/http/state.py +82 -0
  271. synapse/replication/http/streams.py +101 -0
  272. synapse/replication/tcp/__init__.py +56 -0
  273. synapse/replication/tcp/client.py +552 -0
  274. synapse/replication/tcp/commands.py +569 -0
  275. synapse/replication/tcp/context.py +41 -0
  276. synapse/replication/tcp/external_cache.py +156 -0
  277. synapse/replication/tcp/handler.py +922 -0
  278. synapse/replication/tcp/protocol.py +608 -0
  279. synapse/replication/tcp/redis.py +509 -0
  280. synapse/replication/tcp/resource.py +348 -0
  281. synapse/replication/tcp/streams/__init__.py +96 -0
  282. synapse/replication/tcp/streams/_base.py +765 -0
  283. synapse/replication/tcp/streams/events.py +287 -0
  284. synapse/replication/tcp/streams/federation.py +92 -0
  285. synapse/replication/tcp/streams/partial_state.py +80 -0
  286. synapse/res/providers.json +29 -0
  287. synapse/res/templates/_base.html +29 -0
  288. synapse/res/templates/account_previously_renewed.html +6 -0
  289. synapse/res/templates/account_renewed.html +6 -0
  290. synapse/res/templates/add_threepid.html +8 -0
  291. synapse/res/templates/add_threepid.txt +6 -0
  292. synapse/res/templates/add_threepid_failure.html +7 -0
  293. synapse/res/templates/add_threepid_success.html +6 -0
  294. synapse/res/templates/already_in_use.html +12 -0
  295. synapse/res/templates/already_in_use.txt +10 -0
  296. synapse/res/templates/auth_success.html +21 -0
  297. synapse/res/templates/invalid_token.html +6 -0
  298. synapse/res/templates/mail-Element.css +7 -0
  299. synapse/res/templates/mail-Vector.css +7 -0
  300. synapse/res/templates/mail-expiry.css +4 -0
  301. synapse/res/templates/mail.css +156 -0
  302. synapse/res/templates/notice_expiry.html +46 -0
  303. synapse/res/templates/notice_expiry.txt +7 -0
  304. synapse/res/templates/notif.html +51 -0
  305. synapse/res/templates/notif.txt +22 -0
  306. synapse/res/templates/notif_mail.html +59 -0
  307. synapse/res/templates/notif_mail.txt +10 -0
  308. synapse/res/templates/password_reset.html +10 -0
  309. synapse/res/templates/password_reset.txt +7 -0
  310. synapse/res/templates/password_reset_confirmation.html +15 -0
  311. synapse/res/templates/password_reset_failure.html +7 -0
  312. synapse/res/templates/password_reset_success.html +6 -0
  313. synapse/res/templates/recaptcha.html +42 -0
  314. synapse/res/templates/registration.html +12 -0
  315. synapse/res/templates/registration.txt +10 -0
  316. synapse/res/templates/registration_failure.html +6 -0
  317. synapse/res/templates/registration_success.html +6 -0
  318. synapse/res/templates/registration_token.html +18 -0
  319. synapse/res/templates/room.html +33 -0
  320. synapse/res/templates/room.txt +9 -0
  321. synapse/res/templates/sso.css +129 -0
  322. synapse/res/templates/sso_account_deactivated.html +25 -0
  323. synapse/res/templates/sso_auth_account_details.html +186 -0
  324. synapse/res/templates/sso_auth_account_details.js +116 -0
  325. synapse/res/templates/sso_auth_bad_user.html +26 -0
  326. synapse/res/templates/sso_auth_confirm.html +27 -0
  327. synapse/res/templates/sso_auth_success.html +26 -0
  328. synapse/res/templates/sso_error.html +71 -0
  329. synapse/res/templates/sso_footer.html +19 -0
  330. synapse/res/templates/sso_login_idp_picker.html +60 -0
  331. synapse/res/templates/sso_new_user_consent.html +30 -0
  332. synapse/res/templates/sso_partial_profile.html +19 -0
  333. synapse/res/templates/sso_redirect_confirm.html +39 -0
  334. synapse/res/templates/style.css +33 -0
  335. synapse/res/templates/terms.html +27 -0
  336. synapse/rest/__init__.py +197 -0
  337. synapse/rest/admin/__init__.py +390 -0
  338. synapse/rest/admin/_base.py +72 -0
  339. synapse/rest/admin/background_updates.py +171 -0
  340. synapse/rest/admin/devices.py +221 -0
  341. synapse/rest/admin/event_reports.py +173 -0
  342. synapse/rest/admin/events.py +69 -0
  343. synapse/rest/admin/experimental_features.py +137 -0
  344. synapse/rest/admin/federation.py +243 -0
  345. synapse/rest/admin/media.py +540 -0
  346. synapse/rest/admin/registration_tokens.py +358 -0
  347. synapse/rest/admin/rooms.py +1061 -0
  348. synapse/rest/admin/scheduled_tasks.py +70 -0
  349. synapse/rest/admin/server_notice_servlet.py +132 -0
  350. synapse/rest/admin/statistics.py +132 -0
  351. synapse/rest/admin/username_available.py +58 -0
  352. synapse/rest/admin/users.py +1606 -0
  353. synapse/rest/client/__init__.py +20 -0
  354. synapse/rest/client/_base.py +113 -0
  355. synapse/rest/client/account.py +930 -0
  356. synapse/rest/client/account_data.py +319 -0
  357. synapse/rest/client/account_validity.py +103 -0
  358. synapse/rest/client/appservice_ping.py +125 -0
  359. synapse/rest/client/auth.py +218 -0
  360. synapse/rest/client/auth_metadata.py +122 -0
  361. synapse/rest/client/capabilities.py +121 -0
  362. synapse/rest/client/delayed_events.py +165 -0
  363. synapse/rest/client/devices.py +587 -0
  364. synapse/rest/client/directory.py +211 -0
  365. synapse/rest/client/events.py +116 -0
  366. synapse/rest/client/filter.py +112 -0
  367. synapse/rest/client/initial_sync.py +65 -0
  368. synapse/rest/client/keys.py +678 -0
  369. synapse/rest/client/knock.py +104 -0
  370. synapse/rest/client/login.py +750 -0
  371. synapse/rest/client/login_token_request.py +127 -0
  372. synapse/rest/client/logout.py +93 -0
  373. synapse/rest/client/matrixrtc.py +52 -0
  374. synapse/rest/client/media.py +285 -0
  375. synapse/rest/client/mutual_rooms.py +93 -0
  376. synapse/rest/client/notifications.py +137 -0
  377. synapse/rest/client/openid.py +109 -0
  378. synapse/rest/client/password_policy.py +69 -0
  379. synapse/rest/client/presence.py +131 -0
  380. synapse/rest/client/profile.py +291 -0
  381. synapse/rest/client/push_rule.py +331 -0
  382. synapse/rest/client/pusher.py +181 -0
  383. synapse/rest/client/read_marker.py +104 -0
  384. synapse/rest/client/receipts.py +165 -0
  385. synapse/rest/client/register.py +1067 -0
  386. synapse/rest/client/relations.py +138 -0
  387. synapse/rest/client/rendezvous.py +76 -0
  388. synapse/rest/client/reporting.py +207 -0
  389. synapse/rest/client/room.py +1669 -0
  390. synapse/rest/client/room_keys.py +426 -0
  391. synapse/rest/client/room_upgrade_rest_servlet.py +112 -0
  392. synapse/rest/client/sendtodevice.py +85 -0
  393. synapse/rest/client/sync.py +1131 -0
  394. synapse/rest/client/tags.py +129 -0
  395. synapse/rest/client/thirdparty.py +130 -0
  396. synapse/rest/client/thread_subscriptions.py +247 -0
  397. synapse/rest/client/tokenrefresh.py +52 -0
  398. synapse/rest/client/transactions.py +149 -0
  399. synapse/rest/client/user_directory.py +90 -0
  400. synapse/rest/client/versions.py +191 -0
  401. synapse/rest/client/voip.py +88 -0
  402. synapse/rest/consent/__init__.py +0 -0
  403. synapse/rest/consent/consent_resource.py +210 -0
  404. synapse/rest/health.py +38 -0
  405. synapse/rest/key/__init__.py +20 -0
  406. synapse/rest/key/v2/__init__.py +40 -0
  407. synapse/rest/key/v2/local_key_resource.py +125 -0
  408. synapse/rest/key/v2/remote_key_resource.py +302 -0
  409. synapse/rest/media/__init__.py +0 -0
  410. synapse/rest/media/config_resource.py +53 -0
  411. synapse/rest/media/create_resource.py +90 -0
  412. synapse/rest/media/download_resource.py +110 -0
  413. synapse/rest/media/media_repository_resource.py +113 -0
  414. synapse/rest/media/preview_url_resource.py +77 -0
  415. synapse/rest/media/thumbnail_resource.py +142 -0
  416. synapse/rest/media/upload_resource.py +187 -0
  417. synapse/rest/media/v1/__init__.py +39 -0
  418. synapse/rest/media/v1/_base.py +23 -0
  419. synapse/rest/media/v1/media_storage.py +23 -0
  420. synapse/rest/media/v1/storage_provider.py +23 -0
  421. synapse/rest/synapse/__init__.py +20 -0
  422. synapse/rest/synapse/client/__init__.py +93 -0
  423. synapse/rest/synapse/client/federation_whitelist.py +66 -0
  424. synapse/rest/synapse/client/jwks.py +77 -0
  425. synapse/rest/synapse/client/new_user_consent.py +115 -0
  426. synapse/rest/synapse/client/oidc/__init__.py +45 -0
  427. synapse/rest/synapse/client/oidc/backchannel_logout_resource.py +42 -0
  428. synapse/rest/synapse/client/oidc/callback_resource.py +48 -0
  429. synapse/rest/synapse/client/password_reset.py +129 -0
  430. synapse/rest/synapse/client/pick_idp.py +107 -0
  431. synapse/rest/synapse/client/pick_username.py +153 -0
  432. synapse/rest/synapse/client/rendezvous.py +58 -0
  433. synapse/rest/synapse/client/saml2/__init__.py +42 -0
  434. synapse/rest/synapse/client/saml2/metadata_resource.py +46 -0
  435. synapse/rest/synapse/client/saml2/response_resource.py +52 -0
  436. synapse/rest/synapse/client/sso_register.py +56 -0
  437. synapse/rest/synapse/client/unsubscribe.py +88 -0
  438. synapse/rest/synapse/mas/__init__.py +71 -0
  439. synapse/rest/synapse/mas/_base.py +55 -0
  440. synapse/rest/synapse/mas/devices.py +239 -0
  441. synapse/rest/synapse/mas/users.py +469 -0
  442. synapse/rest/well_known.py +148 -0
  443. synapse/server.py +1257 -0
  444. synapse/server_notices/__init__.py +0 -0
  445. synapse/server_notices/consent_server_notices.py +136 -0
  446. synapse/server_notices/resource_limits_server_notices.py +215 -0
  447. synapse/server_notices/server_notices_manager.py +388 -0
  448. synapse/server_notices/server_notices_sender.py +67 -0
  449. synapse/server_notices/worker_server_notices_sender.py +46 -0
  450. synapse/spam_checker_api/__init__.py +31 -0
  451. synapse/state/__init__.py +1022 -0
  452. synapse/state/v1.py +369 -0
  453. synapse/state/v2.py +984 -0
  454. synapse/static/client/login/index.html +47 -0
  455. synapse/static/client/login/js/jquery-3.4.1.min.js +2 -0
  456. synapse/static/client/login/js/login.js +291 -0
  457. synapse/static/client/login/spinner.gif +0 -0
  458. synapse/static/client/login/style.css +79 -0
  459. synapse/static/index.html +63 -0
  460. synapse/storage/__init__.py +43 -0
  461. synapse/storage/_base.py +245 -0
  462. synapse/storage/admin_client_config.py +25 -0
  463. synapse/storage/background_updates.py +1188 -0
  464. synapse/storage/controllers/__init__.py +57 -0
  465. synapse/storage/controllers/persist_events.py +1237 -0
  466. synapse/storage/controllers/purge_events.py +455 -0
  467. synapse/storage/controllers/state.py +950 -0
  468. synapse/storage/controllers/stats.py +119 -0
  469. synapse/storage/database.py +2719 -0
  470. synapse/storage/databases/__init__.py +175 -0
  471. synapse/storage/databases/main/__init__.py +420 -0
  472. synapse/storage/databases/main/account_data.py +1059 -0
  473. synapse/storage/databases/main/appservice.py +473 -0
  474. synapse/storage/databases/main/cache.py +911 -0
  475. synapse/storage/databases/main/censor_events.py +225 -0
  476. synapse/storage/databases/main/client_ips.py +815 -0
  477. synapse/storage/databases/main/delayed_events.py +562 -0
  478. synapse/storage/databases/main/deviceinbox.py +1271 -0
  479. synapse/storage/databases/main/devices.py +2578 -0
  480. synapse/storage/databases/main/directory.py +212 -0
  481. synapse/storage/databases/main/e2e_room_keys.py +689 -0
  482. synapse/storage/databases/main/end_to_end_keys.py +1894 -0
  483. synapse/storage/databases/main/event_federation.py +2508 -0
  484. synapse/storage/databases/main/event_push_actions.py +1933 -0
  485. synapse/storage/databases/main/events.py +3765 -0
  486. synapse/storage/databases/main/events_bg_updates.py +2910 -0
  487. synapse/storage/databases/main/events_forward_extremities.py +126 -0
  488. synapse/storage/databases/main/events_worker.py +2786 -0
  489. synapse/storage/databases/main/experimental_features.py +130 -0
  490. synapse/storage/databases/main/filtering.py +231 -0
  491. synapse/storage/databases/main/keys.py +291 -0
  492. synapse/storage/databases/main/lock.py +553 -0
  493. synapse/storage/databases/main/media_repository.py +1068 -0
  494. synapse/storage/databases/main/metrics.py +460 -0
  495. synapse/storage/databases/main/monthly_active_users.py +443 -0
  496. synapse/storage/databases/main/openid.py +60 -0
  497. synapse/storage/databases/main/presence.py +509 -0
  498. synapse/storage/databases/main/profile.py +539 -0
  499. synapse/storage/databases/main/purge_events.py +521 -0
  500. synapse/storage/databases/main/push_rule.py +970 -0
  501. synapse/storage/databases/main/pusher.py +793 -0
  502. synapse/storage/databases/main/receipts.py +1341 -0
  503. synapse/storage/databases/main/registration.py +3072 -0
  504. synapse/storage/databases/main/rejections.py +37 -0
  505. synapse/storage/databases/main/relations.py +1116 -0
  506. synapse/storage/databases/main/room.py +2779 -0
  507. synapse/storage/databases/main/roommember.py +2110 -0
  508. synapse/storage/databases/main/search.py +939 -0
  509. synapse/storage/databases/main/session.py +151 -0
  510. synapse/storage/databases/main/signatures.py +94 -0
  511. synapse/storage/databases/main/sliding_sync.py +603 -0
  512. synapse/storage/databases/main/state.py +1002 -0
  513. synapse/storage/databases/main/state_deltas.py +329 -0
  514. synapse/storage/databases/main/stats.py +789 -0
  515. synapse/storage/databases/main/stream.py +2577 -0
  516. synapse/storage/databases/main/tags.py +360 -0
  517. synapse/storage/databases/main/task_scheduler.py +225 -0
  518. synapse/storage/databases/main/thread_subscriptions.py +589 -0
  519. synapse/storage/databases/main/transactions.py +675 -0
  520. synapse/storage/databases/main/ui_auth.py +420 -0
  521. synapse/storage/databases/main/user_directory.py +1330 -0
  522. synapse/storage/databases/main/user_erasure_store.py +117 -0
  523. synapse/storage/databases/state/__init__.py +22 -0
  524. synapse/storage/databases/state/bg_updates.py +497 -0
  525. synapse/storage/databases/state/deletion.py +557 -0
  526. synapse/storage/databases/state/store.py +948 -0
  527. synapse/storage/engines/__init__.py +70 -0
  528. synapse/storage/engines/_base.py +154 -0
  529. synapse/storage/engines/postgres.py +261 -0
  530. synapse/storage/engines/sqlite.py +199 -0
  531. synapse/storage/invite_rule.py +112 -0
  532. synapse/storage/keys.py +40 -0
  533. synapse/storage/prepare_database.py +730 -0
  534. synapse/storage/push_rule.py +28 -0
  535. synapse/storage/roommember.py +88 -0
  536. synapse/storage/schema/README.md +4 -0
  537. synapse/storage/schema/__init__.py +186 -0
  538. synapse/storage/schema/common/delta/25/00background_updates.sql +40 -0
  539. synapse/storage/schema/common/delta/35/00background_updates_add_col.sql +36 -0
  540. synapse/storage/schema/common/delta/58/00background_update_ordering.sql +38 -0
  541. synapse/storage/schema/common/full_schemas/72/full.sql.postgres +8 -0
  542. synapse/storage/schema/common/full_schemas/72/full.sql.sqlite +6 -0
  543. synapse/storage/schema/common/schema_version.sql +60 -0
  544. synapse/storage/schema/main/delta/12/v12.sql +82 -0
  545. synapse/storage/schema/main/delta/13/v13.sql +38 -0
  546. synapse/storage/schema/main/delta/14/v14.sql +42 -0
  547. synapse/storage/schema/main/delta/15/appservice_txns.sql +50 -0
  548. synapse/storage/schema/main/delta/15/presence_indices.sql +2 -0
  549. synapse/storage/schema/main/delta/15/v15.sql +24 -0
  550. synapse/storage/schema/main/delta/16/events_order_index.sql +4 -0
  551. synapse/storage/schema/main/delta/16/remote_media_cache_index.sql +2 -0
  552. synapse/storage/schema/main/delta/16/remove_duplicates.sql +9 -0
  553. synapse/storage/schema/main/delta/16/room_alias_index.sql +3 -0
  554. synapse/storage/schema/main/delta/16/unique_constraints.sql +72 -0
  555. synapse/storage/schema/main/delta/16/users.sql +56 -0
  556. synapse/storage/schema/main/delta/17/drop_indexes.sql +37 -0
  557. synapse/storage/schema/main/delta/17/server_keys.sql +43 -0
  558. synapse/storage/schema/main/delta/17/user_threepids.sql +9 -0
  559. synapse/storage/schema/main/delta/18/server_keys_bigger_ints.sql +51 -0
  560. synapse/storage/schema/main/delta/19/event_index.sql +38 -0
  561. synapse/storage/schema/main/delta/20/dummy.sql +1 -0
  562. synapse/storage/schema/main/delta/20/pushers.py +93 -0
  563. synapse/storage/schema/main/delta/21/end_to_end_keys.sql +53 -0
  564. synapse/storage/schema/main/delta/21/receipts.sql +57 -0
  565. synapse/storage/schema/main/delta/22/receipts_index.sql +41 -0
  566. synapse/storage/schema/main/delta/22/user_threepids_unique.sql +19 -0
  567. synapse/storage/schema/main/delta/24/stats_reporting.sql +37 -0
  568. synapse/storage/schema/main/delta/25/fts.py +81 -0
  569. synapse/storage/schema/main/delta/25/guest_access.sql +44 -0
  570. synapse/storage/schema/main/delta/25/history_visibility.sql +44 -0
  571. synapse/storage/schema/main/delta/25/tags.sql +57 -0
  572. synapse/storage/schema/main/delta/26/account_data.sql +36 -0
  573. synapse/storage/schema/main/delta/27/account_data.sql +55 -0
  574. synapse/storage/schema/main/delta/27/forgotten_memberships.sql +45 -0
  575. synapse/storage/schema/main/delta/27/ts.py +61 -0
  576. synapse/storage/schema/main/delta/28/event_push_actions.sql +46 -0
  577. synapse/storage/schema/main/delta/28/events_room_stream.sql +39 -0
  578. synapse/storage/schema/main/delta/28/public_roms_index.sql +39 -0
  579. synapse/storage/schema/main/delta/28/receipts_user_id_index.sql +41 -0
  580. synapse/storage/schema/main/delta/28/upgrade_times.sql +40 -0
  581. synapse/storage/schema/main/delta/28/users_is_guest.sql +41 -0
  582. synapse/storage/schema/main/delta/29/push_actions.sql +54 -0
  583. synapse/storage/schema/main/delta/30/alias_creator.sql +35 -0
  584. synapse/storage/schema/main/delta/30/as_users.py +82 -0
  585. synapse/storage/schema/main/delta/30/deleted_pushers.sql +44 -0
  586. synapse/storage/schema/main/delta/30/presence_stream.sql +49 -0
  587. synapse/storage/schema/main/delta/30/public_rooms.sql +42 -0
  588. synapse/storage/schema/main/delta/30/push_rule_stream.sql +57 -0
  589. synapse/storage/schema/main/delta/30/threepid_guest_access_tokens.sql +43 -0
  590. synapse/storage/schema/main/delta/31/invites.sql +61 -0
  591. synapse/storage/schema/main/delta/31/local_media_repository_url_cache.sql +46 -0
  592. synapse/storage/schema/main/delta/31/pushers_0.py +92 -0
  593. synapse/storage/schema/main/delta/31/pushers_index.sql +41 -0
  594. synapse/storage/schema/main/delta/31/search_update.py +65 -0
  595. synapse/storage/schema/main/delta/32/events.sql +35 -0
  596. synapse/storage/schema/main/delta/32/openid.sql +9 -0
  597. synapse/storage/schema/main/delta/32/pusher_throttle.sql +42 -0
  598. synapse/storage/schema/main/delta/32/remove_indices.sql +52 -0
  599. synapse/storage/schema/main/delta/32/reports.sql +44 -0
  600. synapse/storage/schema/main/delta/33/access_tokens_device_index.sql +36 -0
  601. synapse/storage/schema/main/delta/33/devices.sql +40 -0
  602. synapse/storage/schema/main/delta/33/devices_for_e2e_keys.sql +38 -0
  603. synapse/storage/schema/main/delta/33/devices_for_e2e_keys_clear_unknown_device.sql +39 -0
  604. synapse/storage/schema/main/delta/33/event_fields.py +61 -0
  605. synapse/storage/schema/main/delta/33/remote_media_ts.py +43 -0
  606. synapse/storage/schema/main/delta/33/user_ips_index.sql +36 -0
  607. synapse/storage/schema/main/delta/34/appservice_stream.sql +42 -0
  608. synapse/storage/schema/main/delta/34/cache_stream.py +50 -0
  609. synapse/storage/schema/main/delta/34/device_inbox.sql +43 -0
  610. synapse/storage/schema/main/delta/34/push_display_name_rename.sql +39 -0
  611. synapse/storage/schema/main/delta/34/received_txn_purge.py +36 -0
  612. synapse/storage/schema/main/delta/35/contains_url.sql +36 -0
  613. synapse/storage/schema/main/delta/35/device_outbox.sql +58 -0
  614. synapse/storage/schema/main/delta/35/device_stream_id.sql +40 -0
  615. synapse/storage/schema/main/delta/35/event_push_actions_index.sql +36 -0
  616. synapse/storage/schema/main/delta/35/public_room_list_change_stream.sql +52 -0
  617. synapse/storage/schema/main/delta/35/stream_order_to_extrem.sql +56 -0
  618. synapse/storage/schema/main/delta/36/readd_public_rooms.sql +45 -0
  619. synapse/storage/schema/main/delta/37/remove_auth_idx.py +89 -0
  620. synapse/storage/schema/main/delta/37/user_threepids.sql +71 -0
  621. synapse/storage/schema/main/delta/38/postgres_fts_gist.sql +38 -0
  622. synapse/storage/schema/main/delta/39/appservice_room_list.sql +48 -0
  623. synapse/storage/schema/main/delta/39/device_federation_stream_idx.sql +35 -0
  624. synapse/storage/schema/main/delta/39/event_push_index.sql +36 -0
  625. synapse/storage/schema/main/delta/39/federation_out_position.sql +41 -0
  626. synapse/storage/schema/main/delta/39/membership_profile.sql +39 -0
  627. synapse/storage/schema/main/delta/40/current_state_idx.sql +36 -0
  628. synapse/storage/schema/main/delta/40/device_inbox.sql +40 -0
  629. synapse/storage/schema/main/delta/40/device_list_streams.sql +79 -0
  630. synapse/storage/schema/main/delta/40/event_push_summary.sql +57 -0
  631. synapse/storage/schema/main/delta/40/pushers.sql +58 -0
  632. synapse/storage/schema/main/delta/41/device_list_stream_idx.sql +36 -0
  633. synapse/storage/schema/main/delta/41/device_outbound_index.sql +35 -0
  634. synapse/storage/schema/main/delta/41/event_search_event_id_idx.sql +36 -0
  635. synapse/storage/schema/main/delta/41/ratelimit.sql +41 -0
  636. synapse/storage/schema/main/delta/42/current_state_delta.sql +48 -0
  637. synapse/storage/schema/main/delta/42/device_list_last_id.sql +52 -0
  638. synapse/storage/schema/main/delta/42/event_auth_state_only.sql +36 -0
  639. synapse/storage/schema/main/delta/42/user_dir.py +88 -0
  640. synapse/storage/schema/main/delta/43/blocked_rooms.sql +40 -0
  641. synapse/storage/schema/main/delta/43/quarantine_media.sql +36 -0
  642. synapse/storage/schema/main/delta/43/url_cache.sql +35 -0
  643. synapse/storage/schema/main/delta/43/user_share.sql +52 -0
  644. synapse/storage/schema/main/delta/44/expire_url_cache.sql +60 -0
  645. synapse/storage/schema/main/delta/45/group_server.sql +186 -0
  646. synapse/storage/schema/main/delta/45/profile_cache.sql +47 -0
  647. synapse/storage/schema/main/delta/46/drop_refresh_tokens.sql +36 -0
  648. synapse/storage/schema/main/delta/46/drop_unique_deleted_pushers.sql +54 -0
  649. synapse/storage/schema/main/delta/46/group_server.sql +51 -0
  650. synapse/storage/schema/main/delta/46/local_media_repository_url_idx.sql +43 -0
  651. synapse/storage/schema/main/delta/46/user_dir_null_room_ids.sql +54 -0
  652. synapse/storage/schema/main/delta/46/user_dir_typos.sql +43 -0
  653. synapse/storage/schema/main/delta/47/last_access_media.sql +35 -0
  654. synapse/storage/schema/main/delta/47/postgres_fts_gin.sql +36 -0
  655. synapse/storage/schema/main/delta/47/push_actions_staging.sql +47 -0
  656. synapse/storage/schema/main/delta/48/add_user_consent.sql +37 -0
  657. synapse/storage/schema/main/delta/48/add_user_ips_last_seen_index.sql +36 -0
  658. synapse/storage/schema/main/delta/48/deactivated_users.sql +44 -0
  659. synapse/storage/schema/main/delta/48/group_unique_indexes.py +67 -0
  660. synapse/storage/schema/main/delta/48/groups_joinable.sql +41 -0
  661. synapse/storage/schema/main/delta/49/add_user_consent_server_notice_sent.sql +39 -0
  662. synapse/storage/schema/main/delta/49/add_user_daily_visits.sql +40 -0
  663. synapse/storage/schema/main/delta/49/add_user_ips_last_seen_only_index.sql +36 -0
  664. synapse/storage/schema/main/delta/50/add_creation_ts_users_index.sql +38 -0
  665. synapse/storage/schema/main/delta/50/erasure_store.sql +40 -0
  666. synapse/storage/schema/main/delta/50/make_event_content_nullable.py +102 -0
  667. synapse/storage/schema/main/delta/51/e2e_room_keys.sql +58 -0
  668. synapse/storage/schema/main/delta/51/monthly_active_users.sql +46 -0
  669. synapse/storage/schema/main/delta/52/add_event_to_state_group_index.sql +38 -0
  670. synapse/storage/schema/main/delta/52/device_list_streams_unique_idx.sql +55 -0
  671. synapse/storage/schema/main/delta/52/e2e_room_keys.sql +72 -0
  672. synapse/storage/schema/main/delta/53/add_user_type_to_users.sql +38 -0
  673. synapse/storage/schema/main/delta/53/drop_sent_transactions.sql +35 -0
  674. synapse/storage/schema/main/delta/53/event_format_version.sql +35 -0
  675. synapse/storage/schema/main/delta/53/user_dir_populate.sql +49 -0
  676. synapse/storage/schema/main/delta/53/user_ips_index.sql +49 -0
  677. synapse/storage/schema/main/delta/53/user_share.sql +63 -0
  678. synapse/storage/schema/main/delta/53/user_threepid_id.sql +48 -0
  679. synapse/storage/schema/main/delta/53/users_in_public_rooms.sql +47 -0
  680. synapse/storage/schema/main/delta/54/account_validity_with_renewal.sql +49 -0
  681. synapse/storage/schema/main/delta/54/add_validity_to_server_keys.sql +42 -0
  682. synapse/storage/schema/main/delta/54/delete_forward_extremities.sql +42 -0
  683. synapse/storage/schema/main/delta/54/drop_legacy_tables.sql +49 -0
  684. synapse/storage/schema/main/delta/54/drop_presence_list.sql +35 -0
  685. synapse/storage/schema/main/delta/54/relations.sql +46 -0
  686. synapse/storage/schema/main/delta/54/stats.sql +99 -0
  687. synapse/storage/schema/main/delta/54/stats2.sql +47 -0
  688. synapse/storage/schema/main/delta/55/access_token_expiry.sql +37 -0
  689. synapse/storage/schema/main/delta/55/track_threepid_validations.sql +50 -0
  690. synapse/storage/schema/main/delta/55/users_alter_deactivated.sql +38 -0
  691. synapse/storage/schema/main/delta/56/add_spans_to_device_lists.sql +39 -0
  692. synapse/storage/schema/main/delta/56/current_state_events_membership.sql +41 -0
  693. synapse/storage/schema/main/delta/56/current_state_events_membership_mk2.sql +43 -0
  694. synapse/storage/schema/main/delta/56/delete_keys_from_deleted_backups.sql +44 -0
  695. synapse/storage/schema/main/delta/56/destinations_failure_ts.sql +44 -0
  696. synapse/storage/schema/main/delta/56/destinations_retry_interval_type.sql.postgres +18 -0
  697. synapse/storage/schema/main/delta/56/device_stream_id_insert.sql +39 -0
  698. synapse/storage/schema/main/delta/56/devices_last_seen.sql +43 -0
  699. synapse/storage/schema/main/delta/56/drop_unused_event_tables.sql +39 -0
  700. synapse/storage/schema/main/delta/56/event_expiry.sql +40 -0
  701. synapse/storage/schema/main/delta/56/event_labels.sql +49 -0
  702. synapse/storage/schema/main/delta/56/event_labels_background_update.sql +36 -0
  703. synapse/storage/schema/main/delta/56/fix_room_keys_index.sql +37 -0
  704. synapse/storage/schema/main/delta/56/hidden_devices.sql +37 -0
  705. synapse/storage/schema/main/delta/56/hidden_devices_fix.sql.sqlite +42 -0
  706. synapse/storage/schema/main/delta/56/nuke_empty_communities_from_db.sql +48 -0
  707. synapse/storage/schema/main/delta/56/public_room_list_idx.sql +35 -0
  708. synapse/storage/schema/main/delta/56/redaction_censor.sql +35 -0
  709. synapse/storage/schema/main/delta/56/redaction_censor2.sql +41 -0
  710. synapse/storage/schema/main/delta/56/redaction_censor3_fix_update.sql.postgres +25 -0
  711. synapse/storage/schema/main/delta/56/redaction_censor4.sql +35 -0
  712. synapse/storage/schema/main/delta/56/remove_tombstoned_rooms_from_directory.sql +38 -0
  713. synapse/storage/schema/main/delta/56/room_key_etag.sql +36 -0
  714. synapse/storage/schema/main/delta/56/room_membership_idx.sql +37 -0
  715. synapse/storage/schema/main/delta/56/room_retention.sql +52 -0
  716. synapse/storage/schema/main/delta/56/signing_keys.sql +75 -0
  717. synapse/storage/schema/main/delta/56/signing_keys_nonunique_signatures.sql +41 -0
  718. synapse/storage/schema/main/delta/56/stats_separated.sql +175 -0
  719. synapse/storage/schema/main/delta/56/unique_user_filter_index.py +46 -0
  720. synapse/storage/schema/main/delta/56/user_external_ids.sql +43 -0
  721. synapse/storage/schema/main/delta/56/users_in_public_rooms_idx.sql +36 -0
  722. synapse/storage/schema/main/delta/57/delete_old_current_state_events.sql +41 -0
  723. synapse/storage/schema/main/delta/57/device_list_remote_cache_stale.sql +44 -0
  724. synapse/storage/schema/main/delta/57/local_current_membership.py +111 -0
  725. synapse/storage/schema/main/delta/57/remove_sent_outbound_pokes.sql +40 -0
  726. synapse/storage/schema/main/delta/57/rooms_version_column.sql +43 -0
  727. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.postgres +35 -0
  728. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.sqlite +22 -0
  729. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.postgres +39 -0
  730. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.sqlite +23 -0
  731. synapse/storage/schema/main/delta/58/02remove_dup_outbound_pokes.sql +41 -0
  732. synapse/storage/schema/main/delta/58/03persist_ui_auth.sql +55 -0
  733. synapse/storage/schema/main/delta/58/05cache_instance.sql.postgres +30 -0
  734. synapse/storage/schema/main/delta/58/06dlols_unique_idx.py +83 -0
  735. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.postgres +33 -0
  736. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.sqlite +44 -0
  737. synapse/storage/schema/main/delta/58/07persist_ui_auth_ips.sql +44 -0
  738. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.postgres +18 -0
  739. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.sqlite +18 -0
  740. synapse/storage/schema/main/delta/58/09shadow_ban.sql +37 -0
  741. synapse/storage/schema/main/delta/58/10_pushrules_enabled_delete_obsolete.sql +47 -0
  742. synapse/storage/schema/main/delta/58/10drop_local_rejections_stream.sql +41 -0
  743. synapse/storage/schema/main/delta/58/10federation_pos_instance_name.sql +41 -0
  744. synapse/storage/schema/main/delta/58/11dehydration.sql +39 -0
  745. synapse/storage/schema/main/delta/58/11fallback.sql +43 -0
  746. synapse/storage/schema/main/delta/58/11user_id_seq.py +38 -0
  747. synapse/storage/schema/main/delta/58/12room_stats.sql +51 -0
  748. synapse/storage/schema/main/delta/58/13remove_presence_allow_inbound.sql +36 -0
  749. synapse/storage/schema/main/delta/58/14events_instance_name.sql +35 -0
  750. synapse/storage/schema/main/delta/58/14events_instance_name.sql.postgres +28 -0
  751. synapse/storage/schema/main/delta/58/15_catchup_destination_rooms.sql +61 -0
  752. synapse/storage/schema/main/delta/58/15unread_count.sql +45 -0
  753. synapse/storage/schema/main/delta/58/16populate_stats_process_rooms_fix.sql +41 -0
  754. synapse/storage/schema/main/delta/58/17_catchup_last_successful.sql +40 -0
  755. synapse/storage/schema/main/delta/58/18stream_positions.sql +41 -0
  756. synapse/storage/schema/main/delta/58/19instance_map.sql.postgres +25 -0
  757. synapse/storage/schema/main/delta/58/19txn_id.sql +59 -0
  758. synapse/storage/schema/main/delta/58/20instance_name_event_tables.sql +36 -0
  759. synapse/storage/schema/main/delta/58/20user_daily_visits.sql +37 -0
  760. synapse/storage/schema/main/delta/58/21as_device_stream.sql +36 -0
  761. synapse/storage/schema/main/delta/58/21drop_device_max_stream_id.sql +1 -0
  762. synapse/storage/schema/main/delta/58/22puppet_token.sql +36 -0
  763. synapse/storage/schema/main/delta/58/22users_have_local_media.sql +2 -0
  764. synapse/storage/schema/main/delta/58/23e2e_cross_signing_keys_idx.sql +36 -0
  765. synapse/storage/schema/main/delta/58/24drop_event_json_index.sql +38 -0
  766. synapse/storage/schema/main/delta/58/25user_external_ids_user_id_idx.sql +36 -0
  767. synapse/storage/schema/main/delta/58/26access_token_last_validated.sql +37 -0
  768. synapse/storage/schema/main/delta/58/27local_invites.sql +37 -0
  769. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.postgres +16 -0
  770. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.sqlite +62 -0
  771. synapse/storage/schema/main/delta/59/01ignored_user.py +85 -0
  772. synapse/storage/schema/main/delta/59/02shard_send_to_device.sql +37 -0
  773. synapse/storage/schema/main/delta/59/03shard_send_to_device_sequence.sql.postgres +25 -0
  774. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql +71 -0
  775. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql.postgres +16 -0
  776. synapse/storage/schema/main/delta/59/04drop_account_data.sql +36 -0
  777. synapse/storage/schema/main/delta/59/05cache_invalidation.sql +36 -0
  778. synapse/storage/schema/main/delta/59/06chain_cover_index.sql +36 -0
  779. synapse/storage/schema/main/delta/59/06shard_account_data.sql +39 -0
  780. synapse/storage/schema/main/delta/59/06shard_account_data.sql.postgres +32 -0
  781. synapse/storage/schema/main/delta/59/07shard_account_data_fix.sql +37 -0
  782. synapse/storage/schema/main/delta/59/08delete_pushers_for_deactivated_accounts.sql +39 -0
  783. synapse/storage/schema/main/delta/59/08delete_stale_pushers.sql +39 -0
  784. synapse/storage/schema/main/delta/59/09rejected_events_metadata.sql +45 -0
  785. synapse/storage/schema/main/delta/59/10delete_purged_chain_cover.sql +36 -0
  786. synapse/storage/schema/main/delta/59/11add_knock_members_to_stats.sql +39 -0
  787. synapse/storage/schema/main/delta/59/11drop_thumbnail_constraint.sql.postgres +22 -0
  788. synapse/storage/schema/main/delta/59/12account_validity_token_used_ts_ms.sql +37 -0
  789. synapse/storage/schema/main/delta/59/12presence_stream_instance.sql +37 -0
  790. synapse/storage/schema/main/delta/59/12presence_stream_instance_seq.sql.postgres +20 -0
  791. synapse/storage/schema/main/delta/59/13users_to_send_full_presence_to.sql +53 -0
  792. synapse/storage/schema/main/delta/59/14refresh_tokens.sql +53 -0
  793. synapse/storage/schema/main/delta/59/15locks.sql +56 -0
  794. synapse/storage/schema/main/delta/59/16federation_inbound_staging.sql +51 -0
  795. synapse/storage/schema/main/delta/60/01recreate_stream_ordering.sql.postgres +45 -0
  796. synapse/storage/schema/main/delta/60/02change_stream_ordering_columns.sql.postgres +30 -0
  797. synapse/storage/schema/main/delta/61/01change_appservices_txns.sql.postgres +23 -0
  798. synapse/storage/schema/main/delta/61/01insertion_event_lookups.sql +68 -0
  799. synapse/storage/schema/main/delta/61/02drop_redundant_room_depth_index.sql +37 -0
  800. synapse/storage/schema/main/delta/61/03recreate_min_depth.py +74 -0
  801. synapse/storage/schema/main/delta/62/01insertion_event_extremities.sql +43 -0
  802. synapse/storage/schema/main/delta/63/01create_registration_tokens.sql +42 -0
  803. synapse/storage/schema/main/delta/63/02delete_unlinked_email_pushers.sql +39 -0
  804. synapse/storage/schema/main/delta/63/02populate-rooms-creator.sql +36 -0
  805. synapse/storage/schema/main/delta/63/03session_store.sql +42 -0
  806. synapse/storage/schema/main/delta/63/04add_presence_stream_not_offline_index.sql +37 -0
  807. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.postgres +23 -0
  808. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.sqlite +37 -0
  809. synapse/storage/schema/main/delta/65/01msc2716_insertion_event_edges.sql +38 -0
  810. synapse/storage/schema/main/delta/65/03remove_hidden_devices_from_device_inbox.sql +41 -0
  811. synapse/storage/schema/main/delta/65/04_local_group_updates.sql +37 -0
  812. synapse/storage/schema/main/delta/65/05_remove_room_stats_historical_and_user_stats_historical.sql +38 -0
  813. synapse/storage/schema/main/delta/65/06remove_deleted_devices_from_device_inbox.sql +53 -0
  814. synapse/storage/schema/main/delta/65/07_arbitrary_relations.sql +37 -0
  815. synapse/storage/schema/main/delta/65/08_device_inbox_background_updates.sql +37 -0
  816. synapse/storage/schema/main/delta/65/10_expirable_refresh_tokens.sql +47 -0
  817. synapse/storage/schema/main/delta/65/11_devices_auth_provider_session.sql +46 -0
  818. synapse/storage/schema/main/delta/67/01drop_public_room_list_stream.sql +37 -0
  819. synapse/storage/schema/main/delta/68/01event_columns.sql +45 -0
  820. synapse/storage/schema/main/delta/68/02_msc2409_add_device_id_appservice_stream_type.sql +40 -0
  821. synapse/storage/schema/main/delta/68/03_delete_account_data_for_deactivated_accounts.sql +39 -0
  822. synapse/storage/schema/main/delta/68/04_refresh_tokens_index_next_token_id.sql +47 -0
  823. synapse/storage/schema/main/delta/68/04partial_state_rooms.sql +60 -0
  824. synapse/storage/schema/main/delta/68/05_delete_non_strings_from_event_search.sql.sqlite +22 -0
  825. synapse/storage/schema/main/delta/68/05partial_state_rooms_triggers.py +80 -0
  826. synapse/storage/schema/main/delta/68/06_msc3202_add_device_list_appservice_stream_type.sql +42 -0
  827. synapse/storage/schema/main/delta/69/01as_txn_seq.py +54 -0
  828. synapse/storage/schema/main/delta/69/01device_list_oubound_by_room.sql +57 -0
  829. synapse/storage/schema/main/delta/69/02cache_invalidation_index.sql +37 -0
  830. synapse/storage/schema/main/delta/70/01clean_table_purged_rooms.sql +39 -0
  831. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.postgres +43 -0
  832. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.sqlite +47 -0
  833. synapse/storage/schema/main/delta/71/01remove_noop_background_updates.sql +80 -0
  834. synapse/storage/schema/main/delta/71/02event_push_summary_unique.sql +37 -0
  835. synapse/storage/schema/main/delta/72/01add_room_type_to_state_stats.sql +38 -0
  836. synapse/storage/schema/main/delta/72/01event_push_summary_receipt.sql +54 -0
  837. synapse/storage/schema/main/delta/72/02event_push_actions_index.sql +38 -0
  838. synapse/storage/schema/main/delta/72/03bg_populate_events_columns.py +57 -0
  839. synapse/storage/schema/main/delta/72/03drop_event_reference_hashes.sql +36 -0
  840. synapse/storage/schema/main/delta/72/03remove_groups.sql +50 -0
  841. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.postgres +17 -0
  842. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.sqlite +40 -0
  843. synapse/storage/schema/main/delta/72/05receipts_event_stream_ordering.sql +38 -0
  844. synapse/storage/schema/main/delta/72/05remove_unstable_private_read_receipts.sql +38 -0
  845. synapse/storage/schema/main/delta/72/06add_consent_ts_to_users.sql +35 -0
  846. synapse/storage/schema/main/delta/72/06thread_notifications.sql +49 -0
  847. synapse/storage/schema/main/delta/72/07force_update_current_state_events_membership.py +67 -0
  848. synapse/storage/schema/main/delta/72/07thread_receipts.sql.postgres +30 -0
  849. synapse/storage/schema/main/delta/72/07thread_receipts.sql.sqlite +70 -0
  850. synapse/storage/schema/main/delta/72/08begin_cache_invalidation_seq_at_2.sql.postgres +23 -0
  851. synapse/storage/schema/main/delta/72/08thread_receipts.sql +39 -0
  852. synapse/storage/schema/main/delta/72/09partial_indices.sql.sqlite +56 -0
  853. synapse/storage/schema/main/delta/73/01event_failed_pull_attempts.sql +48 -0
  854. synapse/storage/schema/main/delta/73/02add_pusher_enabled.sql +35 -0
  855. synapse/storage/schema/main/delta/73/02room_id_indexes_for_purging.sql +41 -0
  856. synapse/storage/schema/main/delta/73/03pusher_device_id.sql +39 -0
  857. synapse/storage/schema/main/delta/73/03users_approved_column.sql +39 -0
  858. synapse/storage/schema/main/delta/73/04partial_join_details.sql +42 -0
  859. synapse/storage/schema/main/delta/73/04pending_device_list_updates.sql +47 -0
  860. synapse/storage/schema/main/delta/73/05old_push_actions.sql.postgres +22 -0
  861. synapse/storage/schema/main/delta/73/05old_push_actions.sql.sqlite +24 -0
  862. synapse/storage/schema/main/delta/73/06thread_notifications_thread_id_idx.sql +42 -0
  863. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.postgres +23 -0
  864. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.sqlite +76 -0
  865. synapse/storage/schema/main/delta/73/09partial_joined_via_destination.sql +37 -0
  866. synapse/storage/schema/main/delta/73/09threads_table.sql +49 -0
  867. synapse/storage/schema/main/delta/73/10_update_sqlite_fts4_tokenizer.py +71 -0
  868. synapse/storage/schema/main/delta/73/10login_tokens.sql +54 -0
  869. synapse/storage/schema/main/delta/73/11event_search_room_id_n_distinct.sql.postgres +33 -0
  870. synapse/storage/schema/main/delta/73/12refactor_device_list_outbound_pokes.sql +72 -0
  871. synapse/storage/schema/main/delta/73/13add_device_lists_index.sql +39 -0
  872. synapse/storage/schema/main/delta/73/20_un_partial_stated_room_stream.sql +51 -0
  873. synapse/storage/schema/main/delta/73/21_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  874. synapse/storage/schema/main/delta/73/22_rebuild_user_dir_stats.sql +48 -0
  875. synapse/storage/schema/main/delta/73/22_un_partial_stated_event_stream.sql +53 -0
  876. synapse/storage/schema/main/delta/73/23_fix_thread_index.sql +52 -0
  877. synapse/storage/schema/main/delta/73/23_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  878. synapse/storage/schema/main/delta/73/24_events_jump_to_date_index.sql +36 -0
  879. synapse/storage/schema/main/delta/73/25drop_presence.sql +36 -0
  880. synapse/storage/schema/main/delta/74/01_user_directory_stale_remote_users.sql +58 -0
  881. synapse/storage/schema/main/delta/74/02_set_device_id_for_pushers_bg_update.sql +38 -0
  882. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.postgres +29 -0
  883. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.sqlite +23 -0
  884. synapse/storage/schema/main/delta/74/03_room_membership_index.sql +38 -0
  885. synapse/storage/schema/main/delta/74/04_delete_e2e_backup_keys_for_deactivated_users.sql +36 -0
  886. synapse/storage/schema/main/delta/74/04_membership_tables_event_stream_ordering_triggers.py +87 -0
  887. synapse/storage/schema/main/delta/74/05_events_txn_id_device_id.sql +72 -0
  888. synapse/storage/schema/main/delta/74/90COMMENTS_destinations.sql.postgres +52 -0
  889. synapse/storage/schema/main/delta/76/01_add_profiles_full_user_id_column.sql +39 -0
  890. synapse/storage/schema/main/delta/76/02_add_user_filters_full_user_id_column.sql +39 -0
  891. synapse/storage/schema/main/delta/76/03_per_user_experimental_features.sql +46 -0
  892. synapse/storage/schema/main/delta/76/04_add_room_forgetter.sql +43 -0
  893. synapse/storage/schema/main/delta/77/01_add_profiles_not_valid_check.sql.postgres +16 -0
  894. synapse/storage/schema/main/delta/77/02_add_user_filters_not_valid_check.sql.postgres +16 -0
  895. synapse/storage/schema/main/delta/77/03bg_populate_full_user_id_profiles.sql +35 -0
  896. synapse/storage/schema/main/delta/77/04bg_populate_full_user_id_user_filters.sql +35 -0
  897. synapse/storage/schema/main/delta/77/05thread_notifications_backfill.sql +67 -0
  898. synapse/storage/schema/main/delta/77/06thread_notifications_not_null.sql.sqlite +102 -0
  899. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions.sql.postgres +27 -0
  900. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions_staging.sql.postgres +27 -0
  901. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_summary.sql.postgres +29 -0
  902. synapse/storage/schema/main/delta/77/14bg_indices_event_stream_ordering.sql +39 -0
  903. synapse/storage/schema/main/delta/78/01_validate_and_update_profiles.py +99 -0
  904. synapse/storage/schema/main/delta/78/02_validate_and_update_user_filters.py +100 -0
  905. synapse/storage/schema/main/delta/78/03_remove_unused_indexes_user_filters.py +72 -0
  906. synapse/storage/schema/main/delta/78/03event_extremities_constraints.py +65 -0
  907. synapse/storage/schema/main/delta/78/04_add_full_user_id_index_user_filters.py +32 -0
  908. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.postgres +102 -0
  909. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.sqlite +72 -0
  910. synapse/storage/schema/main/delta/79/04_mitigate_stream_ordering_update_race.py +70 -0
  911. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.postgres +69 -0
  912. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.sqlite +65 -0
  913. synapse/storage/schema/main/delta/80/01_users_alter_locked.sql +35 -0
  914. synapse/storage/schema/main/delta/80/02_read_write_locks_unlogged.sql.postgres +30 -0
  915. synapse/storage/schema/main/delta/80/02_scheduled_tasks.sql +47 -0
  916. synapse/storage/schema/main/delta/80/03_read_write_locks_triggers.sql.postgres +37 -0
  917. synapse/storage/schema/main/delta/80/04_read_write_locks_deadlock.sql.postgres +71 -0
  918. synapse/storage/schema/main/delta/82/02_scheduled_tasks_index.sql +35 -0
  919. synapse/storage/schema/main/delta/82/04_add_indices_for_purging_rooms.sql +39 -0
  920. synapse/storage/schema/main/delta/82/05gaps.sql +44 -0
  921. synapse/storage/schema/main/delta/83/01_drop_old_tables.sql +43 -0
  922. synapse/storage/schema/main/delta/83/03_instance_name_receipts.sql.sqlite +17 -0
  923. synapse/storage/schema/main/delta/83/05_cross_signing_key_update_grant.sql +34 -0
  924. synapse/storage/schema/main/delta/83/06_event_push_summary_room.sql +36 -0
  925. synapse/storage/schema/main/delta/84/01_auth_links_stats.sql.postgres +20 -0
  926. synapse/storage/schema/main/delta/84/02_auth_links_index.sql +16 -0
  927. synapse/storage/schema/main/delta/84/03_auth_links_analyze.sql.postgres +16 -0
  928. synapse/storage/schema/main/delta/84/04_access_token_index.sql +15 -0
  929. synapse/storage/schema/main/delta/85/01_add_suspended.sql +14 -0
  930. synapse/storage/schema/main/delta/85/02_add_instance_names.sql +27 -0
  931. synapse/storage/schema/main/delta/85/03_new_sequences.sql.postgres +54 -0
  932. synapse/storage/schema/main/delta/85/04_cleanup_device_federation_outbox.sql +15 -0
  933. synapse/storage/schema/main/delta/85/05_add_instance_names_converted_pos.sql +16 -0
  934. synapse/storage/schema/main/delta/85/06_add_room_reports.sql +20 -0
  935. synapse/storage/schema/main/delta/86/01_authenticate_media.sql +15 -0
  936. synapse/storage/schema/main/delta/86/02_receipts_event_id_index.sql +15 -0
  937. synapse/storage/schema/main/delta/87/01_sliding_sync_memberships.sql +169 -0
  938. synapse/storage/schema/main/delta/87/02_per_connection_state.sql +81 -0
  939. synapse/storage/schema/main/delta/87/03_current_state_index.sql +19 -0
  940. synapse/storage/schema/main/delta/88/01_add_delayed_events.sql +43 -0
  941. synapse/storage/schema/main/delta/88/01_custom_profile_fields.sql +15 -0
  942. synapse/storage/schema/main/delta/88/02_fix_sliding_sync_membership_snapshots_forgotten_column.sql +21 -0
  943. synapse/storage/schema/main/delta/88/03_add_otk_ts_added_index.sql +18 -0
  944. synapse/storage/schema/main/delta/88/04_current_state_delta_index.sql +18 -0
  945. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.postgres +19 -0
  946. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.sqlite +19 -0
  947. synapse/storage/schema/main/delta/88/05_sliding_sync_room_config_index.sql +20 -0
  948. synapse/storage/schema/main/delta/88/06_events_received_ts_index.sql +17 -0
  949. synapse/storage/schema/main/delta/89/01_sliding_sync_membership_snapshot_index.sql +15 -0
  950. synapse/storage/schema/main/delta/90/01_add_column_participant_room_memberships_table.sql +16 -0
  951. synapse/storage/schema/main/delta/91/01_media_hash.sql +28 -0
  952. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.postgres +16 -0
  953. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.sqlite +16 -0
  954. synapse/storage/schema/main/delta/92/02_remove_populate_participant_bg_update.sql +17 -0
  955. synapse/storage/schema/main/delta/92/04_ss_membership_snapshot_idx.sql +16 -0
  956. synapse/storage/schema/main/delta/92/04_thread_subscriptions.sql +59 -0
  957. synapse/storage/schema/main/delta/92/04_thread_subscriptions_seq.sql.postgres +19 -0
  958. synapse/storage/schema/main/delta/92/05_fixup_max_depth_cap.sql +17 -0
  959. synapse/storage/schema/main/delta/92/05_thread_subscriptions_comments.sql.postgres +18 -0
  960. synapse/storage/schema/main/delta/92/06_device_federation_inbox_index.sql +16 -0
  961. synapse/storage/schema/main/delta/92/06_threads_last_sent_stream_ordering_comments.sql.postgres +24 -0
  962. synapse/storage/schema/main/delta/92/07_add_user_reports.sql +22 -0
  963. synapse/storage/schema/main/delta/92/07_event_txn_id_device_id_txn_id2.sql +15 -0
  964. synapse/storage/schema/main/delta/92/08_room_ban_redactions.sql +21 -0
  965. synapse/storage/schema/main/delta/92/08_thread_subscriptions_seq_fixup.sql.postgres +19 -0
  966. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql +20 -0
  967. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql.postgres +18 -0
  968. synapse/storage/schema/main/delta/93/01_add_delayed_events.sql +15 -0
  969. synapse/storage/schema/main/full_schemas/72/full.sql.postgres +1344 -0
  970. synapse/storage/schema/main/full_schemas/72/full.sql.sqlite +646 -0
  971. synapse/storage/schema/state/delta/23/drop_state_index.sql +35 -0
  972. synapse/storage/schema/state/delta/32/remove_state_indices.sql +38 -0
  973. synapse/storage/schema/state/delta/35/add_state_index.sql +36 -0
  974. synapse/storage/schema/state/delta/35/state.sql +41 -0
  975. synapse/storage/schema/state/delta/35/state_dedupe.sql +36 -0
  976. synapse/storage/schema/state/delta/47/state_group_seq.py +38 -0
  977. synapse/storage/schema/state/delta/56/state_group_room_idx.sql +36 -0
  978. synapse/storage/schema/state/delta/61/02state_groups_state_n_distinct.sql.postgres +34 -0
  979. synapse/storage/schema/state/delta/70/08_state_group_edges_unique.sql +36 -0
  980. synapse/storage/schema/state/delta/89/01_state_groups_deletion.sql +39 -0
  981. synapse/storage/schema/state/delta/90/02_delete_unreferenced_state_groups.sql +16 -0
  982. synapse/storage/schema/state/delta/90/03_remove_old_deletion_bg_update.sql +15 -0
  983. synapse/storage/schema/state/full_schemas/72/full.sql.postgres +30 -0
  984. synapse/storage/schema/state/full_schemas/72/full.sql.sqlite +20 -0
  985. synapse/storage/types.py +183 -0
  986. synapse/storage/util/__init__.py +20 -0
  987. synapse/storage/util/id_generators.py +928 -0
  988. synapse/storage/util/partial_state_events_tracker.py +194 -0
  989. synapse/storage/util/sequence.py +315 -0
  990. synapse/streams/__init__.py +43 -0
  991. synapse/streams/config.py +91 -0
  992. synapse/streams/events.py +203 -0
  993. synapse/synapse_rust/__init__.pyi +3 -0
  994. synapse/synapse_rust/acl.pyi +20 -0
  995. synapse/synapse_rust/events.pyi +136 -0
  996. synapse/synapse_rust/http_client.pyi +32 -0
  997. synapse/synapse_rust/push.pyi +86 -0
  998. synapse/synapse_rust/rendezvous.pyi +30 -0
  999. synapse/synapse_rust/segmenter.pyi +1 -0
  1000. synapse/synapse_rust.abi3.so +0 -0
  1001. synapse/types/__init__.py +1600 -0
  1002. synapse/types/handlers/__init__.py +93 -0
  1003. synapse/types/handlers/policy_server.py +16 -0
  1004. synapse/types/handlers/sliding_sync.py +908 -0
  1005. synapse/types/rest/__init__.py +25 -0
  1006. synapse/types/rest/client/__init__.py +413 -0
  1007. synapse/types/state.py +634 -0
  1008. synapse/types/storage/__init__.py +66 -0
  1009. synapse/util/__init__.py +169 -0
  1010. synapse/util/async_helpers.py +1045 -0
  1011. synapse/util/background_queue.py +142 -0
  1012. synapse/util/batching_queue.py +202 -0
  1013. synapse/util/caches/__init__.py +300 -0
  1014. synapse/util/caches/cached_call.py +143 -0
  1015. synapse/util/caches/deferred_cache.py +530 -0
  1016. synapse/util/caches/descriptors.py +692 -0
  1017. synapse/util/caches/dictionary_cache.py +346 -0
  1018. synapse/util/caches/expiringcache.py +249 -0
  1019. synapse/util/caches/lrucache.py +975 -0
  1020. synapse/util/caches/response_cache.py +322 -0
  1021. synapse/util/caches/stream_change_cache.py +370 -0
  1022. synapse/util/caches/treecache.py +189 -0
  1023. synapse/util/caches/ttlcache.py +197 -0
  1024. synapse/util/cancellation.py +63 -0
  1025. synapse/util/check_dependencies.py +335 -0
  1026. synapse/util/clock.py +567 -0
  1027. synapse/util/constants.py +22 -0
  1028. synapse/util/daemonize.py +165 -0
  1029. synapse/util/distributor.py +157 -0
  1030. synapse/util/events.py +134 -0
  1031. synapse/util/file_consumer.py +164 -0
  1032. synapse/util/frozenutils.py +57 -0
  1033. synapse/util/gai_resolver.py +178 -0
  1034. synapse/util/hash.py +38 -0
  1035. synapse/util/httpresourcetree.py +108 -0
  1036. synapse/util/iterutils.py +189 -0
  1037. synapse/util/json.py +56 -0
  1038. synapse/util/linked_list.py +156 -0
  1039. synapse/util/logcontext.py +46 -0
  1040. synapse/util/logformatter.py +28 -0
  1041. synapse/util/macaroons.py +325 -0
  1042. synapse/util/manhole.py +191 -0
  1043. synapse/util/metrics.py +339 -0
  1044. synapse/util/module_loader.py +116 -0
  1045. synapse/util/msisdn.py +51 -0
  1046. synapse/util/patch_inline_callbacks.py +250 -0
  1047. synapse/util/pydantic_models.py +63 -0
  1048. synapse/util/ratelimitutils.py +419 -0
  1049. synapse/util/retryutils.py +339 -0
  1050. synapse/util/rlimit.py +42 -0
  1051. synapse/util/rust.py +133 -0
  1052. synapse/util/sentinel.py +21 -0
  1053. synapse/util/stringutils.py +293 -0
  1054. synapse/util/task_scheduler.py +493 -0
  1055. synapse/util/templates.py +126 -0
  1056. synapse/util/threepids.py +123 -0
  1057. synapse/util/wheel_timer.py +112 -0
  1058. synapse/visibility.py +835 -0
@@ -0,0 +1,2347 @@
1
+ #
2
+ # This file is licensed under the Affero General Public License (AGPL) version 3.
3
+ #
4
+ # Copyright 2019-2020 The Matrix.org Foundation C.I.C.
5
+ # Copyright 2014-2016 OpenMarket Ltd
6
+ # Copyright (C) 2023 New Vector, Ltd
7
+ #
8
+ # This program is free software: you can redistribute it and/or modify
9
+ # it under the terms of the GNU Affero General Public License as
10
+ # published by the Free Software Foundation, either version 3 of the
11
+ # License, or (at your option) any later version.
12
+ #
13
+ # See the GNU Affero General Public License for more details:
14
+ # <https://www.gnu.org/licenses/agpl-3.0.html>.
15
+ #
16
+ # Originally licensed under the Apache License, Version 2.0:
17
+ # <http://www.apache.org/licenses/LICENSE-2.0>.
18
+ #
19
+ # [This file includes modifications made by New Vector Limited]
20
+ #
21
+ #
22
+ import logging
23
+ import random
24
+ from http import HTTPStatus
25
+ from typing import TYPE_CHECKING, Any, Mapping, Sequence
26
+
27
+ from canonicaljson import encode_canonical_json
28
+
29
+ from twisted.internet.interfaces import IDelayedCall
30
+
31
+ from synapse import event_auth
32
+ from synapse.api.constants import (
33
+ EventContentFields,
34
+ EventTypes,
35
+ GuestAccess,
36
+ HistoryVisibility,
37
+ JoinRules,
38
+ Membership,
39
+ RelationTypes,
40
+ UserTypes,
41
+ )
42
+ from synapse.api.errors import (
43
+ AuthError,
44
+ Codes,
45
+ ConsentNotGivenError,
46
+ NotFoundError,
47
+ PartialStateConflictError,
48
+ ShadowBanError,
49
+ SynapseError,
50
+ UnstableSpecAuthError,
51
+ UnsupportedRoomVersionError,
52
+ )
53
+ from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
54
+ from synapse.api.urls import ConsentURIBuilder
55
+ from synapse.event_auth import validate_event_for_room_version
56
+ from synapse.events import EventBase, relation_from_event
57
+ from synapse.events.builder import EventBuilder
58
+ from synapse.events.snapshot import (
59
+ EventContext,
60
+ EventPersistencePair,
61
+ UnpersistedEventContext,
62
+ UnpersistedEventContextBase,
63
+ )
64
+ from synapse.events.utils import SerializeEventConfig, maybe_upsert_event_field
65
+ from synapse.events.validator import EventValidator
66
+ from synapse.handlers.directory import DirectoryHandler
67
+ from synapse.handlers.worker_lock import NEW_EVENT_DURING_PURGE_LOCK_NAME
68
+ from synapse.logging import opentracing
69
+ from synapse.logging.context import make_deferred_yieldable, run_in_background
70
+ from synapse.replication.http.send_events import ReplicationSendEventsRestServlet
71
+ from synapse.storage.databases.main.events_worker import EventRedactBehaviour
72
+ from synapse.types import (
73
+ JsonDict,
74
+ PersistedEventPosition,
75
+ Requester,
76
+ RoomAlias,
77
+ StateMap,
78
+ StreamToken,
79
+ UserID,
80
+ create_requester,
81
+ )
82
+ from synapse.types.state import StateFilter
83
+ from synapse.util import log_failure, unwrapFirstError
84
+ from synapse.util.async_helpers import Linearizer, gather_results
85
+ from synapse.util.caches.expiringcache import ExpiringCache
86
+ from synapse.util.json import json_decoder, json_encoder
87
+ from synapse.util.metrics import measure_func
88
+ from synapse.visibility import get_effective_room_visibility_from_state
89
+
90
+ if TYPE_CHECKING:
91
+ from synapse.server import HomeServer
92
+
93
+ logger = logging.getLogger(__name__)
94
+
95
+
96
+ class MessageHandler:
97
+ """Contains some read only APIs to get state about a room"""
98
+
99
+ def __init__(self, hs: "HomeServer"):
100
+ self.server_name = hs.hostname
101
+ self.hs = hs
102
+ self.auth = hs.get_auth()
103
+ self.clock = hs.get_clock()
104
+ self.state = hs.get_state_handler()
105
+ self.store = hs.get_datastores().main
106
+ self._storage_controllers = hs.get_storage_controllers()
107
+ self._state_storage_controller = self._storage_controllers.state
108
+ self._event_serializer = hs.get_event_client_serializer()
109
+ self._ephemeral_events_enabled = hs.config.server.enable_ephemeral_messages
110
+
111
+ # The scheduled call to self._expire_event. None if no call is currently
112
+ # scheduled.
113
+ self._scheduled_expiry: IDelayedCall | None = None
114
+
115
+ if not hs.config.worker.worker_app:
116
+ self.hs.run_as_background_process(
117
+ "_schedule_next_expiry", self._schedule_next_expiry
118
+ )
119
+
120
+ async def get_room_data(
121
+ self,
122
+ requester: Requester,
123
+ room_id: str,
124
+ event_type: str,
125
+ state_key: str,
126
+ ) -> EventBase | None:
127
+ """Get data from a room.
128
+
129
+ Args:
130
+ requester: The user who did the request.
131
+ room_id
132
+ event_type
133
+ state_key
134
+ Returns:
135
+ The path data content.
136
+ Raises:
137
+ SynapseError or AuthError if the user is not in the room
138
+ """
139
+ (
140
+ membership,
141
+ membership_event_id,
142
+ ) = await self.auth.check_user_in_room_or_world_readable(
143
+ room_id, requester, allow_departed_users=True
144
+ )
145
+
146
+ if membership == Membership.JOIN:
147
+ data = await self._storage_controllers.state.get_current_state_event(
148
+ room_id, event_type, state_key
149
+ )
150
+ elif membership == Membership.LEAVE:
151
+ key = (event_type, state_key)
152
+ # If the membership is not JOIN, then the event ID should exist.
153
+ assert membership_event_id is not None, (
154
+ "check_user_in_room_or_world_readable returned invalid data"
155
+ )
156
+ room_state = await self._state_storage_controller.get_state_for_events(
157
+ [membership_event_id], StateFilter.from_types([key])
158
+ )
159
+ data = room_state[membership_event_id].get(key)
160
+ else:
161
+ # check_user_in_room_or_world_readable, if it doesn't raise an AuthError, should
162
+ # only ever return a Membership.JOIN/LEAVE object
163
+ #
164
+ # Safeguard in case it returned something else
165
+ logger.error(
166
+ "Attempted to retrieve data from a room for a user that has never been in it. "
167
+ "This should not have happened."
168
+ )
169
+ raise UnstableSpecAuthError(
170
+ 403,
171
+ "User not in room",
172
+ errcode=Codes.NOT_JOINED,
173
+ )
174
+
175
+ return data
176
+
177
+ async def get_state_events(
178
+ self,
179
+ requester: Requester,
180
+ room_id: str,
181
+ state_filter: StateFilter | None = None,
182
+ at_token: StreamToken | None = None,
183
+ ) -> list[dict]:
184
+ """Retrieve all state events for a given room. If the user is
185
+ joined to the room then return the current state. If the user has
186
+ left the room return the state events from when they left. If an explicit
187
+ 'at' parameter is passed, return the state events as of that event, if
188
+ visible.
189
+
190
+ Args:
191
+ requester: The user requesting state events.
192
+ room_id: The room ID to get all state events from.
193
+ state_filter: The state filter used to fetch state from the database.
194
+ at_token: the stream token of the at which we are requesting
195
+ the stats. If the user is not allowed to view the state as of that
196
+ stream token, we raise a 403 SynapseError. If None, returns the current
197
+ state based on the current_state_events table.
198
+ Returns:
199
+ A list of dicts representing state events. [{}, {}, {}]
200
+ Raises:
201
+ NotFoundError (404) if the at token does not yield an event
202
+
203
+ AuthError (403) if the user doesn't have permission to view
204
+ members of this room.
205
+ """
206
+ if state_filter is None:
207
+ state_filter = StateFilter.all()
208
+
209
+ user_id = requester.user.to_string()
210
+
211
+ if at_token:
212
+ last_event_id = (
213
+ await self.store.get_last_event_id_in_room_before_stream_ordering(
214
+ room_id,
215
+ end_token=at_token.room_key,
216
+ )
217
+ )
218
+
219
+ if not last_event_id:
220
+ raise NotFoundError("Can't find event for token %s" % (at_token,))
221
+
222
+ if not await self._user_can_see_state_at_event(
223
+ user_id, room_id, last_event_id
224
+ ):
225
+ raise AuthError(
226
+ 403,
227
+ "User %s not allowed to view events in room %s at token %s"
228
+ % (user_id, room_id, at_token),
229
+ )
230
+
231
+ room_state_events = (
232
+ await self._state_storage_controller.get_state_for_events(
233
+ [last_event_id], state_filter=state_filter
234
+ )
235
+ )
236
+ room_state: Mapping[Any, EventBase] = room_state_events[last_event_id]
237
+ else:
238
+ (
239
+ membership,
240
+ membership_event_id,
241
+ ) = await self.auth.check_user_in_room_or_world_readable(
242
+ room_id, requester, allow_departed_users=True
243
+ )
244
+
245
+ if membership == Membership.JOIN:
246
+ state_ids = await self._state_storage_controller.get_current_state_ids(
247
+ room_id, state_filter=state_filter
248
+ )
249
+ room_state = await self.store.get_events(state_ids.values())
250
+ elif membership == Membership.LEAVE:
251
+ # If the membership is not JOIN, then the event ID should exist.
252
+ assert membership_event_id is not None, (
253
+ "check_user_in_room_or_world_readable returned invalid data"
254
+ )
255
+ room_state_events = (
256
+ await self._state_storage_controller.get_state_for_events(
257
+ [membership_event_id], state_filter=state_filter
258
+ )
259
+ )
260
+ room_state = room_state_events[membership_event_id]
261
+
262
+ events = await self._event_serializer.serialize_events(
263
+ room_state.values(),
264
+ self.clock.time_msec(),
265
+ config=SerializeEventConfig(requester=requester),
266
+ )
267
+ return events
268
+
269
+ async def _user_can_see_state_at_event(
270
+ self, user_id: str, room_id: str, event_id: str
271
+ ) -> bool:
272
+ # check whether the user was in the room, and the history visibility,
273
+ # at that time.
274
+ state_map = await self._state_storage_controller.get_state_for_event(
275
+ event_id,
276
+ StateFilter.from_types(
277
+ [
278
+ (EventTypes.Member, user_id),
279
+ (EventTypes.RoomHistoryVisibility, ""),
280
+ ]
281
+ ),
282
+ )
283
+
284
+ membership = None
285
+ membership_event = state_map.get((EventTypes.Member, user_id))
286
+ if membership_event:
287
+ membership = membership_event.membership
288
+
289
+ # if the user was a member of the room at the time of the event,
290
+ # they can see it.
291
+ if membership == Membership.JOIN:
292
+ return True
293
+
294
+ # otherwise, it depends on the history visibility.
295
+ visibility = get_effective_room_visibility_from_state(state_map)
296
+
297
+ if visibility == HistoryVisibility.JOINED:
298
+ # we weren't a member at the time of the event, so we can't see this event.
299
+ return False
300
+
301
+ # otherwise *invited* is good enough
302
+ if membership == Membership.INVITE:
303
+ return True
304
+
305
+ if visibility == HistoryVisibility.INVITED:
306
+ # we weren't invited, so we can't see this event.
307
+ return False
308
+
309
+ if visibility == HistoryVisibility.WORLD_READABLE:
310
+ return True
311
+
312
+ # So it's SHARED, and the user was not a member at the time. The user cannot
313
+ # see history, unless they have *subsequently* joined the room.
314
+ #
315
+ # XXX: if the user has subsequently joined and then left again,
316
+ # ideally we would share history up to the point they left. But
317
+ # we don't know when they left. We just treat it as though they
318
+ # never joined, and restrict access.
319
+
320
+ (
321
+ current_membership,
322
+ _,
323
+ ) = await self.store.get_local_current_membership_for_user_in_room(
324
+ user_id, event_id
325
+ )
326
+ return current_membership == Membership.JOIN
327
+
328
+ async def get_joined_members(self, requester: Requester, room_id: str) -> dict:
329
+ """Get all the joined members in the room and their profile information.
330
+
331
+ If the user has left the room return the state events from when they left.
332
+
333
+ Args:
334
+ requester: The user requesting state events.
335
+ room_id: The room ID to get all state events from.
336
+ Returns:
337
+ A dict of user_id to profile info
338
+ """
339
+ if not requester.app_service:
340
+ # We check AS auth after fetching the room membership, as it
341
+ # requires us to pull out all joined members anyway.
342
+ membership, _ = await self.auth.check_user_in_room_or_world_readable(
343
+ room_id, requester, allow_departed_users=True
344
+ )
345
+ if membership != Membership.JOIN:
346
+ raise SynapseError(
347
+ code=403,
348
+ errcode=Codes.FORBIDDEN,
349
+ msg="Getting joined members while not being a current member of the room is forbidden.",
350
+ )
351
+
352
+ users_with_profile = (
353
+ await self._state_storage_controller.get_users_in_room_with_profiles(
354
+ room_id
355
+ )
356
+ )
357
+
358
+ # If this is an AS, double check that they are allowed to see the members.
359
+ # This can either be because the AS user is in the room or because there
360
+ # is a user in the room that the AS is "interested in"
361
+ if (
362
+ requester.app_service
363
+ and requester.user.to_string() not in users_with_profile
364
+ ):
365
+ for uid in users_with_profile:
366
+ if requester.app_service.is_interested_in_user(uid):
367
+ break
368
+ else:
369
+ # Loop fell through, AS has no interested users in room
370
+ raise UnstableSpecAuthError(
371
+ 403,
372
+ "Appservice not in room",
373
+ errcode=Codes.NOT_JOINED,
374
+ )
375
+
376
+ return {
377
+ user_id: {
378
+ "avatar_url": profile.avatar_url,
379
+ "display_name": profile.display_name,
380
+ }
381
+ for user_id, profile in users_with_profile.items()
382
+ }
383
+
384
+ def maybe_schedule_expiry(self, event: EventBase) -> None:
385
+ """Schedule the expiry of an event if there's not already one scheduled,
386
+ or if the one running is for an event that will expire after the provided
387
+ timestamp.
388
+
389
+ This function needs to invalidate the event cache, which is only possible on
390
+ the master process, and therefore needs to be run on there.
391
+
392
+ Args:
393
+ event: The event to schedule the expiry of.
394
+ """
395
+
396
+ expiry_ts = event.content.get(EventContentFields.SELF_DESTRUCT_AFTER)
397
+ if type(expiry_ts) is not int or event.is_state(): # noqa: E721
398
+ return
399
+
400
+ # _schedule_expiry_for_event won't actually schedule anything if there's already
401
+ # a task scheduled for a timestamp that's sooner than the provided one.
402
+ self._schedule_expiry_for_event(event.event_id, expiry_ts)
403
+
404
+ async def _schedule_next_expiry(self) -> None:
405
+ """Retrieve the ID and the expiry timestamp of the next event to be expired,
406
+ and schedule an expiry task for it.
407
+
408
+ If there's no event left to expire, set _expiry_scheduled to None so that a
409
+ future call to save_expiry_ts can schedule a new expiry task.
410
+ """
411
+ # Try to get the expiry timestamp of the next event to expire.
412
+ res = await self.store.get_next_event_to_expire()
413
+ if res:
414
+ event_id, expiry_ts = res
415
+ self._schedule_expiry_for_event(event_id, expiry_ts)
416
+
417
+ def _schedule_expiry_for_event(self, event_id: str, expiry_ts: int) -> None:
418
+ """Schedule an expiry task for the provided event if there's not already one
419
+ scheduled at a timestamp that's sooner than the provided one.
420
+
421
+ Args:
422
+ event_id: The ID of the event to expire.
423
+ expiry_ts: The timestamp at which to expire the event.
424
+ """
425
+ if self._scheduled_expiry:
426
+ # If the provided timestamp refers to a time before the scheduled time of the
427
+ # next expiry task, cancel that task and reschedule it for this timestamp.
428
+ next_scheduled_expiry_ts = self._scheduled_expiry.getTime() * 1000
429
+ if expiry_ts < next_scheduled_expiry_ts:
430
+ self._scheduled_expiry.cancel()
431
+ else:
432
+ return
433
+
434
+ # Figure out how many seconds we need to wait before expiring the event.
435
+ now_ms = self.clock.time_msec()
436
+ delay = (expiry_ts - now_ms) / 1000
437
+
438
+ # callLater doesn't support negative delays, so trim the delay to 0 if we're
439
+ # in that case.
440
+ if delay < 0:
441
+ delay = 0
442
+
443
+ logger.info("Scheduling expiry for event %s in %.3fs", event_id, delay)
444
+
445
+ self._scheduled_expiry = self.clock.call_later(
446
+ delay,
447
+ self.hs.run_as_background_process,
448
+ "_expire_event",
449
+ self._expire_event,
450
+ event_id,
451
+ )
452
+
453
+ async def _expire_event(self, event_id: str) -> None:
454
+ """Retrieve and expire an event that needs to be expired from the database.
455
+
456
+ If the event doesn't exist in the database, log it and delete the expiry date
457
+ from the database (so that we don't try to expire it again).
458
+ """
459
+ assert self._ephemeral_events_enabled
460
+
461
+ self._scheduled_expiry = None
462
+
463
+ logger.info("Expiring event %s", event_id)
464
+
465
+ try:
466
+ # Expire the event if we know about it. This function also deletes the expiry
467
+ # date from the database in the same database transaction.
468
+ await self.store.expire_event(event_id)
469
+ except Exception as e:
470
+ logger.exception("Could not expire event %s: %r", event_id, e)
471
+
472
+ # Schedule the expiry of the next event to expire.
473
+ await self._schedule_next_expiry()
474
+
475
+
476
+ # The duration (in ms) after which rooms should be removed
477
+ # `_rooms_to_exclude_from_dummy_event_insertion` (with the effect that we will try
478
+ # to generate a dummy event for them once more)
479
+ #
480
+ _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY = 7 * 24 * 60 * 60 * 1000
481
+
482
+
483
+ class EventCreationHandler:
484
+ def __init__(self, hs: "HomeServer"):
485
+ self.hs = hs
486
+ self.validator = EventValidator()
487
+ self.event_builder_factory = hs.get_event_builder_factory()
488
+ self.server_name = hs.hostname # nb must be called this for @measure_func
489
+ self.clock = hs.get_clock() # nb must be called this for @measure_func
490
+ self.auth_blocking = hs.get_auth_blocking()
491
+ self._event_auth_handler = hs.get_event_auth_handler()
492
+ self.store = hs.get_datastores().main
493
+ self._storage_controllers = hs.get_storage_controllers()
494
+ self.state = hs.get_state_handler()
495
+ self.profile_handler = hs.get_profile_handler()
496
+ self.notifier = hs.get_notifier()
497
+ self.config = hs.config
498
+ self.require_membership_for_aliases = (
499
+ hs.config.server.require_membership_for_aliases
500
+ )
501
+ self._events_shard_config = self.config.worker.events_shard_config
502
+ self._instance_name = hs.get_instance_name()
503
+ self._notifier = hs.get_notifier()
504
+ self._worker_lock_handler = hs.get_worker_locks_handler()
505
+ self._policy_handler = hs.get_room_policy_handler()
506
+
507
+ self.room_prejoin_state_types = self.hs.config.api.room_prejoin_state
508
+
509
+ self.send_events = ReplicationSendEventsRestServlet.make_client(hs)
510
+
511
+ self.request_ratelimiter = hs.get_request_ratelimiter()
512
+
513
+ # We limit concurrent event creation for a room to 1. This prevents state resolution
514
+ # from occurring when sending bursts of events to a local room
515
+ self.limiter = Linearizer(
516
+ max_count=1, name="room_event_creation_limit", clock=self.clock
517
+ )
518
+
519
+ self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()
520
+
521
+ self._spam_checker_module_callbacks = hs.get_module_api_callbacks().spam_checker
522
+ self._third_party_event_rules = (
523
+ self.hs.get_module_api_callbacks().third_party_event_rules
524
+ )
525
+
526
+ self._block_events_without_consent_error = (
527
+ self.config.consent.block_events_without_consent_error
528
+ )
529
+
530
+ # we need to construct a ConsentURIBuilder here, as it checks that the necessary
531
+ # config options, but *only* if we have a configuration for which we are
532
+ # going to need it.
533
+ if self._block_events_without_consent_error:
534
+ self._consent_uri_builder = ConsentURIBuilder(self.config)
535
+
536
+ # Rooms which should be excluded from dummy insertion. (For instance,
537
+ # those without local users who can send events into the room).
538
+ #
539
+ # map from room id to time-of-last-attempt.
540
+ #
541
+ self._rooms_to_exclude_from_dummy_event_insertion: dict[str, int] = {}
542
+ # The number of forward extremeities before a dummy event is sent.
543
+ self._dummy_events_threshold = hs.config.server.dummy_events_threshold
544
+
545
+ if (
546
+ self.config.worker.run_background_tasks
547
+ and self.config.server.cleanup_extremities_with_dummy_events
548
+ ):
549
+ self.clock.looping_call(
550
+ lambda: self.hs.run_as_background_process(
551
+ "send_dummy_events_to_fill_extremities",
552
+ self._send_dummy_events_to_fill_extremities,
553
+ ),
554
+ 5 * 60 * 1000,
555
+ )
556
+
557
+ self._message_handler = hs.get_message_handler()
558
+
559
+ self._ephemeral_events_enabled = hs.config.server.enable_ephemeral_messages
560
+
561
+ self._external_cache = hs.get_external_cache()
562
+
563
+ # Stores the state groups we've recently added to the joined hosts
564
+ # external cache. Note that the timeout must be significantly less than
565
+ # the TTL on the external cache.
566
+ self._external_cache_joined_hosts_updates: ExpiringCache | None = None
567
+ if self._external_cache.is_enabled():
568
+ self._external_cache_joined_hosts_updates = ExpiringCache(
569
+ cache_name="_external_cache_joined_hosts_updates",
570
+ server_name=self.server_name,
571
+ hs=self.hs,
572
+ clock=self.clock,
573
+ expiry_ms=30 * 60 * 1000,
574
+ )
575
+
576
+ async def create_event(
577
+ self,
578
+ requester: Requester,
579
+ event_dict: dict,
580
+ txn_id: str | None = None,
581
+ prev_event_ids: list[str] | None = None,
582
+ auth_event_ids: list[str] | None = None,
583
+ state_event_ids: list[str] | None = None,
584
+ require_consent: bool = True,
585
+ outlier: bool = False,
586
+ depth: int | None = None,
587
+ state_map: StateMap[str] | None = None,
588
+ for_batch: bool = False,
589
+ current_state_group: int | None = None,
590
+ ) -> tuple[EventBase, UnpersistedEventContextBase]:
591
+ """
592
+ Given a dict from a client, create a new event. If bool for_batch is true, will
593
+ create an event using the prev_event_ids, and will create an event context for
594
+ the event using the parameters state_map and current_state_group, thus these parameters
595
+ must be provided in this case if for_batch is True. The subsequently created event
596
+ and context are suitable for being batched up and bulk persisted to the database
597
+ with other similarly created events.
598
+
599
+ Creates an FrozenEvent object, filling out auth_events, prev_events,
600
+ etc.
601
+
602
+ Args:
603
+ requester
604
+ event_dict: An entire event
605
+ txn_id
606
+ prev_event_ids:
607
+ the forward extremities to use as the prev_events for the
608
+ new event.
609
+
610
+ If None, they will be requested from the database.
611
+
612
+ auth_event_ids:
613
+ The event ids to use as the auth_events for the new event.
614
+ Should normally be left as None, which will cause them to be calculated
615
+ based on the room state at the prev_events.
616
+
617
+ If non-None, prev_event_ids must also be provided.
618
+
619
+ state_event_ids:
620
+ The full state at a given event. This was previously used particularly
621
+ by the MSC2716 /batch_send endpoint. This should normally be left as
622
+ None, which will cause the auth_event_ids to be calculated based on the
623
+ room state at the prev_events.
624
+
625
+ require_consent: Whether to check if the requester has
626
+ consented to the privacy policy.
627
+
628
+ outlier: Indicates whether the event is an `outlier`, i.e. if
629
+ it's from an arbitrary point and floating in the DAG as
630
+ opposed to being inline with the current DAG.
631
+
632
+ depth: Override the depth used to order the event in the DAG.
633
+ Should normally be set to None, which will cause the depth to be calculated
634
+ based on the prev_events.
635
+
636
+ state_map: A state map of previously created events, used only when creating events
637
+ for batch persisting
638
+
639
+ for_batch: whether the event is being created for batch persisting to the db
640
+
641
+ current_state_group: the current state group, used only for creating events for
642
+ batch persisting
643
+
644
+ Raises:
645
+ ResourceLimitError if server is blocked to some resource being
646
+ exceeded
647
+
648
+ Returns:
649
+ Tuple of created event, Context
650
+ """
651
+ await self.auth_blocking.check_auth_blocking(requester=requester)
652
+
653
+ # The requester may be a regular user, but puppeted by the server.
654
+ request_by_server = (
655
+ requester.authenticated_entity == self.hs.config.server.server_name
656
+ )
657
+
658
+ # If the request is initiated by the server, ignore whether the
659
+ # requester or target is suspended.
660
+ if not request_by_server:
661
+ requester_suspended = await self.store.get_user_suspended_status(
662
+ requester.user.to_string()
663
+ )
664
+ if requester_suspended:
665
+ # We want to allow suspended users to perform "corrective" actions
666
+ # asked of them by server admins, such as redact their messages and
667
+ # leave rooms.
668
+ if event_dict["type"] in ["m.room.redaction", "m.room.member"]:
669
+ if event_dict["type"] == "m.room.redaction":
670
+ event = await self.store.get_event(
671
+ event_dict["content"]["redacts"], allow_none=True
672
+ )
673
+ if event:
674
+ if event.sender != requester.user.to_string():
675
+ raise SynapseError(
676
+ 403,
677
+ "You can only redact your own events while account is suspended.",
678
+ Codes.USER_ACCOUNT_SUSPENDED,
679
+ )
680
+ if event_dict["type"] == "m.room.member":
681
+ if event_dict["content"]["membership"] != "leave":
682
+ raise SynapseError(
683
+ 403,
684
+ "Changing membership while account is suspended is not allowed.",
685
+ Codes.USER_ACCOUNT_SUSPENDED,
686
+ )
687
+ else:
688
+ raise SynapseError(
689
+ 403,
690
+ "Sending messages while account is suspended is not allowed.",
691
+ Codes.USER_ACCOUNT_SUSPENDED,
692
+ )
693
+
694
+ is_create_event = (
695
+ event_dict["type"] == EventTypes.Create and event_dict["state_key"] == ""
696
+ )
697
+ if is_create_event:
698
+ room_version_id = event_dict["content"]["room_version"]
699
+ maybe_room_version_obj = KNOWN_ROOM_VERSIONS.get(room_version_id)
700
+ if not maybe_room_version_obj:
701
+ # this can happen if support is withdrawn for a room version
702
+ raise UnsupportedRoomVersionError(room_version_id)
703
+ room_version_obj = maybe_room_version_obj
704
+ else:
705
+ try:
706
+ room_version_obj = await self.store.get_room_version(
707
+ event_dict["room_id"]
708
+ )
709
+ except NotFoundError:
710
+ raise AuthError(403, "Unknown room")
711
+
712
+ builder = self.event_builder_factory.for_room_version(
713
+ room_version_obj, event_dict
714
+ )
715
+
716
+ self.validator.validate_builder(builder)
717
+
718
+ is_exempt = await self._is_exempt_from_privacy_policy(builder, requester)
719
+ if require_consent and not is_exempt:
720
+ await self.assert_accepted_privacy_policy(requester)
721
+
722
+ # Save the the device ID and the transaction ID in the event internal metadata.
723
+ # This is useful to determine if we should echo the transaction_id in events.
724
+ # See `synapse.events.utils.EventClientSerializer.serialize_event`
725
+ if requester.device_id is not None:
726
+ builder.internal_metadata.device_id = requester.device_id
727
+
728
+ if txn_id is not None:
729
+ builder.internal_metadata.txn_id = txn_id
730
+
731
+ builder.internal_metadata.outlier = outlier
732
+
733
+ event, unpersisted_context = await self.create_new_client_event(
734
+ builder=builder,
735
+ requester=requester,
736
+ prev_event_ids=prev_event_ids,
737
+ auth_event_ids=auth_event_ids,
738
+ state_event_ids=state_event_ids,
739
+ depth=depth,
740
+ state_map=state_map,
741
+ for_batch=for_batch,
742
+ current_state_group=current_state_group,
743
+ )
744
+
745
+ # In an ideal world we wouldn't need the second part of this condition. However,
746
+ # this behaviour isn't spec'd yet, meaning we should be able to deactivate this
747
+ # behaviour. Another reason is that this code is also evaluated each time a new
748
+ # m.room.aliases event is created, which includes hitting a /directory route.
749
+ # Therefore not including this condition here would render the similar one in
750
+ # synapse.handlers.directory pointless.
751
+ if builder.type == EventTypes.Aliases and self.require_membership_for_aliases:
752
+ # Ideally we'd do the membership check in event_auth.check(), which
753
+ # describes a spec'd algorithm for authenticating events received over
754
+ # federation as well as those created locally. As of room v3, aliases events
755
+ # can be created by users that are not in the room, therefore we have to
756
+ # tolerate them in event_auth.check().
757
+ if for_batch:
758
+ assert state_map is not None
759
+ prev_event_id = state_map.get((EventTypes.Member, event.sender))
760
+ else:
761
+ prev_state_ids = await unpersisted_context.get_prev_state_ids(
762
+ StateFilter.from_types([(EventTypes.Member, event.sender)])
763
+ )
764
+ prev_event_id = prev_state_ids.get((EventTypes.Member, event.sender))
765
+ prev_event = (
766
+ await self.store.get_event(prev_event_id, allow_none=True)
767
+ if prev_event_id
768
+ else None
769
+ )
770
+ if not prev_event or prev_event.membership != Membership.JOIN:
771
+ logger.warning(
772
+ (
773
+ "Attempt to send `m.room.aliases` in room %s by user %s but"
774
+ " membership is %s"
775
+ ),
776
+ event.room_id,
777
+ event.sender,
778
+ prev_event.membership if prev_event else None,
779
+ )
780
+
781
+ raise AuthError(
782
+ 403, "You must be in the room to create an alias for it"
783
+ )
784
+
785
+ self.validator.validate_new(event, self.config)
786
+ return event, unpersisted_context
787
+
788
+ async def _is_exempt_from_privacy_policy(
789
+ self, builder: EventBuilder, requester: Requester
790
+ ) -> bool:
791
+ """ "Determine if an event to be sent is exempt from having to consent
792
+ to the privacy policy
793
+
794
+ Args:
795
+ builder: event being created
796
+ requester: user requesting this event
797
+
798
+ Returns:
799
+ true if the event can be sent without the user consenting
800
+ """
801
+ # the only thing the user can do is join the server notices room.
802
+ if builder.type == EventTypes.Member:
803
+ assert builder.room_id is not None
804
+ membership = builder.content.get("membership", None)
805
+ if membership == Membership.JOIN:
806
+ return await self.store.is_server_notice_room(builder.room_id)
807
+ elif membership == Membership.LEAVE:
808
+ # the user is always allowed to leave (but not kick people)
809
+ return builder.state_key == requester.user.to_string()
810
+ return False
811
+
812
+ async def assert_accepted_privacy_policy(self, requester: Requester) -> None:
813
+ """Check if a user has accepted the privacy policy
814
+
815
+ Called when the given user is about to do something that requires
816
+ privacy consent. We see if the user is exempt and otherwise check that
817
+ they have given consent. If they have not, a ConsentNotGiven error is
818
+ raised.
819
+
820
+ Args:
821
+ requester: The user making the request
822
+
823
+ Returns:
824
+ Returns normally if the user has consented or is exempt
825
+
826
+ Raises:
827
+ ConsentNotGivenError: if the user has not given consent yet
828
+ """
829
+ if self._block_events_without_consent_error is None:
830
+ return
831
+
832
+ # exempt AS users from needing consent
833
+ if requester.app_service is not None:
834
+ return
835
+
836
+ user_id = requester.authenticated_entity
837
+ if not user_id.startswith("@"):
838
+ # The authenticated entity might not be a user, e.g. if it's the
839
+ # server puppetting the user.
840
+ return
841
+
842
+ user = UserID.from_string(user_id)
843
+
844
+ # exempt the system notices user
845
+ if (
846
+ self.config.servernotices.server_notices_mxid is not None
847
+ and user_id == self.config.servernotices.server_notices_mxid
848
+ ):
849
+ return
850
+
851
+ u = await self.store.get_user_by_id(user_id)
852
+ assert u is not None
853
+ if u.user_type in (UserTypes.SUPPORT, UserTypes.BOT):
854
+ # support and bot users are not required to consent
855
+ return
856
+ if u.appservice_id is not None:
857
+ # users registered by an appservice are exempt
858
+ return
859
+ if u.consent_version == self.config.consent.user_consent_version:
860
+ return
861
+
862
+ consent_uri = self._consent_uri_builder.build_user_consent_uri(user.localpart)
863
+ msg = self._block_events_without_consent_error % {"consent_uri": consent_uri}
864
+ raise ConsentNotGivenError(msg=msg, consent_uri=consent_uri)
865
+
866
+ async def deduplicate_state_event(
867
+ self, event: EventBase, context: EventContext
868
+ ) -> EventBase | None:
869
+ """
870
+ Checks whether event is in the latest resolved state in context.
871
+
872
+ Args:
873
+ event: The event to check for duplication.
874
+ context: The event context.
875
+
876
+ Returns:
877
+ The previous version of the event is returned, if it is found in the
878
+ event context. Otherwise, None is returned.
879
+ """
880
+ if event.internal_metadata.is_outlier():
881
+ # This can happen due to out of band memberships
882
+ return None
883
+
884
+ prev_state_ids = await context.get_prev_state_ids(
885
+ StateFilter.from_types([(event.type, event.state_key)])
886
+ )
887
+ prev_event_id = prev_state_ids.get((event.type, event.state_key))
888
+ if not prev_event_id:
889
+ return None
890
+ prev_event = await self.store.get_event(prev_event_id, allow_none=True)
891
+ if not prev_event:
892
+ return None
893
+
894
+ if prev_event and event.user_id == prev_event.user_id:
895
+ prev_content = encode_canonical_json(prev_event.content)
896
+ next_content = encode_canonical_json(event.content)
897
+ if prev_content == next_content:
898
+ return prev_event
899
+ return None
900
+
901
+ async def get_event_id_from_transaction(
902
+ self,
903
+ requester: Requester,
904
+ txn_id: str,
905
+ room_id: str,
906
+ ) -> str | None:
907
+ """For the given transaction ID and room ID, check if there is a matching event ID.
908
+
909
+ Args:
910
+ requester: The requester making the request in the context of which we want
911
+ to fetch the event.
912
+ txn_id: The transaction ID.
913
+ room_id: The room ID.
914
+
915
+ Returns:
916
+ An event ID if one could be found, None otherwise.
917
+ """
918
+ existing_event_id = None
919
+
920
+ # According to the spec, transactions are scoped to a user's device ID.
921
+ if requester.device_id:
922
+ existing_event_id = (
923
+ await self.store.get_event_id_from_transaction_id_and_device_id(
924
+ room_id,
925
+ requester.user.to_string(),
926
+ requester.device_id,
927
+ txn_id,
928
+ )
929
+ )
930
+ if existing_event_id:
931
+ return existing_event_id
932
+
933
+ return existing_event_id
934
+
935
+ async def get_event_from_transaction(
936
+ self,
937
+ requester: Requester,
938
+ txn_id: str,
939
+ room_id: str,
940
+ ) -> EventBase | None:
941
+ """For the given transaction ID and room ID, check if there is a matching event.
942
+ If so, fetch it and return it.
943
+
944
+ Args:
945
+ requester: The requester making the request in the context of which we want
946
+ to fetch the event.
947
+ txn_id: The transaction ID.
948
+ room_id: The room ID.
949
+
950
+ Returns:
951
+ An event if one could be found, None otherwise.
952
+ """
953
+ existing_event_id = await self.get_event_id_from_transaction(
954
+ requester, txn_id, room_id
955
+ )
956
+ if existing_event_id:
957
+ return await self.store.get_event(existing_event_id)
958
+ return None
959
+
960
+ async def create_and_send_nonmember_event(
961
+ self,
962
+ requester: Requester,
963
+ event_dict: dict,
964
+ prev_event_ids: list[str] | None = None,
965
+ state_event_ids: list[str] | None = None,
966
+ ratelimit: bool = True,
967
+ txn_id: str | None = None,
968
+ ignore_shadow_ban: bool = False,
969
+ outlier: bool = False,
970
+ depth: int | None = None,
971
+ ) -> tuple[EventBase, int]:
972
+ """
973
+ Creates an event, then sends it.
974
+
975
+ See self.create_event and self.handle_new_client_event.
976
+
977
+ Args:
978
+ requester: The requester sending the event.
979
+ event_dict: An entire event.
980
+ prev_event_ids:
981
+ The event IDs to use as the prev events.
982
+ Should normally be left as None to automatically request them
983
+ from the database.
984
+ state_event_ids:
985
+ The full state at a given event. This was previously used particularly
986
+ by the MSC2716 /batch_send endpoint. This should normally be left as
987
+ None, which will cause the auth_event_ids to be calculated based on the
988
+ room state at the prev_events.
989
+ ratelimit: Whether to rate limit this send.
990
+ txn_id: The transaction ID.
991
+ ignore_shadow_ban: True if shadow-banned users should be allowed to
992
+ send this event.
993
+ outlier: Indicates whether the event is an `outlier`, i.e. if
994
+ it's from an arbitrary point and floating in the DAG as
995
+ opposed to being inline with the current DAG.
996
+ depth: Override the depth used to order the event in the DAG.
997
+ Should normally be set to None, which will cause the depth to be calculated
998
+ based on the prev_events.
999
+
1000
+ Returns:
1001
+ The event, and its stream ordering (if deduplication happened,
1002
+ the previous, duplicate event).
1003
+
1004
+ Raises:
1005
+ ShadowBanError if the requester has been shadow-banned.
1006
+ """
1007
+
1008
+ if event_dict["type"] == EventTypes.Member:
1009
+ raise SynapseError(
1010
+ 500, "Tried to send member event through non-member codepath"
1011
+ )
1012
+
1013
+ if not ignore_shadow_ban and requester.shadow_banned:
1014
+ # We randomly sleep a bit just to annoy the requester.
1015
+ await self.clock.sleep(random.randint(1, 10))
1016
+ raise ShadowBanError()
1017
+
1018
+ room_version = None
1019
+
1020
+ if (
1021
+ event_dict["type"] == EventTypes.Redaction
1022
+ and "redacts" in event_dict["content"]
1023
+ and self.hs.config.experimental.msc4169_enabled
1024
+ ):
1025
+ room_id = event_dict["room_id"]
1026
+ try:
1027
+ room_version = await self.store.get_room_version(room_id)
1028
+ except NotFoundError:
1029
+ raise AuthError(403, f"User {requester.user} not in room {room_id}")
1030
+
1031
+ if not room_version.updated_redaction_rules:
1032
+ # Legacy room versions need the "redacts" field outside of the event's
1033
+ # content. However clients may still send it within the content, so move
1034
+ # the field if necessary for compatibility.
1035
+ redacts = event_dict.get("redacts") or event_dict["content"].pop(
1036
+ "redacts", None
1037
+ )
1038
+ if redacts is not None and "redacts" not in event_dict:
1039
+ event_dict["redacts"] = redacts
1040
+
1041
+ if ratelimit:
1042
+ if room_version is None:
1043
+ room_id = event_dict["room_id"]
1044
+ try:
1045
+ room_version = await self.store.get_room_version(room_id)
1046
+ except NotFoundError:
1047
+ raise AuthError(403, f"User {requester.user} not in room {room_id}")
1048
+
1049
+ if room_version.updated_redaction_rules:
1050
+ redacts = event_dict["content"].get("redacts")
1051
+ else:
1052
+ redacts = event_dict.get("redacts")
1053
+
1054
+ is_admin_redaction = await self.is_admin_redaction(
1055
+ event_type=event_dict["type"],
1056
+ sender=event_dict["sender"],
1057
+ redacts=redacts,
1058
+ )
1059
+ await self.request_ratelimiter.ratelimit(
1060
+ requester, is_admin_redaction=is_admin_redaction, update=False
1061
+ )
1062
+
1063
+ # We limit the number of concurrent event sends in a room so that we
1064
+ # don't fork the DAG too much. If we don't limit then we can end up in
1065
+ # a situation where event persistence can't keep up, causing
1066
+ # extremities to pile up, which in turn leads to state resolution
1067
+ # taking longer.
1068
+ room_id = event_dict["room_id"]
1069
+ async with self.limiter.queue(room_id):
1070
+ if txn_id:
1071
+ event = await self.get_event_from_transaction(
1072
+ requester, txn_id, room_id
1073
+ )
1074
+ if event:
1075
+ # we know it was persisted, so must have a stream ordering
1076
+ assert event.internal_metadata.stream_ordering
1077
+ return (
1078
+ event,
1079
+ event.internal_metadata.stream_ordering,
1080
+ )
1081
+
1082
+ async with self._worker_lock_handler.acquire_read_write_lock(
1083
+ NEW_EVENT_DURING_PURGE_LOCK_NAME, room_id, write=False
1084
+ ):
1085
+ return await self._create_and_send_nonmember_event_locked(
1086
+ requester=requester,
1087
+ event_dict=event_dict,
1088
+ prev_event_ids=prev_event_ids,
1089
+ state_event_ids=state_event_ids,
1090
+ ratelimit=ratelimit,
1091
+ txn_id=txn_id,
1092
+ ignore_shadow_ban=ignore_shadow_ban,
1093
+ outlier=outlier,
1094
+ depth=depth,
1095
+ )
1096
+
1097
+ async def _create_and_send_nonmember_event_locked(
1098
+ self,
1099
+ requester: Requester,
1100
+ event_dict: dict,
1101
+ prev_event_ids: list[str] | None = None,
1102
+ state_event_ids: list[str] | None = None,
1103
+ ratelimit: bool = True,
1104
+ txn_id: str | None = None,
1105
+ ignore_shadow_ban: bool = False,
1106
+ outlier: bool = False,
1107
+ depth: int | None = None,
1108
+ ) -> tuple[EventBase, int]:
1109
+ room_id = event_dict["room_id"]
1110
+
1111
+ # If we don't have any prev event IDs specified then we need to
1112
+ # check that the host is in the room (as otherwise populating the
1113
+ # prev events will fail), at which point we may as well check the
1114
+ # local user is in the room.
1115
+ if not prev_event_ids:
1116
+ user_id = requester.user.to_string()
1117
+ is_user_in_room = await self.store.check_local_user_in_room(
1118
+ user_id, room_id
1119
+ )
1120
+ if not is_user_in_room:
1121
+ raise AuthError(403, f"User {user_id} not in room {room_id}")
1122
+
1123
+ # Try several times, it could fail with PartialStateConflictError
1124
+ # in handle_new_client_event, cf comment in except block.
1125
+ max_retries = 5
1126
+ for i in range(max_retries):
1127
+ try:
1128
+ event, unpersisted_context = await self.create_event(
1129
+ requester,
1130
+ event_dict,
1131
+ txn_id=txn_id,
1132
+ prev_event_ids=prev_event_ids,
1133
+ state_event_ids=state_event_ids,
1134
+ outlier=outlier,
1135
+ depth=depth,
1136
+ )
1137
+ context = await unpersisted_context.persist(event)
1138
+
1139
+ assert self.hs.is_mine_id(event.sender), "User must be our own: %s" % (
1140
+ event.sender,
1141
+ )
1142
+ # if this room uses a policy server, try to get a signature now.
1143
+ # We use verify=False here as we are about to call is_event_allowed on the same event
1144
+ # which will do sig checks.
1145
+ await self._policy_handler.ask_policy_server_to_sign_event(
1146
+ event, verify=False
1147
+ )
1148
+
1149
+ policy_allowed = await self._policy_handler.is_event_allowed(event)
1150
+ if not policy_allowed:
1151
+ # We shouldn't need to set the metadata because the raise should
1152
+ # cause the request to be denied, but just in case:
1153
+ event.internal_metadata.policy_server_spammy = True
1154
+ logger.warning(
1155
+ "Event not allowed by policy server, rejecting %s",
1156
+ event.event_id,
1157
+ )
1158
+ raise SynapseError(
1159
+ 403,
1160
+ "This message has been rejected as probable spam",
1161
+ Codes.FORBIDDEN,
1162
+ )
1163
+
1164
+ spam_check_result = (
1165
+ await self._spam_checker_module_callbacks.check_event_for_spam(
1166
+ event
1167
+ )
1168
+ )
1169
+ if spam_check_result != self._spam_checker_module_callbacks.NOT_SPAM:
1170
+ if isinstance(spam_check_result, tuple):
1171
+ try:
1172
+ [code, dict] = spam_check_result
1173
+ raise SynapseError(
1174
+ 403,
1175
+ "This message has been rejected as probable spam",
1176
+ code,
1177
+ dict,
1178
+ )
1179
+ except ValueError:
1180
+ logger.error(
1181
+ "Spam-check module returned invalid error value. Expecting [code, dict], got %s",
1182
+ spam_check_result,
1183
+ )
1184
+
1185
+ raise SynapseError(
1186
+ 403,
1187
+ "This message has been rejected as probable spam",
1188
+ Codes.FORBIDDEN,
1189
+ )
1190
+
1191
+ # Backwards compatibility: if the return value is not an error code, it
1192
+ # means the module returned an error message to be included in the
1193
+ # SynapseError (which is now deprecated).
1194
+ raise SynapseError(
1195
+ 403,
1196
+ spam_check_result,
1197
+ Codes.FORBIDDEN,
1198
+ )
1199
+
1200
+ ev = await self.handle_new_client_event(
1201
+ requester=requester,
1202
+ events_and_context=[(event, context)],
1203
+ ratelimit=ratelimit,
1204
+ ignore_shadow_ban=ignore_shadow_ban,
1205
+ )
1206
+
1207
+ break
1208
+ except PartialStateConflictError as e:
1209
+ # Persisting couldn't happen because the room got un-partial stated
1210
+ # in the meantime and context needs to be recomputed, so let's do so.
1211
+ if i == max_retries - 1:
1212
+ raise e
1213
+
1214
+ # we know it was persisted, so must have a stream ordering
1215
+ assert ev.internal_metadata.stream_ordering
1216
+ return ev, ev.internal_metadata.stream_ordering
1217
+
1218
+ @measure_func("create_new_client_event")
1219
+ async def create_new_client_event(
1220
+ self,
1221
+ builder: EventBuilder,
1222
+ requester: Requester | None = None,
1223
+ prev_event_ids: list[str] | None = None,
1224
+ auth_event_ids: list[str] | None = None,
1225
+ state_event_ids: list[str] | None = None,
1226
+ depth: int | None = None,
1227
+ state_map: StateMap[str] | None = None,
1228
+ for_batch: bool = False,
1229
+ current_state_group: int | None = None,
1230
+ ) -> tuple[EventBase, UnpersistedEventContextBase]:
1231
+ """Create a new event for a local client. If bool for_batch is true, will
1232
+ create an event using the prev_event_ids, and will create an event context for
1233
+ the event using the parameters state_map and current_state_group, thus these parameters
1234
+ must be provided in this case if for_batch is True. The subsequently created event
1235
+ and context are suitable for being batched up and bulk persisted to the database
1236
+ with other similarly created events. Note that this returns an UnpersistedEventContext,
1237
+ which must be converted to an EventContext before it can be sent to the DB.
1238
+
1239
+ Args:
1240
+ builder:
1241
+ requester:
1242
+ prev_event_ids:
1243
+ the forward extremities to use as the prev_events for the
1244
+ new event.
1245
+
1246
+ If None, they will be requested from the database.
1247
+
1248
+ auth_event_ids:
1249
+ The event ids to use as the auth_events for the new event.
1250
+ Should normally be left as None, which will cause them to be calculated
1251
+ based on the room state at the prev_events.
1252
+
1253
+ state_event_ids:
1254
+ The full state at a given event. This was previously used particularly
1255
+ by the MSC2716 /batch_send endpoint. This should normally be left as
1256
+ None, which will cause the auth_event_ids to be calculated based on the
1257
+ room state at the prev_events.
1258
+
1259
+ depth: Override the depth used to order the event in the DAG.
1260
+ Should normally be set to None, which will cause the depth to be calculated
1261
+ based on the prev_events.
1262
+
1263
+ state_map: A state map of previously created events, used only when creating events
1264
+ for batch persisting
1265
+
1266
+ for_batch: whether the event is being created for batch persisting to the db
1267
+
1268
+ current_state_group: the current state group, used only for creating events for
1269
+ batch persisting
1270
+
1271
+ Returns:
1272
+ Tuple of created event, UnpersistedEventContext
1273
+ """
1274
+ # Strip down the state_event_ids to only what we need to auth the event.
1275
+ # For example, we don't need extra m.room.member that don't match event.sender
1276
+ if state_event_ids is not None:
1277
+ # Do a quick check to make sure that prev_event_ids is present to
1278
+ # make the type-checking around `builder.build` happy.
1279
+ assert prev_event_ids is not None
1280
+
1281
+ temp_event = await builder.build(
1282
+ prev_event_ids=prev_event_ids,
1283
+ auth_event_ids=state_event_ids,
1284
+ depth=depth,
1285
+ )
1286
+ state_events = await self.store.get_events_as_list(state_event_ids)
1287
+ # Create a StateMap[str]
1288
+ current_state_ids = {
1289
+ (e.type, e.state_key): e.event_id for e in state_events
1290
+ }
1291
+ # Actually strip down and only use the necessary auth events
1292
+ auth_event_ids = self._event_auth_handler.compute_auth_events(
1293
+ event=temp_event,
1294
+ current_state_ids=current_state_ids,
1295
+ for_verification=False,
1296
+ )
1297
+
1298
+ if (
1299
+ builder.room_version.msc4291_room_ids_as_hashes
1300
+ and builder.type == EventTypes.Create
1301
+ and builder.is_state()
1302
+ ):
1303
+ if builder.room_id is not None:
1304
+ raise SynapseError(
1305
+ 400,
1306
+ "Cannot resend m.room.create event",
1307
+ Codes.INVALID_PARAM,
1308
+ )
1309
+ else:
1310
+ assert builder.room_id is not None
1311
+
1312
+ if prev_event_ids is not None:
1313
+ assert len(prev_event_ids) <= 10, (
1314
+ "Attempting to create an event with %i prev_events"
1315
+ % (len(prev_event_ids),)
1316
+ )
1317
+ else:
1318
+ if builder.room_id:
1319
+ prev_event_ids = await self.store.get_prev_events_for_room(
1320
+ builder.room_id
1321
+ )
1322
+ else:
1323
+ prev_event_ids = [] # can only happen for the create event in MSC4291 rooms
1324
+
1325
+ if builder.type == EventTypes.Create and builder.is_state():
1326
+ if len(prev_event_ids) != 0:
1327
+ raise SynapseError(
1328
+ 400,
1329
+ "Cannot resend m.room.create event",
1330
+ Codes.INVALID_PARAM,
1331
+ )
1332
+
1333
+ # We now ought to have some `prev_events` (unless it's a create event).
1334
+ #
1335
+ # Do a quick sanity check here, rather than waiting until we've created the
1336
+ # event and then try to auth it (which fails with a somewhat confusing "No
1337
+ # create event in auth events")
1338
+ assert builder.type == EventTypes.Create or len(prev_event_ids) > 0, (
1339
+ "Attempting to create an event with no prev_events"
1340
+ )
1341
+
1342
+ if for_batch:
1343
+ assert prev_event_ids is not None
1344
+ assert state_map is not None
1345
+ auth_ids = self._event_auth_handler.compute_auth_events(builder, state_map)
1346
+ event = await builder.build(
1347
+ prev_event_ids=prev_event_ids, auth_event_ids=auth_ids, depth=depth
1348
+ )
1349
+
1350
+ context: UnpersistedEventContextBase = (
1351
+ await self.state.calculate_context_info(
1352
+ event,
1353
+ state_ids_before_event=state_map,
1354
+ partial_state=False,
1355
+ state_group_before_event=current_state_group,
1356
+ )
1357
+ )
1358
+
1359
+ else:
1360
+ event = await builder.build(
1361
+ prev_event_ids=prev_event_ids,
1362
+ auth_event_ids=auth_event_ids,
1363
+ depth=depth,
1364
+ )
1365
+
1366
+ # Pass on the outlier property from the builder to the event
1367
+ # after it is created
1368
+ if builder.internal_metadata.outlier:
1369
+ event.internal_metadata.outlier = True
1370
+ context = EventContext.for_outlier(self._storage_controllers)
1371
+ else:
1372
+ context = await self.state.calculate_context_info(event)
1373
+
1374
+ if requester:
1375
+ context.app_service = requester.app_service
1376
+
1377
+ res, new_content = await self._third_party_event_rules.check_event_allowed(
1378
+ event, context
1379
+ )
1380
+ if res is False:
1381
+ logger.info(
1382
+ "Event %s forbidden by third-party rules",
1383
+ event,
1384
+ )
1385
+ raise SynapseError(
1386
+ 403, "This event is not allowed in this context", Codes.FORBIDDEN
1387
+ )
1388
+ elif new_content is not None:
1389
+ # the third-party rules want to replace the event. We'll need to build a new
1390
+ # event.
1391
+ event, context = await self._rebuild_event_after_third_party_rules(
1392
+ new_content, event
1393
+ )
1394
+
1395
+ self.validator.validate_new(event, self.config)
1396
+ await self._validate_event_relation(event)
1397
+
1398
+ if event.type == EventTypes.CallInvite:
1399
+ room_id = event.room_id
1400
+ room_info = await self.store.get_room_with_stats(room_id)
1401
+ assert room_info is not None
1402
+
1403
+ if room_info.join_rules == JoinRules.PUBLIC:
1404
+ raise SynapseError(
1405
+ 403,
1406
+ "Call invites are not allowed in public rooms.",
1407
+ Codes.FORBIDDEN,
1408
+ )
1409
+ logger.debug("Created event %s", event.event_id)
1410
+
1411
+ return event, context
1412
+
1413
+ async def _validate_event_relation(self, event: EventBase) -> None:
1414
+ """
1415
+ Ensure the relation data on a new event is not bogus.
1416
+
1417
+ Args:
1418
+ event: The event being created.
1419
+
1420
+ Raises:
1421
+ SynapseError if the event is invalid.
1422
+ """
1423
+
1424
+ relation = relation_from_event(event)
1425
+ if not relation:
1426
+ return
1427
+
1428
+ parent_event = await self.store.get_event(relation.parent_id, allow_none=True)
1429
+ if parent_event:
1430
+ # And in the same room.
1431
+ if parent_event.room_id != event.room_id:
1432
+ raise SynapseError(400, "Relations must be in the same room")
1433
+
1434
+ else:
1435
+ # There must be some reason that the client knows the event exists,
1436
+ # see if there are existing relations. If so, assume everything is fine.
1437
+ if not await self.store.event_is_target_of_relation(relation.parent_id):
1438
+ # Otherwise, the client can't know about the parent event!
1439
+ raise SynapseError(400, "Can't send relation to unknown event")
1440
+
1441
+ # If this event is an annotation then we check that that the sender
1442
+ # can't annotate the same way twice (e.g. stops users from liking an
1443
+ # event multiple times).
1444
+ if relation.rel_type == RelationTypes.ANNOTATION:
1445
+ aggregation_key = relation.aggregation_key
1446
+
1447
+ if aggregation_key is None:
1448
+ raise SynapseError(400, "Missing aggregation key")
1449
+
1450
+ if len(aggregation_key) > 500:
1451
+ raise SynapseError(400, "Aggregation key is too long")
1452
+
1453
+ already_exists = await self.store.has_user_annotated_event(
1454
+ relation.parent_id, event.type, aggregation_key, event.sender
1455
+ )
1456
+ if already_exists:
1457
+ raise SynapseError(
1458
+ 400,
1459
+ "Can't send same reaction twice",
1460
+ errcode=Codes.DUPLICATE_ANNOTATION,
1461
+ )
1462
+
1463
+ # Don't attempt to start a thread if the parent event is a relation.
1464
+ elif relation.rel_type == RelationTypes.THREAD:
1465
+ if await self.store.event_includes_relation(relation.parent_id):
1466
+ raise SynapseError(
1467
+ 400, "Cannot start threads from an event with a relation"
1468
+ )
1469
+
1470
+ @measure_func("handle_new_client_event")
1471
+ async def handle_new_client_event(
1472
+ self,
1473
+ requester: Requester,
1474
+ events_and_context: list[EventPersistencePair],
1475
+ ratelimit: bool = True,
1476
+ extra_users: list[UserID] | None = None,
1477
+ ignore_shadow_ban: bool = False,
1478
+ ) -> EventBase:
1479
+ """Processes new events. Please note that if batch persisting events, an error in
1480
+ handling any one of these events will result in all of the events being dropped.
1481
+
1482
+ This includes deduplicating, checking auth, persisting,
1483
+ notifying users, sending to remote servers, etc.
1484
+
1485
+ If called from a worker will hit out to the master process for final
1486
+ processing.
1487
+
1488
+ Args:
1489
+ requester
1490
+ events_and_context: A list of one or more tuples of event, context to be persisted
1491
+ ratelimit
1492
+ extra_users: Any extra users to notify about event
1493
+
1494
+ ignore_shadow_ban: True if shadow-banned users should be allowed to
1495
+ send this event.
1496
+
1497
+ Return:
1498
+ If the event was deduplicated, the previous, duplicate, event. Otherwise,
1499
+ `event`.
1500
+
1501
+ Raises:
1502
+ ShadowBanError if the requester has been shadow-banned.
1503
+ PartialStateConflictError if attempting to persist a partial state event in
1504
+ a room that has been un-partial stated.
1505
+ """
1506
+ extra_users = extra_users or []
1507
+
1508
+ for event, context in events_and_context:
1509
+ # we don't apply shadow-banning to membership events here. Invites are blocked
1510
+ # higher up the stack, and we allow shadow-banned users to send join and leave
1511
+ # events as normal.
1512
+ if (
1513
+ event.type != EventTypes.Member
1514
+ and not ignore_shadow_ban
1515
+ and requester.shadow_banned
1516
+ ):
1517
+ # We randomly sleep a bit just to annoy the requester.
1518
+ await self.clock.sleep(random.randint(1, 10))
1519
+ raise ShadowBanError()
1520
+
1521
+ if event.is_state():
1522
+ prev_event = await self.deduplicate_state_event(event, context)
1523
+ if prev_event is not None:
1524
+ logger.info(
1525
+ "Not bothering to persist state event %s duplicated by %s",
1526
+ event.event_id,
1527
+ prev_event.event_id,
1528
+ )
1529
+ return prev_event
1530
+
1531
+ if not event.is_state() and event.type in [
1532
+ EventTypes.Message,
1533
+ EventTypes.Encrypted,
1534
+ ]:
1535
+ await self.store.set_room_participation(event.user_id, event.room_id)
1536
+
1537
+ if event.internal_metadata.is_out_of_band_membership():
1538
+ # the only sort of out-of-band-membership events we expect to see here are
1539
+ # invite rejections and rescinded knocks that we have generated ourselves.
1540
+ assert event.type == EventTypes.Member
1541
+ assert event.content["membership"] == Membership.LEAVE
1542
+ else:
1543
+ try:
1544
+ validate_event_for_room_version(event)
1545
+ # If we are persisting a batch of events the event(s) needed to auth the
1546
+ # current event may be part of the batch and will not be in the DB yet
1547
+ event_id_to_event = {e.event_id: e for e, _ in events_and_context}
1548
+ batched_auth_events = {}
1549
+ for event_id in event.auth_event_ids():
1550
+ auth_event = event_id_to_event.get(event_id)
1551
+ if auth_event:
1552
+ batched_auth_events[event_id] = auth_event
1553
+ await self._event_auth_handler.check_auth_rules_from_context(
1554
+ event, batched_auth_events
1555
+ )
1556
+ except AuthError as err:
1557
+ logger.warning("Denying new event %r because %s", event, err)
1558
+ raise err
1559
+
1560
+ # Ensure that we can round trip before trying to persist in db
1561
+ try:
1562
+ dump = json_encoder.encode(event.content)
1563
+ json_decoder.decode(dump)
1564
+ except Exception:
1565
+ logger.exception("Failed to encode content: %r", event.content)
1566
+ raise
1567
+
1568
+ # We now persist the event (and update the cache in parallel, since we
1569
+ # don't want to block on it).
1570
+ #
1571
+ # Note: mypy gets confused if we inline dl and check with twisted#11770.
1572
+ # Some kind of bug in mypy's deduction?
1573
+ deferreds = (
1574
+ run_in_background(
1575
+ self._persist_events,
1576
+ requester=requester,
1577
+ events_and_context=events_and_context,
1578
+ ratelimit=ratelimit,
1579
+ extra_users=extra_users,
1580
+ ),
1581
+ run_in_background(
1582
+ self.cache_joined_hosts_for_events, events_and_context
1583
+ ).addErrback(log_failure, "cache_joined_hosts_for_event failed"),
1584
+ )
1585
+ result, _ = await make_deferred_yieldable(
1586
+ gather_results(deferreds, consumeErrors=True)
1587
+ ).addErrback(unwrapFirstError)
1588
+
1589
+ return result
1590
+
1591
+ async def create_and_send_new_client_events(
1592
+ self,
1593
+ requester: Requester,
1594
+ room_id: str,
1595
+ prev_event_id: str | None,
1596
+ event_dicts: Sequence[JsonDict],
1597
+ ratelimit: bool = True,
1598
+ ignore_shadow_ban: bool = False,
1599
+ ) -> None:
1600
+ """Helper to create and send a batch of new client events.
1601
+
1602
+ This supports sending membership events in very limited circumstances
1603
+ (namely that the event is valid as is and doesn't need federation
1604
+ requests or anything). Callers should prefer to use `update_membership`,
1605
+ which correctly handles membership events in all cases. We allow
1606
+ sending membership events here as its useful when copying e.g. bans
1607
+ between rooms.
1608
+
1609
+ All other events and state events are supported.
1610
+
1611
+ Args:
1612
+ requester: The requester sending the events.
1613
+ room_id: The room ID to send the events in.
1614
+ prev_event_id: The event ID to use as the previous event for the first
1615
+ of the events, must have already been persisted.
1616
+ event_dicts: A sequence of event dictionaries to create and send.
1617
+ ratelimit: Whether to rate limit this send.
1618
+ ignore_shadow_ban: True if shadow-banned users should be allowed to
1619
+ send these events.
1620
+ """
1621
+
1622
+ if not event_dicts:
1623
+ # Nothing to do.
1624
+ return
1625
+
1626
+ if prev_event_id is None:
1627
+ # Pick the latest forward extremity as the previous event ID.
1628
+ prev_event_ids = await self.store.get_forward_extremities_for_room(room_id)
1629
+ prev_event_ids.sort(key=lambda x: x[2]) # Sort by depth.
1630
+ prev_event_id = prev_event_ids[-1][0]
1631
+
1632
+ state_groups = await self._storage_controllers.state.get_state_group_for_events(
1633
+ [prev_event_id]
1634
+ )
1635
+ if prev_event_id not in state_groups:
1636
+ # This should only happen if we got passed a prev event ID that
1637
+ # hasn't been persisted yet.
1638
+ raise Exception("Previous event ID not found ")
1639
+
1640
+ current_state_group = state_groups[prev_event_id]
1641
+ state_map = await self._storage_controllers.state.get_state_ids_for_group(
1642
+ current_state_group
1643
+ )
1644
+
1645
+ events_and_contexts_to_send = []
1646
+ state_map = dict(state_map)
1647
+ depth = None
1648
+
1649
+ for event_dict in event_dicts:
1650
+ event, context = await self.create_event(
1651
+ requester=requester,
1652
+ event_dict=event_dict,
1653
+ prev_event_ids=[prev_event_id],
1654
+ depth=depth,
1655
+ # Take a copy to ensure each event gets a unique copy of
1656
+ # state_map since it is modified below.
1657
+ state_map=dict(state_map),
1658
+ for_batch=True,
1659
+ )
1660
+ events_and_contexts_to_send.append((event, context))
1661
+
1662
+ prev_event_id = event.event_id
1663
+ depth = event.depth + 1
1664
+ if event.is_state():
1665
+ # If this is a state event, we need to update the state map
1666
+ # so that it can be used for the next event.
1667
+ state_map[(event.type, event.state_key)] = event.event_id
1668
+
1669
+ datastore = self.hs.get_datastores().state
1670
+ events_and_context = (
1671
+ await UnpersistedEventContext.batch_persist_unpersisted_contexts(
1672
+ events_and_contexts_to_send, room_id, current_state_group, datastore
1673
+ )
1674
+ )
1675
+
1676
+ await self.handle_new_client_event(
1677
+ requester,
1678
+ events_and_context,
1679
+ ignore_shadow_ban=ignore_shadow_ban,
1680
+ ratelimit=ratelimit,
1681
+ )
1682
+
1683
+ async def _persist_events(
1684
+ self,
1685
+ requester: Requester,
1686
+ events_and_context: list[EventPersistencePair],
1687
+ ratelimit: bool = True,
1688
+ extra_users: list[UserID] | None = None,
1689
+ ) -> EventBase:
1690
+ """Actually persists new events. Should only be called by
1691
+ `handle_new_client_event`, and see its docstring for documentation of
1692
+ the arguments. Please note that if batch persisting events, an error in
1693
+ handling any one of these events will result in all of the events being dropped.
1694
+
1695
+ PartialStateConflictError: if attempting to persist a partial state event in
1696
+ a room that has been un-partial stated.
1697
+ """
1698
+
1699
+ await self._bulk_push_rule_evaluator.action_for_events_by_user(
1700
+ events_and_context
1701
+ )
1702
+
1703
+ try:
1704
+ # If we're a worker we need to hit out to the master.
1705
+ first_event, _ = events_and_context[0]
1706
+ writer_instance = self._events_shard_config.get_instance(
1707
+ first_event.room_id
1708
+ )
1709
+ if writer_instance != self._instance_name:
1710
+ # Ratelimit before sending to the other event persister, to
1711
+ # ensure that we correctly have ratelimits on both the event
1712
+ # creators and event persisters.
1713
+ if ratelimit:
1714
+ for event, _ in events_and_context:
1715
+ is_admin_redaction = await self.is_admin_redaction(
1716
+ event.type, event.sender, event.redacts
1717
+ )
1718
+ await self.request_ratelimiter.ratelimit(
1719
+ requester, is_admin_redaction=is_admin_redaction
1720
+ )
1721
+
1722
+ try:
1723
+ result = await self.send_events(
1724
+ instance_name=writer_instance,
1725
+ events_and_context=events_and_context,
1726
+ store=self.store,
1727
+ requester=requester,
1728
+ ratelimit=ratelimit,
1729
+ extra_users=extra_users,
1730
+ )
1731
+ except SynapseError as e:
1732
+ if e.code == HTTPStatus.CONFLICT:
1733
+ raise PartialStateConflictError()
1734
+ raise
1735
+ stream_id = result["stream_id"]
1736
+ event_id = result["event_id"]
1737
+
1738
+ # If we batch persisted events we return the last persisted event, otherwise
1739
+ # we return the one event that was persisted
1740
+ event, _ = events_and_context[-1]
1741
+
1742
+ if event_id != event.event_id:
1743
+ # If we get a different event back then it means that its
1744
+ # been de-duplicated, so we replace the given event with the
1745
+ # one already persisted.
1746
+ event = await self.store.get_event(event_id)
1747
+ else:
1748
+ # If we newly persisted the event then we need to update its
1749
+ # stream_ordering entry manually (as it was persisted on
1750
+ # another worker).
1751
+ event.internal_metadata.stream_ordering = stream_id
1752
+ event.internal_metadata.instance_name = writer_instance
1753
+
1754
+ return event
1755
+
1756
+ event = await self.persist_and_notify_client_events(
1757
+ requester,
1758
+ events_and_context,
1759
+ ratelimit=ratelimit,
1760
+ extra_users=extra_users,
1761
+ )
1762
+
1763
+ return event
1764
+ except Exception:
1765
+ for event, _ in events_and_context:
1766
+ # Ensure that we actually remove the entries in the push actions
1767
+ # staging area, if we calculated them.
1768
+ await self.store.remove_push_actions_from_staging(event.event_id)
1769
+ raise
1770
+
1771
+ async def cache_joined_hosts_for_events(
1772
+ self, events_and_context: list[EventPersistencePair]
1773
+ ) -> None:
1774
+ """Precalculate the joined hosts at each of the given events, when using Redis, so that
1775
+ external federation senders don't have to recalculate it themselves.
1776
+ """
1777
+
1778
+ if not self._external_cache.is_enabled():
1779
+ return
1780
+
1781
+ # If external cache is enabled we should always have this.
1782
+ assert self._external_cache_joined_hosts_updates is not None
1783
+
1784
+ for event, event_context in events_and_context:
1785
+ if event_context.partial_state:
1786
+ # To populate the cache for a partial-state event, we either have to
1787
+ # block until full state, which the code below does, or change the
1788
+ # meaning of cache values to be the list of hosts to which we plan to
1789
+ # send events and calculate that instead.
1790
+ #
1791
+ # The federation senders don't use the external cache when sending
1792
+ # events in partial-state rooms anyway, so let's not bother populating
1793
+ # the cache.
1794
+ continue
1795
+
1796
+ # We actually store two mappings, event ID -> prev state group,
1797
+ # state group -> joined hosts, which is much more space efficient
1798
+ # than event ID -> joined hosts.
1799
+ #
1800
+ # Note: We have to cache event ID -> prev state group, as we don't
1801
+ # store that in the DB.
1802
+ #
1803
+ # Note: We set the state group -> joined hosts cache if it hasn't been
1804
+ # set for a while, so that the expiry time is reset.
1805
+
1806
+ state_entry = await self.state.resolve_state_groups_for_events(
1807
+ event.room_id, event_ids=event.prev_event_ids()
1808
+ )
1809
+
1810
+ if state_entry.state_group:
1811
+ await self._external_cache.set(
1812
+ "event_to_prev_state_group",
1813
+ event.event_id,
1814
+ state_entry.state_group,
1815
+ expiry_ms=60 * 60 * 1000,
1816
+ )
1817
+
1818
+ if state_entry.state_group in self._external_cache_joined_hosts_updates:
1819
+ return
1820
+
1821
+ with opentracing.start_active_span("get_joined_hosts"):
1822
+ joined_hosts = (
1823
+ await self._storage_controllers.state.get_joined_hosts(
1824
+ event.room_id, state_entry
1825
+ )
1826
+ )
1827
+
1828
+ # Note that the expiry times must be larger than the expiry time in
1829
+ # _external_cache_joined_hosts_updates.
1830
+ await self._external_cache.set(
1831
+ "get_joined_hosts",
1832
+ str(state_entry.state_group),
1833
+ list(joined_hosts),
1834
+ expiry_ms=60 * 60 * 1000,
1835
+ )
1836
+
1837
+ self._external_cache_joined_hosts_updates[state_entry.state_group] = (
1838
+ None
1839
+ )
1840
+
1841
+ async def _validate_canonical_alias(
1842
+ self,
1843
+ directory_handler: DirectoryHandler,
1844
+ room_alias_str: str,
1845
+ expected_room_id: str,
1846
+ ) -> None:
1847
+ """
1848
+ Ensure that the given room alias points to the expected room ID.
1849
+
1850
+ Args:
1851
+ directory_handler: The directory handler object.
1852
+ room_alias_str: The room alias to check.
1853
+ expected_room_id: The room ID that the alias should point to.
1854
+ """
1855
+ room_alias = RoomAlias.from_string(room_alias_str)
1856
+ try:
1857
+ mapping = await directory_handler.get_association(room_alias)
1858
+ except SynapseError as e:
1859
+ # Turn M_NOT_FOUND errors into M_BAD_ALIAS errors.
1860
+ if e.errcode == Codes.NOT_FOUND:
1861
+ raise SynapseError(
1862
+ 400,
1863
+ "Room alias %s does not point to the room" % (room_alias_str,),
1864
+ Codes.BAD_ALIAS,
1865
+ )
1866
+ raise
1867
+
1868
+ if mapping["room_id"] != expected_room_id:
1869
+ raise SynapseError(
1870
+ 400,
1871
+ "Room alias %s does not point to the room" % (room_alias_str,),
1872
+ Codes.BAD_ALIAS,
1873
+ )
1874
+
1875
+ async def persist_and_notify_client_events(
1876
+ self,
1877
+ requester: Requester,
1878
+ events_and_context: list[EventPersistencePair],
1879
+ ratelimit: bool = True,
1880
+ extra_users: list[UserID] | None = None,
1881
+ ) -> EventBase:
1882
+ """Called when we have fully built the events, have already
1883
+ calculated the push actions for the events, and checked auth.
1884
+
1885
+ This should only be run on the instance in charge of persisting events.
1886
+
1887
+ Please note that if batch persisting events, an error in
1888
+ handling any one of these events will result in all of the events being dropped.
1889
+
1890
+ Returns:
1891
+ The persisted event, if one event is passed in, or the last event in the
1892
+ list in the case of batch persisting. If only one event was persisted, the
1893
+ returned event may be different than the given event if it was de-duplicated
1894
+ (e.g. because we had already persisted an event with the same transaction ID.)
1895
+
1896
+ Raises:
1897
+ PartialStateConflictError: if attempting to persist a partial state event in
1898
+ a room that has been un-partial stated.
1899
+ """
1900
+ extra_users = extra_users or []
1901
+
1902
+ for event, context in events_and_context:
1903
+ assert self._events_shard_config.should_handle(
1904
+ self._instance_name, event.room_id
1905
+ )
1906
+
1907
+ if ratelimit:
1908
+ # We check if this is a room admin redacting an event so that we
1909
+ # can apply different ratelimiting. We do this by simply checking
1910
+ # it's not a self-redaction (to avoid having to look up whether the
1911
+ # user is actually admin or not).
1912
+ is_admin_redaction = await self.is_admin_redaction(
1913
+ event.type, event.sender, event.redacts
1914
+ )
1915
+
1916
+ await self.request_ratelimiter.ratelimit(
1917
+ requester, is_admin_redaction=is_admin_redaction
1918
+ )
1919
+
1920
+ # run checks/actions on event based on type
1921
+ if event.type == EventTypes.Member and event.membership == Membership.JOIN:
1922
+ (
1923
+ current_membership,
1924
+ _,
1925
+ ) = await self.store.get_local_current_membership_for_user_in_room(
1926
+ event.state_key, event.room_id
1927
+ )
1928
+ if current_membership != Membership.JOIN:
1929
+ self._notifier.notify_user_joined_room(
1930
+ event.event_id, event.room_id
1931
+ )
1932
+
1933
+ if event.type == EventTypes.ServerACL:
1934
+ self._storage_controllers.state.get_server_acl_for_room.invalidate(
1935
+ (event.room_id,)
1936
+ )
1937
+
1938
+ await self._maybe_kick_guest_users(event, context)
1939
+
1940
+ if event.type == EventTypes.CanonicalAlias:
1941
+ # Validate a newly added alias or newly added alt_aliases.
1942
+
1943
+ original_alias = None
1944
+ original_alt_aliases: object = []
1945
+
1946
+ original_event_id = event.unsigned.get("replaces_state")
1947
+ if original_event_id:
1948
+ original_alias_event = await self.store.get_event(original_event_id)
1949
+
1950
+ if original_alias_event:
1951
+ original_alias = original_alias_event.content.get("alias", None)
1952
+ original_alt_aliases = original_alias_event.content.get(
1953
+ "alt_aliases", []
1954
+ )
1955
+
1956
+ # Check the alias is currently valid (if it has changed).
1957
+ room_alias_str = event.content.get("alias", None)
1958
+ directory_handler = self.hs.get_directory_handler()
1959
+ if room_alias_str and room_alias_str != original_alias:
1960
+ await self._validate_canonical_alias(
1961
+ directory_handler, room_alias_str, event.room_id
1962
+ )
1963
+
1964
+ # Check that alt_aliases is the proper form.
1965
+ alt_aliases = event.content.get("alt_aliases", [])
1966
+ if not isinstance(alt_aliases, (list, tuple)):
1967
+ raise SynapseError(
1968
+ 400,
1969
+ "The alt_aliases property must be a list.",
1970
+ Codes.INVALID_PARAM,
1971
+ )
1972
+
1973
+ # If the old version of alt_aliases is of an unknown form,
1974
+ # completely replace it.
1975
+ if not isinstance(original_alt_aliases, (list, tuple)):
1976
+ # TODO: check that the original_alt_aliases' entries are all strings
1977
+ original_alt_aliases = []
1978
+
1979
+ # Check that each alias is currently valid.
1980
+ new_alt_aliases = set(alt_aliases) - set(original_alt_aliases)
1981
+ if new_alt_aliases:
1982
+ for alias_str in new_alt_aliases:
1983
+ await self._validate_canonical_alias(
1984
+ directory_handler, alias_str, event.room_id
1985
+ )
1986
+
1987
+ federation_handler = self.hs.get_federation_handler()
1988
+
1989
+ if event.type == EventTypes.Member:
1990
+ if event.content["membership"] == Membership.INVITE:
1991
+ maybe_upsert_event_field(
1992
+ event,
1993
+ event.unsigned,
1994
+ "invite_room_state",
1995
+ await self.store.get_stripped_room_state_from_event_context(
1996
+ context,
1997
+ self.room_prejoin_state_types,
1998
+ membership_user_id=event.sender,
1999
+ ),
2000
+ )
2001
+
2002
+ invitee = UserID.from_string(event.state_key)
2003
+ if not self.hs.is_mine(invitee):
2004
+ # TODO: Can we add signature from remote server in a nicer
2005
+ # way? If we have been invited by a remote server, we need
2006
+ # to get them to sign the event.
2007
+
2008
+ returned_invite = await federation_handler.send_invite(
2009
+ invitee.domain, event
2010
+ )
2011
+ event.unsigned.pop("room_state", None)
2012
+
2013
+ # TODO: Make sure the signatures actually are correct.
2014
+ event.signatures.update(returned_invite.signatures)
2015
+
2016
+ if event.content["membership"] == Membership.KNOCK:
2017
+ maybe_upsert_event_field(
2018
+ event,
2019
+ event.unsigned,
2020
+ "knock_room_state",
2021
+ await self.store.get_stripped_room_state_from_event_context(
2022
+ context,
2023
+ self.room_prejoin_state_types,
2024
+ ),
2025
+ )
2026
+
2027
+ if event.type == EventTypes.Redaction:
2028
+ assert event.redacts is not None
2029
+
2030
+ original_event = await self.store.get_event(
2031
+ event.redacts,
2032
+ redact_behaviour=EventRedactBehaviour.as_is,
2033
+ get_prev_content=False,
2034
+ allow_rejected=False,
2035
+ allow_none=True,
2036
+ )
2037
+
2038
+ room_version = await self.store.get_room_version_id(event.room_id)
2039
+ room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
2040
+
2041
+ # we can make some additional checks now if we have the original event.
2042
+ if original_event:
2043
+ if original_event.type == EventTypes.Create:
2044
+ raise AuthError(403, "Redacting create events is not permitted")
2045
+
2046
+ if original_event.room_id != event.room_id:
2047
+ raise SynapseError(
2048
+ 400, "Cannot redact event from a different room"
2049
+ )
2050
+
2051
+ if original_event.type == EventTypes.ServerACL:
2052
+ raise AuthError(
2053
+ 403, "Redacting server ACL events is not permitted"
2054
+ )
2055
+
2056
+ event_types = event_auth.auth_types_for_event(event.room_version, event)
2057
+ prev_state_ids = await context.get_prev_state_ids(
2058
+ StateFilter.from_types(event_types)
2059
+ )
2060
+
2061
+ auth_events_ids = self._event_auth_handler.compute_auth_events(
2062
+ event, prev_state_ids, for_verification=True
2063
+ )
2064
+ auth_events_map = await self.store.get_events(auth_events_ids)
2065
+ auth_events = {
2066
+ (e.type, e.state_key): e for e in auth_events_map.values()
2067
+ }
2068
+
2069
+ if event_auth.check_redaction(
2070
+ room_version_obj, event, auth_events=auth_events
2071
+ ):
2072
+ # this user doesn't have 'redact' rights, so we need to do some more
2073
+ # checks on the original event. Let's start by checking the original
2074
+ # event exists.
2075
+ if not original_event:
2076
+ raise NotFoundError(
2077
+ "Could not find event %s" % (event.redacts,)
2078
+ )
2079
+
2080
+ if event.user_id != original_event.user_id:
2081
+ raise AuthError(
2082
+ 403, "You don't have permission to redact events"
2083
+ )
2084
+
2085
+ # all the checks are done.
2086
+ event.internal_metadata.recheck_redaction = False
2087
+
2088
+ if event.type == EventTypes.Create:
2089
+ prev_state_ids = await context.get_prev_state_ids()
2090
+ if prev_state_ids:
2091
+ raise AuthError(403, "Changing the room create event is forbidden")
2092
+
2093
+ assert self._storage_controllers.persistence is not None
2094
+ (
2095
+ persisted_events,
2096
+ max_stream_token,
2097
+ ) = await self._storage_controllers.persistence.persist_events(
2098
+ events_and_context,
2099
+ )
2100
+
2101
+ events_and_pos = []
2102
+ for event in persisted_events:
2103
+ if self._ephemeral_events_enabled:
2104
+ # If there's an expiry timestamp on the event, schedule its expiry.
2105
+ self._message_handler.maybe_schedule_expiry(event)
2106
+
2107
+ stream_ordering = event.internal_metadata.stream_ordering
2108
+ assert stream_ordering is not None
2109
+ pos = PersistedEventPosition(self._instance_name, stream_ordering)
2110
+ events_and_pos.append((event, pos))
2111
+
2112
+ if event.type == EventTypes.Message:
2113
+ # We don't want to block sending messages on any presence code. This
2114
+ # matters as sometimes presence code can take a while.
2115
+ self.hs.run_as_background_process(
2116
+ "bump_presence_active_time",
2117
+ self._bump_active_time,
2118
+ requester.user,
2119
+ requester.device_id,
2120
+ )
2121
+
2122
+ async def _notify() -> None:
2123
+ try:
2124
+ await self.notifier.on_new_room_events(
2125
+ events_and_pos, max_stream_token, extra_users=extra_users
2126
+ )
2127
+ except Exception:
2128
+ logger.exception("Error notifying about new room events")
2129
+
2130
+ run_in_background(_notify)
2131
+
2132
+ return persisted_events[-1]
2133
+
2134
+ async def is_admin_redaction(
2135
+ self, event_type: str, sender: str, redacts: str | None
2136
+ ) -> bool:
2137
+ """Return whether the event is a redaction made by an admin, and thus
2138
+ should use a different ratelimiter.
2139
+ """
2140
+ if event_type != EventTypes.Redaction:
2141
+ return False
2142
+
2143
+ assert redacts is not None
2144
+
2145
+ original_event = await self.store.get_event(
2146
+ redacts,
2147
+ redact_behaviour=EventRedactBehaviour.as_is,
2148
+ get_prev_content=False,
2149
+ allow_rejected=False,
2150
+ allow_none=True,
2151
+ )
2152
+
2153
+ return bool(original_event and sender != original_event.sender)
2154
+
2155
+ async def _maybe_kick_guest_users(
2156
+ self, event: EventBase, context: EventContext
2157
+ ) -> None:
2158
+ if event.type != EventTypes.GuestAccess:
2159
+ return
2160
+
2161
+ guest_access = event.content.get(EventContentFields.GUEST_ACCESS)
2162
+ if guest_access == GuestAccess.CAN_JOIN:
2163
+ return
2164
+
2165
+ current_state_ids = await context.get_current_state_ids()
2166
+
2167
+ # since this is a client-generated event, it cannot be an outlier and we must
2168
+ # therefore have the state ids.
2169
+ assert current_state_ids is not None
2170
+ current_state_dict = await self.store.get_events(
2171
+ list(current_state_ids.values())
2172
+ )
2173
+ current_state = list(current_state_dict.values())
2174
+ logger.info("maybe_kick_guest_users %r", current_state)
2175
+ await self.hs.get_room_member_handler().kick_guest_users(current_state)
2176
+
2177
+ async def _bump_active_time(self, user: UserID, device_id: str | None) -> None:
2178
+ try:
2179
+ presence = self.hs.get_presence_handler()
2180
+ await presence.bump_presence_active_time(user, device_id)
2181
+ except Exception:
2182
+ logger.exception("Error bumping presence active time")
2183
+
2184
+ async def _send_dummy_events_to_fill_extremities(self) -> None:
2185
+ """Background task to send dummy events into rooms that have a large
2186
+ number of extremities
2187
+ """
2188
+ self._expire_rooms_to_exclude_from_dummy_event_insertion()
2189
+ room_ids = await self.store.get_rooms_with_many_extremities(
2190
+ min_count=self._dummy_events_threshold,
2191
+ limit=5,
2192
+ room_id_filter=self._rooms_to_exclude_from_dummy_event_insertion.keys(),
2193
+ )
2194
+
2195
+ for room_id in room_ids:
2196
+ async with self._worker_lock_handler.acquire_read_write_lock(
2197
+ NEW_EVENT_DURING_PURGE_LOCK_NAME, room_id, write=False
2198
+ ):
2199
+ dummy_event_sent = await self._send_dummy_event_for_room(room_id)
2200
+
2201
+ if not dummy_event_sent:
2202
+ # Did not find a valid user in the room, so remove from future attempts
2203
+ # Exclusion is time limited, so the room will be rechecked in the future
2204
+ # dependent on _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY
2205
+ logger.info(
2206
+ "Failed to send dummy event into room %s. Will exclude it from "
2207
+ "future attempts until cache expires",
2208
+ room_id,
2209
+ )
2210
+ now = self.clock.time_msec()
2211
+ self._rooms_to_exclude_from_dummy_event_insertion[room_id] = now
2212
+
2213
+ async def _send_dummy_event_for_room(self, room_id: str) -> bool:
2214
+ """Attempt to send a dummy event for the given room.
2215
+
2216
+ Args:
2217
+ room_id: room to try to send an event from
2218
+
2219
+ Returns:
2220
+ True if a dummy event was successfully sent. False if no user was able
2221
+ to send an event.
2222
+ """
2223
+
2224
+ # For each room we need to find a joined member we can use to send
2225
+ # the dummy event with.
2226
+ members = await self.store.get_local_users_in_room(room_id)
2227
+ for user_id in members:
2228
+ requester = create_requester(user_id, authenticated_entity=self.server_name)
2229
+ try:
2230
+ # Try several times, it could fail with PartialStateConflictError
2231
+ # in handle_new_client_event, cf comment in except block.
2232
+ max_retries = 5
2233
+ for i in range(max_retries):
2234
+ try:
2235
+ event, unpersisted_context = await self.create_event(
2236
+ requester,
2237
+ {
2238
+ "type": EventTypes.Dummy,
2239
+ "content": {},
2240
+ "room_id": room_id,
2241
+ "sender": user_id,
2242
+ },
2243
+ )
2244
+ context = await unpersisted_context.persist(event)
2245
+
2246
+ event.internal_metadata.proactively_send = False
2247
+
2248
+ # Since this is a dummy-event it is OK if it is sent by a
2249
+ # shadow-banned user.
2250
+ await self.handle_new_client_event(
2251
+ requester,
2252
+ events_and_context=[(event, context)],
2253
+ ratelimit=False,
2254
+ ignore_shadow_ban=True,
2255
+ )
2256
+
2257
+ break
2258
+ except PartialStateConflictError as e:
2259
+ # Persisting couldn't happen because the room got un-partial stated
2260
+ # in the meantime and context needs to be recomputed, so let's do so.
2261
+ if i == max_retries - 1:
2262
+ raise e
2263
+ return True
2264
+ except AuthError:
2265
+ logger.info(
2266
+ "Failed to send dummy event into room %s for user %s due to "
2267
+ "lack of power. Will try another user",
2268
+ room_id,
2269
+ user_id,
2270
+ )
2271
+ return False
2272
+
2273
+ def _expire_rooms_to_exclude_from_dummy_event_insertion(self) -> None:
2274
+ expire_before = self.clock.time_msec() - _DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY
2275
+ to_expire = set()
2276
+ for room_id, time in self._rooms_to_exclude_from_dummy_event_insertion.items():
2277
+ if time < expire_before:
2278
+ to_expire.add(room_id)
2279
+ for room_id in to_expire:
2280
+ logger.debug(
2281
+ "Expiring room id %s from dummy event insertion exclusion cache",
2282
+ room_id,
2283
+ )
2284
+ del self._rooms_to_exclude_from_dummy_event_insertion[room_id]
2285
+
2286
+ async def _rebuild_event_after_third_party_rules(
2287
+ self, third_party_result: dict, original_event: EventBase
2288
+ ) -> tuple[EventBase, UnpersistedEventContextBase]:
2289
+ # the third_party_event_rules want to replace the event.
2290
+ # we do some basic checks, and then return the replacement event.
2291
+
2292
+ # Construct a new EventBuilder and validate it, which helps with the
2293
+ # rest of these checks.
2294
+ try:
2295
+ builder = self.event_builder_factory.for_room_version(
2296
+ original_event.room_version, third_party_result
2297
+ )
2298
+ self.validator.validate_builder(builder)
2299
+ assert builder.room_id is not None
2300
+ except SynapseError as e:
2301
+ raise Exception(
2302
+ "Third party rules module created an invalid event: " + e.msg,
2303
+ )
2304
+
2305
+ immutable_fields = [
2306
+ # changing the room is going to break things: we've already checked that the
2307
+ # room exists, and are holding a concurrency limiter token for that room.
2308
+ # Also, we might need to use a different room version.
2309
+ "room_id",
2310
+ # changing the type or state key might work, but we'd need to check that the
2311
+ # calling functions aren't making assumptions about them.
2312
+ "type",
2313
+ "state_key",
2314
+ ]
2315
+
2316
+ for k in immutable_fields:
2317
+ if getattr(builder, k, None) != original_event.get(k):
2318
+ raise Exception(
2319
+ "Third party rules module created an invalid event: "
2320
+ "cannot change field " + k
2321
+ )
2322
+
2323
+ # check that the new sender belongs to this HS
2324
+ if not self.hs.is_mine_id(builder.sender):
2325
+ raise Exception(
2326
+ "Third party rules module created an invalid event: "
2327
+ "invalid sender " + builder.sender
2328
+ )
2329
+
2330
+ # copy over the original internal metadata
2331
+ for k, v in original_event.internal_metadata.get_dict().items():
2332
+ setattr(builder.internal_metadata, k, v)
2333
+
2334
+ # modules can send new state events, so we re-calculate the auth events just in
2335
+ # case.
2336
+ prev_event_ids = await self.store.get_prev_events_for_room(builder.room_id)
2337
+
2338
+ event = await builder.build(
2339
+ prev_event_ids=prev_event_ids,
2340
+ auth_event_ids=None,
2341
+ )
2342
+
2343
+ # we rebuild the event context, to be on the safe side. If nothing else,
2344
+ # delta_ids might need an update.
2345
+ context = await self.state.calculate_context_info(event)
2346
+
2347
+ return event, context