matrix-synapse 1.142.0rc3__cp314-abi3-musllinux_1_2_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (1057) hide show
  1. matrix_synapse-1.142.0rc3.dist-info/AUTHORS.rst +51 -0
  2. matrix_synapse-1.142.0rc3.dist-info/LICENSE-AGPL-3.0 +661 -0
  3. matrix_synapse-1.142.0rc3.dist-info/LICENSE-COMMERCIAL +6 -0
  4. matrix_synapse-1.142.0rc3.dist-info/METADATA +375 -0
  5. matrix_synapse-1.142.0rc3.dist-info/RECORD +1057 -0
  6. matrix_synapse-1.142.0rc3.dist-info/WHEEL +4 -0
  7. matrix_synapse-1.142.0rc3.dist-info/entry_points.txt +14 -0
  8. matrix_synapse.libs/libgcc_s-2d945d6c.so.1 +0 -0
  9. synapse/__init__.py +97 -0
  10. synapse/_scripts/__init__.py +0 -0
  11. synapse/_scripts/export_signing_key.py +109 -0
  12. synapse/_scripts/generate_config.py +83 -0
  13. synapse/_scripts/generate_log_config.py +56 -0
  14. synapse/_scripts/generate_signing_key.py +55 -0
  15. synapse/_scripts/generate_workers_map.py +318 -0
  16. synapse/_scripts/hash_password.py +95 -0
  17. synapse/_scripts/move_remote_media_to_new_store.py +128 -0
  18. synapse/_scripts/register_new_matrix_user.py +374 -0
  19. synapse/_scripts/review_recent_signups.py +212 -0
  20. synapse/_scripts/synapse_port_db.py +1603 -0
  21. synapse/_scripts/synctl.py +365 -0
  22. synapse/_scripts/update_synapse_database.py +130 -0
  23. synapse/api/__init__.py +20 -0
  24. synapse/api/auth/__init__.py +207 -0
  25. synapse/api/auth/base.py +406 -0
  26. synapse/api/auth/internal.py +299 -0
  27. synapse/api/auth/mas.py +457 -0
  28. synapse/api/auth/msc3861_delegated.py +617 -0
  29. synapse/api/auth_blocking.py +144 -0
  30. synapse/api/constants.py +362 -0
  31. synapse/api/errors.py +907 -0
  32. synapse/api/filtering.py +539 -0
  33. synapse/api/presence.py +104 -0
  34. synapse/api/ratelimiting.py +482 -0
  35. synapse/api/room_versions.py +535 -0
  36. synapse/api/urls.py +119 -0
  37. synapse/app/__init__.py +60 -0
  38. synapse/app/_base.py +866 -0
  39. synapse/app/admin_cmd.py +388 -0
  40. synapse/app/appservice.py +30 -0
  41. synapse/app/client_reader.py +30 -0
  42. synapse/app/complement_fork_starter.py +206 -0
  43. synapse/app/event_creator.py +29 -0
  44. synapse/app/federation_reader.py +30 -0
  45. synapse/app/federation_sender.py +30 -0
  46. synapse/app/frontend_proxy.py +30 -0
  47. synapse/app/generic_worker.py +475 -0
  48. synapse/app/homeserver.py +504 -0
  49. synapse/app/media_repository.py +30 -0
  50. synapse/app/phone_stats_home.py +296 -0
  51. synapse/app/pusher.py +30 -0
  52. synapse/app/synchrotron.py +30 -0
  53. synapse/app/user_dir.py +31 -0
  54. synapse/appservice/__init__.py +461 -0
  55. synapse/appservice/api.py +569 -0
  56. synapse/appservice/scheduler.py +567 -0
  57. synapse/config/__init__.py +27 -0
  58. synapse/config/__main__.py +62 -0
  59. synapse/config/_base.py +1108 -0
  60. synapse/config/_base.pyi +217 -0
  61. synapse/config/_util.py +99 -0
  62. synapse/config/account_validity.py +116 -0
  63. synapse/config/api.py +141 -0
  64. synapse/config/appservice.py +210 -0
  65. synapse/config/auth.py +80 -0
  66. synapse/config/auto_accept_invites.py +43 -0
  67. synapse/config/background_updates.py +44 -0
  68. synapse/config/cache.py +231 -0
  69. synapse/config/captcha.py +90 -0
  70. synapse/config/cas.py +116 -0
  71. synapse/config/consent.py +73 -0
  72. synapse/config/database.py +184 -0
  73. synapse/config/emailconfig.py +367 -0
  74. synapse/config/experimental.py +595 -0
  75. synapse/config/federation.py +114 -0
  76. synapse/config/homeserver.py +141 -0
  77. synapse/config/jwt.py +55 -0
  78. synapse/config/key.py +447 -0
  79. synapse/config/logger.py +390 -0
  80. synapse/config/mas.py +191 -0
  81. synapse/config/matrixrtc.py +66 -0
  82. synapse/config/metrics.py +84 -0
  83. synapse/config/modules.py +40 -0
  84. synapse/config/oembed.py +185 -0
  85. synapse/config/oidc.py +509 -0
  86. synapse/config/password_auth_providers.py +82 -0
  87. synapse/config/push.py +64 -0
  88. synapse/config/ratelimiting.py +254 -0
  89. synapse/config/redis.py +74 -0
  90. synapse/config/registration.py +296 -0
  91. synapse/config/repository.py +311 -0
  92. synapse/config/retention.py +162 -0
  93. synapse/config/room.py +88 -0
  94. synapse/config/room_directory.py +165 -0
  95. synapse/config/saml2.py +251 -0
  96. synapse/config/server.py +1170 -0
  97. synapse/config/server_notices.py +84 -0
  98. synapse/config/spam_checker.py +66 -0
  99. synapse/config/sso.py +121 -0
  100. synapse/config/stats.py +54 -0
  101. synapse/config/third_party_event_rules.py +40 -0
  102. synapse/config/tls.py +192 -0
  103. synapse/config/tracer.py +71 -0
  104. synapse/config/user_directory.py +47 -0
  105. synapse/config/user_types.py +44 -0
  106. synapse/config/voip.py +59 -0
  107. synapse/config/workers.py +642 -0
  108. synapse/crypto/__init__.py +20 -0
  109. synapse/crypto/context_factory.py +278 -0
  110. synapse/crypto/event_signing.py +194 -0
  111. synapse/crypto/keyring.py +931 -0
  112. synapse/event_auth.py +1266 -0
  113. synapse/events/__init__.py +668 -0
  114. synapse/events/auto_accept_invites.py +216 -0
  115. synapse/events/builder.py +387 -0
  116. synapse/events/presence_router.py +245 -0
  117. synapse/events/snapshot.py +559 -0
  118. synapse/events/utils.py +928 -0
  119. synapse/events/validator.py +305 -0
  120. synapse/federation/__init__.py +22 -0
  121. synapse/federation/federation_base.py +383 -0
  122. synapse/federation/federation_client.py +2134 -0
  123. synapse/federation/federation_server.py +1544 -0
  124. synapse/federation/persistence.py +71 -0
  125. synapse/federation/send_queue.py +532 -0
  126. synapse/federation/sender/__init__.py +1165 -0
  127. synapse/federation/sender/per_destination_queue.py +884 -0
  128. synapse/federation/sender/transaction_manager.py +210 -0
  129. synapse/federation/transport/__init__.py +28 -0
  130. synapse/federation/transport/client.py +1201 -0
  131. synapse/federation/transport/server/__init__.py +334 -0
  132. synapse/federation/transport/server/_base.py +429 -0
  133. synapse/federation/transport/server/federation.py +912 -0
  134. synapse/federation/units.py +133 -0
  135. synapse/handlers/__init__.py +20 -0
  136. synapse/handlers/account.py +162 -0
  137. synapse/handlers/account_data.py +362 -0
  138. synapse/handlers/account_validity.py +361 -0
  139. synapse/handlers/admin.py +618 -0
  140. synapse/handlers/appservice.py +991 -0
  141. synapse/handlers/auth.py +2494 -0
  142. synapse/handlers/cas.py +413 -0
  143. synapse/handlers/deactivate_account.py +363 -0
  144. synapse/handlers/delayed_events.py +635 -0
  145. synapse/handlers/device.py +1873 -0
  146. synapse/handlers/devicemessage.py +399 -0
  147. synapse/handlers/directory.py +554 -0
  148. synapse/handlers/e2e_keys.py +1834 -0
  149. synapse/handlers/e2e_room_keys.py +455 -0
  150. synapse/handlers/event_auth.py +390 -0
  151. synapse/handlers/events.py +201 -0
  152. synapse/handlers/federation.py +2043 -0
  153. synapse/handlers/federation_event.py +2420 -0
  154. synapse/handlers/identity.py +812 -0
  155. synapse/handlers/initial_sync.py +528 -0
  156. synapse/handlers/jwt.py +120 -0
  157. synapse/handlers/message.py +2347 -0
  158. synapse/handlers/oidc.py +1803 -0
  159. synapse/handlers/pagination.py +768 -0
  160. synapse/handlers/password_policy.py +102 -0
  161. synapse/handlers/presence.py +2638 -0
  162. synapse/handlers/profile.py +655 -0
  163. synapse/handlers/push_rules.py +164 -0
  164. synapse/handlers/read_marker.py +79 -0
  165. synapse/handlers/receipts.py +351 -0
  166. synapse/handlers/register.py +1060 -0
  167. synapse/handlers/relations.py +624 -0
  168. synapse/handlers/reports.py +98 -0
  169. synapse/handlers/room.py +2447 -0
  170. synapse/handlers/room_list.py +632 -0
  171. synapse/handlers/room_member.py +2365 -0
  172. synapse/handlers/room_member_worker.py +146 -0
  173. synapse/handlers/room_policy.py +186 -0
  174. synapse/handlers/room_summary.py +1057 -0
  175. synapse/handlers/saml.py +524 -0
  176. synapse/handlers/search.py +723 -0
  177. synapse/handlers/send_email.py +209 -0
  178. synapse/handlers/set_password.py +71 -0
  179. synapse/handlers/sliding_sync/__init__.py +1701 -0
  180. synapse/handlers/sliding_sync/extensions.py +970 -0
  181. synapse/handlers/sliding_sync/room_lists.py +2266 -0
  182. synapse/handlers/sliding_sync/store.py +128 -0
  183. synapse/handlers/sso.py +1292 -0
  184. synapse/handlers/state_deltas.py +82 -0
  185. synapse/handlers/stats.py +322 -0
  186. synapse/handlers/sync.py +3109 -0
  187. synapse/handlers/thread_subscriptions.py +190 -0
  188. synapse/handlers/typing.py +606 -0
  189. synapse/handlers/ui_auth/__init__.py +48 -0
  190. synapse/handlers/ui_auth/checkers.py +332 -0
  191. synapse/handlers/user_directory.py +783 -0
  192. synapse/handlers/worker_lock.py +365 -0
  193. synapse/http/__init__.py +106 -0
  194. synapse/http/additional_resource.py +62 -0
  195. synapse/http/client.py +1360 -0
  196. synapse/http/connectproxyclient.py +309 -0
  197. synapse/http/federation/__init__.py +19 -0
  198. synapse/http/federation/matrix_federation_agent.py +490 -0
  199. synapse/http/federation/srv_resolver.py +196 -0
  200. synapse/http/federation/well_known_resolver.py +367 -0
  201. synapse/http/matrixfederationclient.py +1875 -0
  202. synapse/http/proxy.py +290 -0
  203. synapse/http/proxyagent.py +497 -0
  204. synapse/http/replicationagent.py +203 -0
  205. synapse/http/request_metrics.py +309 -0
  206. synapse/http/server.py +1114 -0
  207. synapse/http/servlet.py +1019 -0
  208. synapse/http/site.py +825 -0
  209. synapse/http/types.py +27 -0
  210. synapse/logging/__init__.py +31 -0
  211. synapse/logging/_remote.py +261 -0
  212. synapse/logging/_terse_json.py +95 -0
  213. synapse/logging/context.py +1211 -0
  214. synapse/logging/formatter.py +63 -0
  215. synapse/logging/handlers.py +99 -0
  216. synapse/logging/loggers.py +25 -0
  217. synapse/logging/opentracing.py +1132 -0
  218. synapse/logging/scopecontextmanager.py +161 -0
  219. synapse/media/_base.py +827 -0
  220. synapse/media/filepath.py +417 -0
  221. synapse/media/media_repository.py +1580 -0
  222. synapse/media/media_storage.py +704 -0
  223. synapse/media/oembed.py +277 -0
  224. synapse/media/preview_html.py +559 -0
  225. synapse/media/storage_provider.py +195 -0
  226. synapse/media/thumbnailer.py +833 -0
  227. synapse/media/url_previewer.py +875 -0
  228. synapse/metrics/__init__.py +754 -0
  229. synapse/metrics/_gc.py +219 -0
  230. synapse/metrics/_reactor_metrics.py +171 -0
  231. synapse/metrics/_types.py +38 -0
  232. synapse/metrics/background_process_metrics.py +556 -0
  233. synapse/metrics/common_usage_metrics.py +94 -0
  234. synapse/metrics/jemalloc.py +248 -0
  235. synapse/module_api/__init__.py +2154 -0
  236. synapse/module_api/callbacks/__init__.py +50 -0
  237. synapse/module_api/callbacks/account_validity_callbacks.py +106 -0
  238. synapse/module_api/callbacks/media_repository_callbacks.py +160 -0
  239. synapse/module_api/callbacks/ratelimit_callbacks.py +79 -0
  240. synapse/module_api/callbacks/spamchecker_callbacks.py +1113 -0
  241. synapse/module_api/callbacks/third_party_event_rules_callbacks.py +599 -0
  242. synapse/module_api/errors.py +42 -0
  243. synapse/notifier.py +972 -0
  244. synapse/push/__init__.py +212 -0
  245. synapse/push/bulk_push_rule_evaluator.py +637 -0
  246. synapse/push/clientformat.py +126 -0
  247. synapse/push/emailpusher.py +333 -0
  248. synapse/push/httppusher.py +564 -0
  249. synapse/push/mailer.py +1012 -0
  250. synapse/push/presentable_names.py +216 -0
  251. synapse/push/push_tools.py +114 -0
  252. synapse/push/push_types.py +141 -0
  253. synapse/push/pusher.py +87 -0
  254. synapse/push/pusherpool.py +501 -0
  255. synapse/push/rulekinds.py +33 -0
  256. synapse/py.typed +0 -0
  257. synapse/replication/__init__.py +20 -0
  258. synapse/replication/http/__init__.py +68 -0
  259. synapse/replication/http/_base.py +468 -0
  260. synapse/replication/http/account_data.py +297 -0
  261. synapse/replication/http/deactivate_account.py +81 -0
  262. synapse/replication/http/delayed_events.py +62 -0
  263. synapse/replication/http/devices.py +254 -0
  264. synapse/replication/http/federation.py +334 -0
  265. synapse/replication/http/login.py +106 -0
  266. synapse/replication/http/membership.py +364 -0
  267. synapse/replication/http/presence.py +133 -0
  268. synapse/replication/http/push.py +156 -0
  269. synapse/replication/http/register.py +172 -0
  270. synapse/replication/http/send_events.py +182 -0
  271. synapse/replication/http/state.py +82 -0
  272. synapse/replication/http/streams.py +101 -0
  273. synapse/replication/tcp/__init__.py +56 -0
  274. synapse/replication/tcp/client.py +552 -0
  275. synapse/replication/tcp/commands.py +569 -0
  276. synapse/replication/tcp/context.py +41 -0
  277. synapse/replication/tcp/external_cache.py +156 -0
  278. synapse/replication/tcp/handler.py +942 -0
  279. synapse/replication/tcp/protocol.py +608 -0
  280. synapse/replication/tcp/redis.py +509 -0
  281. synapse/replication/tcp/resource.py +348 -0
  282. synapse/replication/tcp/streams/__init__.py +96 -0
  283. synapse/replication/tcp/streams/_base.py +766 -0
  284. synapse/replication/tcp/streams/events.py +287 -0
  285. synapse/replication/tcp/streams/federation.py +92 -0
  286. synapse/replication/tcp/streams/partial_state.py +80 -0
  287. synapse/res/providers.json +29 -0
  288. synapse/res/templates/_base.html +29 -0
  289. synapse/res/templates/account_previously_renewed.html +6 -0
  290. synapse/res/templates/account_renewed.html +6 -0
  291. synapse/res/templates/add_threepid.html +8 -0
  292. synapse/res/templates/add_threepid.txt +6 -0
  293. synapse/res/templates/add_threepid_failure.html +7 -0
  294. synapse/res/templates/add_threepid_success.html +6 -0
  295. synapse/res/templates/already_in_use.html +12 -0
  296. synapse/res/templates/already_in_use.txt +10 -0
  297. synapse/res/templates/auth_success.html +21 -0
  298. synapse/res/templates/invalid_token.html +6 -0
  299. synapse/res/templates/mail-Element.css +7 -0
  300. synapse/res/templates/mail-Vector.css +7 -0
  301. synapse/res/templates/mail-expiry.css +4 -0
  302. synapse/res/templates/mail.css +156 -0
  303. synapse/res/templates/notice_expiry.html +46 -0
  304. synapse/res/templates/notice_expiry.txt +7 -0
  305. synapse/res/templates/notif.html +51 -0
  306. synapse/res/templates/notif.txt +22 -0
  307. synapse/res/templates/notif_mail.html +59 -0
  308. synapse/res/templates/notif_mail.txt +10 -0
  309. synapse/res/templates/password_reset.html +10 -0
  310. synapse/res/templates/password_reset.txt +7 -0
  311. synapse/res/templates/password_reset_confirmation.html +15 -0
  312. synapse/res/templates/password_reset_failure.html +7 -0
  313. synapse/res/templates/password_reset_success.html +6 -0
  314. synapse/res/templates/recaptcha.html +42 -0
  315. synapse/res/templates/registration.html +12 -0
  316. synapse/res/templates/registration.txt +10 -0
  317. synapse/res/templates/registration_failure.html +6 -0
  318. synapse/res/templates/registration_success.html +6 -0
  319. synapse/res/templates/registration_token.html +18 -0
  320. synapse/res/templates/room.html +33 -0
  321. synapse/res/templates/room.txt +9 -0
  322. synapse/res/templates/sso.css +129 -0
  323. synapse/res/templates/sso_account_deactivated.html +25 -0
  324. synapse/res/templates/sso_auth_account_details.html +186 -0
  325. synapse/res/templates/sso_auth_account_details.js +116 -0
  326. synapse/res/templates/sso_auth_bad_user.html +26 -0
  327. synapse/res/templates/sso_auth_confirm.html +27 -0
  328. synapse/res/templates/sso_auth_success.html +26 -0
  329. synapse/res/templates/sso_error.html +71 -0
  330. synapse/res/templates/sso_footer.html +19 -0
  331. synapse/res/templates/sso_login_idp_picker.html +60 -0
  332. synapse/res/templates/sso_new_user_consent.html +30 -0
  333. synapse/res/templates/sso_partial_profile.html +19 -0
  334. synapse/res/templates/sso_redirect_confirm.html +39 -0
  335. synapse/res/templates/style.css +33 -0
  336. synapse/res/templates/terms.html +27 -0
  337. synapse/rest/__init__.py +197 -0
  338. synapse/rest/admin/__init__.py +390 -0
  339. synapse/rest/admin/_base.py +72 -0
  340. synapse/rest/admin/background_updates.py +171 -0
  341. synapse/rest/admin/devices.py +221 -0
  342. synapse/rest/admin/event_reports.py +173 -0
  343. synapse/rest/admin/events.py +69 -0
  344. synapse/rest/admin/experimental_features.py +137 -0
  345. synapse/rest/admin/federation.py +243 -0
  346. synapse/rest/admin/media.py +540 -0
  347. synapse/rest/admin/registration_tokens.py +358 -0
  348. synapse/rest/admin/rooms.py +1061 -0
  349. synapse/rest/admin/scheduled_tasks.py +70 -0
  350. synapse/rest/admin/server_notice_servlet.py +132 -0
  351. synapse/rest/admin/statistics.py +132 -0
  352. synapse/rest/admin/username_available.py +58 -0
  353. synapse/rest/admin/users.py +1608 -0
  354. synapse/rest/client/__init__.py +20 -0
  355. synapse/rest/client/_base.py +113 -0
  356. synapse/rest/client/account.py +930 -0
  357. synapse/rest/client/account_data.py +319 -0
  358. synapse/rest/client/account_validity.py +103 -0
  359. synapse/rest/client/appservice_ping.py +125 -0
  360. synapse/rest/client/auth.py +218 -0
  361. synapse/rest/client/auth_metadata.py +122 -0
  362. synapse/rest/client/capabilities.py +121 -0
  363. synapse/rest/client/delayed_events.py +111 -0
  364. synapse/rest/client/devices.py +587 -0
  365. synapse/rest/client/directory.py +211 -0
  366. synapse/rest/client/events.py +116 -0
  367. synapse/rest/client/filter.py +112 -0
  368. synapse/rest/client/initial_sync.py +65 -0
  369. synapse/rest/client/keys.py +678 -0
  370. synapse/rest/client/knock.py +104 -0
  371. synapse/rest/client/login.py +754 -0
  372. synapse/rest/client/login_token_request.py +127 -0
  373. synapse/rest/client/logout.py +93 -0
  374. synapse/rest/client/matrixrtc.py +52 -0
  375. synapse/rest/client/media.py +286 -0
  376. synapse/rest/client/mutual_rooms.py +93 -0
  377. synapse/rest/client/notifications.py +137 -0
  378. synapse/rest/client/openid.py +109 -0
  379. synapse/rest/client/password_policy.py +69 -0
  380. synapse/rest/client/presence.py +131 -0
  381. synapse/rest/client/profile.py +291 -0
  382. synapse/rest/client/push_rule.py +331 -0
  383. synapse/rest/client/pusher.py +181 -0
  384. synapse/rest/client/read_marker.py +104 -0
  385. synapse/rest/client/receipts.py +165 -0
  386. synapse/rest/client/register.py +1067 -0
  387. synapse/rest/client/relations.py +138 -0
  388. synapse/rest/client/rendezvous.py +76 -0
  389. synapse/rest/client/reporting.py +207 -0
  390. synapse/rest/client/room.py +1669 -0
  391. synapse/rest/client/room_keys.py +426 -0
  392. synapse/rest/client/room_upgrade_rest_servlet.py +112 -0
  393. synapse/rest/client/sendtodevice.py +85 -0
  394. synapse/rest/client/sync.py +1131 -0
  395. synapse/rest/client/tags.py +129 -0
  396. synapse/rest/client/thirdparty.py +130 -0
  397. synapse/rest/client/thread_subscriptions.py +247 -0
  398. synapse/rest/client/tokenrefresh.py +52 -0
  399. synapse/rest/client/transactions.py +149 -0
  400. synapse/rest/client/user_directory.py +90 -0
  401. synapse/rest/client/versions.py +191 -0
  402. synapse/rest/client/voip.py +88 -0
  403. synapse/rest/consent/__init__.py +0 -0
  404. synapse/rest/consent/consent_resource.py +210 -0
  405. synapse/rest/health.py +38 -0
  406. synapse/rest/key/__init__.py +20 -0
  407. synapse/rest/key/v2/__init__.py +40 -0
  408. synapse/rest/key/v2/local_key_resource.py +125 -0
  409. synapse/rest/key/v2/remote_key_resource.py +302 -0
  410. synapse/rest/media/__init__.py +0 -0
  411. synapse/rest/media/config_resource.py +53 -0
  412. synapse/rest/media/create_resource.py +90 -0
  413. synapse/rest/media/download_resource.py +110 -0
  414. synapse/rest/media/media_repository_resource.py +113 -0
  415. synapse/rest/media/preview_url_resource.py +77 -0
  416. synapse/rest/media/thumbnail_resource.py +142 -0
  417. synapse/rest/media/upload_resource.py +187 -0
  418. synapse/rest/media/v1/__init__.py +39 -0
  419. synapse/rest/media/v1/_base.py +23 -0
  420. synapse/rest/media/v1/media_storage.py +23 -0
  421. synapse/rest/media/v1/storage_provider.py +23 -0
  422. synapse/rest/synapse/__init__.py +20 -0
  423. synapse/rest/synapse/client/__init__.py +93 -0
  424. synapse/rest/synapse/client/federation_whitelist.py +66 -0
  425. synapse/rest/synapse/client/jwks.py +77 -0
  426. synapse/rest/synapse/client/new_user_consent.py +115 -0
  427. synapse/rest/synapse/client/oidc/__init__.py +45 -0
  428. synapse/rest/synapse/client/oidc/backchannel_logout_resource.py +42 -0
  429. synapse/rest/synapse/client/oidc/callback_resource.py +48 -0
  430. synapse/rest/synapse/client/password_reset.py +129 -0
  431. synapse/rest/synapse/client/pick_idp.py +107 -0
  432. synapse/rest/synapse/client/pick_username.py +153 -0
  433. synapse/rest/synapse/client/rendezvous.py +58 -0
  434. synapse/rest/synapse/client/saml2/__init__.py +42 -0
  435. synapse/rest/synapse/client/saml2/metadata_resource.py +46 -0
  436. synapse/rest/synapse/client/saml2/response_resource.py +52 -0
  437. synapse/rest/synapse/client/sso_register.py +56 -0
  438. synapse/rest/synapse/client/unsubscribe.py +88 -0
  439. synapse/rest/synapse/mas/__init__.py +71 -0
  440. synapse/rest/synapse/mas/_base.py +55 -0
  441. synapse/rest/synapse/mas/devices.py +239 -0
  442. synapse/rest/synapse/mas/users.py +469 -0
  443. synapse/rest/well_known.py +148 -0
  444. synapse/server.py +1258 -0
  445. synapse/server_notices/__init__.py +0 -0
  446. synapse/server_notices/consent_server_notices.py +136 -0
  447. synapse/server_notices/resource_limits_server_notices.py +215 -0
  448. synapse/server_notices/server_notices_manager.py +388 -0
  449. synapse/server_notices/server_notices_sender.py +67 -0
  450. synapse/server_notices/worker_server_notices_sender.py +46 -0
  451. synapse/spam_checker_api/__init__.py +31 -0
  452. synapse/state/__init__.py +1022 -0
  453. synapse/state/v1.py +370 -0
  454. synapse/state/v2.py +985 -0
  455. synapse/static/client/login/index.html +47 -0
  456. synapse/static/client/login/js/jquery-3.4.1.min.js +2 -0
  457. synapse/static/client/login/js/login.js +291 -0
  458. synapse/static/client/login/spinner.gif +0 -0
  459. synapse/static/client/login/style.css +79 -0
  460. synapse/static/index.html +63 -0
  461. synapse/storage/__init__.py +43 -0
  462. synapse/storage/_base.py +245 -0
  463. synapse/storage/admin_client_config.py +26 -0
  464. synapse/storage/background_updates.py +1189 -0
  465. synapse/storage/controllers/__init__.py +57 -0
  466. synapse/storage/controllers/persist_events.py +1239 -0
  467. synapse/storage/controllers/purge_events.py +456 -0
  468. synapse/storage/controllers/state.py +954 -0
  469. synapse/storage/controllers/stats.py +119 -0
  470. synapse/storage/database.py +2720 -0
  471. synapse/storage/databases/__init__.py +175 -0
  472. synapse/storage/databases/main/__init__.py +424 -0
  473. synapse/storage/databases/main/account_data.py +1060 -0
  474. synapse/storage/databases/main/appservice.py +473 -0
  475. synapse/storage/databases/main/cache.py +911 -0
  476. synapse/storage/databases/main/censor_events.py +225 -0
  477. synapse/storage/databases/main/client_ips.py +817 -0
  478. synapse/storage/databases/main/delayed_events.py +560 -0
  479. synapse/storage/databases/main/deviceinbox.py +1272 -0
  480. synapse/storage/databases/main/devices.py +2581 -0
  481. synapse/storage/databases/main/directory.py +212 -0
  482. synapse/storage/databases/main/e2e_room_keys.py +690 -0
  483. synapse/storage/databases/main/end_to_end_keys.py +1896 -0
  484. synapse/storage/databases/main/event_federation.py +2509 -0
  485. synapse/storage/databases/main/event_push_actions.py +1937 -0
  486. synapse/storage/databases/main/events.py +3746 -0
  487. synapse/storage/databases/main/events_bg_updates.py +2910 -0
  488. synapse/storage/databases/main/events_forward_extremities.py +126 -0
  489. synapse/storage/databases/main/events_worker.py +2784 -0
  490. synapse/storage/databases/main/experimental_features.py +130 -0
  491. synapse/storage/databases/main/filtering.py +231 -0
  492. synapse/storage/databases/main/keys.py +291 -0
  493. synapse/storage/databases/main/lock.py +553 -0
  494. synapse/storage/databases/main/media_repository.py +1070 -0
  495. synapse/storage/databases/main/metrics.py +460 -0
  496. synapse/storage/databases/main/monthly_active_users.py +443 -0
  497. synapse/storage/databases/main/openid.py +61 -0
  498. synapse/storage/databases/main/presence.py +511 -0
  499. synapse/storage/databases/main/profile.py +541 -0
  500. synapse/storage/databases/main/purge_events.py +511 -0
  501. synapse/storage/databases/main/push_rule.py +972 -0
  502. synapse/storage/databases/main/pusher.py +794 -0
  503. synapse/storage/databases/main/receipts.py +1342 -0
  504. synapse/storage/databases/main/registration.py +3076 -0
  505. synapse/storage/databases/main/rejections.py +38 -0
  506. synapse/storage/databases/main/relations.py +1118 -0
  507. synapse/storage/databases/main/room.py +2781 -0
  508. synapse/storage/databases/main/roommember.py +2112 -0
  509. synapse/storage/databases/main/search.py +941 -0
  510. synapse/storage/databases/main/session.py +151 -0
  511. synapse/storage/databases/main/signatures.py +94 -0
  512. synapse/storage/databases/main/sliding_sync.py +603 -0
  513. synapse/storage/databases/main/state.py +1006 -0
  514. synapse/storage/databases/main/state_deltas.py +329 -0
  515. synapse/storage/databases/main/stats.py +791 -0
  516. synapse/storage/databases/main/stream.py +2580 -0
  517. synapse/storage/databases/main/tags.py +360 -0
  518. synapse/storage/databases/main/task_scheduler.py +225 -0
  519. synapse/storage/databases/main/thread_subscriptions.py +591 -0
  520. synapse/storage/databases/main/transactions.py +681 -0
  521. synapse/storage/databases/main/ui_auth.py +420 -0
  522. synapse/storage/databases/main/user_directory.py +1331 -0
  523. synapse/storage/databases/main/user_erasure_store.py +117 -0
  524. synapse/storage/databases/state/__init__.py +22 -0
  525. synapse/storage/databases/state/bg_updates.py +499 -0
  526. synapse/storage/databases/state/deletion.py +558 -0
  527. synapse/storage/databases/state/store.py +949 -0
  528. synapse/storage/engines/__init__.py +70 -0
  529. synapse/storage/engines/_base.py +154 -0
  530. synapse/storage/engines/postgres.py +261 -0
  531. synapse/storage/engines/sqlite.py +199 -0
  532. synapse/storage/invite_rule.py +112 -0
  533. synapse/storage/keys.py +40 -0
  534. synapse/storage/prepare_database.py +731 -0
  535. synapse/storage/push_rule.py +28 -0
  536. synapse/storage/roommember.py +89 -0
  537. synapse/storage/schema/README.md +4 -0
  538. synapse/storage/schema/__init__.py +182 -0
  539. synapse/storage/schema/common/delta/25/00background_updates.sql +40 -0
  540. synapse/storage/schema/common/delta/35/00background_updates_add_col.sql +36 -0
  541. synapse/storage/schema/common/delta/58/00background_update_ordering.sql +38 -0
  542. synapse/storage/schema/common/full_schemas/72/full.sql.postgres +8 -0
  543. synapse/storage/schema/common/full_schemas/72/full.sql.sqlite +6 -0
  544. synapse/storage/schema/common/schema_version.sql +60 -0
  545. synapse/storage/schema/main/delta/12/v12.sql +82 -0
  546. synapse/storage/schema/main/delta/13/v13.sql +38 -0
  547. synapse/storage/schema/main/delta/14/v14.sql +42 -0
  548. synapse/storage/schema/main/delta/15/appservice_txns.sql +50 -0
  549. synapse/storage/schema/main/delta/15/presence_indices.sql +2 -0
  550. synapse/storage/schema/main/delta/15/v15.sql +24 -0
  551. synapse/storage/schema/main/delta/16/events_order_index.sql +4 -0
  552. synapse/storage/schema/main/delta/16/remote_media_cache_index.sql +2 -0
  553. synapse/storage/schema/main/delta/16/remove_duplicates.sql +9 -0
  554. synapse/storage/schema/main/delta/16/room_alias_index.sql +3 -0
  555. synapse/storage/schema/main/delta/16/unique_constraints.sql +72 -0
  556. synapse/storage/schema/main/delta/16/users.sql +56 -0
  557. synapse/storage/schema/main/delta/17/drop_indexes.sql +37 -0
  558. synapse/storage/schema/main/delta/17/server_keys.sql +43 -0
  559. synapse/storage/schema/main/delta/17/user_threepids.sql +9 -0
  560. synapse/storage/schema/main/delta/18/server_keys_bigger_ints.sql +51 -0
  561. synapse/storage/schema/main/delta/19/event_index.sql +38 -0
  562. synapse/storage/schema/main/delta/20/dummy.sql +1 -0
  563. synapse/storage/schema/main/delta/20/pushers.py +93 -0
  564. synapse/storage/schema/main/delta/21/end_to_end_keys.sql +53 -0
  565. synapse/storage/schema/main/delta/21/receipts.sql +57 -0
  566. synapse/storage/schema/main/delta/22/receipts_index.sql +41 -0
  567. synapse/storage/schema/main/delta/22/user_threepids_unique.sql +19 -0
  568. synapse/storage/schema/main/delta/24/stats_reporting.sql +37 -0
  569. synapse/storage/schema/main/delta/25/fts.py +81 -0
  570. synapse/storage/schema/main/delta/25/guest_access.sql +44 -0
  571. synapse/storage/schema/main/delta/25/history_visibility.sql +44 -0
  572. synapse/storage/schema/main/delta/25/tags.sql +57 -0
  573. synapse/storage/schema/main/delta/26/account_data.sql +36 -0
  574. synapse/storage/schema/main/delta/27/account_data.sql +55 -0
  575. synapse/storage/schema/main/delta/27/forgotten_memberships.sql +45 -0
  576. synapse/storage/schema/main/delta/27/ts.py +61 -0
  577. synapse/storage/schema/main/delta/28/event_push_actions.sql +46 -0
  578. synapse/storage/schema/main/delta/28/events_room_stream.sql +39 -0
  579. synapse/storage/schema/main/delta/28/public_roms_index.sql +39 -0
  580. synapse/storage/schema/main/delta/28/receipts_user_id_index.sql +41 -0
  581. synapse/storage/schema/main/delta/28/upgrade_times.sql +40 -0
  582. synapse/storage/schema/main/delta/28/users_is_guest.sql +41 -0
  583. synapse/storage/schema/main/delta/29/push_actions.sql +54 -0
  584. synapse/storage/schema/main/delta/30/alias_creator.sql +35 -0
  585. synapse/storage/schema/main/delta/30/as_users.py +82 -0
  586. synapse/storage/schema/main/delta/30/deleted_pushers.sql +44 -0
  587. synapse/storage/schema/main/delta/30/presence_stream.sql +49 -0
  588. synapse/storage/schema/main/delta/30/public_rooms.sql +42 -0
  589. synapse/storage/schema/main/delta/30/push_rule_stream.sql +57 -0
  590. synapse/storage/schema/main/delta/30/threepid_guest_access_tokens.sql +43 -0
  591. synapse/storage/schema/main/delta/31/invites.sql +61 -0
  592. synapse/storage/schema/main/delta/31/local_media_repository_url_cache.sql +46 -0
  593. synapse/storage/schema/main/delta/31/pushers_0.py +92 -0
  594. synapse/storage/schema/main/delta/31/pushers_index.sql +41 -0
  595. synapse/storage/schema/main/delta/31/search_update.py +65 -0
  596. synapse/storage/schema/main/delta/32/events.sql +35 -0
  597. synapse/storage/schema/main/delta/32/openid.sql +9 -0
  598. synapse/storage/schema/main/delta/32/pusher_throttle.sql +42 -0
  599. synapse/storage/schema/main/delta/32/remove_indices.sql +52 -0
  600. synapse/storage/schema/main/delta/32/reports.sql +44 -0
  601. synapse/storage/schema/main/delta/33/access_tokens_device_index.sql +36 -0
  602. synapse/storage/schema/main/delta/33/devices.sql +40 -0
  603. synapse/storage/schema/main/delta/33/devices_for_e2e_keys.sql +38 -0
  604. synapse/storage/schema/main/delta/33/devices_for_e2e_keys_clear_unknown_device.sql +39 -0
  605. synapse/storage/schema/main/delta/33/event_fields.py +61 -0
  606. synapse/storage/schema/main/delta/33/remote_media_ts.py +43 -0
  607. synapse/storage/schema/main/delta/33/user_ips_index.sql +36 -0
  608. synapse/storage/schema/main/delta/34/appservice_stream.sql +42 -0
  609. synapse/storage/schema/main/delta/34/cache_stream.py +50 -0
  610. synapse/storage/schema/main/delta/34/device_inbox.sql +43 -0
  611. synapse/storage/schema/main/delta/34/push_display_name_rename.sql +39 -0
  612. synapse/storage/schema/main/delta/34/received_txn_purge.py +36 -0
  613. synapse/storage/schema/main/delta/35/contains_url.sql +36 -0
  614. synapse/storage/schema/main/delta/35/device_outbox.sql +58 -0
  615. synapse/storage/schema/main/delta/35/device_stream_id.sql +40 -0
  616. synapse/storage/schema/main/delta/35/event_push_actions_index.sql +36 -0
  617. synapse/storage/schema/main/delta/35/public_room_list_change_stream.sql +52 -0
  618. synapse/storage/schema/main/delta/35/stream_order_to_extrem.sql +56 -0
  619. synapse/storage/schema/main/delta/36/readd_public_rooms.sql +45 -0
  620. synapse/storage/schema/main/delta/37/remove_auth_idx.py +89 -0
  621. synapse/storage/schema/main/delta/37/user_threepids.sql +71 -0
  622. synapse/storage/schema/main/delta/38/postgres_fts_gist.sql +38 -0
  623. synapse/storage/schema/main/delta/39/appservice_room_list.sql +48 -0
  624. synapse/storage/schema/main/delta/39/device_federation_stream_idx.sql +35 -0
  625. synapse/storage/schema/main/delta/39/event_push_index.sql +36 -0
  626. synapse/storage/schema/main/delta/39/federation_out_position.sql +41 -0
  627. synapse/storage/schema/main/delta/39/membership_profile.sql +39 -0
  628. synapse/storage/schema/main/delta/40/current_state_idx.sql +36 -0
  629. synapse/storage/schema/main/delta/40/device_inbox.sql +40 -0
  630. synapse/storage/schema/main/delta/40/device_list_streams.sql +79 -0
  631. synapse/storage/schema/main/delta/40/event_push_summary.sql +57 -0
  632. synapse/storage/schema/main/delta/40/pushers.sql +58 -0
  633. synapse/storage/schema/main/delta/41/device_list_stream_idx.sql +36 -0
  634. synapse/storage/schema/main/delta/41/device_outbound_index.sql +35 -0
  635. synapse/storage/schema/main/delta/41/event_search_event_id_idx.sql +36 -0
  636. synapse/storage/schema/main/delta/41/ratelimit.sql +41 -0
  637. synapse/storage/schema/main/delta/42/current_state_delta.sql +48 -0
  638. synapse/storage/schema/main/delta/42/device_list_last_id.sql +52 -0
  639. synapse/storage/schema/main/delta/42/event_auth_state_only.sql +36 -0
  640. synapse/storage/schema/main/delta/42/user_dir.py +88 -0
  641. synapse/storage/schema/main/delta/43/blocked_rooms.sql +40 -0
  642. synapse/storage/schema/main/delta/43/quarantine_media.sql +36 -0
  643. synapse/storage/schema/main/delta/43/url_cache.sql +35 -0
  644. synapse/storage/schema/main/delta/43/user_share.sql +52 -0
  645. synapse/storage/schema/main/delta/44/expire_url_cache.sql +60 -0
  646. synapse/storage/schema/main/delta/45/group_server.sql +186 -0
  647. synapse/storage/schema/main/delta/45/profile_cache.sql +47 -0
  648. synapse/storage/schema/main/delta/46/drop_refresh_tokens.sql +36 -0
  649. synapse/storage/schema/main/delta/46/drop_unique_deleted_pushers.sql +54 -0
  650. synapse/storage/schema/main/delta/46/group_server.sql +51 -0
  651. synapse/storage/schema/main/delta/46/local_media_repository_url_idx.sql +43 -0
  652. synapse/storage/schema/main/delta/46/user_dir_null_room_ids.sql +54 -0
  653. synapse/storage/schema/main/delta/46/user_dir_typos.sql +43 -0
  654. synapse/storage/schema/main/delta/47/last_access_media.sql +35 -0
  655. synapse/storage/schema/main/delta/47/postgres_fts_gin.sql +36 -0
  656. synapse/storage/schema/main/delta/47/push_actions_staging.sql +47 -0
  657. synapse/storage/schema/main/delta/48/add_user_consent.sql +37 -0
  658. synapse/storage/schema/main/delta/48/add_user_ips_last_seen_index.sql +36 -0
  659. synapse/storage/schema/main/delta/48/deactivated_users.sql +44 -0
  660. synapse/storage/schema/main/delta/48/group_unique_indexes.py +67 -0
  661. synapse/storage/schema/main/delta/48/groups_joinable.sql +41 -0
  662. synapse/storage/schema/main/delta/49/add_user_consent_server_notice_sent.sql +39 -0
  663. synapse/storage/schema/main/delta/49/add_user_daily_visits.sql +40 -0
  664. synapse/storage/schema/main/delta/49/add_user_ips_last_seen_only_index.sql +36 -0
  665. synapse/storage/schema/main/delta/50/add_creation_ts_users_index.sql +38 -0
  666. synapse/storage/schema/main/delta/50/erasure_store.sql +40 -0
  667. synapse/storage/schema/main/delta/50/make_event_content_nullable.py +102 -0
  668. synapse/storage/schema/main/delta/51/e2e_room_keys.sql +58 -0
  669. synapse/storage/schema/main/delta/51/monthly_active_users.sql +46 -0
  670. synapse/storage/schema/main/delta/52/add_event_to_state_group_index.sql +38 -0
  671. synapse/storage/schema/main/delta/52/device_list_streams_unique_idx.sql +55 -0
  672. synapse/storage/schema/main/delta/52/e2e_room_keys.sql +72 -0
  673. synapse/storage/schema/main/delta/53/add_user_type_to_users.sql +38 -0
  674. synapse/storage/schema/main/delta/53/drop_sent_transactions.sql +35 -0
  675. synapse/storage/schema/main/delta/53/event_format_version.sql +35 -0
  676. synapse/storage/schema/main/delta/53/user_dir_populate.sql +49 -0
  677. synapse/storage/schema/main/delta/53/user_ips_index.sql +49 -0
  678. synapse/storage/schema/main/delta/53/user_share.sql +63 -0
  679. synapse/storage/schema/main/delta/53/user_threepid_id.sql +48 -0
  680. synapse/storage/schema/main/delta/53/users_in_public_rooms.sql +47 -0
  681. synapse/storage/schema/main/delta/54/account_validity_with_renewal.sql +49 -0
  682. synapse/storage/schema/main/delta/54/add_validity_to_server_keys.sql +42 -0
  683. synapse/storage/schema/main/delta/54/delete_forward_extremities.sql +42 -0
  684. synapse/storage/schema/main/delta/54/drop_legacy_tables.sql +49 -0
  685. synapse/storage/schema/main/delta/54/drop_presence_list.sql +35 -0
  686. synapse/storage/schema/main/delta/54/relations.sql +46 -0
  687. synapse/storage/schema/main/delta/54/stats.sql +99 -0
  688. synapse/storage/schema/main/delta/54/stats2.sql +47 -0
  689. synapse/storage/schema/main/delta/55/access_token_expiry.sql +37 -0
  690. synapse/storage/schema/main/delta/55/track_threepid_validations.sql +50 -0
  691. synapse/storage/schema/main/delta/55/users_alter_deactivated.sql +38 -0
  692. synapse/storage/schema/main/delta/56/add_spans_to_device_lists.sql +39 -0
  693. synapse/storage/schema/main/delta/56/current_state_events_membership.sql +41 -0
  694. synapse/storage/schema/main/delta/56/current_state_events_membership_mk2.sql +43 -0
  695. synapse/storage/schema/main/delta/56/delete_keys_from_deleted_backups.sql +44 -0
  696. synapse/storage/schema/main/delta/56/destinations_failure_ts.sql +44 -0
  697. synapse/storage/schema/main/delta/56/destinations_retry_interval_type.sql.postgres +18 -0
  698. synapse/storage/schema/main/delta/56/device_stream_id_insert.sql +39 -0
  699. synapse/storage/schema/main/delta/56/devices_last_seen.sql +43 -0
  700. synapse/storage/schema/main/delta/56/drop_unused_event_tables.sql +39 -0
  701. synapse/storage/schema/main/delta/56/event_expiry.sql +40 -0
  702. synapse/storage/schema/main/delta/56/event_labels.sql +49 -0
  703. synapse/storage/schema/main/delta/56/event_labels_background_update.sql +36 -0
  704. synapse/storage/schema/main/delta/56/fix_room_keys_index.sql +37 -0
  705. synapse/storage/schema/main/delta/56/hidden_devices.sql +37 -0
  706. synapse/storage/schema/main/delta/56/hidden_devices_fix.sql.sqlite +42 -0
  707. synapse/storage/schema/main/delta/56/nuke_empty_communities_from_db.sql +48 -0
  708. synapse/storage/schema/main/delta/56/public_room_list_idx.sql +35 -0
  709. synapse/storage/schema/main/delta/56/redaction_censor.sql +35 -0
  710. synapse/storage/schema/main/delta/56/redaction_censor2.sql +41 -0
  711. synapse/storage/schema/main/delta/56/redaction_censor3_fix_update.sql.postgres +25 -0
  712. synapse/storage/schema/main/delta/56/redaction_censor4.sql +35 -0
  713. synapse/storage/schema/main/delta/56/remove_tombstoned_rooms_from_directory.sql +38 -0
  714. synapse/storage/schema/main/delta/56/room_key_etag.sql +36 -0
  715. synapse/storage/schema/main/delta/56/room_membership_idx.sql +37 -0
  716. synapse/storage/schema/main/delta/56/room_retention.sql +52 -0
  717. synapse/storage/schema/main/delta/56/signing_keys.sql +75 -0
  718. synapse/storage/schema/main/delta/56/signing_keys_nonunique_signatures.sql +41 -0
  719. synapse/storage/schema/main/delta/56/stats_separated.sql +175 -0
  720. synapse/storage/schema/main/delta/56/unique_user_filter_index.py +46 -0
  721. synapse/storage/schema/main/delta/56/user_external_ids.sql +43 -0
  722. synapse/storage/schema/main/delta/56/users_in_public_rooms_idx.sql +36 -0
  723. synapse/storage/schema/main/delta/57/delete_old_current_state_events.sql +41 -0
  724. synapse/storage/schema/main/delta/57/device_list_remote_cache_stale.sql +44 -0
  725. synapse/storage/schema/main/delta/57/local_current_membership.py +111 -0
  726. synapse/storage/schema/main/delta/57/remove_sent_outbound_pokes.sql +40 -0
  727. synapse/storage/schema/main/delta/57/rooms_version_column.sql +43 -0
  728. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.postgres +35 -0
  729. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.sqlite +22 -0
  730. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.postgres +39 -0
  731. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.sqlite +23 -0
  732. synapse/storage/schema/main/delta/58/02remove_dup_outbound_pokes.sql +41 -0
  733. synapse/storage/schema/main/delta/58/03persist_ui_auth.sql +55 -0
  734. synapse/storage/schema/main/delta/58/05cache_instance.sql.postgres +30 -0
  735. synapse/storage/schema/main/delta/58/06dlols_unique_idx.py +83 -0
  736. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.postgres +33 -0
  737. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.sqlite +44 -0
  738. synapse/storage/schema/main/delta/58/07persist_ui_auth_ips.sql +44 -0
  739. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.postgres +18 -0
  740. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.sqlite +18 -0
  741. synapse/storage/schema/main/delta/58/09shadow_ban.sql +37 -0
  742. synapse/storage/schema/main/delta/58/10_pushrules_enabled_delete_obsolete.sql +47 -0
  743. synapse/storage/schema/main/delta/58/10drop_local_rejections_stream.sql +41 -0
  744. synapse/storage/schema/main/delta/58/10federation_pos_instance_name.sql +41 -0
  745. synapse/storage/schema/main/delta/58/11dehydration.sql +39 -0
  746. synapse/storage/schema/main/delta/58/11fallback.sql +43 -0
  747. synapse/storage/schema/main/delta/58/11user_id_seq.py +38 -0
  748. synapse/storage/schema/main/delta/58/12room_stats.sql +51 -0
  749. synapse/storage/schema/main/delta/58/13remove_presence_allow_inbound.sql +36 -0
  750. synapse/storage/schema/main/delta/58/14events_instance_name.sql +35 -0
  751. synapse/storage/schema/main/delta/58/14events_instance_name.sql.postgres +28 -0
  752. synapse/storage/schema/main/delta/58/15_catchup_destination_rooms.sql +61 -0
  753. synapse/storage/schema/main/delta/58/15unread_count.sql +45 -0
  754. synapse/storage/schema/main/delta/58/16populate_stats_process_rooms_fix.sql +41 -0
  755. synapse/storage/schema/main/delta/58/17_catchup_last_successful.sql +40 -0
  756. synapse/storage/schema/main/delta/58/18stream_positions.sql +41 -0
  757. synapse/storage/schema/main/delta/58/19instance_map.sql.postgres +25 -0
  758. synapse/storage/schema/main/delta/58/19txn_id.sql +59 -0
  759. synapse/storage/schema/main/delta/58/20instance_name_event_tables.sql +36 -0
  760. synapse/storage/schema/main/delta/58/20user_daily_visits.sql +37 -0
  761. synapse/storage/schema/main/delta/58/21as_device_stream.sql +36 -0
  762. synapse/storage/schema/main/delta/58/21drop_device_max_stream_id.sql +1 -0
  763. synapse/storage/schema/main/delta/58/22puppet_token.sql +36 -0
  764. synapse/storage/schema/main/delta/58/22users_have_local_media.sql +2 -0
  765. synapse/storage/schema/main/delta/58/23e2e_cross_signing_keys_idx.sql +36 -0
  766. synapse/storage/schema/main/delta/58/24drop_event_json_index.sql +38 -0
  767. synapse/storage/schema/main/delta/58/25user_external_ids_user_id_idx.sql +36 -0
  768. synapse/storage/schema/main/delta/58/26access_token_last_validated.sql +37 -0
  769. synapse/storage/schema/main/delta/58/27local_invites.sql +37 -0
  770. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.postgres +16 -0
  771. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.sqlite +62 -0
  772. synapse/storage/schema/main/delta/59/01ignored_user.py +85 -0
  773. synapse/storage/schema/main/delta/59/02shard_send_to_device.sql +37 -0
  774. synapse/storage/schema/main/delta/59/03shard_send_to_device_sequence.sql.postgres +25 -0
  775. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql +71 -0
  776. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql.postgres +16 -0
  777. synapse/storage/schema/main/delta/59/04drop_account_data.sql +36 -0
  778. synapse/storage/schema/main/delta/59/05cache_invalidation.sql +36 -0
  779. synapse/storage/schema/main/delta/59/06chain_cover_index.sql +36 -0
  780. synapse/storage/schema/main/delta/59/06shard_account_data.sql +39 -0
  781. synapse/storage/schema/main/delta/59/06shard_account_data.sql.postgres +32 -0
  782. synapse/storage/schema/main/delta/59/07shard_account_data_fix.sql +37 -0
  783. synapse/storage/schema/main/delta/59/08delete_pushers_for_deactivated_accounts.sql +39 -0
  784. synapse/storage/schema/main/delta/59/08delete_stale_pushers.sql +39 -0
  785. synapse/storage/schema/main/delta/59/09rejected_events_metadata.sql +45 -0
  786. synapse/storage/schema/main/delta/59/10delete_purged_chain_cover.sql +36 -0
  787. synapse/storage/schema/main/delta/59/11add_knock_members_to_stats.sql +39 -0
  788. synapse/storage/schema/main/delta/59/11drop_thumbnail_constraint.sql.postgres +22 -0
  789. synapse/storage/schema/main/delta/59/12account_validity_token_used_ts_ms.sql +37 -0
  790. synapse/storage/schema/main/delta/59/12presence_stream_instance.sql +37 -0
  791. synapse/storage/schema/main/delta/59/12presence_stream_instance_seq.sql.postgres +20 -0
  792. synapse/storage/schema/main/delta/59/13users_to_send_full_presence_to.sql +53 -0
  793. synapse/storage/schema/main/delta/59/14refresh_tokens.sql +53 -0
  794. synapse/storage/schema/main/delta/59/15locks.sql +56 -0
  795. synapse/storage/schema/main/delta/59/16federation_inbound_staging.sql +51 -0
  796. synapse/storage/schema/main/delta/60/01recreate_stream_ordering.sql.postgres +45 -0
  797. synapse/storage/schema/main/delta/60/02change_stream_ordering_columns.sql.postgres +30 -0
  798. synapse/storage/schema/main/delta/61/01change_appservices_txns.sql.postgres +23 -0
  799. synapse/storage/schema/main/delta/61/01insertion_event_lookups.sql +68 -0
  800. synapse/storage/schema/main/delta/61/02drop_redundant_room_depth_index.sql +37 -0
  801. synapse/storage/schema/main/delta/61/03recreate_min_depth.py +74 -0
  802. synapse/storage/schema/main/delta/62/01insertion_event_extremities.sql +43 -0
  803. synapse/storage/schema/main/delta/63/01create_registration_tokens.sql +42 -0
  804. synapse/storage/schema/main/delta/63/02delete_unlinked_email_pushers.sql +39 -0
  805. synapse/storage/schema/main/delta/63/02populate-rooms-creator.sql +36 -0
  806. synapse/storage/schema/main/delta/63/03session_store.sql +42 -0
  807. synapse/storage/schema/main/delta/63/04add_presence_stream_not_offline_index.sql +37 -0
  808. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.postgres +23 -0
  809. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.sqlite +37 -0
  810. synapse/storage/schema/main/delta/65/01msc2716_insertion_event_edges.sql +38 -0
  811. synapse/storage/schema/main/delta/65/03remove_hidden_devices_from_device_inbox.sql +41 -0
  812. synapse/storage/schema/main/delta/65/04_local_group_updates.sql +37 -0
  813. synapse/storage/schema/main/delta/65/05_remove_room_stats_historical_and_user_stats_historical.sql +38 -0
  814. synapse/storage/schema/main/delta/65/06remove_deleted_devices_from_device_inbox.sql +53 -0
  815. synapse/storage/schema/main/delta/65/07_arbitrary_relations.sql +37 -0
  816. synapse/storage/schema/main/delta/65/08_device_inbox_background_updates.sql +37 -0
  817. synapse/storage/schema/main/delta/65/10_expirable_refresh_tokens.sql +47 -0
  818. synapse/storage/schema/main/delta/65/11_devices_auth_provider_session.sql +46 -0
  819. synapse/storage/schema/main/delta/67/01drop_public_room_list_stream.sql +37 -0
  820. synapse/storage/schema/main/delta/68/01event_columns.sql +45 -0
  821. synapse/storage/schema/main/delta/68/02_msc2409_add_device_id_appservice_stream_type.sql +40 -0
  822. synapse/storage/schema/main/delta/68/03_delete_account_data_for_deactivated_accounts.sql +39 -0
  823. synapse/storage/schema/main/delta/68/04_refresh_tokens_index_next_token_id.sql +47 -0
  824. synapse/storage/schema/main/delta/68/04partial_state_rooms.sql +60 -0
  825. synapse/storage/schema/main/delta/68/05_delete_non_strings_from_event_search.sql.sqlite +22 -0
  826. synapse/storage/schema/main/delta/68/05partial_state_rooms_triggers.py +80 -0
  827. synapse/storage/schema/main/delta/68/06_msc3202_add_device_list_appservice_stream_type.sql +42 -0
  828. synapse/storage/schema/main/delta/69/01as_txn_seq.py +54 -0
  829. synapse/storage/schema/main/delta/69/01device_list_oubound_by_room.sql +57 -0
  830. synapse/storage/schema/main/delta/69/02cache_invalidation_index.sql +37 -0
  831. synapse/storage/schema/main/delta/70/01clean_table_purged_rooms.sql +39 -0
  832. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.postgres +43 -0
  833. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.sqlite +47 -0
  834. synapse/storage/schema/main/delta/71/01remove_noop_background_updates.sql +80 -0
  835. synapse/storage/schema/main/delta/71/02event_push_summary_unique.sql +37 -0
  836. synapse/storage/schema/main/delta/72/01add_room_type_to_state_stats.sql +38 -0
  837. synapse/storage/schema/main/delta/72/01event_push_summary_receipt.sql +54 -0
  838. synapse/storage/schema/main/delta/72/02event_push_actions_index.sql +38 -0
  839. synapse/storage/schema/main/delta/72/03bg_populate_events_columns.py +57 -0
  840. synapse/storage/schema/main/delta/72/03drop_event_reference_hashes.sql +36 -0
  841. synapse/storage/schema/main/delta/72/03remove_groups.sql +50 -0
  842. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.postgres +17 -0
  843. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.sqlite +40 -0
  844. synapse/storage/schema/main/delta/72/05receipts_event_stream_ordering.sql +38 -0
  845. synapse/storage/schema/main/delta/72/05remove_unstable_private_read_receipts.sql +38 -0
  846. synapse/storage/schema/main/delta/72/06add_consent_ts_to_users.sql +35 -0
  847. synapse/storage/schema/main/delta/72/06thread_notifications.sql +49 -0
  848. synapse/storage/schema/main/delta/72/07force_update_current_state_events_membership.py +67 -0
  849. synapse/storage/schema/main/delta/72/07thread_receipts.sql.postgres +30 -0
  850. synapse/storage/schema/main/delta/72/07thread_receipts.sql.sqlite +70 -0
  851. synapse/storage/schema/main/delta/72/08begin_cache_invalidation_seq_at_2.sql.postgres +23 -0
  852. synapse/storage/schema/main/delta/72/08thread_receipts.sql +39 -0
  853. synapse/storage/schema/main/delta/72/09partial_indices.sql.sqlite +56 -0
  854. synapse/storage/schema/main/delta/73/01event_failed_pull_attempts.sql +48 -0
  855. synapse/storage/schema/main/delta/73/02add_pusher_enabled.sql +35 -0
  856. synapse/storage/schema/main/delta/73/02room_id_indexes_for_purging.sql +41 -0
  857. synapse/storage/schema/main/delta/73/03pusher_device_id.sql +39 -0
  858. synapse/storage/schema/main/delta/73/03users_approved_column.sql +39 -0
  859. synapse/storage/schema/main/delta/73/04partial_join_details.sql +42 -0
  860. synapse/storage/schema/main/delta/73/04pending_device_list_updates.sql +47 -0
  861. synapse/storage/schema/main/delta/73/05old_push_actions.sql.postgres +22 -0
  862. synapse/storage/schema/main/delta/73/05old_push_actions.sql.sqlite +24 -0
  863. synapse/storage/schema/main/delta/73/06thread_notifications_thread_id_idx.sql +42 -0
  864. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.postgres +23 -0
  865. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.sqlite +76 -0
  866. synapse/storage/schema/main/delta/73/09partial_joined_via_destination.sql +37 -0
  867. synapse/storage/schema/main/delta/73/09threads_table.sql +49 -0
  868. synapse/storage/schema/main/delta/73/10_update_sqlite_fts4_tokenizer.py +71 -0
  869. synapse/storage/schema/main/delta/73/10login_tokens.sql +54 -0
  870. synapse/storage/schema/main/delta/73/11event_search_room_id_n_distinct.sql.postgres +33 -0
  871. synapse/storage/schema/main/delta/73/12refactor_device_list_outbound_pokes.sql +72 -0
  872. synapse/storage/schema/main/delta/73/13add_device_lists_index.sql +39 -0
  873. synapse/storage/schema/main/delta/73/20_un_partial_stated_room_stream.sql +51 -0
  874. synapse/storage/schema/main/delta/73/21_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  875. synapse/storage/schema/main/delta/73/22_rebuild_user_dir_stats.sql +48 -0
  876. synapse/storage/schema/main/delta/73/22_un_partial_stated_event_stream.sql +53 -0
  877. synapse/storage/schema/main/delta/73/23_fix_thread_index.sql +52 -0
  878. synapse/storage/schema/main/delta/73/23_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  879. synapse/storage/schema/main/delta/73/24_events_jump_to_date_index.sql +36 -0
  880. synapse/storage/schema/main/delta/73/25drop_presence.sql +36 -0
  881. synapse/storage/schema/main/delta/74/01_user_directory_stale_remote_users.sql +58 -0
  882. synapse/storage/schema/main/delta/74/02_set_device_id_for_pushers_bg_update.sql +38 -0
  883. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.postgres +29 -0
  884. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.sqlite +23 -0
  885. synapse/storage/schema/main/delta/74/03_room_membership_index.sql +38 -0
  886. synapse/storage/schema/main/delta/74/04_delete_e2e_backup_keys_for_deactivated_users.sql +36 -0
  887. synapse/storage/schema/main/delta/74/04_membership_tables_event_stream_ordering_triggers.py +87 -0
  888. synapse/storage/schema/main/delta/74/05_events_txn_id_device_id.sql +72 -0
  889. synapse/storage/schema/main/delta/74/90COMMENTS_destinations.sql.postgres +52 -0
  890. synapse/storage/schema/main/delta/76/01_add_profiles_full_user_id_column.sql +39 -0
  891. synapse/storage/schema/main/delta/76/02_add_user_filters_full_user_id_column.sql +39 -0
  892. synapse/storage/schema/main/delta/76/03_per_user_experimental_features.sql +46 -0
  893. synapse/storage/schema/main/delta/76/04_add_room_forgetter.sql +43 -0
  894. synapse/storage/schema/main/delta/77/01_add_profiles_not_valid_check.sql.postgres +16 -0
  895. synapse/storage/schema/main/delta/77/02_add_user_filters_not_valid_check.sql.postgres +16 -0
  896. synapse/storage/schema/main/delta/77/03bg_populate_full_user_id_profiles.sql +35 -0
  897. synapse/storage/schema/main/delta/77/04bg_populate_full_user_id_user_filters.sql +35 -0
  898. synapse/storage/schema/main/delta/77/05thread_notifications_backfill.sql +67 -0
  899. synapse/storage/schema/main/delta/77/06thread_notifications_not_null.sql.sqlite +102 -0
  900. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions.sql.postgres +27 -0
  901. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions_staging.sql.postgres +27 -0
  902. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_summary.sql.postgres +29 -0
  903. synapse/storage/schema/main/delta/77/14bg_indices_event_stream_ordering.sql +39 -0
  904. synapse/storage/schema/main/delta/78/01_validate_and_update_profiles.py +99 -0
  905. synapse/storage/schema/main/delta/78/02_validate_and_update_user_filters.py +100 -0
  906. synapse/storage/schema/main/delta/78/03_remove_unused_indexes_user_filters.py +72 -0
  907. synapse/storage/schema/main/delta/78/03event_extremities_constraints.py +65 -0
  908. synapse/storage/schema/main/delta/78/04_add_full_user_id_index_user_filters.py +32 -0
  909. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.postgres +102 -0
  910. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.sqlite +72 -0
  911. synapse/storage/schema/main/delta/79/04_mitigate_stream_ordering_update_race.py +70 -0
  912. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.postgres +69 -0
  913. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.sqlite +65 -0
  914. synapse/storage/schema/main/delta/80/01_users_alter_locked.sql +35 -0
  915. synapse/storage/schema/main/delta/80/02_read_write_locks_unlogged.sql.postgres +30 -0
  916. synapse/storage/schema/main/delta/80/02_scheduled_tasks.sql +47 -0
  917. synapse/storage/schema/main/delta/80/03_read_write_locks_triggers.sql.postgres +37 -0
  918. synapse/storage/schema/main/delta/80/04_read_write_locks_deadlock.sql.postgres +71 -0
  919. synapse/storage/schema/main/delta/82/02_scheduled_tasks_index.sql +35 -0
  920. synapse/storage/schema/main/delta/82/04_add_indices_for_purging_rooms.sql +39 -0
  921. synapse/storage/schema/main/delta/82/05gaps.sql +44 -0
  922. synapse/storage/schema/main/delta/83/01_drop_old_tables.sql +43 -0
  923. synapse/storage/schema/main/delta/83/03_instance_name_receipts.sql.sqlite +17 -0
  924. synapse/storage/schema/main/delta/83/05_cross_signing_key_update_grant.sql +34 -0
  925. synapse/storage/schema/main/delta/83/06_event_push_summary_room.sql +36 -0
  926. synapse/storage/schema/main/delta/84/01_auth_links_stats.sql.postgres +20 -0
  927. synapse/storage/schema/main/delta/84/02_auth_links_index.sql +16 -0
  928. synapse/storage/schema/main/delta/84/03_auth_links_analyze.sql.postgres +16 -0
  929. synapse/storage/schema/main/delta/84/04_access_token_index.sql +15 -0
  930. synapse/storage/schema/main/delta/85/01_add_suspended.sql +14 -0
  931. synapse/storage/schema/main/delta/85/02_add_instance_names.sql +27 -0
  932. synapse/storage/schema/main/delta/85/03_new_sequences.sql.postgres +54 -0
  933. synapse/storage/schema/main/delta/85/04_cleanup_device_federation_outbox.sql +15 -0
  934. synapse/storage/schema/main/delta/85/05_add_instance_names_converted_pos.sql +16 -0
  935. synapse/storage/schema/main/delta/85/06_add_room_reports.sql +20 -0
  936. synapse/storage/schema/main/delta/86/01_authenticate_media.sql +15 -0
  937. synapse/storage/schema/main/delta/86/02_receipts_event_id_index.sql +15 -0
  938. synapse/storage/schema/main/delta/87/01_sliding_sync_memberships.sql +169 -0
  939. synapse/storage/schema/main/delta/87/02_per_connection_state.sql +81 -0
  940. synapse/storage/schema/main/delta/87/03_current_state_index.sql +19 -0
  941. synapse/storage/schema/main/delta/88/01_add_delayed_events.sql +43 -0
  942. synapse/storage/schema/main/delta/88/01_custom_profile_fields.sql +15 -0
  943. synapse/storage/schema/main/delta/88/02_fix_sliding_sync_membership_snapshots_forgotten_column.sql +21 -0
  944. synapse/storage/schema/main/delta/88/03_add_otk_ts_added_index.sql +18 -0
  945. synapse/storage/schema/main/delta/88/04_current_state_delta_index.sql +18 -0
  946. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.postgres +19 -0
  947. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.sqlite +19 -0
  948. synapse/storage/schema/main/delta/88/05_sliding_sync_room_config_index.sql +20 -0
  949. synapse/storage/schema/main/delta/88/06_events_received_ts_index.sql +17 -0
  950. synapse/storage/schema/main/delta/89/01_sliding_sync_membership_snapshot_index.sql +15 -0
  951. synapse/storage/schema/main/delta/90/01_add_column_participant_room_memberships_table.sql +16 -0
  952. synapse/storage/schema/main/delta/91/01_media_hash.sql +28 -0
  953. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.postgres +16 -0
  954. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.sqlite +16 -0
  955. synapse/storage/schema/main/delta/92/02_remove_populate_participant_bg_update.sql +17 -0
  956. synapse/storage/schema/main/delta/92/04_ss_membership_snapshot_idx.sql +16 -0
  957. synapse/storage/schema/main/delta/92/04_thread_subscriptions.sql +59 -0
  958. synapse/storage/schema/main/delta/92/04_thread_subscriptions_seq.sql.postgres +19 -0
  959. synapse/storage/schema/main/delta/92/05_fixup_max_depth_cap.sql +17 -0
  960. synapse/storage/schema/main/delta/92/05_thread_subscriptions_comments.sql.postgres +18 -0
  961. synapse/storage/schema/main/delta/92/06_device_federation_inbox_index.sql +16 -0
  962. synapse/storage/schema/main/delta/92/06_threads_last_sent_stream_ordering_comments.sql.postgres +24 -0
  963. synapse/storage/schema/main/delta/92/07_add_user_reports.sql +22 -0
  964. synapse/storage/schema/main/delta/92/07_event_txn_id_device_id_txn_id2.sql +15 -0
  965. synapse/storage/schema/main/delta/92/08_room_ban_redactions.sql +21 -0
  966. synapse/storage/schema/main/delta/92/08_thread_subscriptions_seq_fixup.sql.postgres +19 -0
  967. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql +20 -0
  968. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql.postgres +18 -0
  969. synapse/storage/schema/main/full_schemas/72/full.sql.postgres +1344 -0
  970. synapse/storage/schema/main/full_schemas/72/full.sql.sqlite +646 -0
  971. synapse/storage/schema/state/delta/23/drop_state_index.sql +35 -0
  972. synapse/storage/schema/state/delta/32/remove_state_indices.sql +38 -0
  973. synapse/storage/schema/state/delta/35/add_state_index.sql +36 -0
  974. synapse/storage/schema/state/delta/35/state.sql +41 -0
  975. synapse/storage/schema/state/delta/35/state_dedupe.sql +36 -0
  976. synapse/storage/schema/state/delta/47/state_group_seq.py +38 -0
  977. synapse/storage/schema/state/delta/56/state_group_room_idx.sql +36 -0
  978. synapse/storage/schema/state/delta/61/02state_groups_state_n_distinct.sql.postgres +34 -0
  979. synapse/storage/schema/state/delta/70/08_state_group_edges_unique.sql +36 -0
  980. synapse/storage/schema/state/delta/89/01_state_groups_deletion.sql +39 -0
  981. synapse/storage/schema/state/delta/90/02_delete_unreferenced_state_groups.sql +16 -0
  982. synapse/storage/schema/state/delta/90/03_remove_old_deletion_bg_update.sql +15 -0
  983. synapse/storage/schema/state/full_schemas/72/full.sql.postgres +30 -0
  984. synapse/storage/schema/state/full_schemas/72/full.sql.sqlite +20 -0
  985. synapse/storage/types.py +185 -0
  986. synapse/storage/util/__init__.py +20 -0
  987. synapse/storage/util/id_generators.py +909 -0
  988. synapse/storage/util/partial_state_events_tracker.py +194 -0
  989. synapse/storage/util/sequence.py +315 -0
  990. synapse/streams/__init__.py +43 -0
  991. synapse/streams/config.py +92 -0
  992. synapse/streams/events.py +203 -0
  993. synapse/synapse_rust/__init__.pyi +3 -0
  994. synapse/synapse_rust/acl.pyi +20 -0
  995. synapse/synapse_rust/events.pyi +136 -0
  996. synapse/synapse_rust/http_client.pyi +32 -0
  997. synapse/synapse_rust/push.pyi +86 -0
  998. synapse/synapse_rust/rendezvous.pyi +30 -0
  999. synapse/synapse_rust/segmenter.pyi +1 -0
  1000. synapse/synapse_rust.abi3.so +0 -0
  1001. synapse/types/__init__.py +1600 -0
  1002. synapse/types/handlers/__init__.py +93 -0
  1003. synapse/types/handlers/policy_server.py +16 -0
  1004. synapse/types/handlers/sliding_sync.py +909 -0
  1005. synapse/types/rest/__init__.py +25 -0
  1006. synapse/types/rest/client/__init__.py +415 -0
  1007. synapse/types/state.py +635 -0
  1008. synapse/types/storage/__init__.py +66 -0
  1009. synapse/util/__init__.py +170 -0
  1010. synapse/util/async_helpers.py +1067 -0
  1011. synapse/util/batching_queue.py +202 -0
  1012. synapse/util/caches/__init__.py +300 -0
  1013. synapse/util/caches/cached_call.py +143 -0
  1014. synapse/util/caches/deferred_cache.py +530 -0
  1015. synapse/util/caches/descriptors.py +694 -0
  1016. synapse/util/caches/dictionary_cache.py +350 -0
  1017. synapse/util/caches/expiringcache.py +251 -0
  1018. synapse/util/caches/lrucache.py +977 -0
  1019. synapse/util/caches/response_cache.py +323 -0
  1020. synapse/util/caches/stream_change_cache.py +370 -0
  1021. synapse/util/caches/treecache.py +189 -0
  1022. synapse/util/caches/ttlcache.py +197 -0
  1023. synapse/util/cancellation.py +63 -0
  1024. synapse/util/check_dependencies.py +335 -0
  1025. synapse/util/clock.py +500 -0
  1026. synapse/util/constants.py +22 -0
  1027. synapse/util/daemonize.py +165 -0
  1028. synapse/util/distributor.py +159 -0
  1029. synapse/util/events.py +134 -0
  1030. synapse/util/file_consumer.py +164 -0
  1031. synapse/util/frozenutils.py +57 -0
  1032. synapse/util/gai_resolver.py +180 -0
  1033. synapse/util/hash.py +38 -0
  1034. synapse/util/httpresourcetree.py +108 -0
  1035. synapse/util/iterutils.py +189 -0
  1036. synapse/util/json.py +56 -0
  1037. synapse/util/linked_list.py +156 -0
  1038. synapse/util/logcontext.py +46 -0
  1039. synapse/util/logformatter.py +28 -0
  1040. synapse/util/macaroons.py +325 -0
  1041. synapse/util/manhole.py +191 -0
  1042. synapse/util/metrics.py +340 -0
  1043. synapse/util/module_loader.py +116 -0
  1044. synapse/util/msisdn.py +51 -0
  1045. synapse/util/patch_inline_callbacks.py +250 -0
  1046. synapse/util/pydantic_models.py +56 -0
  1047. synapse/util/ratelimitutils.py +420 -0
  1048. synapse/util/retryutils.py +339 -0
  1049. synapse/util/rlimit.py +42 -0
  1050. synapse/util/rust.py +134 -0
  1051. synapse/util/sentinel.py +21 -0
  1052. synapse/util/stringutils.py +293 -0
  1053. synapse/util/task_scheduler.py +493 -0
  1054. synapse/util/templates.py +126 -0
  1055. synapse/util/threepids.py +123 -0
  1056. synapse/util/wheel_timer.py +112 -0
  1057. synapse/visibility.py +836 -0
@@ -0,0 +1,3076 @@
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
+ import re
25
+ from typing import TYPE_CHECKING, Any, Optional, Union, cast
26
+
27
+ import attr
28
+
29
+ from synapse.api.constants import UserTypes
30
+ from synapse.api.errors import (
31
+ Codes,
32
+ NotFoundError,
33
+ StoreError,
34
+ SynapseError,
35
+ ThreepidValidationError,
36
+ )
37
+ from synapse.config.homeserver import HomeServerConfig
38
+ from synapse.metrics.background_process_metrics import wrap_as_background_process
39
+ from synapse.storage.database import (
40
+ DatabasePool,
41
+ LoggingDatabaseConnection,
42
+ LoggingTransaction,
43
+ make_in_list_sql_clause,
44
+ )
45
+ from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
46
+ from synapse.storage.databases.main.stats import StatsStore
47
+ from synapse.storage.types import Cursor
48
+ from synapse.storage.util.id_generators import IdGenerator
49
+ from synapse.storage.util.sequence import build_sequence_generator
50
+ from synapse.types import JsonDict, StrCollection, UserID, UserInfo
51
+ from synapse.util.caches.descriptors import cached
52
+ from synapse.util.iterutils import batch_iter
53
+
54
+ if TYPE_CHECKING:
55
+ from synapse.server import HomeServer
56
+
57
+ THIRTY_MINUTES_IN_MS = 30 * 60 * 1000
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ class ExternalIDReuseException(Exception):
63
+ """Exception if writing an external id for a user fails,
64
+ because this external id is given to an other user."""
65
+
66
+
67
+ class LoginTokenExpired(Exception):
68
+ """Exception if the login token sent expired"""
69
+
70
+
71
+ class LoginTokenReused(Exception):
72
+ """Exception if the login token sent was already used"""
73
+
74
+
75
+ @attr.s(frozen=True, slots=True, auto_attribs=True)
76
+ class TokenLookupResult:
77
+ """Result of looking up an access token.
78
+
79
+ Attributes:
80
+ user_id: The user that this token authenticates as
81
+ is_guest
82
+ shadow_banned
83
+ token_id: The ID of the access token looked up
84
+ device_id: The device associated with the token, if any.
85
+ valid_until_ms: The timestamp the token expires, if any.
86
+ token_owner: The "owner" of the token. This is either the same as the
87
+ user, or a server admin who is logged in as the user.
88
+ token_used: True if this token was used at least once in a request.
89
+ This field can be out of date since `get_user_by_access_token` is
90
+ cached.
91
+ """
92
+
93
+ user_id: str
94
+ token_id: int
95
+ is_guest: bool = False
96
+ shadow_banned: bool = False
97
+ device_id: Optional[str] = None
98
+ valid_until_ms: Optional[int] = None
99
+ token_owner: str = attr.ib()
100
+ token_used: bool = False
101
+
102
+ # Make the token owner default to the user ID, which is the common case.
103
+ @token_owner.default
104
+ def _default_token_owner(self) -> str:
105
+ return self.user_id
106
+
107
+
108
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
109
+ class RefreshTokenLookupResult:
110
+ """Result of looking up a refresh token."""
111
+
112
+ user_id: str
113
+ """The user this token belongs to."""
114
+
115
+ device_id: str
116
+ """The device associated with this refresh token."""
117
+
118
+ token_id: int
119
+ """The ID of this refresh token."""
120
+
121
+ next_token_id: Optional[int]
122
+ """The ID of the refresh token which replaced this one."""
123
+
124
+ has_next_refresh_token_been_refreshed: bool
125
+ """True if the next refresh token was used for another refresh."""
126
+
127
+ has_next_access_token_been_used: bool
128
+ """True if the next access token was already used at least once."""
129
+
130
+ expiry_ts: Optional[int]
131
+ """The time at which the refresh token expires and can not be used.
132
+ If None, the refresh token doesn't expire."""
133
+
134
+ ultimate_session_expiry_ts: Optional[int]
135
+ """The time at which the session comes to an end and can no longer be
136
+ refreshed.
137
+ If None, the session can be refreshed indefinitely."""
138
+
139
+
140
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
141
+ class LoginTokenLookupResult:
142
+ """Result of looking up a login token."""
143
+
144
+ user_id: str
145
+ """The user this token belongs to."""
146
+
147
+ auth_provider_id: Optional[str]
148
+ """The SSO Identity Provider that the user authenticated with, to get this token."""
149
+
150
+ auth_provider_session_id: Optional[str]
151
+ """The session ID advertised by the SSO Identity Provider."""
152
+
153
+
154
+ @attr.s(frozen=True, slots=True, auto_attribs=True)
155
+ class ThreepidResult:
156
+ medium: str
157
+ address: str
158
+ validated_at: int
159
+ added_at: int
160
+
161
+
162
+ @attr.s(frozen=True, slots=True, auto_attribs=True)
163
+ class ThreepidValidationSession:
164
+ address: str
165
+ """address of the 3pid"""
166
+ medium: str
167
+ """medium of the 3pid"""
168
+ client_secret: str
169
+ """a secret provided by the client for this validation session"""
170
+ session_id: str
171
+ """ID of the validation session"""
172
+ last_send_attempt: int
173
+ """a number serving to dedupe send attempts for this session"""
174
+ validated_at: Optional[int]
175
+ """timestamp of when this session was validated if so"""
176
+
177
+
178
+ class RegistrationWorkerStore(StatsStore, CacheInvalidationWorkerStore):
179
+ def __init__(
180
+ self,
181
+ database: DatabasePool,
182
+ db_conn: LoggingDatabaseConnection,
183
+ hs: "HomeServer",
184
+ ):
185
+ super().__init__(database, db_conn, hs)
186
+
187
+ self.config: HomeServerConfig = hs.config
188
+
189
+ # Note: we don't check this sequence for consistency as we'd have to
190
+ # call `find_max_generated_user_id_localpart` each time, which is
191
+ # expensive if there are many entries.
192
+ self._user_id_seq = build_sequence_generator(
193
+ db_conn,
194
+ database.engine,
195
+ find_max_generated_user_id_localpart,
196
+ "user_id_seq",
197
+ table=None,
198
+ id_column=None,
199
+ )
200
+
201
+ self._account_validity_enabled = (
202
+ hs.config.account_validity.account_validity_enabled
203
+ )
204
+ self._account_validity_period = None
205
+ self._account_validity_startup_job_max_delta = None
206
+ if self._account_validity_enabled:
207
+ self._account_validity_period = (
208
+ hs.config.account_validity.account_validity_period
209
+ )
210
+ self._account_validity_startup_job_max_delta = (
211
+ hs.config.account_validity.account_validity_startup_job_max_delta
212
+ )
213
+
214
+ if hs.config.worker.run_background_tasks:
215
+ self.clock.call_later(
216
+ 0.0,
217
+ self._set_expiration_date_when_missing,
218
+ )
219
+
220
+ # If support for MSC3866 is enabled and configured to require approval for new
221
+ # account, we will create new users with an 'approved' flag set to false.
222
+ self._require_approval = (
223
+ hs.config.experimental.msc3866.enabled
224
+ and hs.config.experimental.msc3866.require_approval_for_new_accounts
225
+ )
226
+
227
+ # Create a background job for culling expired 3PID validity tokens
228
+ if hs.config.worker.run_background_tasks:
229
+ self.clock.looping_call(
230
+ self.cull_expired_threepid_validation_tokens, THIRTY_MINUTES_IN_MS
231
+ )
232
+
233
+ async def register_user(
234
+ self,
235
+ user_id: str,
236
+ password_hash: Optional[str] = None,
237
+ was_guest: bool = False,
238
+ make_guest: bool = False,
239
+ appservice_id: Optional[str] = None,
240
+ create_profile_with_displayname: Optional[str] = None,
241
+ admin: bool = False,
242
+ user_type: Optional[str] = None,
243
+ shadow_banned: bool = False,
244
+ approved: bool = False,
245
+ ) -> None:
246
+ """Attempts to register an account.
247
+
248
+ Args:
249
+ user_id: The desired user ID to register.
250
+ password_hash: Optional. The password hash for this user.
251
+ was_guest: Whether this is a guest account being upgraded to a
252
+ non-guest account.
253
+ make_guest: True if the the new user should be guest, false to add a
254
+ regular user account.
255
+ appservice_id: The ID of the appservice registering the user.
256
+ create_profile_with_displayname: Optionally create a profile for
257
+ the user, setting their displayname to the given value
258
+ admin: is an admin user?
259
+ user_type: type of user. One of the values from api.constants.UserTypes,
260
+ a custom value set in the configuration file, or None for a normal
261
+ user.
262
+ shadow_banned: Whether the user is shadow-banned, i.e. they may be
263
+ told their requests succeeded but we ignore them.
264
+ approved: Whether to consider the user has already been approved by an
265
+ administrator.
266
+
267
+ Raises:
268
+ StoreError if the user_id could not be registered.
269
+ """
270
+ await self.db_pool.runInteraction(
271
+ "register_user",
272
+ self._register_user,
273
+ user_id,
274
+ password_hash,
275
+ was_guest,
276
+ make_guest,
277
+ appservice_id,
278
+ create_profile_with_displayname,
279
+ admin,
280
+ user_type,
281
+ shadow_banned,
282
+ approved,
283
+ )
284
+
285
+ def _register_user(
286
+ self,
287
+ txn: LoggingTransaction,
288
+ user_id: str,
289
+ password_hash: Optional[str],
290
+ was_guest: bool,
291
+ make_guest: bool,
292
+ appservice_id: Optional[str],
293
+ create_profile_with_displayname: Optional[str],
294
+ admin: bool,
295
+ user_type: Optional[str],
296
+ shadow_banned: bool,
297
+ approved: bool,
298
+ ) -> None:
299
+ user_id_obj = UserID.from_string(user_id)
300
+
301
+ now = int(self.clock.time())
302
+
303
+ user_approved = approved or not self._require_approval
304
+
305
+ try:
306
+ if was_guest:
307
+ # Ensure that the guest user actually exists
308
+ # ``allow_none=False`` makes this raise an exception
309
+ # if the row isn't in the database.
310
+ self.db_pool.simple_select_one_txn(
311
+ txn,
312
+ "users",
313
+ keyvalues={"name": user_id, "is_guest": 1},
314
+ retcols=("name",),
315
+ allow_none=False,
316
+ )
317
+
318
+ self.db_pool.simple_update_one_txn(
319
+ txn,
320
+ "users",
321
+ keyvalues={"name": user_id, "is_guest": 1},
322
+ updatevalues={
323
+ "password_hash": password_hash,
324
+ "upgrade_ts": now,
325
+ "is_guest": 1 if make_guest else 0,
326
+ "appservice_id": appservice_id,
327
+ "admin": 1 if admin else 0,
328
+ "user_type": user_type,
329
+ "shadow_banned": shadow_banned,
330
+ "approved": user_approved,
331
+ },
332
+ )
333
+ else:
334
+ self.db_pool.simple_insert_txn(
335
+ txn,
336
+ "users",
337
+ values={
338
+ "name": user_id,
339
+ "password_hash": password_hash,
340
+ "creation_ts": now,
341
+ "is_guest": 1 if make_guest else 0,
342
+ "appservice_id": appservice_id,
343
+ "admin": 1 if admin else 0,
344
+ "user_type": user_type,
345
+ "shadow_banned": shadow_banned,
346
+ "approved": user_approved,
347
+ },
348
+ )
349
+
350
+ except self.database_engine.module.IntegrityError:
351
+ raise StoreError(400, "User ID already taken.", errcode=Codes.USER_IN_USE)
352
+
353
+ if self._account_validity_enabled:
354
+ self.set_expiration_date_for_user_txn(txn, user_id)
355
+
356
+ if create_profile_with_displayname:
357
+ # set a default displayname serverside to avoid ugly race
358
+ # between auto-joins and clients trying to set displaynames
359
+ #
360
+ # *obviously* the 'profiles' table uses localpart for user_id
361
+ # while everything else uses the full mxid.
362
+ txn.execute(
363
+ "INSERT INTO profiles(full_user_id, user_id, displayname) VALUES (?,?,?)",
364
+ (user_id, user_id_obj.localpart, create_profile_with_displayname),
365
+ )
366
+
367
+ if self.hs.config.stats.stats_enabled:
368
+ # we create a new completed user statistics row
369
+
370
+ # we don't strictly need current_token since this user really can't
371
+ # have any state deltas before now (as it is a new user), but still,
372
+ # we include it for completeness.
373
+ current_token = self._get_max_stream_id_in_current_state_deltas_txn(txn)
374
+
375
+ self._update_stats_delta_txn(
376
+ txn, now, "user", user_id, {}, complete_with_stream_id=current_token
377
+ )
378
+
379
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
380
+
381
+ @cached()
382
+ async def get_user_by_id(self, user_id: str) -> Optional[UserInfo]:
383
+ """Returns info about the user account, if it exists."""
384
+
385
+ def get_user_by_id_txn(txn: LoggingTransaction) -> Optional[UserInfo]:
386
+ # We could technically use simple_select_one here, but it would not perform
387
+ # the COALESCEs (unless hacked into the column names), which could yield
388
+ # confusing results.
389
+ txn.execute(
390
+ """
391
+ SELECT
392
+ name, is_guest, admin, consent_version, consent_ts,
393
+ consent_server_notice_sent, appservice_id, creation_ts, user_type,
394
+ deactivated, COALESCE(shadow_banned, FALSE) AS shadow_banned,
395
+ COALESCE(approved, TRUE) AS approved,
396
+ COALESCE(locked, FALSE) AS locked,
397
+ suspended
398
+ FROM users
399
+ WHERE name = ?
400
+ """,
401
+ (user_id,),
402
+ )
403
+
404
+ row = txn.fetchone()
405
+ if not row:
406
+ return None
407
+
408
+ (
409
+ name,
410
+ is_guest,
411
+ admin,
412
+ consent_version,
413
+ consent_ts,
414
+ consent_server_notice_sent,
415
+ appservice_id,
416
+ creation_ts,
417
+ user_type,
418
+ deactivated,
419
+ shadow_banned,
420
+ approved,
421
+ locked,
422
+ suspended,
423
+ ) = row
424
+
425
+ return UserInfo(
426
+ appservice_id=appservice_id,
427
+ consent_server_notice_sent=consent_server_notice_sent,
428
+ consent_version=consent_version,
429
+ consent_ts=consent_ts,
430
+ creation_ts=creation_ts,
431
+ is_admin=bool(admin),
432
+ is_deactivated=bool(deactivated),
433
+ is_guest=bool(is_guest),
434
+ is_shadow_banned=bool(shadow_banned),
435
+ user_id=UserID.from_string(name),
436
+ user_type=user_type,
437
+ approved=bool(approved),
438
+ locked=bool(locked),
439
+ suspended=bool(suspended),
440
+ )
441
+
442
+ return await self.db_pool.runInteraction(
443
+ desc="get_user_by_id",
444
+ func=get_user_by_id_txn,
445
+ )
446
+
447
+ async def is_trial_user(self, user_id: str) -> bool:
448
+ """Checks if user is in the "trial" period, i.e. within the first
449
+ N days of registration defined by `mau_trial_days` config or the
450
+ `mau_appservice_trial_days` config.
451
+
452
+ Args:
453
+ user_id: The user to check for trial status.
454
+ """
455
+
456
+ info = await self.get_user_by_id(user_id)
457
+ if not info:
458
+ return False
459
+
460
+ now = self.clock.time_msec()
461
+ days = self.config.server.mau_appservice_trial_days.get(
462
+ info.appservice_id, self.config.server.mau_trial_days
463
+ )
464
+ trial_duration_ms = days * 24 * 60 * 60 * 1000
465
+ is_trial = (now - info.creation_ts * 1000) < trial_duration_ms
466
+ return is_trial
467
+
468
+ @cached()
469
+ async def get_user_by_access_token(self, token: str) -> Optional[TokenLookupResult]:
470
+ """Get a user from the given access token.
471
+
472
+ Args:
473
+ token: The access token of a user.
474
+ Returns:
475
+ None, if the token did not match, otherwise a `TokenLookupResult`
476
+ """
477
+ return await self.db_pool.runInteraction(
478
+ "get_user_by_access_token", self._query_for_auth, token
479
+ )
480
+
481
+ @cached()
482
+ async def get_expiration_ts_for_user(self, user_id: str) -> Optional[int]:
483
+ """Get the expiration timestamp for the account bearing a given user ID.
484
+
485
+ Args:
486
+ user_id: The ID of the user.
487
+ Returns:
488
+ None, if the account has no expiration timestamp, otherwise int
489
+ representation of the timestamp (as a number of milliseconds since epoch).
490
+ """
491
+ return await self.db_pool.simple_select_one_onecol(
492
+ table="account_validity",
493
+ keyvalues={"user_id": user_id},
494
+ retcol="expiration_ts_ms",
495
+ allow_none=True,
496
+ desc="get_expiration_ts_for_user",
497
+ )
498
+
499
+ async def is_account_expired(self, user_id: str, current_ts: int) -> bool:
500
+ """
501
+ Returns whether an user account is expired.
502
+
503
+ Args:
504
+ user_id: The user's ID
505
+ current_ts: The current timestamp
506
+
507
+ Returns:
508
+ Whether the user account has expired
509
+ """
510
+ expiration_ts = await self.get_expiration_ts_for_user(user_id)
511
+ return expiration_ts is not None and current_ts >= expiration_ts
512
+
513
+ async def set_account_validity_for_user(
514
+ self,
515
+ user_id: str,
516
+ expiration_ts: int,
517
+ email_sent: bool,
518
+ renewal_token: Optional[str] = None,
519
+ token_used_ts: Optional[int] = None,
520
+ ) -> None:
521
+ """Updates the account validity properties of the given account, with the
522
+ given values.
523
+
524
+ Args:
525
+ user_id: ID of the account to update properties for.
526
+ expiration_ts: New expiration date, as a timestamp in milliseconds
527
+ since epoch.
528
+ email_sent: True means a renewal email has been sent for this account
529
+ and there's no need to send another one for the current validity
530
+ period.
531
+ renewal_token: Renewal token the user can use to extend the validity
532
+ of their account. Defaults to no token.
533
+ token_used_ts: A timestamp of when the current token was used to renew
534
+ the account.
535
+ """
536
+
537
+ def set_account_validity_for_user_txn(txn: LoggingTransaction) -> None:
538
+ self.db_pool.simple_update_txn(
539
+ txn=txn,
540
+ table="account_validity",
541
+ keyvalues={"user_id": user_id},
542
+ updatevalues={
543
+ "expiration_ts_ms": expiration_ts,
544
+ "email_sent": email_sent,
545
+ "renewal_token": renewal_token,
546
+ "token_used_ts_ms": token_used_ts,
547
+ },
548
+ )
549
+ self._invalidate_cache_and_stream(
550
+ txn, self.get_expiration_ts_for_user, (user_id,)
551
+ )
552
+
553
+ await self.db_pool.runInteraction(
554
+ "set_account_validity_for_user", set_account_validity_for_user_txn
555
+ )
556
+
557
+ async def set_renewal_token_for_user(
558
+ self, user_id: str, renewal_token: str
559
+ ) -> None:
560
+ """Defines a renewal token for a given user, and clears the token_used timestamp.
561
+
562
+ Args:
563
+ user_id: ID of the user to set the renewal token for.
564
+ renewal_token: Random unique string that will be used to renew the
565
+ user's account.
566
+
567
+ Raises:
568
+ StoreError: The provided token is already set for another user.
569
+ """
570
+ await self.db_pool.simple_update_one(
571
+ table="account_validity",
572
+ keyvalues={"user_id": user_id},
573
+ updatevalues={"renewal_token": renewal_token, "token_used_ts_ms": None},
574
+ desc="set_renewal_token_for_user",
575
+ )
576
+
577
+ async def get_user_from_renewal_token(
578
+ self, renewal_token: str
579
+ ) -> tuple[str, int, Optional[int]]:
580
+ """Get a user ID and renewal status from a renewal token.
581
+
582
+ Args:
583
+ renewal_token: The renewal token to perform the lookup with.
584
+
585
+ Returns:
586
+ A tuple of containing the following values:
587
+ * The ID of a user to which the token belongs.
588
+ * An int representing the user's expiry timestamp as milliseconds since the
589
+ epoch, or 0 if the token was invalid.
590
+ * An optional int representing the timestamp of when the user renewed their
591
+ account timestamp as milliseconds since the epoch. None if the account
592
+ has not been renewed using the current token yet.
593
+ """
594
+ return cast(
595
+ tuple[str, int, Optional[int]],
596
+ await self.db_pool.simple_select_one(
597
+ table="account_validity",
598
+ keyvalues={"renewal_token": renewal_token},
599
+ retcols=["user_id", "expiration_ts_ms", "token_used_ts_ms"],
600
+ desc="get_user_from_renewal_token",
601
+ ),
602
+ )
603
+
604
+ async def get_renewal_token_for_user(self, user_id: str) -> str:
605
+ """Get the renewal token associated with a given user ID.
606
+
607
+ Args:
608
+ user_id: The user ID to lookup a token for.
609
+
610
+ Returns:
611
+ The renewal token associated with this user ID.
612
+ """
613
+ return await self.db_pool.simple_select_one_onecol(
614
+ table="account_validity",
615
+ keyvalues={"user_id": user_id},
616
+ retcol="renewal_token",
617
+ desc="get_renewal_token_for_user",
618
+ )
619
+
620
+ async def get_users_expiring_soon(self) -> list[tuple[str, int]]:
621
+ """Selects users whose account will expire in the [now, now + renew_at] time
622
+ window (see configuration for account_validity for information on what renew_at
623
+ refers to).
624
+
625
+ Returns:
626
+ A list of tuples, each with a user ID and expiration time (in milliseconds).
627
+ """
628
+
629
+ def select_users_txn(
630
+ txn: LoggingTransaction, now_ms: int, renew_at: int
631
+ ) -> list[tuple[str, int]]:
632
+ sql = (
633
+ "SELECT user_id, expiration_ts_ms FROM account_validity"
634
+ " WHERE email_sent = FALSE AND (expiration_ts_ms - ?) <= ?"
635
+ )
636
+ values = [now_ms, renew_at]
637
+ txn.execute(sql, values)
638
+ return cast(list[tuple[str, int]], txn.fetchall())
639
+
640
+ return await self.db_pool.runInteraction(
641
+ "get_users_expiring_soon",
642
+ select_users_txn,
643
+ self.clock.time_msec(),
644
+ self.config.account_validity.account_validity_renew_at,
645
+ )
646
+
647
+ async def set_renewal_mail_status(self, user_id: str, email_sent: bool) -> None:
648
+ """Sets or unsets the flag that indicates whether a renewal email has been sent
649
+ to the user (and the user hasn't renewed their account yet).
650
+
651
+ Args:
652
+ user_id: ID of the user to set/unset the flag for.
653
+ email_sent: Flag which indicates whether a renewal email has been sent
654
+ to this user.
655
+ """
656
+ await self.db_pool.simple_update_one(
657
+ table="account_validity",
658
+ keyvalues={"user_id": user_id},
659
+ updatevalues={"email_sent": email_sent},
660
+ desc="set_renewal_mail_status",
661
+ )
662
+
663
+ async def delete_account_validity_for_user(self, user_id: str) -> None:
664
+ """Deletes the entry for the given user in the account validity table, removing
665
+ their expiration date and renewal token.
666
+
667
+ Args:
668
+ user_id: ID of the user to remove from the account validity table.
669
+ """
670
+ await self.db_pool.simple_delete_one(
671
+ table="account_validity",
672
+ keyvalues={"user_id": user_id},
673
+ desc="delete_account_validity_for_user",
674
+ )
675
+
676
+ @cached(max_entries=100000)
677
+ async def is_server_admin(self, user: str) -> bool:
678
+ """Determines if a user is an admin of this homeserver.
679
+
680
+ Args:
681
+ user: user ID of the user to test
682
+
683
+ Returns:
684
+ true iff the user is a server admin, false otherwise.
685
+ """
686
+ res = await self.db_pool.simple_select_one_onecol(
687
+ table="users",
688
+ keyvalues={"name": user},
689
+ retcol="admin",
690
+ allow_none=True,
691
+ desc="is_server_admin",
692
+ )
693
+
694
+ return bool(res) if res else False
695
+
696
+ async def set_server_admin(self, user: UserID, admin: bool) -> None:
697
+ """Sets whether a user is an admin of this homeserver.
698
+
699
+ Args:
700
+ user: user ID of the user to test
701
+ admin: true iff the user is to be a server admin, false otherwise.
702
+ """
703
+
704
+ def set_server_admin_txn(txn: LoggingTransaction) -> None:
705
+ self.db_pool.simple_update_one_txn(
706
+ txn, "users", {"name": user.to_string()}, {"admin": 1 if admin else 0}
707
+ )
708
+ self._invalidate_cache_and_stream(
709
+ txn, self.get_user_by_id, (user.to_string(),)
710
+ )
711
+ self._invalidate_cache_and_stream(
712
+ txn, self.is_server_admin, (user.to_string(),)
713
+ )
714
+
715
+ await self.db_pool.runInteraction("set_server_admin", set_server_admin_txn)
716
+
717
+ async def set_shadow_banned(self, user: UserID, shadow_banned: bool) -> None:
718
+ """Sets whether a user shadow-banned.
719
+
720
+ Args:
721
+ user: user ID of the user to test
722
+ shadow_banned: true iff the user is to be shadow-banned, false otherwise.
723
+ """
724
+
725
+ def set_shadow_banned_txn(txn: LoggingTransaction) -> None:
726
+ user_id = user.to_string()
727
+ self.db_pool.simple_update_one_txn(
728
+ txn,
729
+ table="users",
730
+ keyvalues={"name": user_id},
731
+ updatevalues={"shadow_banned": shadow_banned},
732
+ )
733
+ # In order for this to apply immediately, clear the cache for this user.
734
+ tokens = self.db_pool.simple_select_list_txn(
735
+ txn,
736
+ table="access_tokens",
737
+ keyvalues={"user_id": user_id},
738
+ retcols=("token",),
739
+ )
740
+ self._invalidate_cache_and_stream_bulk(
741
+ txn, self.get_user_by_access_token, tokens
742
+ )
743
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
744
+
745
+ await self.db_pool.runInteraction("set_shadow_banned", set_shadow_banned_txn)
746
+
747
+ async def set_user_type(
748
+ self, user: UserID, user_type: Optional[Union[UserTypes, str]]
749
+ ) -> None:
750
+ """Sets the user type.
751
+
752
+ Args:
753
+ user: user ID of the user.
754
+ user_type: type of the user or None for a user without a type.
755
+ """
756
+
757
+ def set_user_type_txn(txn: LoggingTransaction) -> None:
758
+ self.db_pool.simple_update_one_txn(
759
+ txn, "users", {"name": user.to_string()}, {"user_type": user_type}
760
+ )
761
+ self._invalidate_cache_and_stream(
762
+ txn, self.get_user_by_id, (user.to_string(),)
763
+ )
764
+
765
+ await self.db_pool.runInteraction("set_user_type", set_user_type_txn)
766
+
767
+ def _query_for_auth(
768
+ self, txn: LoggingTransaction, token: str
769
+ ) -> Optional[TokenLookupResult]:
770
+ sql = """
771
+ SELECT users.name as user_id,
772
+ users.is_guest,
773
+ users.shadow_banned,
774
+ access_tokens.id as token_id,
775
+ access_tokens.device_id,
776
+ access_tokens.valid_until_ms,
777
+ access_tokens.user_id as token_owner,
778
+ access_tokens.used as token_used
779
+ FROM users
780
+ INNER JOIN access_tokens on users.name = COALESCE(puppets_user_id, access_tokens.user_id)
781
+ WHERE token = ?
782
+ """
783
+
784
+ txn.execute(sql, (token,))
785
+ row = txn.fetchone()
786
+
787
+ if row:
788
+ (
789
+ user_id,
790
+ is_guest,
791
+ shadow_banned,
792
+ token_id,
793
+ device_id,
794
+ valid_until_ms,
795
+ token_owner,
796
+ token_used,
797
+ ) = row
798
+
799
+ return TokenLookupResult(
800
+ user_id=user_id,
801
+ is_guest=is_guest,
802
+ shadow_banned=shadow_banned,
803
+ token_id=token_id,
804
+ device_id=device_id,
805
+ valid_until_ms=valid_until_ms,
806
+ token_owner=token_owner,
807
+ # This field is nullable, ensure it comes out as a boolean
808
+ token_used=bool(token_used),
809
+ )
810
+
811
+ return None
812
+
813
+ @cached()
814
+ async def is_real_user(self, user_id: str) -> bool:
815
+ """Determines if the user is a real user, ie does not have a 'user_type'.
816
+
817
+ Args:
818
+ user_id: user id to test
819
+
820
+ Returns:
821
+ True if user 'user_type' is null or empty string
822
+ """
823
+ return await self.db_pool.runInteraction(
824
+ "is_real_user", self.is_real_user_txn, user_id
825
+ )
826
+
827
+ @cached()
828
+ async def is_support_user(self, user_id: str) -> bool:
829
+ """Determines if the user is of type UserTypes.SUPPORT
830
+
831
+ Args:
832
+ user_id: user id to test
833
+
834
+ Returns:
835
+ True if user is of type UserTypes.SUPPORT
836
+ """
837
+ return await self.db_pool.runInteraction(
838
+ "is_support_user", self.is_support_user_txn, user_id
839
+ )
840
+
841
+ def is_real_user_txn(self, txn: LoggingTransaction, user_id: str) -> bool:
842
+ res = self.db_pool.simple_select_one_onecol_txn(
843
+ txn=txn,
844
+ table="users",
845
+ keyvalues={"name": user_id},
846
+ retcol="user_type",
847
+ allow_none=True,
848
+ )
849
+ return res is None or res not in [UserTypes.BOT, UserTypes.SUPPORT]
850
+
851
+ def is_support_user_txn(self, txn: LoggingTransaction, user_id: str) -> bool:
852
+ res = self.db_pool.simple_select_one_onecol_txn(
853
+ txn=txn,
854
+ table="users",
855
+ keyvalues={"name": user_id},
856
+ retcol="user_type",
857
+ allow_none=True,
858
+ )
859
+ return True if res == UserTypes.SUPPORT else False
860
+
861
+ async def get_users_by_id_case_insensitive(self, user_id: str) -> dict[str, str]:
862
+ """Gets users that match user_id case insensitively.
863
+
864
+ Returns:
865
+ A mapping of user_id -> password_hash.
866
+ """
867
+
868
+ def f(txn: LoggingTransaction) -> dict[str, str]:
869
+ sql = "SELECT name, password_hash FROM users WHERE lower(name) = lower(?)"
870
+ txn.execute(sql, (user_id,))
871
+ result = cast(list[tuple[str, str]], txn.fetchall())
872
+ return dict(result)
873
+
874
+ return await self.db_pool.runInteraction("get_users_by_id_case_insensitive", f)
875
+
876
+ async def record_user_external_id(
877
+ self, auth_provider: str, external_id: str, user_id: str
878
+ ) -> None:
879
+ """Record a mapping from an external user id to a mxid
880
+
881
+ See notes in _record_user_external_id_txn about what constitutes valid data.
882
+
883
+ Args:
884
+ auth_provider: identifier for the remote auth provider
885
+ external_id: id on that system
886
+ user_id: complete mxid that it is mapped to
887
+
888
+ Raises:
889
+ ExternalIDReuseException if the new external_id could not be mapped.
890
+ """
891
+
892
+ try:
893
+ await self.db_pool.runInteraction(
894
+ "record_user_external_id",
895
+ self._record_user_external_id_txn,
896
+ auth_provider,
897
+ external_id,
898
+ user_id,
899
+ )
900
+ except self.database_engine.module.IntegrityError:
901
+ raise ExternalIDReuseException()
902
+
903
+ def _record_user_external_id_txn(
904
+ self,
905
+ txn: LoggingTransaction,
906
+ auth_provider: str,
907
+ external_id: str,
908
+ user_id: str,
909
+ ) -> None:
910
+ """
911
+ Record a mapping from an external user id to a mxid.
912
+
913
+ Note that the auth provider IDs (and the external IDs) are not validated
914
+ against configured IdPs as Synapse does not know its relationship to
915
+ external systems. For example, it might be useful to pre-configure users
916
+ before enabling a new IdP or an IdP might be temporarily offline, but
917
+ still valid.
918
+
919
+ Args:
920
+ txn: The database transaction.
921
+ auth_provider: identifier for the remote auth provider
922
+ external_id: id on that system
923
+ user_id: complete mxid that it is mapped to
924
+ """
925
+ self._invalidate_cache_and_stream(
926
+ txn, self.get_user_by_external_id, (auth_provider, external_id)
927
+ )
928
+
929
+ # This INSERT ... ON CONFLICT DO NOTHING statement will cause a
930
+ # 'could not serialize access due to concurrent update'
931
+ # if the row is added concurrently by another transaction.
932
+ # This is exactly what we want, as it makes the transaction get retried
933
+ # in a new snapshot where we can check for a genuine conflict.
934
+ was_inserted = self.db_pool.simple_upsert_txn(
935
+ txn,
936
+ table="user_external_ids",
937
+ keyvalues={"auth_provider": auth_provider, "external_id": external_id},
938
+ values={},
939
+ insertion_values={"user_id": user_id},
940
+ )
941
+
942
+ if not was_inserted:
943
+ existing_id = self.db_pool.simple_select_one_onecol_txn(
944
+ txn,
945
+ table="user_external_ids",
946
+ keyvalues={"auth_provider": auth_provider, "user_id": user_id},
947
+ retcol="external_id",
948
+ allow_none=True,
949
+ )
950
+
951
+ if existing_id != external_id:
952
+ raise ExternalIDReuseException(
953
+ f"{user_id!r} has external id {existing_id!r} for {auth_provider} but trying to add {external_id!r}"
954
+ )
955
+
956
+ async def remove_user_external_id(
957
+ self, auth_provider: str, external_id: str, user_id: str
958
+ ) -> None:
959
+ """Remove a mapping from an external user id to a mxid
960
+ If the mapping is not found, this method does nothing.
961
+ Args:
962
+ auth_provider: identifier for the remote auth provider
963
+ external_id: id on that system
964
+ user_id: complete mxid that it is mapped to
965
+ """
966
+ await self.db_pool.simple_delete(
967
+ table="user_external_ids",
968
+ keyvalues={
969
+ "auth_provider": auth_provider,
970
+ "external_id": external_id,
971
+ "user_id": user_id,
972
+ },
973
+ desc="remove_user_external_id",
974
+ )
975
+ await self.invalidate_cache_and_stream(
976
+ "get_user_by_external_id", (auth_provider, external_id)
977
+ )
978
+
979
+ async def replace_user_external_id(
980
+ self,
981
+ record_external_ids: list[tuple[str, str]],
982
+ user_id: str,
983
+ ) -> None:
984
+ """Replace mappings from external user ids to a mxid in a single transaction.
985
+ All mappings are deleted and the new ones are created.
986
+
987
+ See notes in _record_user_external_id_txn about what constitutes valid data.
988
+
989
+ Args:
990
+ record_external_ids:
991
+ List with tuple of auth_provider and external_id to record
992
+ user_id: complete mxid that it is mapped to
993
+
994
+ Raises:
995
+ ExternalIDReuseException if the new external_id could not be mapped.
996
+ """
997
+
998
+ def _replace_user_external_id_txn(
999
+ txn: LoggingTransaction,
1000
+ ) -> None:
1001
+ self.db_pool.simple_delete_txn(
1002
+ txn,
1003
+ table="user_external_ids",
1004
+ keyvalues={"user_id": user_id},
1005
+ )
1006
+
1007
+ for auth_provider, external_id in record_external_ids:
1008
+ self._invalidate_cache_and_stream(
1009
+ txn, self.get_user_by_external_id, (auth_provider, external_id)
1010
+ )
1011
+
1012
+ self._record_user_external_id_txn(
1013
+ txn,
1014
+ auth_provider,
1015
+ external_id,
1016
+ user_id,
1017
+ )
1018
+
1019
+ try:
1020
+ await self.db_pool.runInteraction(
1021
+ "replace_user_external_id",
1022
+ _replace_user_external_id_txn,
1023
+ )
1024
+ except self.database_engine.module.IntegrityError:
1025
+ raise ExternalIDReuseException()
1026
+
1027
+ @cached()
1028
+ async def get_user_by_external_id(
1029
+ self, auth_provider: str, external_id: str
1030
+ ) -> Optional[str]:
1031
+ """Look up a user by their external auth id
1032
+
1033
+ Args:
1034
+ auth_provider: identifier for the remote auth provider
1035
+ external_id: id on that system
1036
+
1037
+ Returns:
1038
+ the mxid of the user, or None if they are not known
1039
+ """
1040
+ return await self.db_pool.simple_select_one_onecol(
1041
+ table="user_external_ids",
1042
+ keyvalues={"auth_provider": auth_provider, "external_id": external_id},
1043
+ retcol="user_id",
1044
+ allow_none=True,
1045
+ desc="get_user_by_external_id",
1046
+ )
1047
+
1048
+ async def get_external_ids_by_user(self, mxid: str) -> list[tuple[str, str]]:
1049
+ """Look up external ids for the given user
1050
+
1051
+ Args:
1052
+ mxid: the MXID to be looked up
1053
+
1054
+ Returns:
1055
+ Tuples of (auth_provider, external_id)
1056
+ """
1057
+ return cast(
1058
+ list[tuple[str, str]],
1059
+ await self.db_pool.simple_select_list(
1060
+ table="user_external_ids",
1061
+ keyvalues={"user_id": mxid},
1062
+ retcols=("auth_provider", "external_id"),
1063
+ desc="get_external_ids_by_user",
1064
+ ),
1065
+ )
1066
+
1067
+ async def count_all_users(self) -> int:
1068
+ """Counts all users registered on the homeserver."""
1069
+
1070
+ def _count_users(txn: LoggingTransaction) -> int:
1071
+ txn.execute("SELECT COUNT(*) FROM users")
1072
+ row = txn.fetchone()
1073
+ assert row is not None
1074
+ return row[0]
1075
+
1076
+ return await self.db_pool.runInteraction("count_users", _count_users)
1077
+
1078
+ async def count_daily_user_type(self) -> dict[str, int]:
1079
+ """
1080
+ Counts 1) native non guest users
1081
+ 2) native guests users
1082
+ 3) bridged users
1083
+ who registered on the homeserver in the past 24 hours
1084
+ """
1085
+
1086
+ def _count_daily_user_type(txn: LoggingTransaction) -> dict[str, int]:
1087
+ yesterday = int(self.clock.time()) - (60 * 60 * 24)
1088
+
1089
+ sql = """
1090
+ SELECT user_type, COUNT(*) AS count FROM (
1091
+ SELECT
1092
+ CASE
1093
+ WHEN is_guest=0 AND appservice_id IS NULL THEN 'native'
1094
+ WHEN is_guest=1 AND appservice_id IS NULL THEN 'guest'
1095
+ WHEN is_guest=0 AND appservice_id IS NOT NULL THEN 'bridged'
1096
+ END AS user_type
1097
+ FROM users
1098
+ WHERE creation_ts > ?
1099
+ ) AS t GROUP BY user_type
1100
+ """
1101
+ results = {"native": 0, "guest": 0, "bridged": 0}
1102
+ txn.execute(sql, (yesterday,))
1103
+ for row in txn:
1104
+ results[row[0]] = row[1]
1105
+ return results
1106
+
1107
+ return await self.db_pool.runInteraction(
1108
+ "count_daily_user_type", _count_daily_user_type
1109
+ )
1110
+
1111
+ async def count_nonbridged_users(self) -> int:
1112
+ def _count_users(txn: LoggingTransaction) -> int:
1113
+ txn.execute(
1114
+ """
1115
+ SELECT COUNT(*) FROM users
1116
+ WHERE appservice_id IS NULL
1117
+ """
1118
+ )
1119
+ (count,) = cast(tuple[int], txn.fetchone())
1120
+ return count
1121
+
1122
+ return await self.db_pool.runInteraction("count_users", _count_users)
1123
+
1124
+ async def count_real_users(self) -> int:
1125
+ """Counts all users without the bot or support user_types registered on the homeserver."""
1126
+
1127
+ def _count_users(txn: LoggingTransaction) -> int:
1128
+ txn.execute(
1129
+ f"SELECT COUNT(*) FROM users WHERE user_type IS NULL OR user_type NOT IN ('{UserTypes.BOT}', '{UserTypes.SUPPORT}')"
1130
+ )
1131
+ row = txn.fetchone()
1132
+ assert row is not None
1133
+ return row[0]
1134
+
1135
+ return await self.db_pool.runInteraction("count_real_users", _count_users)
1136
+
1137
+ async def generate_user_id(self) -> str:
1138
+ """Generate a suitable localpart for a guest user
1139
+
1140
+ Returns: a (hopefully) free localpart
1141
+ """
1142
+ next_id = await self.db_pool.runInteraction(
1143
+ "generate_user_id", self._user_id_seq.get_next_id_txn
1144
+ )
1145
+
1146
+ return str(next_id)
1147
+
1148
+ async def get_user_id_by_threepid(self, medium: str, address: str) -> Optional[str]:
1149
+ """Returns user id from threepid
1150
+
1151
+ Args:
1152
+ medium: threepid medium e.g. email
1153
+ address: threepid address e.g. me@example.com. This must already be
1154
+ in canonical form.
1155
+
1156
+ Returns:
1157
+ The user ID or None if no user id/threepid mapping exists
1158
+ """
1159
+ user_id = await self.db_pool.runInteraction(
1160
+ "get_user_id_by_threepid", self.get_user_id_by_threepid_txn, medium, address
1161
+ )
1162
+ return user_id
1163
+
1164
+ def get_user_id_by_threepid_txn(
1165
+ self, txn: LoggingTransaction, medium: str, address: str
1166
+ ) -> Optional[str]:
1167
+ """Returns user id from threepid
1168
+
1169
+ Args:
1170
+ txn:
1171
+ medium: threepid medium e.g. email
1172
+ address: threepid address e.g. me@example.com
1173
+
1174
+ Returns:
1175
+ user id, or None if no user id/threepid mapping exists
1176
+ """
1177
+ return self.db_pool.simple_select_one_onecol_txn(
1178
+ txn,
1179
+ "user_threepids",
1180
+ {"medium": medium, "address": address},
1181
+ "user_id",
1182
+ True,
1183
+ )
1184
+
1185
+ async def user_add_threepid(
1186
+ self,
1187
+ user_id: str,
1188
+ medium: str,
1189
+ address: str,
1190
+ validated_at: int,
1191
+ added_at: int,
1192
+ ) -> None:
1193
+ await self.db_pool.simple_upsert(
1194
+ "user_threepids",
1195
+ {"medium": medium, "address": address},
1196
+ {"user_id": user_id, "validated_at": validated_at, "added_at": added_at},
1197
+ )
1198
+
1199
+ async def user_get_threepids(self, user_id: str) -> list[ThreepidResult]:
1200
+ results = cast(
1201
+ list[tuple[str, str, int, int]],
1202
+ await self.db_pool.simple_select_list(
1203
+ "user_threepids",
1204
+ keyvalues={"user_id": user_id},
1205
+ retcols=["medium", "address", "validated_at", "added_at"],
1206
+ desc="user_get_threepids",
1207
+ ),
1208
+ )
1209
+ return [
1210
+ ThreepidResult(
1211
+ medium=r[0],
1212
+ address=r[1],
1213
+ validated_at=r[2],
1214
+ added_at=r[3],
1215
+ )
1216
+ for r in results
1217
+ ]
1218
+
1219
+ async def user_delete_threepid(
1220
+ self, user_id: str, medium: str, address: str
1221
+ ) -> None:
1222
+ await self.db_pool.simple_delete(
1223
+ "user_threepids",
1224
+ keyvalues={"user_id": user_id, "medium": medium, "address": address},
1225
+ desc="user_delete_threepid",
1226
+ )
1227
+
1228
+ async def add_user_bound_threepid(
1229
+ self, user_id: str, medium: str, address: str, id_server: str
1230
+ ) -> None:
1231
+ """The server proxied a bind request to the given identity server on
1232
+ behalf of the given user. We need to remember this in case the user
1233
+ asks us to unbind the threepid.
1234
+
1235
+ Args:
1236
+ user_id
1237
+ medium
1238
+ address
1239
+ id_server
1240
+ """
1241
+ # We need to use an upsert, in case they user had already bound the
1242
+ # threepid
1243
+ await self.db_pool.simple_upsert(
1244
+ table="user_threepid_id_server",
1245
+ keyvalues={
1246
+ "user_id": user_id,
1247
+ "medium": medium,
1248
+ "address": address,
1249
+ "id_server": id_server,
1250
+ },
1251
+ values={},
1252
+ insertion_values={},
1253
+ desc="add_user_bound_threepid",
1254
+ )
1255
+
1256
+ async def user_get_bound_threepids(self, user_id: str) -> list[tuple[str, str]]:
1257
+ """Get the threepids that a user has bound to an identity server through the homeserver
1258
+ The homeserver remembers where binds to an identity server occurred. Using this
1259
+ method can retrieve those threepids.
1260
+
1261
+ Args:
1262
+ user_id: The ID of the user to retrieve threepids for
1263
+
1264
+ Returns:
1265
+ List of tuples of two strings:
1266
+ medium: The medium of the threepid (e.g "email")
1267
+ address: The address of the threepid (e.g "bob@example.com")
1268
+ """
1269
+ return cast(
1270
+ list[tuple[str, str]],
1271
+ await self.db_pool.simple_select_list(
1272
+ table="user_threepid_id_server",
1273
+ keyvalues={"user_id": user_id},
1274
+ retcols=["medium", "address"],
1275
+ desc="user_get_bound_threepids",
1276
+ ),
1277
+ )
1278
+
1279
+ async def remove_user_bound_threepid(
1280
+ self, user_id: str, medium: str, address: str, id_server: str
1281
+ ) -> None:
1282
+ """The server proxied an unbind request to the given identity server on
1283
+ behalf of the given user, so we remove the mapping of threepid to
1284
+ identity server.
1285
+
1286
+ Args:
1287
+ user_id
1288
+ medium
1289
+ address
1290
+ id_server
1291
+ """
1292
+ await self.db_pool.simple_delete(
1293
+ table="user_threepid_id_server",
1294
+ keyvalues={
1295
+ "user_id": user_id,
1296
+ "medium": medium,
1297
+ "address": address,
1298
+ "id_server": id_server,
1299
+ },
1300
+ desc="remove_user_bound_threepid",
1301
+ )
1302
+
1303
+ async def get_id_servers_user_bound(
1304
+ self, user_id: str, medium: str, address: str
1305
+ ) -> list[str]:
1306
+ """Get the list of identity servers that the server proxied bind
1307
+ requests to for given user and threepid
1308
+
1309
+ Args:
1310
+ user_id: The user to query for identity servers.
1311
+ medium: The medium to query for identity servers.
1312
+ address: The address to query for identity servers.
1313
+
1314
+ Returns:
1315
+ A list of identity servers
1316
+ """
1317
+ return await self.db_pool.simple_select_onecol(
1318
+ table="user_threepid_id_server",
1319
+ keyvalues={"user_id": user_id, "medium": medium, "address": address},
1320
+ retcol="id_server",
1321
+ desc="get_id_servers_user_bound",
1322
+ )
1323
+
1324
+ @cached()
1325
+ async def get_user_deactivated_status(self, user_id: str) -> bool:
1326
+ """Retrieve the value for the `deactivated` property for the provided user.
1327
+
1328
+ Args:
1329
+ user_id: The ID of the user to retrieve the status for.
1330
+
1331
+ Returns:
1332
+ True if the user was deactivated, false if the user is still active.
1333
+ """
1334
+
1335
+ res = await self.db_pool.simple_select_one_onecol(
1336
+ table="users",
1337
+ keyvalues={"name": user_id},
1338
+ retcol="deactivated",
1339
+ desc="get_user_deactivated_status",
1340
+ )
1341
+
1342
+ # Convert the integer into a boolean.
1343
+ return res == 1
1344
+
1345
+ @cached()
1346
+ async def get_user_locked_status(self, user_id: str) -> bool:
1347
+ """Retrieve the value for the `locked` property for the provided user.
1348
+
1349
+ Args:
1350
+ user_id: The ID of the user to retrieve the status for.
1351
+
1352
+ Returns:
1353
+ True if the user was locked, false if the user is still active.
1354
+ """
1355
+
1356
+ res = await self.db_pool.simple_select_one_onecol(
1357
+ table="users",
1358
+ keyvalues={"name": user_id},
1359
+ retcol="locked",
1360
+ desc="get_user_locked_status",
1361
+ )
1362
+
1363
+ # Convert the potential integer into a boolean.
1364
+ return bool(res)
1365
+
1366
+ @cached()
1367
+ async def get_user_suspended_status(self, user_id: str) -> bool:
1368
+ """
1369
+ Determine whether the user's account is suspended.
1370
+ Args:
1371
+ user_id: The user ID of the user in question
1372
+ Returns:
1373
+ True if the user's account is suspended, false if it is not suspended or
1374
+ if the user ID cannot be found.
1375
+ """
1376
+
1377
+ res = await self.db_pool.simple_select_one_onecol(
1378
+ table="users",
1379
+ keyvalues={"name": user_id},
1380
+ retcol="suspended",
1381
+ allow_none=True,
1382
+ desc="get_user_suspended",
1383
+ )
1384
+
1385
+ return bool(res)
1386
+
1387
+ async def get_threepid_validation_session(
1388
+ self,
1389
+ medium: Optional[str],
1390
+ client_secret: str,
1391
+ address: Optional[str] = None,
1392
+ sid: Optional[str] = None,
1393
+ validated: Optional[bool] = True,
1394
+ ) -> Optional[ThreepidValidationSession]:
1395
+ """Gets a session_id and last_send_attempt (if available) for a
1396
+ combination of validation metadata
1397
+
1398
+ Args:
1399
+ medium: The medium of the 3PID
1400
+ client_secret: A unique string provided by the client to help identify this
1401
+ validation attempt
1402
+ address: The address of the 3PID
1403
+ sid: The ID of the validation session
1404
+ validated: Whether sessions should be filtered by
1405
+ whether they have been validated already or not. None to
1406
+ perform no filtering
1407
+
1408
+ Returns:
1409
+ A ThreepidValidationSession or None if a validation session is not found
1410
+ """
1411
+ if not client_secret:
1412
+ raise SynapseError(
1413
+ 400, "Missing parameter: client_secret", errcode=Codes.MISSING_PARAM
1414
+ )
1415
+
1416
+ keyvalues = {"client_secret": client_secret}
1417
+ if medium:
1418
+ keyvalues["medium"] = medium
1419
+ if address:
1420
+ keyvalues["address"] = address
1421
+ if sid:
1422
+ keyvalues["session_id"] = sid
1423
+
1424
+ assert address or sid
1425
+
1426
+ def get_threepid_validation_session_txn(
1427
+ txn: LoggingTransaction,
1428
+ ) -> Optional[ThreepidValidationSession]:
1429
+ sql = """
1430
+ SELECT address, session_id, medium, client_secret,
1431
+ last_send_attempt, validated_at
1432
+ FROM threepid_validation_session WHERE %s
1433
+ """ % (" AND ".join("%s = ?" % k for k in keyvalues.keys()),)
1434
+
1435
+ if validated is not None:
1436
+ sql += " AND validated_at IS " + ("NOT NULL" if validated else "NULL")
1437
+
1438
+ sql += " LIMIT 1"
1439
+
1440
+ txn.execute(sql, list(keyvalues.values()))
1441
+ row = txn.fetchone()
1442
+ if not row:
1443
+ return None
1444
+
1445
+ return ThreepidValidationSession(
1446
+ address=row[0],
1447
+ session_id=row[1],
1448
+ medium=row[2],
1449
+ client_secret=row[3],
1450
+ last_send_attempt=row[4],
1451
+ validated_at=row[5],
1452
+ )
1453
+
1454
+ return await self.db_pool.runInteraction(
1455
+ "get_threepid_validation_session", get_threepid_validation_session_txn
1456
+ )
1457
+
1458
+ async def delete_threepid_session(self, session_id: str) -> None:
1459
+ """Removes a threepid validation session from the database. This can
1460
+ be done after validation has been performed and whatever action was
1461
+ waiting on it has been carried out
1462
+
1463
+ Args:
1464
+ session_id: The ID of the session to delete
1465
+ """
1466
+
1467
+ def delete_threepid_session_txn(txn: LoggingTransaction) -> None:
1468
+ self.db_pool.simple_delete_txn(
1469
+ txn,
1470
+ table="threepid_validation_token",
1471
+ keyvalues={"session_id": session_id},
1472
+ )
1473
+ self.db_pool.simple_delete_txn(
1474
+ txn,
1475
+ table="threepid_validation_session",
1476
+ keyvalues={"session_id": session_id},
1477
+ )
1478
+
1479
+ await self.db_pool.runInteraction(
1480
+ "delete_threepid_session", delete_threepid_session_txn
1481
+ )
1482
+
1483
+ @wrap_as_background_process("cull_expired_threepid_validation_tokens")
1484
+ async def cull_expired_threepid_validation_tokens(self) -> None:
1485
+ """Remove threepid validation tokens with expiry dates that have passed"""
1486
+
1487
+ def cull_expired_threepid_validation_tokens_txn(
1488
+ txn: LoggingTransaction, ts: int
1489
+ ) -> None:
1490
+ sql = """
1491
+ DELETE FROM threepid_validation_token WHERE
1492
+ expires < ?
1493
+ """
1494
+ txn.execute(sql, (ts,))
1495
+
1496
+ await self.db_pool.runInteraction(
1497
+ "cull_expired_threepid_validation_tokens",
1498
+ cull_expired_threepid_validation_tokens_txn,
1499
+ self.clock.time_msec(),
1500
+ )
1501
+
1502
+ @wrap_as_background_process("account_validity_set_expiration_dates")
1503
+ async def _set_expiration_date_when_missing(self) -> None:
1504
+ """
1505
+ Retrieves the list of registered users that don't have an expiration date, and
1506
+ adds an expiration date for each of them.
1507
+ """
1508
+
1509
+ def select_users_with_no_expiration_date_txn(txn: LoggingTransaction) -> None:
1510
+ """Retrieves the list of registered users with no expiration date from the
1511
+ database, filtering out deactivated users.
1512
+ """
1513
+ sql = (
1514
+ "SELECT users.name FROM users"
1515
+ " LEFT JOIN account_validity ON (users.name = account_validity.user_id)"
1516
+ " WHERE account_validity.user_id is NULL AND users.deactivated = 0;"
1517
+ )
1518
+ txn.execute(sql, [])
1519
+
1520
+ for (name,) in txn.fetchall():
1521
+ self.set_expiration_date_for_user_txn(txn, name, use_delta=True)
1522
+
1523
+ await self.db_pool.runInteraction(
1524
+ "get_users_with_no_expiration_date",
1525
+ select_users_with_no_expiration_date_txn,
1526
+ )
1527
+
1528
+ def set_expiration_date_for_user_txn(
1529
+ self, txn: LoggingTransaction, user_id: str, use_delta: bool = False
1530
+ ) -> None:
1531
+ """Sets an expiration date to the account with the given user ID.
1532
+
1533
+ Args:
1534
+ user_id: User ID to set an expiration date for.
1535
+ use_delta: If set to False, the expiration date for the user will be
1536
+ now + validity period. If set to True, this expiration date will be a
1537
+ random value in the [now + period - d ; now + period] range, d being a
1538
+ delta equal to 10% of the validity period.
1539
+ """
1540
+ now_ms = self.clock.time_msec()
1541
+ assert self._account_validity_period is not None
1542
+ expiration_ts = now_ms + self._account_validity_period
1543
+
1544
+ if use_delta:
1545
+ assert self._account_validity_startup_job_max_delta is not None
1546
+ expiration_ts = random.randrange(
1547
+ int(expiration_ts - self._account_validity_startup_job_max_delta),
1548
+ expiration_ts,
1549
+ )
1550
+
1551
+ self.db_pool.simple_upsert_txn(
1552
+ txn,
1553
+ "account_validity",
1554
+ keyvalues={"user_id": user_id},
1555
+ values={"expiration_ts_ms": expiration_ts, "email_sent": False},
1556
+ )
1557
+
1558
+ async def get_user_pending_deactivation(self) -> Optional[str]:
1559
+ """
1560
+ Gets one user from the table of users waiting to be parted from all the rooms
1561
+ they're in.
1562
+ """
1563
+ return await self.db_pool.simple_select_one_onecol(
1564
+ "users_pending_deactivation",
1565
+ keyvalues={},
1566
+ retcol="user_id",
1567
+ allow_none=True,
1568
+ desc="get_users_pending_deactivation",
1569
+ )
1570
+
1571
+ async def del_user_pending_deactivation(self, user_id: str) -> None:
1572
+ """
1573
+ Removes the given user to the table of users who need to be parted from all the
1574
+ rooms they're in, effectively marking that user as fully deactivated.
1575
+ """
1576
+ # XXX: This should be simple_delete_one but we failed to put a unique index on
1577
+ # the table, so somehow duplicate entries have ended up in it.
1578
+ await self.db_pool.simple_delete(
1579
+ "users_pending_deactivation",
1580
+ keyvalues={"user_id": user_id},
1581
+ desc="del_user_pending_deactivation",
1582
+ )
1583
+
1584
+ async def get_access_token_last_validated(self, token_id: int) -> int:
1585
+ """Retrieves the time (in milliseconds) of the last validation of an access token.
1586
+
1587
+ Args:
1588
+ token_id: The ID of the access token to update.
1589
+ Raises:
1590
+ StoreError if the access token was not found.
1591
+
1592
+ Returns:
1593
+ The last validation time.
1594
+ """
1595
+ result = await self.db_pool.simple_select_one_onecol(
1596
+ "access_tokens", {"id": token_id}, "last_validated"
1597
+ )
1598
+
1599
+ # If this token has not been validated (since starting to track this),
1600
+ # return 0 instead of None.
1601
+ return result or 0
1602
+
1603
+ async def update_access_token_last_validated(self, token_id: int) -> None:
1604
+ """Updates the last time an access token was validated.
1605
+
1606
+ Args:
1607
+ token_id: The ID of the access token to update.
1608
+ Raises:
1609
+ StoreError if there was a problem updating this.
1610
+ """
1611
+ now = self.clock.time_msec()
1612
+
1613
+ await self.db_pool.simple_update_one(
1614
+ "access_tokens",
1615
+ {"id": token_id},
1616
+ {"last_validated": now},
1617
+ desc="update_access_token_last_validated",
1618
+ )
1619
+
1620
+ async def registration_token_is_valid(self, token: str) -> bool:
1621
+ """Checks if a token can be used to authenticate a registration.
1622
+
1623
+ Args:
1624
+ token: The registration token to be checked
1625
+ Returns:
1626
+ True if the token is valid, False otherwise.
1627
+ """
1628
+ res = await self.db_pool.simple_select_one(
1629
+ "registration_tokens",
1630
+ keyvalues={"token": token},
1631
+ retcols=["uses_allowed", "pending", "completed", "expiry_time"],
1632
+ allow_none=True,
1633
+ )
1634
+
1635
+ # Check if the token exists
1636
+ if res is None:
1637
+ return False
1638
+
1639
+ uses_allowed, pending, completed, expiry_time = res
1640
+
1641
+ # Check if the token has expired
1642
+ now = self.clock.time_msec()
1643
+ if expiry_time and expiry_time < now:
1644
+ return False
1645
+
1646
+ # Check if the token has been used up
1647
+ if uses_allowed and pending + completed >= uses_allowed:
1648
+ return False
1649
+
1650
+ # Otherwise, the token is valid
1651
+ return True
1652
+
1653
+ async def set_registration_token_pending(self, token: str) -> None:
1654
+ """Increment the pending registrations counter for a token.
1655
+
1656
+ Args:
1657
+ token: The registration token pending use
1658
+ """
1659
+
1660
+ def _set_registration_token_pending_txn(txn: LoggingTransaction) -> None:
1661
+ pending = self.db_pool.simple_select_one_onecol_txn(
1662
+ txn,
1663
+ "registration_tokens",
1664
+ keyvalues={"token": token},
1665
+ retcol="pending",
1666
+ )
1667
+ self.db_pool.simple_update_one_txn(
1668
+ txn,
1669
+ "registration_tokens",
1670
+ keyvalues={"token": token},
1671
+ updatevalues={"pending": pending + 1},
1672
+ )
1673
+
1674
+ await self.db_pool.runInteraction(
1675
+ "set_registration_token_pending", _set_registration_token_pending_txn
1676
+ )
1677
+
1678
+ async def use_registration_token(self, token: str) -> None:
1679
+ """Complete a use of the given registration token.
1680
+
1681
+ The `pending` counter will be decremented, and the `completed`
1682
+ counter will be incremented.
1683
+
1684
+ Args:
1685
+ token: The registration token to be 'used'
1686
+ """
1687
+
1688
+ def _use_registration_token_txn(txn: LoggingTransaction) -> None:
1689
+ # Normally, res is Optional[dict[str, Any]].
1690
+ # Override type because the return type is only optional if
1691
+ # allow_none is True, and we don't want mypy throwing errors
1692
+ # about None not being indexable.
1693
+ row = self.db_pool.simple_select_one_txn(
1694
+ txn,
1695
+ "registration_tokens",
1696
+ keyvalues={"token": token},
1697
+ retcols=("pending", "completed"),
1698
+ )
1699
+ pending = int(row[0])
1700
+ completed = int(row[1])
1701
+
1702
+ # Decrement pending and increment completed
1703
+ self.db_pool.simple_update_one_txn(
1704
+ txn,
1705
+ "registration_tokens",
1706
+ keyvalues={"token": token},
1707
+ updatevalues={
1708
+ "completed": completed + 1,
1709
+ "pending": pending - 1,
1710
+ },
1711
+ )
1712
+
1713
+ await self.db_pool.runInteraction(
1714
+ "use_registration_token", _use_registration_token_txn
1715
+ )
1716
+
1717
+ async def get_registration_tokens(
1718
+ self, valid: Optional[bool] = None
1719
+ ) -> list[tuple[str, Optional[int], int, int, Optional[int]]]:
1720
+ """List all registration tokens. Used by the admin API.
1721
+
1722
+ Args:
1723
+ valid: If True, only valid tokens are returned.
1724
+ If False, only invalid tokens are returned.
1725
+ Default is None: return all tokens regardless of validity.
1726
+
1727
+ Returns:
1728
+ A list of tuples containing:
1729
+ * The token
1730
+ * The number of users allowed (or None)
1731
+ * Whether it is pending
1732
+ * Whether it has been completed
1733
+ * An expiry time (or None if no expiry)
1734
+ """
1735
+
1736
+ def select_registration_tokens_txn(
1737
+ txn: LoggingTransaction, now: int, valid: Optional[bool]
1738
+ ) -> list[tuple[str, Optional[int], int, int, Optional[int]]]:
1739
+ if valid is None:
1740
+ # Return all tokens regardless of validity
1741
+ txn.execute(
1742
+ """
1743
+ SELECT token, uses_allowed, pending, completed, expiry_time
1744
+ FROM registration_tokens
1745
+ """
1746
+ )
1747
+
1748
+ elif valid:
1749
+ # Select valid tokens only
1750
+ sql = """
1751
+ SELECT token, uses_allowed, pending, completed, expiry_time
1752
+ FROM registration_tokens
1753
+ WHERE (uses_allowed > pending + completed OR uses_allowed IS NULL)
1754
+ AND (expiry_time > ? OR expiry_time IS NULL)
1755
+ """
1756
+ txn.execute(sql, [now])
1757
+
1758
+ else:
1759
+ # Select invalid tokens only
1760
+ sql = """
1761
+ SELECT token, uses_allowed, pending, completed, expiry_time
1762
+ FROM registration_tokens
1763
+ WHERE uses_allowed <= pending + completed OR expiry_time <= ?
1764
+ """
1765
+ txn.execute(sql, [now])
1766
+
1767
+ return cast(
1768
+ list[tuple[str, Optional[int], int, int, Optional[int]]], txn.fetchall()
1769
+ )
1770
+
1771
+ return await self.db_pool.runInteraction(
1772
+ "select_registration_tokens",
1773
+ select_registration_tokens_txn,
1774
+ self.clock.time_msec(),
1775
+ valid,
1776
+ )
1777
+
1778
+ async def get_one_registration_token(self, token: str) -> Optional[dict[str, Any]]:
1779
+ """Get info about the given registration token. Used by the admin API.
1780
+
1781
+ Args:
1782
+ token: The token to retrieve information about.
1783
+
1784
+ Returns:
1785
+ A dict, or None if token doesn't exist.
1786
+ """
1787
+ row = await self.db_pool.simple_select_one(
1788
+ "registration_tokens",
1789
+ keyvalues={"token": token},
1790
+ retcols=["token", "uses_allowed", "pending", "completed", "expiry_time"],
1791
+ allow_none=True,
1792
+ desc="get_one_registration_token",
1793
+ )
1794
+ if row is None:
1795
+ return None
1796
+ return {
1797
+ "token": row[0],
1798
+ "uses_allowed": row[1],
1799
+ "pending": row[2],
1800
+ "completed": row[3],
1801
+ "expiry_time": row[4],
1802
+ }
1803
+
1804
+ async def generate_registration_token(
1805
+ self, length: int, chars: str
1806
+ ) -> Optional[str]:
1807
+ """Generate a random registration token. Used by the admin API.
1808
+
1809
+ Args:
1810
+ length: The length of the token to generate.
1811
+ chars: A string of the characters allowed in the generated token.
1812
+
1813
+ Returns:
1814
+ The generated token.
1815
+
1816
+ Raises:
1817
+ SynapseError if a unique registration token could still not be
1818
+ generated after a few tries.
1819
+ """
1820
+ # Make a few attempts at generating a unique token of the required
1821
+ # length before failing.
1822
+ for _i in range(3):
1823
+ # Generate token
1824
+ token = "".join(random.choices(chars, k=length))
1825
+
1826
+ # Check if the token already exists
1827
+ existing_token = await self.db_pool.simple_select_one_onecol(
1828
+ "registration_tokens",
1829
+ keyvalues={"token": token},
1830
+ retcol="token",
1831
+ allow_none=True,
1832
+ desc="check_if_registration_token_exists",
1833
+ )
1834
+
1835
+ if existing_token is None:
1836
+ # The generated token doesn't exist yet, return it
1837
+ return token
1838
+
1839
+ raise SynapseError(
1840
+ 500,
1841
+ "Unable to generate a unique registration token. Try again with a greater length",
1842
+ Codes.UNKNOWN,
1843
+ )
1844
+
1845
+ async def create_registration_token(
1846
+ self, token: str, uses_allowed: Optional[int], expiry_time: Optional[int]
1847
+ ) -> bool:
1848
+ """Create a new registration token. Used by the admin API.
1849
+
1850
+ Args:
1851
+ token: The token to create.
1852
+ uses_allowed: The number of times the token can be used to complete
1853
+ a registration before it becomes invalid. A value of None indicates
1854
+ unlimited uses.
1855
+ expiry_time: The latest time the token is valid. Given as the
1856
+ number of milliseconds since 1970-01-01 00:00:00 UTC. A value of
1857
+ None indicates that the token does not expire.
1858
+
1859
+ Returns:
1860
+ Whether the row was inserted or not.
1861
+ """
1862
+
1863
+ def _create_registration_token_txn(txn: LoggingTransaction) -> bool:
1864
+ row = self.db_pool.simple_select_one_txn(
1865
+ txn,
1866
+ "registration_tokens",
1867
+ keyvalues={"token": token},
1868
+ retcols=["token"],
1869
+ allow_none=True,
1870
+ )
1871
+
1872
+ if row is not None:
1873
+ # Token already exists
1874
+ return False
1875
+
1876
+ self.db_pool.simple_insert_txn(
1877
+ txn,
1878
+ "registration_tokens",
1879
+ values={
1880
+ "token": token,
1881
+ "uses_allowed": uses_allowed,
1882
+ "pending": 0,
1883
+ "completed": 0,
1884
+ "expiry_time": expiry_time,
1885
+ },
1886
+ )
1887
+
1888
+ return True
1889
+
1890
+ return await self.db_pool.runInteraction(
1891
+ "create_registration_token", _create_registration_token_txn
1892
+ )
1893
+
1894
+ async def update_registration_token(
1895
+ self, token: str, updatevalues: dict[str, Optional[int]]
1896
+ ) -> Optional[dict[str, Any]]:
1897
+ """Update a registration token. Used by the admin API.
1898
+
1899
+ Args:
1900
+ token: The token to update.
1901
+ updatevalues: A dict with the fields to update. E.g.:
1902
+ `{"uses_allowed": 3}` to update just uses_allowed, or
1903
+ `{"uses_allowed": 3, "expiry_time": None}` to update both.
1904
+ This is passed straight to simple_update_one.
1905
+
1906
+ Returns:
1907
+ A dict with all info about the token, or None if token doesn't exist.
1908
+ """
1909
+
1910
+ def _update_registration_token_txn(
1911
+ txn: LoggingTransaction,
1912
+ ) -> Optional[dict[str, Any]]:
1913
+ try:
1914
+ self.db_pool.simple_update_one_txn(
1915
+ txn,
1916
+ "registration_tokens",
1917
+ keyvalues={"token": token},
1918
+ updatevalues=updatevalues,
1919
+ )
1920
+ except StoreError:
1921
+ # Update failed because token does not exist
1922
+ return None
1923
+
1924
+ # Get all info about the token so it can be sent in the response
1925
+ result = self.db_pool.simple_select_one_txn(
1926
+ txn,
1927
+ "registration_tokens",
1928
+ keyvalues={"token": token},
1929
+ retcols=[
1930
+ "token",
1931
+ "uses_allowed",
1932
+ "pending",
1933
+ "completed",
1934
+ "expiry_time",
1935
+ ],
1936
+ allow_none=True,
1937
+ )
1938
+
1939
+ if result is None:
1940
+ return result
1941
+
1942
+ return {
1943
+ "token": result[0],
1944
+ "uses_allowed": result[1],
1945
+ "pending": result[2],
1946
+ "completed": result[3],
1947
+ "expiry_time": result[4],
1948
+ }
1949
+
1950
+ return await self.db_pool.runInteraction(
1951
+ "update_registration_token", _update_registration_token_txn
1952
+ )
1953
+
1954
+ async def delete_registration_token(self, token: str) -> bool:
1955
+ """Delete a registration token. Used by the admin API.
1956
+
1957
+ Args:
1958
+ token: The token to delete.
1959
+
1960
+ Returns:
1961
+ Whether the token was successfully deleted or not.
1962
+ """
1963
+ try:
1964
+ await self.db_pool.simple_delete_one(
1965
+ "registration_tokens",
1966
+ keyvalues={"token": token},
1967
+ desc="delete_registration_token",
1968
+ )
1969
+ except StoreError:
1970
+ # Deletion failed because token does not exist
1971
+ return False
1972
+
1973
+ return True
1974
+
1975
+ @cached()
1976
+ async def mark_access_token_as_used(self, token_id: int) -> None:
1977
+ """
1978
+ Mark the access token as used, which invalidates the refresh token used
1979
+ to obtain it.
1980
+
1981
+ Because get_user_by_access_token is cached, this function might be
1982
+ called multiple times for the same token, effectively doing unnecessary
1983
+ SQL updates. Because updating the `used` field only goes one way (from
1984
+ False to True) it is safe to cache this function as well to avoid this
1985
+ issue.
1986
+
1987
+ Args:
1988
+ token_id: The ID of the access token to update.
1989
+ Raises:
1990
+ StoreError if there was a problem updating this.
1991
+ """
1992
+ await self.db_pool.simple_update_one(
1993
+ "access_tokens",
1994
+ {"id": token_id},
1995
+ {"used": True},
1996
+ desc="mark_access_token_as_used",
1997
+ )
1998
+
1999
+ async def lookup_refresh_token(
2000
+ self, token: str
2001
+ ) -> Optional[RefreshTokenLookupResult]:
2002
+ """Lookup a refresh token with hints about its validity."""
2003
+
2004
+ def _lookup_refresh_token_txn(
2005
+ txn: LoggingTransaction,
2006
+ ) -> Optional[RefreshTokenLookupResult]:
2007
+ txn.execute(
2008
+ """
2009
+ SELECT
2010
+ rt.id token_id,
2011
+ rt.user_id,
2012
+ rt.device_id,
2013
+ rt.next_token_id,
2014
+ (nrt.next_token_id IS NOT NULL) AS has_next_refresh_token_been_refreshed,
2015
+ at.used AS has_next_access_token_been_used,
2016
+ rt.expiry_ts,
2017
+ rt.ultimate_session_expiry_ts
2018
+ FROM refresh_tokens rt
2019
+ LEFT JOIN refresh_tokens nrt ON rt.next_token_id = nrt.id
2020
+ LEFT JOIN access_tokens at ON at.refresh_token_id = nrt.id
2021
+ WHERE rt.token = ?
2022
+ """,
2023
+ (token,),
2024
+ )
2025
+ row = txn.fetchone()
2026
+
2027
+ if row is None:
2028
+ return None
2029
+
2030
+ return RefreshTokenLookupResult(
2031
+ token_id=row[0],
2032
+ user_id=row[1],
2033
+ device_id=row[2],
2034
+ next_token_id=row[3],
2035
+ # SQLite returns 0 or 1 for false/true, so convert to a bool.
2036
+ has_next_refresh_token_been_refreshed=bool(row[4]),
2037
+ # This column is nullable, ensure it's a boolean
2038
+ has_next_access_token_been_used=(row[5] or False),
2039
+ expiry_ts=row[6],
2040
+ ultimate_session_expiry_ts=row[7],
2041
+ )
2042
+
2043
+ return await self.db_pool.runInteraction(
2044
+ "lookup_refresh_token", _lookup_refresh_token_txn
2045
+ )
2046
+
2047
+ async def replace_refresh_token(self, token_id: int, next_token_id: int) -> None:
2048
+ """
2049
+ Set the successor of a refresh token, removing the existing successor
2050
+ if any.
2051
+
2052
+ This also deletes the predecessor refresh and access tokens,
2053
+ since they cannot be valid anymore.
2054
+
2055
+ Args:
2056
+ token_id: ID of the refresh token to update.
2057
+ next_token_id: ID of its successor.
2058
+ """
2059
+
2060
+ def _replace_refresh_token_txn(txn: LoggingTransaction) -> None:
2061
+ # First check if there was an existing refresh token
2062
+ old_next_token_id = self.db_pool.simple_select_one_onecol_txn(
2063
+ txn,
2064
+ "refresh_tokens",
2065
+ {"id": token_id},
2066
+ "next_token_id",
2067
+ allow_none=True,
2068
+ )
2069
+
2070
+ self.db_pool.simple_update_one_txn(
2071
+ txn,
2072
+ "refresh_tokens",
2073
+ {"id": token_id},
2074
+ {"next_token_id": next_token_id},
2075
+ )
2076
+
2077
+ # Delete the old "next" token if it exists. This should cascade and
2078
+ # delete the associated access_token
2079
+ if old_next_token_id is not None:
2080
+ self.db_pool.simple_delete_one_txn(
2081
+ txn,
2082
+ "refresh_tokens",
2083
+ {"id": old_next_token_id},
2084
+ )
2085
+
2086
+ # Delete the previous refresh token, since we only want to keep the
2087
+ # last 2 refresh tokens in the database.
2088
+ # (The predecessor of the latest refresh token is still useful in
2089
+ # case the refresh was interrupted and the client re-uses the old
2090
+ # one.)
2091
+ # This cascades to delete the associated access token.
2092
+ self.db_pool.simple_delete_txn(
2093
+ txn, "refresh_tokens", {"next_token_id": token_id}
2094
+ )
2095
+
2096
+ await self.db_pool.runInteraction(
2097
+ "replace_refresh_token", _replace_refresh_token_txn
2098
+ )
2099
+
2100
+ async def set_device_for_refresh_token(
2101
+ self, user_id: str, old_device_id: str, device_id: str
2102
+ ) -> None:
2103
+ """Moves refresh tokens from old device to current device
2104
+
2105
+ Args:
2106
+ user_id: The user of the devices.
2107
+ old_device_id: The old device.
2108
+ device_id: The new device ID.
2109
+ Returns:
2110
+ None
2111
+ """
2112
+
2113
+ await self.db_pool.simple_update(
2114
+ "refresh_tokens",
2115
+ keyvalues={"user_id": user_id, "device_id": old_device_id},
2116
+ updatevalues={"device_id": device_id},
2117
+ desc="set_device_for_refresh_token",
2118
+ )
2119
+
2120
+ def _set_device_for_access_token_txn(
2121
+ self, txn: LoggingTransaction, token: str, device_id: str
2122
+ ) -> str:
2123
+ old_device_id = self.db_pool.simple_select_one_onecol_txn(
2124
+ txn, "access_tokens", {"token": token}, "device_id"
2125
+ )
2126
+
2127
+ self.db_pool.simple_update_txn(
2128
+ txn, "access_tokens", {"token": token}, {"device_id": device_id}
2129
+ )
2130
+
2131
+ self._invalidate_cache_and_stream(txn, self.get_user_by_access_token, (token,))
2132
+
2133
+ return old_device_id
2134
+
2135
+ async def set_device_for_access_token(self, token: str, device_id: str) -> str:
2136
+ """Sets the device ID associated with an access token.
2137
+
2138
+ Args:
2139
+ token: The access token to modify.
2140
+ device_id: The new device ID.
2141
+ Returns:
2142
+ The old device ID associated with the access token.
2143
+ """
2144
+
2145
+ return await self.db_pool.runInteraction(
2146
+ "set_device_for_access_token",
2147
+ self._set_device_for_access_token_txn,
2148
+ token,
2149
+ device_id,
2150
+ )
2151
+
2152
+ async def add_login_token_to_user(
2153
+ self,
2154
+ user_id: str,
2155
+ token: str,
2156
+ expiry_ts: int,
2157
+ auth_provider_id: Optional[str],
2158
+ auth_provider_session_id: Optional[str],
2159
+ ) -> None:
2160
+ """Adds a short-term login token for the given user.
2161
+
2162
+ Args:
2163
+ user_id: The user ID.
2164
+ token: The new login token to add.
2165
+ expiry_ts (milliseconds since the epoch): Time after which the login token
2166
+ cannot be used.
2167
+ auth_provider_id: The SSO Identity Provider that the user authenticated with
2168
+ to get this token, if any
2169
+ auth_provider_session_id: The session ID advertised by the SSO Identity
2170
+ Provider, if any.
2171
+ """
2172
+ await self.db_pool.simple_insert(
2173
+ "login_tokens",
2174
+ {
2175
+ "token": token,
2176
+ "user_id": user_id,
2177
+ "expiry_ts": expiry_ts,
2178
+ "auth_provider_id": auth_provider_id,
2179
+ "auth_provider_session_id": auth_provider_session_id,
2180
+ },
2181
+ desc="add_login_token_to_user",
2182
+ )
2183
+
2184
+ def _consume_login_token(
2185
+ self,
2186
+ txn: LoggingTransaction,
2187
+ token: str,
2188
+ ts: int,
2189
+ ) -> LoginTokenLookupResult:
2190
+ values = self.db_pool.simple_select_one_txn(
2191
+ txn,
2192
+ "login_tokens",
2193
+ keyvalues={"token": token},
2194
+ retcols=(
2195
+ "user_id",
2196
+ "expiry_ts",
2197
+ "used_ts",
2198
+ "auth_provider_id",
2199
+ "auth_provider_session_id",
2200
+ ),
2201
+ allow_none=True,
2202
+ )
2203
+
2204
+ if values is None:
2205
+ raise NotFoundError()
2206
+
2207
+ self.db_pool.simple_update_one_txn(
2208
+ txn,
2209
+ "login_tokens",
2210
+ keyvalues={"token": token},
2211
+ updatevalues={"used_ts": ts},
2212
+ )
2213
+ (
2214
+ user_id,
2215
+ expiry_ts,
2216
+ used_ts,
2217
+ auth_provider_id,
2218
+ auth_provider_session_id,
2219
+ ) = values
2220
+
2221
+ # Token was already used
2222
+ if used_ts is not None:
2223
+ raise LoginTokenReused()
2224
+
2225
+ # Token expired
2226
+ if ts > int(expiry_ts):
2227
+ raise LoginTokenExpired()
2228
+
2229
+ return LoginTokenLookupResult(
2230
+ user_id=user_id,
2231
+ auth_provider_id=auth_provider_id,
2232
+ auth_provider_session_id=auth_provider_session_id,
2233
+ )
2234
+
2235
+ async def consume_login_token(self, token: str) -> LoginTokenLookupResult:
2236
+ """Lookup a login token and consume it.
2237
+
2238
+ Args:
2239
+ token: The login token.
2240
+
2241
+ Returns:
2242
+ The data stored with that token, including the `user_id`. Returns `None` if
2243
+ the token does not exist or if it expired.
2244
+
2245
+ Raises:
2246
+ NotFound if the login token was not found in database
2247
+ LoginTokenExpired if the login token expired
2248
+ LoginTokenReused if the login token was already used
2249
+ """
2250
+ return await self.db_pool.runInteraction(
2251
+ "consume_login_token",
2252
+ self._consume_login_token,
2253
+ token,
2254
+ self.clock.time_msec(),
2255
+ )
2256
+
2257
+ async def invalidate_login_tokens_by_session_id(
2258
+ self, auth_provider_id: str, auth_provider_session_id: str
2259
+ ) -> None:
2260
+ """Invalidate login tokens with the given IdP session ID.
2261
+
2262
+ Args:
2263
+ auth_provider_id: The SSO Identity Provider that the user authenticated with
2264
+ to get this token
2265
+ auth_provider_session_id: The session ID advertised by the SSO Identity
2266
+ Provider
2267
+ """
2268
+ await self.db_pool.simple_update(
2269
+ table="login_tokens",
2270
+ keyvalues={
2271
+ "auth_provider_id": auth_provider_id,
2272
+ "auth_provider_session_id": auth_provider_session_id,
2273
+ },
2274
+ updatevalues={"used_ts": self.clock.time_msec()},
2275
+ desc="invalidate_login_tokens_by_session_id",
2276
+ )
2277
+
2278
+ @cached()
2279
+ async def is_guest(self, user_id: str) -> bool:
2280
+ res = await self.db_pool.simple_select_one_onecol(
2281
+ table="users",
2282
+ keyvalues={"name": user_id},
2283
+ retcol="is_guest",
2284
+ allow_none=True,
2285
+ desc="is_guest",
2286
+ )
2287
+
2288
+ return res if res else False
2289
+
2290
+ @cached()
2291
+ async def is_user_approved(self, user_id: str) -> bool:
2292
+ """Checks if a user is approved and therefore can be allowed to log in.
2293
+
2294
+ If the user's 'approved' column is NULL, we consider it as true given it means
2295
+ the user was registered when support for an approval flow was either disabled
2296
+ or nonexistent.
2297
+
2298
+ Args:
2299
+ user_id: the user to check the approval status of.
2300
+
2301
+ Returns:
2302
+ A boolean that is True if the user is approved, False otherwise.
2303
+ """
2304
+
2305
+ def is_user_approved_txn(txn: LoggingTransaction) -> bool:
2306
+ txn.execute(
2307
+ """
2308
+ SELECT COALESCE(approved, TRUE) AS approved FROM users WHERE name = ?
2309
+ """,
2310
+ (user_id,),
2311
+ )
2312
+
2313
+ row = txn.fetchone()
2314
+ assert row is not None
2315
+
2316
+ # We cast to bool because the value returned by the database engine might
2317
+ # be an integer if we're using SQLite.
2318
+ return bool(row[0])
2319
+
2320
+ return await self.db_pool.runInteraction(
2321
+ desc="is_user_pending_approval",
2322
+ func=is_user_approved_txn,
2323
+ )
2324
+
2325
+ async def set_user_deactivated_status(
2326
+ self, user_id: str, deactivated: bool
2327
+ ) -> None:
2328
+ """Set the `deactivated` property for the provided user to the provided value.
2329
+
2330
+ Args:
2331
+ user_id: The ID of the user to set the status for.
2332
+ deactivated: The value to set for `deactivated`.
2333
+ """
2334
+
2335
+ await self.db_pool.runInteraction(
2336
+ "set_user_deactivated_status",
2337
+ self.set_user_deactivated_status_txn,
2338
+ user_id,
2339
+ deactivated,
2340
+ )
2341
+
2342
+ def set_user_deactivated_status_txn(
2343
+ self, txn: LoggingTransaction, user_id: str, deactivated: bool
2344
+ ) -> None:
2345
+ self.db_pool.simple_update_one_txn(
2346
+ txn=txn,
2347
+ table="users",
2348
+ keyvalues={"name": user_id},
2349
+ updatevalues={"deactivated": 1 if deactivated else 0},
2350
+ )
2351
+ self._invalidate_cache_and_stream(
2352
+ txn, self.get_user_deactivated_status, (user_id,)
2353
+ )
2354
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
2355
+ self._invalidate_cache_and_stream(txn, self.is_guest, (user_id,))
2356
+
2357
+ async def set_user_suspended_status(self, user_id: str, suspended: bool) -> None:
2358
+ """
2359
+ Set whether the user's account is suspended in the `users` table.
2360
+
2361
+ Args:
2362
+ user_id: The user ID of the user in question
2363
+ suspended: True if the user is suspended, false if not
2364
+ """
2365
+ await self.db_pool.runInteraction(
2366
+ "set_user_suspended_status",
2367
+ self.set_user_suspended_status_txn,
2368
+ user_id,
2369
+ suspended,
2370
+ )
2371
+
2372
+ def set_user_suspended_status_txn(
2373
+ self, txn: LoggingTransaction, user_id: str, suspended: bool
2374
+ ) -> None:
2375
+ self.db_pool.simple_update_one_txn(
2376
+ txn=txn,
2377
+ table="users",
2378
+ keyvalues={"name": user_id},
2379
+ updatevalues={"suspended": suspended},
2380
+ )
2381
+ self._invalidate_cache_and_stream(
2382
+ txn, self.get_user_suspended_status, (user_id,)
2383
+ )
2384
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
2385
+
2386
+ async def set_user_locked_status(self, user_id: str, locked: bool) -> None:
2387
+ """Set the `locked` property for the provided user to the provided value.
2388
+
2389
+ Args:
2390
+ user_id: The ID of the user to set the status for.
2391
+ locked: The value to set for `locked`.
2392
+ """
2393
+
2394
+ await self.db_pool.runInteraction(
2395
+ "set_user_locked_status",
2396
+ self.set_user_locked_status_txn,
2397
+ user_id,
2398
+ locked,
2399
+ )
2400
+
2401
+ def set_user_locked_status_txn(
2402
+ self, txn: LoggingTransaction, user_id: str, locked: bool
2403
+ ) -> None:
2404
+ self.db_pool.simple_update_one_txn(
2405
+ txn=txn,
2406
+ table="users",
2407
+ keyvalues={"name": user_id},
2408
+ updatevalues={"locked": locked},
2409
+ )
2410
+ self._invalidate_cache_and_stream(txn, self.get_user_locked_status, (user_id,))
2411
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
2412
+
2413
+ async def update_user_approval_status(
2414
+ self, user_id: UserID, approved: bool
2415
+ ) -> None:
2416
+ """Set the user's 'approved' flag to the given value.
2417
+
2418
+ The boolean will be turned into an int (in update_user_approval_status_txn)
2419
+ because the column is a smallint.
2420
+
2421
+ Args:
2422
+ user_id: the user to update the flag for.
2423
+ approved: the value to set the flag to.
2424
+ """
2425
+ await self.db_pool.runInteraction(
2426
+ "update_user_approval_status",
2427
+ self.update_user_approval_status_txn,
2428
+ user_id.to_string(),
2429
+ approved,
2430
+ )
2431
+
2432
+ def update_user_approval_status_txn(
2433
+ self, txn: LoggingTransaction, user_id: str, approved: bool
2434
+ ) -> None:
2435
+ """Set the user's 'approved' flag to the given value.
2436
+
2437
+ The boolean is turned into an int because the column is a smallint.
2438
+
2439
+ Args:
2440
+ txn: the current database transaction.
2441
+ user_id: the user to update the flag for.
2442
+ approved: the value to set the flag to.
2443
+ """
2444
+ self.db_pool.simple_update_one_txn(
2445
+ txn=txn,
2446
+ table="users",
2447
+ keyvalues={"name": user_id},
2448
+ updatevalues={"approved": approved},
2449
+ )
2450
+
2451
+ # Invalidate the caches of methods that read the value of the 'approved' flag.
2452
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
2453
+ self._invalidate_cache_and_stream(txn, self.is_user_approved, (user_id,))
2454
+
2455
+ async def user_delete_access_tokens(
2456
+ self,
2457
+ user_id: str,
2458
+ except_token_id: Optional[int] = None,
2459
+ device_id: Optional[str] = None,
2460
+ ) -> list[tuple[str, int, Optional[str]]]:
2461
+ """
2462
+ Invalidate access and refresh tokens belonging to a user
2463
+
2464
+ Args:
2465
+ user_id: ID of user the tokens belong to
2466
+ except_token_id: access_tokens ID which should *not* be deleted
2467
+ device_id: ID of device the tokens are associated with.
2468
+ If None, tokens associated with any device (or no device) will
2469
+ be deleted
2470
+ Returns:
2471
+ A tuple of (token, token id, device id) for each of the deleted tokens
2472
+ """
2473
+
2474
+ def f(txn: LoggingTransaction) -> list[tuple[str, int, Optional[str]]]:
2475
+ keyvalues = {"user_id": user_id}
2476
+ if device_id is not None:
2477
+ keyvalues["device_id"] = device_id
2478
+
2479
+ items = keyvalues.items()
2480
+ where_clause = " AND ".join(k + " = ?" for k, _ in items)
2481
+ values: list[Union[str, int]] = [v for _, v in items]
2482
+ # Conveniently, refresh_tokens and access_tokens both use the user_id and device_id fields. Only caveat
2483
+ # is the `except_token_id` param that is tricky to get right, so for now we're just using the same where
2484
+ # clause and values before we handle that. This seems to be only used in the "set password" handler.
2485
+ refresh_where_clause = where_clause
2486
+ refresh_values = values.copy()
2487
+ if except_token_id:
2488
+ # TODO: support that for refresh tokens
2489
+ where_clause += " AND id != ?"
2490
+ values.append(except_token_id)
2491
+
2492
+ txn.execute(
2493
+ "SELECT token, id, device_id FROM access_tokens WHERE %s"
2494
+ % where_clause,
2495
+ values,
2496
+ )
2497
+ tokens_and_devices = [(r[0], r[1], r[2]) for r in txn]
2498
+
2499
+ self._invalidate_cache_and_stream_bulk(
2500
+ txn,
2501
+ self.get_user_by_access_token,
2502
+ [(token,) for token, _, _ in tokens_and_devices],
2503
+ )
2504
+
2505
+ txn.execute("DELETE FROM access_tokens WHERE %s" % where_clause, values)
2506
+
2507
+ txn.execute(
2508
+ "DELETE FROM refresh_tokens WHERE %s" % refresh_where_clause,
2509
+ refresh_values,
2510
+ )
2511
+
2512
+ return tokens_and_devices
2513
+
2514
+ return await self.db_pool.runInteraction("user_delete_access_tokens", f)
2515
+
2516
+ async def user_delete_access_tokens_for_devices(
2517
+ self,
2518
+ user_id: str,
2519
+ device_ids: StrCollection,
2520
+ ) -> list[tuple[str, int, Optional[str]]]:
2521
+ """
2522
+ Invalidate access and refresh tokens belonging to a user
2523
+
2524
+ Args:
2525
+ user_id: ID of user the tokens belong to
2526
+ device_ids: The devices to delete tokens for.
2527
+ Returns:
2528
+ A tuple of (token, token id, device id) for each of the deleted tokens
2529
+ """
2530
+
2531
+ def user_delete_access_tokens_for_devices_txn(
2532
+ txn: LoggingTransaction, batch_device_ids: StrCollection
2533
+ ) -> list[tuple[str, int, Optional[str]]]:
2534
+ self.db_pool.simple_delete_many_txn(
2535
+ txn,
2536
+ table="refresh_tokens",
2537
+ keyvalues={"user_id": user_id},
2538
+ column="device_id",
2539
+ values=batch_device_ids,
2540
+ )
2541
+
2542
+ clause, args = make_in_list_sql_clause(
2543
+ txn.database_engine, "device_id", batch_device_ids
2544
+ )
2545
+ args.append(user_id)
2546
+
2547
+ sql = f"""
2548
+ DELETE FROM access_tokens
2549
+ WHERE {clause} AND user_id = ?
2550
+ RETURNING token, id, device_id
2551
+ """
2552
+ txn.execute(sql, args)
2553
+ tokens_and_devices = txn.fetchall()
2554
+
2555
+ self._invalidate_cache_and_stream_bulk(
2556
+ txn,
2557
+ self.get_user_by_access_token,
2558
+ [(t[0],) for t in tokens_and_devices],
2559
+ )
2560
+ return tokens_and_devices
2561
+
2562
+ results = []
2563
+ for batch_device_ids in batch_iter(device_ids, 1000):
2564
+ tokens_and_devices = await self.db_pool.runInteraction(
2565
+ "user_delete_access_tokens_for_devices",
2566
+ user_delete_access_tokens_for_devices_txn,
2567
+ batch_device_ids,
2568
+ )
2569
+ results.extend(tokens_and_devices)
2570
+
2571
+ return results
2572
+
2573
+ async def delete_access_token(self, access_token: str) -> None:
2574
+ def f(txn: LoggingTransaction) -> None:
2575
+ self.db_pool.simple_delete_one_txn(
2576
+ txn, table="access_tokens", keyvalues={"token": access_token}
2577
+ )
2578
+
2579
+ self._invalidate_cache_and_stream(
2580
+ txn, self.get_user_by_access_token, (access_token,)
2581
+ )
2582
+
2583
+ await self.db_pool.runInteraction("delete_access_token", f)
2584
+
2585
+ async def user_set_password_hash(
2586
+ self, user_id: str, password_hash: Optional[str]
2587
+ ) -> None:
2588
+ """
2589
+ NB. This does *not* evict any cache because the one use for this
2590
+ removes most of the entries subsequently anyway so it would be
2591
+ pointless. Use flush_user separately.
2592
+ """
2593
+
2594
+ def user_set_password_hash_txn(txn: LoggingTransaction) -> None:
2595
+ self.db_pool.simple_update_one_txn(
2596
+ txn, "users", {"name": user_id}, {"password_hash": password_hash}
2597
+ )
2598
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
2599
+
2600
+ await self.db_pool.runInteraction(
2601
+ "user_set_password_hash", user_set_password_hash_txn
2602
+ )
2603
+
2604
+ async def add_user_pending_deactivation(self, user_id: str) -> None:
2605
+ """
2606
+ Adds a user to the table of users who need to be parted from all the rooms they're
2607
+ in
2608
+ """
2609
+ await self.db_pool.simple_insert(
2610
+ "users_pending_deactivation",
2611
+ values={"user_id": user_id},
2612
+ desc="add_user_pending_deactivation",
2613
+ )
2614
+
2615
+
2616
+ class RegistrationBackgroundUpdateStore(RegistrationWorkerStore):
2617
+ def __init__(
2618
+ self,
2619
+ database: DatabasePool,
2620
+ db_conn: LoggingDatabaseConnection,
2621
+ hs: "HomeServer",
2622
+ ):
2623
+ super().__init__(database, db_conn, hs)
2624
+
2625
+ self.config = hs.config
2626
+
2627
+ self.db_pool.updates.register_background_index_update(
2628
+ "access_tokens_device_index",
2629
+ index_name="access_tokens_device_id",
2630
+ table="access_tokens",
2631
+ columns=["user_id", "device_id"],
2632
+ )
2633
+
2634
+ self.db_pool.updates.register_background_index_update(
2635
+ "users_creation_ts",
2636
+ index_name="users_creation_ts",
2637
+ table="users",
2638
+ columns=["creation_ts"],
2639
+ )
2640
+
2641
+ self.db_pool.updates.register_background_update_handler(
2642
+ "users_set_deactivated_flag", self._background_update_set_deactivated_flag
2643
+ )
2644
+
2645
+ self.db_pool.updates.register_background_index_update(
2646
+ "user_external_ids_user_id_idx",
2647
+ index_name="user_external_ids_user_id_idx",
2648
+ table="user_external_ids",
2649
+ columns=["user_id"],
2650
+ unique=False,
2651
+ )
2652
+
2653
+ self.db_pool.updates.register_background_index_update(
2654
+ update_name="access_tokens_refresh_token_id_idx",
2655
+ index_name="access_tokens_refresh_token_id_idx",
2656
+ table="access_tokens",
2657
+ columns=("refresh_token_id",),
2658
+ )
2659
+
2660
+ async def _background_update_set_deactivated_flag(
2661
+ self, progress: JsonDict, batch_size: int
2662
+ ) -> int:
2663
+ """Retrieves a list of all deactivated users and sets the 'deactivated' flag to 1
2664
+ for each of them.
2665
+ """
2666
+
2667
+ last_user = progress.get("user_id", "")
2668
+
2669
+ def _background_update_set_deactivated_flag_txn(
2670
+ txn: LoggingTransaction,
2671
+ ) -> tuple[bool, int]:
2672
+ txn.execute(
2673
+ """
2674
+ SELECT
2675
+ users.name,
2676
+ COUNT(access_tokens.token) AS count_tokens,
2677
+ COUNT(user_threepids.address) AS count_threepids
2678
+ FROM users
2679
+ LEFT JOIN access_tokens ON (access_tokens.user_id = users.name)
2680
+ LEFT JOIN user_threepids ON (user_threepids.user_id = users.name)
2681
+ WHERE (users.password_hash IS NULL OR users.password_hash = '')
2682
+ AND (users.appservice_id IS NULL OR users.appservice_id = '')
2683
+ AND users.is_guest = 0
2684
+ AND users.name > ?
2685
+ GROUP BY users.name
2686
+ ORDER BY users.name ASC
2687
+ LIMIT ?;
2688
+ """,
2689
+ (last_user, batch_size),
2690
+ )
2691
+
2692
+ rows = txn.fetchall()
2693
+
2694
+ if not rows:
2695
+ return True, 0
2696
+
2697
+ rows_processed_nb = 0
2698
+
2699
+ for name, count_tokens, count_threepids in rows:
2700
+ if not count_tokens and not count_threepids:
2701
+ self.set_user_deactivated_status_txn(txn, name, True)
2702
+ rows_processed_nb += 1
2703
+
2704
+ logger.info("Marked %d rows as deactivated", rows_processed_nb)
2705
+
2706
+ self.db_pool.updates._background_update_progress_txn(
2707
+ txn, "users_set_deactivated_flag", {"user_id": rows[-1][0]}
2708
+ )
2709
+
2710
+ if batch_size > len(rows):
2711
+ return True, len(rows)
2712
+ else:
2713
+ return False, len(rows)
2714
+
2715
+ end, nb_processed = await self.db_pool.runInteraction(
2716
+ "users_set_deactivated_flag", _background_update_set_deactivated_flag_txn
2717
+ )
2718
+
2719
+ if end:
2720
+ await self.db_pool.updates._end_background_update(
2721
+ "users_set_deactivated_flag"
2722
+ )
2723
+
2724
+ return nb_processed
2725
+
2726
+
2727
+ class RegistrationStore(RegistrationBackgroundUpdateStore):
2728
+ def __init__(
2729
+ self,
2730
+ database: DatabasePool,
2731
+ db_conn: LoggingDatabaseConnection,
2732
+ hs: "HomeServer",
2733
+ ):
2734
+ super().__init__(database, db_conn, hs)
2735
+
2736
+ self._ignore_unknown_session_error = (
2737
+ hs.config.server.request_token_inhibit_3pid_errors
2738
+ )
2739
+
2740
+ self._access_tokens_id_gen = IdGenerator(db_conn, "access_tokens", "id")
2741
+ self._refresh_tokens_id_gen = IdGenerator(db_conn, "refresh_tokens", "id")
2742
+
2743
+ # Create a background job for removing expired login tokens
2744
+ if hs.config.worker.run_background_tasks:
2745
+ self.clock.looping_call(
2746
+ self._delete_expired_login_tokens, THIRTY_MINUTES_IN_MS
2747
+ )
2748
+
2749
+ async def add_access_token_to_user(
2750
+ self,
2751
+ user_id: str,
2752
+ token: str,
2753
+ device_id: Optional[str],
2754
+ valid_until_ms: Optional[int],
2755
+ puppets_user_id: Optional[str] = None,
2756
+ refresh_token_id: Optional[int] = None,
2757
+ ) -> int:
2758
+ """Adds an access token for the given user.
2759
+
2760
+ Args:
2761
+ user_id: The user ID.
2762
+ token: The new access token to add.
2763
+ device_id: ID of the device to associate with the access token.
2764
+ valid_until_ms: when the token is valid until. None for no expiry.
2765
+ puppets_user_id
2766
+ refresh_token_id: ID of the refresh token generated alongside this
2767
+ access token.
2768
+ Raises:
2769
+ StoreError if there was a problem adding this.
2770
+ Returns:
2771
+ The token ID
2772
+ """
2773
+ next_id = self._access_tokens_id_gen.get_next()
2774
+ now = self.clock.time_msec()
2775
+
2776
+ await self.db_pool.simple_insert(
2777
+ "access_tokens",
2778
+ {
2779
+ "id": next_id,
2780
+ "user_id": user_id,
2781
+ "token": token,
2782
+ "device_id": device_id,
2783
+ "valid_until_ms": valid_until_ms,
2784
+ "puppets_user_id": puppets_user_id,
2785
+ "last_validated": now,
2786
+ "refresh_token_id": refresh_token_id,
2787
+ "used": False,
2788
+ },
2789
+ desc="add_access_token_to_user",
2790
+ )
2791
+
2792
+ return next_id
2793
+
2794
+ async def add_refresh_token_to_user(
2795
+ self,
2796
+ user_id: str,
2797
+ token: str,
2798
+ device_id: Optional[str],
2799
+ expiry_ts: Optional[int],
2800
+ ultimate_session_expiry_ts: Optional[int],
2801
+ ) -> int:
2802
+ """Adds a refresh token for the given user.
2803
+
2804
+ Args:
2805
+ user_id: The user ID.
2806
+ token: The new access token to add.
2807
+ device_id: ID of the device to associate with the refresh token.
2808
+ expiry_ts (milliseconds since the epoch): Time after which the
2809
+ refresh token cannot be used.
2810
+ If None, the refresh token never expires until it has been used.
2811
+ ultimate_session_expiry_ts (milliseconds since the epoch):
2812
+ Time at which the session will end and can not be extended any
2813
+ further.
2814
+ If None, the session can be refreshed indefinitely.
2815
+ Raises:
2816
+ StoreError if there was a problem adding this.
2817
+ Returns:
2818
+ The token ID
2819
+ """
2820
+ next_id = self._refresh_tokens_id_gen.get_next()
2821
+
2822
+ await self.db_pool.simple_insert(
2823
+ "refresh_tokens",
2824
+ {
2825
+ "id": next_id,
2826
+ "user_id": user_id,
2827
+ "device_id": device_id,
2828
+ "token": token,
2829
+ "next_token_id": None,
2830
+ "expiry_ts": expiry_ts,
2831
+ "ultimate_session_expiry_ts": ultimate_session_expiry_ts,
2832
+ },
2833
+ desc="add_refresh_token_to_user",
2834
+ )
2835
+
2836
+ return next_id
2837
+
2838
+ async def user_set_consent_version(
2839
+ self, user_id: str, consent_version: str
2840
+ ) -> None:
2841
+ """Updates the user table to record privacy policy consent
2842
+
2843
+ Args:
2844
+ user_id: full mxid of the user to update
2845
+ consent_version: version of the policy the user has consented to
2846
+
2847
+ Raises:
2848
+ StoreError(404) if user not found
2849
+ """
2850
+
2851
+ def f(txn: LoggingTransaction) -> None:
2852
+ self.db_pool.simple_update_one_txn(
2853
+ txn,
2854
+ table="users",
2855
+ keyvalues={"name": user_id},
2856
+ updatevalues={
2857
+ "consent_version": consent_version,
2858
+ "consent_ts": self.clock.time_msec(),
2859
+ },
2860
+ )
2861
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
2862
+
2863
+ await self.db_pool.runInteraction("user_set_consent_version", f)
2864
+
2865
+ async def user_set_consent_server_notice_sent(
2866
+ self, user_id: str, consent_version: str
2867
+ ) -> None:
2868
+ """Updates the user table to record that we have sent the user a server
2869
+ notice about privacy policy consent
2870
+
2871
+ Args:
2872
+ user_id: full mxid of the user to update
2873
+ consent_version: version of the policy we have notified the user about
2874
+
2875
+ Raises:
2876
+ StoreError(404) if user not found
2877
+ """
2878
+
2879
+ def f(txn: LoggingTransaction) -> None:
2880
+ self.db_pool.simple_update_one_txn(
2881
+ txn,
2882
+ table="users",
2883
+ keyvalues={"name": user_id},
2884
+ updatevalues={"consent_server_notice_sent": consent_version},
2885
+ )
2886
+ self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
2887
+
2888
+ await self.db_pool.runInteraction("user_set_consent_server_notice_sent", f)
2889
+
2890
+ async def validate_threepid_session(
2891
+ self, session_id: str, client_secret: str, token: str, current_ts: int
2892
+ ) -> Optional[str]:
2893
+ """Attempt to validate a threepid session using a token
2894
+
2895
+ Args:
2896
+ session_id: The id of a validation session
2897
+ client_secret: A unique string provided by the client to help identify
2898
+ this validation attempt
2899
+ token: A validation token
2900
+ current_ts: The current unix time in milliseconds. Used for checking
2901
+ token expiry status
2902
+
2903
+ Raises:
2904
+ ThreepidValidationError: if a matching validation token was not found or has
2905
+ expired
2906
+
2907
+ Returns:
2908
+ A str representing a link to redirect the user to if there is one.
2909
+ """
2910
+
2911
+ # Insert everything into a transaction in order to run atomically
2912
+ def validate_threepid_session_txn(txn: LoggingTransaction) -> Optional[str]:
2913
+ row = self.db_pool.simple_select_one_txn(
2914
+ txn,
2915
+ table="threepid_validation_session",
2916
+ keyvalues={"session_id": session_id},
2917
+ retcols=["client_secret", "validated_at"],
2918
+ allow_none=True,
2919
+ )
2920
+
2921
+ if not row:
2922
+ if self._ignore_unknown_session_error:
2923
+ # If we need to inhibit the error caused by an incorrect session ID,
2924
+ # use None as placeholder values for the client secret and the
2925
+ # validation timestamp.
2926
+ # It shouldn't be an issue because they're both only checked after
2927
+ # the token check, which should fail. And if it doesn't for some
2928
+ # reason, the next check is on the client secret, which is NOT NULL,
2929
+ # so we don't have to worry about the client secret matching by
2930
+ # accident.
2931
+ row = None, None
2932
+ else:
2933
+ raise ThreepidValidationError("Unknown session_id")
2934
+
2935
+ retrieved_client_secret, validated_at = row
2936
+
2937
+ row = self.db_pool.simple_select_one_txn(
2938
+ txn,
2939
+ table="threepid_validation_token",
2940
+ keyvalues={"session_id": session_id, "token": token},
2941
+ retcols=["expires", "next_link"],
2942
+ allow_none=True,
2943
+ )
2944
+
2945
+ if not row:
2946
+ raise ThreepidValidationError(
2947
+ "Validation token not found or has expired"
2948
+ )
2949
+ expires, next_link = row
2950
+
2951
+ if retrieved_client_secret != client_secret:
2952
+ raise ThreepidValidationError(
2953
+ "This client_secret does not match the provided session_id"
2954
+ )
2955
+
2956
+ # If the session is already validated, no need to revalidate
2957
+ if validated_at:
2958
+ return next_link
2959
+
2960
+ if expires <= current_ts:
2961
+ raise ThreepidValidationError(
2962
+ "This token has expired. Please request a new one"
2963
+ )
2964
+
2965
+ # Looks good. Validate the session
2966
+ self.db_pool.simple_update_txn(
2967
+ txn,
2968
+ table="threepid_validation_session",
2969
+ keyvalues={"session_id": session_id},
2970
+ updatevalues={"validated_at": self.clock.time_msec()},
2971
+ )
2972
+
2973
+ return next_link
2974
+
2975
+ # Return next_link if it exists
2976
+ return await self.db_pool.runInteraction(
2977
+ "validate_threepid_session_txn", validate_threepid_session_txn
2978
+ )
2979
+
2980
+ async def start_or_continue_validation_session(
2981
+ self,
2982
+ medium: str,
2983
+ address: str,
2984
+ session_id: str,
2985
+ client_secret: str,
2986
+ send_attempt: int,
2987
+ next_link: Optional[str],
2988
+ token: str,
2989
+ token_expires: int,
2990
+ ) -> None:
2991
+ """Creates a new threepid validation session if it does not already
2992
+ exist and associates a new validation token with it
2993
+
2994
+ Args:
2995
+ medium: The medium of the 3PID
2996
+ address: The address of the 3PID
2997
+ session_id: The id of this validation session
2998
+ client_secret: A unique string provided by the client to help
2999
+ identify this validation attempt
3000
+ send_attempt: The latest send_attempt on this session
3001
+ next_link: The link to redirect the user to upon successful validation
3002
+ token: The validation token
3003
+ token_expires: The timestamp for which after the token will no
3004
+ longer be valid
3005
+ """
3006
+
3007
+ def start_or_continue_validation_session_txn(txn: LoggingTransaction) -> None:
3008
+ # Create or update a validation session
3009
+ self.db_pool.simple_upsert_txn(
3010
+ txn,
3011
+ table="threepid_validation_session",
3012
+ keyvalues={"session_id": session_id},
3013
+ values={"last_send_attempt": send_attempt},
3014
+ insertion_values={
3015
+ "medium": medium,
3016
+ "address": address,
3017
+ "client_secret": client_secret,
3018
+ },
3019
+ )
3020
+
3021
+ # Create a new validation token with this session ID
3022
+ self.db_pool.simple_insert_txn(
3023
+ txn,
3024
+ table="threepid_validation_token",
3025
+ values={
3026
+ "session_id": session_id,
3027
+ "token": token,
3028
+ "next_link": next_link,
3029
+ "expires": token_expires,
3030
+ },
3031
+ )
3032
+
3033
+ await self.db_pool.runInteraction(
3034
+ "start_or_continue_validation_session",
3035
+ start_or_continue_validation_session_txn,
3036
+ )
3037
+
3038
+ @wrap_as_background_process("delete_expired_login_tokens")
3039
+ async def _delete_expired_login_tokens(self) -> None:
3040
+ """Remove login tokens with expiry dates that have passed."""
3041
+
3042
+ def _delete_expired_login_tokens_txn(txn: LoggingTransaction, ts: int) -> None:
3043
+ sql = "DELETE FROM login_tokens WHERE expiry_ts <= ?"
3044
+ txn.execute(sql, (ts,))
3045
+
3046
+ # We keep the expired tokens for an extra 5 minutes so we can measure how many
3047
+ # times a token is being used after its expiry
3048
+ now = self.clock.time_msec()
3049
+ await self.db_pool.runInteraction(
3050
+ "delete_expired_login_tokens",
3051
+ _delete_expired_login_tokens_txn,
3052
+ now - (5 * 60 * 1000),
3053
+ )
3054
+
3055
+
3056
+ def find_max_generated_user_id_localpart(cur: Cursor) -> int:
3057
+ """
3058
+ Gets the localpart of the max current generated user ID.
3059
+
3060
+ Generated user IDs are integers, so we find the largest integer user ID
3061
+ already taken and return that.
3062
+ """
3063
+
3064
+ # We bound between '@0' and '@a' to avoid pulling the entire table
3065
+ # out.
3066
+ cur.execute("SELECT name FROM users WHERE '@0' <= name AND name < '@a'")
3067
+
3068
+ regex = re.compile(r"^@(\d+):")
3069
+
3070
+ max_found = 0
3071
+
3072
+ for (user_id,) in cur:
3073
+ match = regex.search(user_id)
3074
+ if match:
3075
+ max_found = max(int(match.group(1)), max_found)
3076
+ return max_found