registration.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017-2018 New Vector Ltd
  4. # Copyright 2019,2020 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. import re
  19. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
  20. import attr
  21. from synapse.api.constants import UserTypes
  22. from synapse.api.errors import Codes, StoreError, SynapseError, ThreepidValidationError
  23. from synapse.metrics.background_process_metrics import wrap_as_background_process
  24. from synapse.storage.database import DatabasePool, LoggingDatabaseConnection
  25. from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
  26. from synapse.storage.databases.main.stats import StatsStore
  27. from synapse.storage.types import Connection, Cursor
  28. from synapse.storage.util.id_generators import IdGenerator
  29. from synapse.storage.util.sequence import build_sequence_generator
  30. from synapse.types import UserID
  31. from synapse.util.caches.descriptors import cached
  32. if TYPE_CHECKING:
  33. from synapse.server import HomeServer
  34. THIRTY_MINUTES_IN_MS = 30 * 60 * 1000
  35. logger = logging.getLogger(__name__)
  36. @attr.s(frozen=True, slots=True)
  37. class TokenLookupResult:
  38. """Result of looking up an access token.
  39. Attributes:
  40. user_id: The user that this token authenticates as
  41. is_guest
  42. shadow_banned
  43. token_id: The ID of the access token looked up
  44. device_id: The device associated with the token, if any.
  45. valid_until_ms: The timestamp the token expires, if any.
  46. token_owner: The "owner" of the token. This is either the same as the
  47. user, or a server admin who is logged in as the user.
  48. """
  49. user_id = attr.ib(type=str)
  50. is_guest = attr.ib(type=bool, default=False)
  51. shadow_banned = attr.ib(type=bool, default=False)
  52. token_id = attr.ib(type=Optional[int], default=None)
  53. device_id = attr.ib(type=Optional[str], default=None)
  54. valid_until_ms = attr.ib(type=Optional[int], default=None)
  55. token_owner = attr.ib(type=str)
  56. # Make the token owner default to the user ID, which is the common case.
  57. @token_owner.default
  58. def _default_token_owner(self):
  59. return self.user_id
  60. class RegistrationWorkerStore(CacheInvalidationWorkerStore):
  61. def __init__(
  62. self,
  63. database: DatabasePool,
  64. db_conn: LoggingDatabaseConnection,
  65. hs: "HomeServer",
  66. ):
  67. super().__init__(database, db_conn, hs)
  68. self.config = hs.config
  69. # Note: we don't check this sequence for consistency as we'd have to
  70. # call `find_max_generated_user_id_localpart` each time, which is
  71. # expensive if there are many entries.
  72. self._user_id_seq = build_sequence_generator(
  73. db_conn,
  74. database.engine,
  75. find_max_generated_user_id_localpart,
  76. "user_id_seq",
  77. table=None,
  78. id_column=None,
  79. )
  80. self._account_validity = hs.config.account_validity
  81. if hs.config.run_background_tasks and self._account_validity.enabled:
  82. self._clock.call_later(
  83. 0.0,
  84. self._set_expiration_date_when_missing,
  85. )
  86. # Create a background job for culling expired 3PID validity tokens
  87. if hs.config.run_background_tasks:
  88. self._clock.looping_call(
  89. self.cull_expired_threepid_validation_tokens, THIRTY_MINUTES_IN_MS
  90. )
  91. @cached()
  92. async def get_user_by_id(self, user_id: str) -> Optional[Dict[str, Any]]:
  93. return await self.db_pool.simple_select_one(
  94. table="users",
  95. keyvalues={"name": user_id},
  96. retcols=[
  97. "name",
  98. "password_hash",
  99. "is_guest",
  100. "admin",
  101. "consent_version",
  102. "consent_server_notice_sent",
  103. "appservice_id",
  104. "creation_ts",
  105. "user_type",
  106. "deactivated",
  107. "shadow_banned",
  108. ],
  109. allow_none=True,
  110. desc="get_user_by_id",
  111. )
  112. async def is_trial_user(self, user_id: str) -> bool:
  113. """Checks if user is in the "trial" period, i.e. within the first
  114. N days of registration defined by `mau_trial_days` config
  115. Args:
  116. user_id: The user to check for trial status.
  117. """
  118. info = await self.get_user_by_id(user_id)
  119. if not info:
  120. return False
  121. now = self._clock.time_msec()
  122. trial_duration_ms = self.config.mau_trial_days * 24 * 60 * 60 * 1000
  123. is_trial = (now - info["creation_ts"] * 1000) < trial_duration_ms
  124. return is_trial
  125. @cached()
  126. async def get_user_by_access_token(self, token: str) -> Optional[TokenLookupResult]:
  127. """Get a user from the given access token.
  128. Args:
  129. token: The access token of a user.
  130. Returns:
  131. None, if the token did not match, otherwise a `TokenLookupResult`
  132. """
  133. return await self.db_pool.runInteraction(
  134. "get_user_by_access_token", self._query_for_auth, token
  135. )
  136. @cached()
  137. async def get_expiration_ts_for_user(self, user_id: str) -> Optional[int]:
  138. """Get the expiration timestamp for the account bearing a given user ID.
  139. Args:
  140. user_id: The ID of the user.
  141. Returns:
  142. None, if the account has no expiration timestamp, otherwise int
  143. representation of the timestamp (as a number of milliseconds since epoch).
  144. """
  145. return await self.db_pool.simple_select_one_onecol(
  146. table="account_validity",
  147. keyvalues={"user_id": user_id},
  148. retcol="expiration_ts_ms",
  149. allow_none=True,
  150. desc="get_expiration_ts_for_user",
  151. )
  152. async def is_account_expired(self, user_id: str, current_ts: int) -> bool:
  153. """
  154. Returns whether an user account is expired.
  155. Args:
  156. user_id: The user's ID
  157. current_ts: The current timestamp
  158. Returns:
  159. Whether the user account has expired
  160. """
  161. expiration_ts = await self.get_expiration_ts_for_user(user_id)
  162. return expiration_ts is not None and current_ts >= expiration_ts
  163. async def set_account_validity_for_user(
  164. self,
  165. user_id: str,
  166. expiration_ts: int,
  167. email_sent: bool,
  168. renewal_token: Optional[str] = None,
  169. ) -> None:
  170. """Updates the account validity properties of the given account, with the
  171. given values.
  172. Args:
  173. user_id: ID of the account to update properties for.
  174. expiration_ts: New expiration date, as a timestamp in milliseconds
  175. since epoch.
  176. email_sent: True means a renewal email has been sent for this account
  177. and there's no need to send another one for the current validity
  178. period.
  179. renewal_token: Renewal token the user can use to extend the validity
  180. of their account. Defaults to no token.
  181. """
  182. def set_account_validity_for_user_txn(txn):
  183. self.db_pool.simple_update_txn(
  184. txn=txn,
  185. table="account_validity",
  186. keyvalues={"user_id": user_id},
  187. updatevalues={
  188. "expiration_ts_ms": expiration_ts,
  189. "email_sent": email_sent,
  190. "renewal_token": renewal_token,
  191. },
  192. )
  193. self._invalidate_cache_and_stream(
  194. txn, self.get_expiration_ts_for_user, (user_id,)
  195. )
  196. await self.db_pool.runInteraction(
  197. "set_account_validity_for_user", set_account_validity_for_user_txn
  198. )
  199. async def set_renewal_token_for_user(
  200. self, user_id: str, renewal_token: str
  201. ) -> None:
  202. """Defines a renewal token for a given user.
  203. Args:
  204. user_id: ID of the user to set the renewal token for.
  205. renewal_token: Random unique string that will be used to renew the
  206. user's account.
  207. Raises:
  208. StoreError: The provided token is already set for another user.
  209. """
  210. await self.db_pool.simple_update_one(
  211. table="account_validity",
  212. keyvalues={"user_id": user_id},
  213. updatevalues={"renewal_token": renewal_token},
  214. desc="set_renewal_token_for_user",
  215. )
  216. async def get_user_from_renewal_token(self, renewal_token: str) -> str:
  217. """Get a user ID from a renewal token.
  218. Args:
  219. renewal_token: The renewal token to perform the lookup with.
  220. Returns:
  221. The ID of the user to which the token belongs.
  222. """
  223. return await self.db_pool.simple_select_one_onecol(
  224. table="account_validity",
  225. keyvalues={"renewal_token": renewal_token},
  226. retcol="user_id",
  227. desc="get_user_from_renewal_token",
  228. )
  229. async def get_renewal_token_for_user(self, user_id: str) -> str:
  230. """Get the renewal token associated with a given user ID.
  231. Args:
  232. user_id: The user ID to lookup a token for.
  233. Returns:
  234. The renewal token associated with this user ID.
  235. """
  236. return await self.db_pool.simple_select_one_onecol(
  237. table="account_validity",
  238. keyvalues={"user_id": user_id},
  239. retcol="renewal_token",
  240. desc="get_renewal_token_for_user",
  241. )
  242. async def get_users_expiring_soon(self) -> List[Dict[str, Any]]:
  243. """Selects users whose account will expire in the [now, now + renew_at] time
  244. window (see configuration for account_validity for information on what renew_at
  245. refers to).
  246. Returns:
  247. A list of dictionaries, each with a user ID and expiration time (in milliseconds).
  248. """
  249. def select_users_txn(txn, now_ms, renew_at):
  250. sql = (
  251. "SELECT user_id, expiration_ts_ms FROM account_validity"
  252. " WHERE email_sent = ? AND (expiration_ts_ms - ?) <= ?"
  253. )
  254. values = [False, now_ms, renew_at]
  255. txn.execute(sql, values)
  256. return self.db_pool.cursor_to_dict(txn)
  257. return await self.db_pool.runInteraction(
  258. "get_users_expiring_soon",
  259. select_users_txn,
  260. self._clock.time_msec(),
  261. self.config.account_validity.renew_at,
  262. )
  263. async def set_renewal_mail_status(self, user_id: str, email_sent: bool) -> None:
  264. """Sets or unsets the flag that indicates whether a renewal email has been sent
  265. to the user (and the user hasn't renewed their account yet).
  266. Args:
  267. user_id: ID of the user to set/unset the flag for.
  268. email_sent: Flag which indicates whether a renewal email has been sent
  269. to this user.
  270. """
  271. await self.db_pool.simple_update_one(
  272. table="account_validity",
  273. keyvalues={"user_id": user_id},
  274. updatevalues={"email_sent": email_sent},
  275. desc="set_renewal_mail_status",
  276. )
  277. async def delete_account_validity_for_user(self, user_id: str) -> None:
  278. """Deletes the entry for the given user in the account validity table, removing
  279. their expiration date and renewal token.
  280. Args:
  281. user_id: ID of the user to remove from the account validity table.
  282. """
  283. await self.db_pool.simple_delete_one(
  284. table="account_validity",
  285. keyvalues={"user_id": user_id},
  286. desc="delete_account_validity_for_user",
  287. )
  288. async def is_server_admin(self, user: UserID) -> bool:
  289. """Determines if a user is an admin of this homeserver.
  290. Args:
  291. user: user ID of the user to test
  292. Returns:
  293. true iff the user is a server admin, false otherwise.
  294. """
  295. res = await self.db_pool.simple_select_one_onecol(
  296. table="users",
  297. keyvalues={"name": user.to_string()},
  298. retcol="admin",
  299. allow_none=True,
  300. desc="is_server_admin",
  301. )
  302. return bool(res) if res else False
  303. async def set_server_admin(self, user: UserID, admin: bool) -> None:
  304. """Sets whether a user is an admin of this homeserver.
  305. Args:
  306. user: user ID of the user to test
  307. admin: true iff the user is to be a server admin, false otherwise.
  308. """
  309. def set_server_admin_txn(txn):
  310. self.db_pool.simple_update_one_txn(
  311. txn, "users", {"name": user.to_string()}, {"admin": 1 if admin else 0}
  312. )
  313. self._invalidate_cache_and_stream(
  314. txn, self.get_user_by_id, (user.to_string(),)
  315. )
  316. await self.db_pool.runInteraction("set_server_admin", set_server_admin_txn)
  317. async def set_shadow_banned(self, user: UserID, shadow_banned: bool) -> None:
  318. """Sets whether a user shadow-banned.
  319. Args:
  320. user: user ID of the user to test
  321. shadow_banned: true iff the user is to be shadow-banned, false otherwise.
  322. """
  323. def set_shadow_banned_txn(txn):
  324. user_id = user.to_string()
  325. self.db_pool.simple_update_one_txn(
  326. txn,
  327. table="users",
  328. keyvalues={"name": user_id},
  329. updatevalues={"shadow_banned": shadow_banned},
  330. )
  331. # In order for this to apply immediately, clear the cache for this user.
  332. tokens = self.db_pool.simple_select_onecol_txn(
  333. txn,
  334. table="access_tokens",
  335. keyvalues={"user_id": user_id},
  336. retcol="token",
  337. )
  338. for token in tokens:
  339. self._invalidate_cache_and_stream(
  340. txn, self.get_user_by_access_token, (token,)
  341. )
  342. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  343. await self.db_pool.runInteraction("set_shadow_banned", set_shadow_banned_txn)
  344. def _query_for_auth(self, txn, token: str) -> Optional[TokenLookupResult]:
  345. sql = """
  346. SELECT users.name as user_id,
  347. users.is_guest,
  348. users.shadow_banned,
  349. access_tokens.id as token_id,
  350. access_tokens.device_id,
  351. access_tokens.valid_until_ms,
  352. access_tokens.user_id as token_owner
  353. FROM users
  354. INNER JOIN access_tokens on users.name = COALESCE(puppets_user_id, access_tokens.user_id)
  355. WHERE token = ?
  356. """
  357. txn.execute(sql, (token,))
  358. rows = self.db_pool.cursor_to_dict(txn)
  359. if rows:
  360. return TokenLookupResult(**rows[0])
  361. return None
  362. @cached()
  363. async def is_real_user(self, user_id: str) -> bool:
  364. """Determines if the user is a real user, ie does not have a 'user_type'.
  365. Args:
  366. user_id: user id to test
  367. Returns:
  368. True if user 'user_type' is null or empty string
  369. """
  370. return await self.db_pool.runInteraction(
  371. "is_real_user", self.is_real_user_txn, user_id
  372. )
  373. @cached()
  374. async def is_support_user(self, user_id: str) -> bool:
  375. """Determines if the user is of type UserTypes.SUPPORT
  376. Args:
  377. user_id: user id to test
  378. Returns:
  379. True if user is of type UserTypes.SUPPORT
  380. """
  381. return await self.db_pool.runInteraction(
  382. "is_support_user", self.is_support_user_txn, user_id
  383. )
  384. def is_real_user_txn(self, txn, user_id):
  385. res = self.db_pool.simple_select_one_onecol_txn(
  386. txn=txn,
  387. table="users",
  388. keyvalues={"name": user_id},
  389. retcol="user_type",
  390. allow_none=True,
  391. )
  392. return res is None
  393. def is_support_user_txn(self, txn, user_id):
  394. res = self.db_pool.simple_select_one_onecol_txn(
  395. txn=txn,
  396. table="users",
  397. keyvalues={"name": user_id},
  398. retcol="user_type",
  399. allow_none=True,
  400. )
  401. return True if res == UserTypes.SUPPORT else False
  402. async def get_users_by_id_case_insensitive(self, user_id: str) -> Dict[str, str]:
  403. """Gets users that match user_id case insensitively.
  404. Returns:
  405. A mapping of user_id -> password_hash.
  406. """
  407. def f(txn):
  408. sql = "SELECT name, password_hash FROM users WHERE lower(name) = lower(?)"
  409. txn.execute(sql, (user_id,))
  410. return dict(txn)
  411. return await self.db_pool.runInteraction("get_users_by_id_case_insensitive", f)
  412. async def record_user_external_id(
  413. self, auth_provider: str, external_id: str, user_id: str
  414. ) -> None:
  415. """Record a mapping from an external user id to a mxid
  416. Args:
  417. auth_provider: identifier for the remote auth provider
  418. external_id: id on that system
  419. user_id: complete mxid that it is mapped to
  420. """
  421. await self.db_pool.simple_insert(
  422. table="user_external_ids",
  423. values={
  424. "auth_provider": auth_provider,
  425. "external_id": external_id,
  426. "user_id": user_id,
  427. },
  428. desc="record_user_external_id",
  429. )
  430. async def get_user_by_external_id(
  431. self, auth_provider: str, external_id: str
  432. ) -> Optional[str]:
  433. """Look up a user by their external auth id
  434. Args:
  435. auth_provider: identifier for the remote auth provider
  436. external_id: id on that system
  437. Returns:
  438. the mxid of the user, or None if they are not known
  439. """
  440. return await self.db_pool.simple_select_one_onecol(
  441. table="user_external_ids",
  442. keyvalues={"auth_provider": auth_provider, "external_id": external_id},
  443. retcol="user_id",
  444. allow_none=True,
  445. desc="get_user_by_external_id",
  446. )
  447. async def get_external_ids_by_user(self, mxid: str) -> List[Tuple[str, str]]:
  448. """Look up external ids for the given user
  449. Args:
  450. mxid: the MXID to be looked up
  451. Returns:
  452. Tuples of (auth_provider, external_id)
  453. """
  454. res = await self.db_pool.simple_select_list(
  455. table="user_external_ids",
  456. keyvalues={"user_id": mxid},
  457. retcols=("auth_provider", "external_id"),
  458. desc="get_external_ids_by_user",
  459. )
  460. return [(r["auth_provider"], r["external_id"]) for r in res]
  461. async def count_all_users(self):
  462. """Counts all users registered on the homeserver."""
  463. def _count_users(txn):
  464. txn.execute("SELECT COUNT(*) AS users FROM users")
  465. rows = self.db_pool.cursor_to_dict(txn)
  466. if rows:
  467. return rows[0]["users"]
  468. return 0
  469. return await self.db_pool.runInteraction("count_users", _count_users)
  470. async def count_daily_user_type(self) -> Dict[str, int]:
  471. """
  472. Counts 1) native non guest users
  473. 2) native guests users
  474. 3) bridged users
  475. who registered on the homeserver in the past 24 hours
  476. """
  477. def _count_daily_user_type(txn):
  478. yesterday = int(self._clock.time()) - (60 * 60 * 24)
  479. sql = """
  480. SELECT user_type, COALESCE(count(*), 0) AS count FROM (
  481. SELECT
  482. CASE
  483. WHEN is_guest=0 AND appservice_id IS NULL THEN 'native'
  484. WHEN is_guest=1 AND appservice_id IS NULL THEN 'guest'
  485. WHEN is_guest=0 AND appservice_id IS NOT NULL THEN 'bridged'
  486. END AS user_type
  487. FROM users
  488. WHERE creation_ts > ?
  489. ) AS t GROUP BY user_type
  490. """
  491. results = {"native": 0, "guest": 0, "bridged": 0}
  492. txn.execute(sql, (yesterday,))
  493. for row in txn:
  494. results[row[0]] = row[1]
  495. return results
  496. return await self.db_pool.runInteraction(
  497. "count_daily_user_type", _count_daily_user_type
  498. )
  499. async def count_nonbridged_users(self):
  500. def _count_users(txn):
  501. txn.execute(
  502. """
  503. SELECT COALESCE(COUNT(*), 0) FROM users
  504. WHERE appservice_id IS NULL
  505. """
  506. )
  507. (count,) = txn.fetchone()
  508. return count
  509. return await self.db_pool.runInteraction("count_users", _count_users)
  510. async def count_real_users(self):
  511. """Counts all users without a special user_type registered on the homeserver."""
  512. def _count_users(txn):
  513. txn.execute("SELECT COUNT(*) AS users FROM users where user_type is null")
  514. rows = self.db_pool.cursor_to_dict(txn)
  515. if rows:
  516. return rows[0]["users"]
  517. return 0
  518. return await self.db_pool.runInteraction("count_real_users", _count_users)
  519. async def generate_user_id(self) -> str:
  520. """Generate a suitable localpart for a guest user
  521. Returns: a (hopefully) free localpart
  522. """
  523. next_id = await self.db_pool.runInteraction(
  524. "generate_user_id", self._user_id_seq.get_next_id_txn
  525. )
  526. return str(next_id)
  527. async def get_user_id_by_threepid(self, medium: str, address: str) -> Optional[str]:
  528. """Returns user id from threepid
  529. Args:
  530. medium: threepid medium e.g. email
  531. address: threepid address e.g. me@example.com
  532. Returns:
  533. The user ID or None if no user id/threepid mapping exists
  534. """
  535. user_id = await self.db_pool.runInteraction(
  536. "get_user_id_by_threepid", self.get_user_id_by_threepid_txn, medium, address
  537. )
  538. return user_id
  539. def get_user_id_by_threepid_txn(self, txn, medium, address):
  540. """Returns user id from threepid
  541. Args:
  542. txn (cursor):
  543. medium (str): threepid medium e.g. email
  544. address (str): threepid address e.g. me@example.com
  545. Returns:
  546. str|None: user id or None if no user id/threepid mapping exists
  547. """
  548. ret = self.db_pool.simple_select_one_txn(
  549. txn,
  550. "user_threepids",
  551. {"medium": medium, "address": address},
  552. ["user_id"],
  553. True,
  554. )
  555. if ret:
  556. return ret["user_id"]
  557. return None
  558. async def user_add_threepid(self, user_id, medium, address, validated_at, added_at):
  559. await self.db_pool.simple_upsert(
  560. "user_threepids",
  561. {"medium": medium, "address": address},
  562. {"user_id": user_id, "validated_at": validated_at, "added_at": added_at},
  563. )
  564. async def user_get_threepids(self, user_id):
  565. return await self.db_pool.simple_select_list(
  566. "user_threepids",
  567. {"user_id": user_id},
  568. ["medium", "address", "validated_at", "added_at"],
  569. "user_get_threepids",
  570. )
  571. async def user_delete_threepid(self, user_id, medium, address) -> None:
  572. await self.db_pool.simple_delete(
  573. "user_threepids",
  574. keyvalues={"user_id": user_id, "medium": medium, "address": address},
  575. desc="user_delete_threepid",
  576. )
  577. async def user_delete_threepids(self, user_id: str) -> None:
  578. """Delete all threepid this user has bound
  579. Args:
  580. user_id: The user id to delete all threepids of
  581. """
  582. await self.db_pool.simple_delete(
  583. "user_threepids",
  584. keyvalues={"user_id": user_id},
  585. desc="user_delete_threepids",
  586. )
  587. async def add_user_bound_threepid(
  588. self, user_id: str, medium: str, address: str, id_server: str
  589. ):
  590. """The server proxied a bind request to the given identity server on
  591. behalf of the given user. We need to remember this in case the user
  592. asks us to unbind the threepid.
  593. Args:
  594. user_id
  595. medium
  596. address
  597. id_server
  598. """
  599. # We need to use an upsert, in case they user had already bound the
  600. # threepid
  601. await self.db_pool.simple_upsert(
  602. table="user_threepid_id_server",
  603. keyvalues={
  604. "user_id": user_id,
  605. "medium": medium,
  606. "address": address,
  607. "id_server": id_server,
  608. },
  609. values={},
  610. insertion_values={},
  611. desc="add_user_bound_threepid",
  612. )
  613. async def user_get_bound_threepids(self, user_id: str) -> List[Dict[str, Any]]:
  614. """Get the threepids that a user has bound to an identity server through the homeserver
  615. The homeserver remembers where binds to an identity server occurred. Using this
  616. method can retrieve those threepids.
  617. Args:
  618. user_id: The ID of the user to retrieve threepids for
  619. Returns:
  620. List of dictionaries containing the following keys:
  621. medium (str): The medium of the threepid (e.g "email")
  622. address (str): The address of the threepid (e.g "bob@example.com")
  623. """
  624. return await self.db_pool.simple_select_list(
  625. table="user_threepid_id_server",
  626. keyvalues={"user_id": user_id},
  627. retcols=["medium", "address"],
  628. desc="user_get_bound_threepids",
  629. )
  630. async def remove_user_bound_threepid(
  631. self, user_id: str, medium: str, address: str, id_server: str
  632. ) -> None:
  633. """The server proxied an unbind request to the given identity server on
  634. behalf of the given user, so we remove the mapping of threepid to
  635. identity server.
  636. Args:
  637. user_id
  638. medium
  639. address
  640. id_server
  641. """
  642. await self.db_pool.simple_delete(
  643. table="user_threepid_id_server",
  644. keyvalues={
  645. "user_id": user_id,
  646. "medium": medium,
  647. "address": address,
  648. "id_server": id_server,
  649. },
  650. desc="remove_user_bound_threepid",
  651. )
  652. async def get_id_servers_user_bound(
  653. self, user_id: str, medium: str, address: str
  654. ) -> List[str]:
  655. """Get the list of identity servers that the server proxied bind
  656. requests to for given user and threepid
  657. Args:
  658. user_id: The user to query for identity servers.
  659. medium: The medium to query for identity servers.
  660. address: The address to query for identity servers.
  661. Returns:
  662. A list of identity servers
  663. """
  664. return await self.db_pool.simple_select_onecol(
  665. table="user_threepid_id_server",
  666. keyvalues={"user_id": user_id, "medium": medium, "address": address},
  667. retcol="id_server",
  668. desc="get_id_servers_user_bound",
  669. )
  670. @cached()
  671. async def get_user_deactivated_status(self, user_id: str) -> bool:
  672. """Retrieve the value for the `deactivated` property for the provided user.
  673. Args:
  674. user_id: The ID of the user to retrieve the status for.
  675. Returns:
  676. True if the user was deactivated, false if the user is still active.
  677. """
  678. res = await self.db_pool.simple_select_one_onecol(
  679. table="users",
  680. keyvalues={"name": user_id},
  681. retcol="deactivated",
  682. desc="get_user_deactivated_status",
  683. )
  684. # Convert the integer into a boolean.
  685. return res == 1
  686. async def get_threepid_validation_session(
  687. self,
  688. medium: Optional[str],
  689. client_secret: str,
  690. address: Optional[str] = None,
  691. sid: Optional[str] = None,
  692. validated: Optional[bool] = True,
  693. ) -> Optional[Dict[str, Any]]:
  694. """Gets a session_id and last_send_attempt (if available) for a
  695. combination of validation metadata
  696. Args:
  697. medium: The medium of the 3PID
  698. client_secret: A unique string provided by the client to help identify this
  699. validation attempt
  700. address: The address of the 3PID
  701. sid: The ID of the validation session
  702. validated: Whether sessions should be filtered by
  703. whether they have been validated already or not. None to
  704. perform no filtering
  705. Returns:
  706. A dict containing the following:
  707. * address - address of the 3pid
  708. * medium - medium of the 3pid
  709. * client_secret - a secret provided by the client for this validation session
  710. * session_id - ID of the validation session
  711. * send_attempt - a number serving to dedupe send attempts for this session
  712. * validated_at - timestamp of when this session was validated if so
  713. Otherwise None if a validation session is not found
  714. """
  715. if not client_secret:
  716. raise SynapseError(
  717. 400, "Missing parameter: client_secret", errcode=Codes.MISSING_PARAM
  718. )
  719. keyvalues = {"client_secret": client_secret}
  720. if medium:
  721. keyvalues["medium"] = medium
  722. if address:
  723. keyvalues["address"] = address
  724. if sid:
  725. keyvalues["session_id"] = sid
  726. assert address or sid
  727. def get_threepid_validation_session_txn(txn):
  728. sql = """
  729. SELECT address, session_id, medium, client_secret,
  730. last_send_attempt, validated_at
  731. FROM threepid_validation_session WHERE %s
  732. """ % (
  733. " AND ".join("%s = ?" % k for k in keyvalues.keys()),
  734. )
  735. if validated is not None:
  736. sql += " AND validated_at IS " + ("NOT NULL" if validated else "NULL")
  737. sql += " LIMIT 1"
  738. txn.execute(sql, list(keyvalues.values()))
  739. rows = self.db_pool.cursor_to_dict(txn)
  740. if not rows:
  741. return None
  742. return rows[0]
  743. return await self.db_pool.runInteraction(
  744. "get_threepid_validation_session", get_threepid_validation_session_txn
  745. )
  746. async def delete_threepid_session(self, session_id: str) -> None:
  747. """Removes a threepid validation session from the database. This can
  748. be done after validation has been performed and whatever action was
  749. waiting on it has been carried out
  750. Args:
  751. session_id: The ID of the session to delete
  752. """
  753. def delete_threepid_session_txn(txn):
  754. self.db_pool.simple_delete_txn(
  755. txn,
  756. table="threepid_validation_token",
  757. keyvalues={"session_id": session_id},
  758. )
  759. self.db_pool.simple_delete_txn(
  760. txn,
  761. table="threepid_validation_session",
  762. keyvalues={"session_id": session_id},
  763. )
  764. await self.db_pool.runInteraction(
  765. "delete_threepid_session", delete_threepid_session_txn
  766. )
  767. @wrap_as_background_process("cull_expired_threepid_validation_tokens")
  768. async def cull_expired_threepid_validation_tokens(self) -> None:
  769. """Remove threepid validation tokens with expiry dates that have passed"""
  770. def cull_expired_threepid_validation_tokens_txn(txn, ts):
  771. sql = """
  772. DELETE FROM threepid_validation_token WHERE
  773. expires < ?
  774. """
  775. txn.execute(sql, (ts,))
  776. await self.db_pool.runInteraction(
  777. "cull_expired_threepid_validation_tokens",
  778. cull_expired_threepid_validation_tokens_txn,
  779. self._clock.time_msec(),
  780. )
  781. @wrap_as_background_process("account_validity_set_expiration_dates")
  782. async def _set_expiration_date_when_missing(self):
  783. """
  784. Retrieves the list of registered users that don't have an expiration date, and
  785. adds an expiration date for each of them.
  786. """
  787. def select_users_with_no_expiration_date_txn(txn):
  788. """Retrieves the list of registered users with no expiration date from the
  789. database, filtering out deactivated users.
  790. """
  791. sql = (
  792. "SELECT users.name FROM users"
  793. " LEFT JOIN account_validity ON (users.name = account_validity.user_id)"
  794. " WHERE account_validity.user_id is NULL AND users.deactivated = 0;"
  795. )
  796. txn.execute(sql, [])
  797. res = self.db_pool.cursor_to_dict(txn)
  798. if res:
  799. for user in res:
  800. self.set_expiration_date_for_user_txn(
  801. txn, user["name"], use_delta=True
  802. )
  803. await self.db_pool.runInteraction(
  804. "get_users_with_no_expiration_date",
  805. select_users_with_no_expiration_date_txn,
  806. )
  807. def set_expiration_date_for_user_txn(self, txn, user_id, use_delta=False):
  808. """Sets an expiration date to the account with the given user ID.
  809. Args:
  810. user_id (str): User ID to set an expiration date for.
  811. use_delta (bool): If set to False, the expiration date for the user will be
  812. now + validity period. If set to True, this expiration date will be a
  813. random value in the [now + period - d ; now + period] range, d being a
  814. delta equal to 10% of the validity period.
  815. """
  816. now_ms = self._clock.time_msec()
  817. expiration_ts = now_ms + self._account_validity.period
  818. if use_delta:
  819. expiration_ts = self.rand.randrange(
  820. expiration_ts - self._account_validity.startup_job_max_delta,
  821. expiration_ts,
  822. )
  823. self.db_pool.simple_upsert_txn(
  824. txn,
  825. "account_validity",
  826. keyvalues={"user_id": user_id},
  827. values={"expiration_ts_ms": expiration_ts, "email_sent": False},
  828. )
  829. async def get_user_pending_deactivation(self) -> Optional[str]:
  830. """
  831. Gets one user from the table of users waiting to be parted from all the rooms
  832. they're in.
  833. """
  834. return await self.db_pool.simple_select_one_onecol(
  835. "users_pending_deactivation",
  836. keyvalues={},
  837. retcol="user_id",
  838. allow_none=True,
  839. desc="get_users_pending_deactivation",
  840. )
  841. async def del_user_pending_deactivation(self, user_id: str) -> None:
  842. """
  843. Removes the given user to the table of users who need to be parted from all the
  844. rooms they're in, effectively marking that user as fully deactivated.
  845. """
  846. # XXX: This should be simple_delete_one but we failed to put a unique index on
  847. # the table, so somehow duplicate entries have ended up in it.
  848. await self.db_pool.simple_delete(
  849. "users_pending_deactivation",
  850. keyvalues={"user_id": user_id},
  851. desc="del_user_pending_deactivation",
  852. )
  853. async def get_access_token_last_validated(self, token_id: int) -> int:
  854. """Retrieves the time (in milliseconds) of the last validation of an access token.
  855. Args:
  856. token_id: The ID of the access token to update.
  857. Raises:
  858. StoreError if the access token was not found.
  859. Returns:
  860. The last validation time.
  861. """
  862. result = await self.db_pool.simple_select_one_onecol(
  863. "access_tokens", {"id": token_id}, "last_validated"
  864. )
  865. # If this token has not been validated (since starting to track this),
  866. # return 0 instead of None.
  867. return result or 0
  868. async def update_access_token_last_validated(self, token_id: int) -> None:
  869. """Updates the last time an access token was validated.
  870. Args:
  871. token_id: The ID of the access token to update.
  872. Raises:
  873. StoreError if there was a problem updating this.
  874. """
  875. now = self._clock.time_msec()
  876. await self.db_pool.simple_update_one(
  877. "access_tokens",
  878. {"id": token_id},
  879. {"last_validated": now},
  880. desc="update_access_token_last_validated",
  881. )
  882. class RegistrationBackgroundUpdateStore(RegistrationWorkerStore):
  883. def __init__(
  884. self,
  885. database: DatabasePool,
  886. db_conn: LoggingDatabaseConnection,
  887. hs: "HomeServer",
  888. ):
  889. super().__init__(database, db_conn, hs)
  890. self._clock = hs.get_clock()
  891. self.config = hs.config
  892. self.db_pool.updates.register_background_index_update(
  893. "access_tokens_device_index",
  894. index_name="access_tokens_device_id",
  895. table="access_tokens",
  896. columns=["user_id", "device_id"],
  897. )
  898. self.db_pool.updates.register_background_index_update(
  899. "users_creation_ts",
  900. index_name="users_creation_ts",
  901. table="users",
  902. columns=["creation_ts"],
  903. )
  904. # we no longer use refresh tokens, but it's possible that some people
  905. # might have a background update queued to build this index. Just
  906. # clear the background update.
  907. self.db_pool.updates.register_noop_background_update(
  908. "refresh_tokens_device_index"
  909. )
  910. self.db_pool.updates.register_background_update_handler(
  911. "user_threepids_grandfather", self._bg_user_threepids_grandfather
  912. )
  913. self.db_pool.updates.register_background_update_handler(
  914. "users_set_deactivated_flag", self._background_update_set_deactivated_flag
  915. )
  916. self.db_pool.updates.register_background_index_update(
  917. "user_external_ids_user_id_idx",
  918. index_name="user_external_ids_user_id_idx",
  919. table="user_external_ids",
  920. columns=["user_id"],
  921. unique=False,
  922. )
  923. async def _background_update_set_deactivated_flag(self, progress, batch_size):
  924. """Retrieves a list of all deactivated users and sets the 'deactivated' flag to 1
  925. for each of them.
  926. """
  927. last_user = progress.get("user_id", "")
  928. def _background_update_set_deactivated_flag_txn(txn):
  929. txn.execute(
  930. """
  931. SELECT
  932. users.name,
  933. COUNT(access_tokens.token) AS count_tokens,
  934. COUNT(user_threepids.address) AS count_threepids
  935. FROM users
  936. LEFT JOIN access_tokens ON (access_tokens.user_id = users.name)
  937. LEFT JOIN user_threepids ON (user_threepids.user_id = users.name)
  938. WHERE (users.password_hash IS NULL OR users.password_hash = '')
  939. AND (users.appservice_id IS NULL OR users.appservice_id = '')
  940. AND users.is_guest = 0
  941. AND users.name > ?
  942. GROUP BY users.name
  943. ORDER BY users.name ASC
  944. LIMIT ?;
  945. """,
  946. (last_user, batch_size),
  947. )
  948. rows = self.db_pool.cursor_to_dict(txn)
  949. if not rows:
  950. return True, 0
  951. rows_processed_nb = 0
  952. for user in rows:
  953. if not user["count_tokens"] and not user["count_threepids"]:
  954. self.set_user_deactivated_status_txn(txn, user["name"], True)
  955. rows_processed_nb += 1
  956. logger.info("Marked %d rows as deactivated", rows_processed_nb)
  957. self.db_pool.updates._background_update_progress_txn(
  958. txn, "users_set_deactivated_flag", {"user_id": rows[-1]["name"]}
  959. )
  960. if batch_size > len(rows):
  961. return True, len(rows)
  962. else:
  963. return False, len(rows)
  964. end, nb_processed = await self.db_pool.runInteraction(
  965. "users_set_deactivated_flag", _background_update_set_deactivated_flag_txn
  966. )
  967. if end:
  968. await self.db_pool.updates._end_background_update(
  969. "users_set_deactivated_flag"
  970. )
  971. return nb_processed
  972. async def _bg_user_threepids_grandfather(self, progress, batch_size):
  973. """We now track which identity servers a user binds their 3PID to, so
  974. we need to handle the case of existing bindings where we didn't track
  975. this.
  976. We do this by grandfathering in existing user threepids assuming that
  977. they used one of the server configured trusted identity servers.
  978. """
  979. id_servers = set(self.config.trusted_third_party_id_servers)
  980. def _bg_user_threepids_grandfather_txn(txn):
  981. sql = """
  982. INSERT INTO user_threepid_id_server
  983. (user_id, medium, address, id_server)
  984. SELECT user_id, medium, address, ?
  985. FROM user_threepids
  986. """
  987. txn.execute_batch(sql, [(id_server,) for id_server in id_servers])
  988. if id_servers:
  989. await self.db_pool.runInteraction(
  990. "_bg_user_threepids_grandfather", _bg_user_threepids_grandfather_txn
  991. )
  992. await self.db_pool.updates._end_background_update("user_threepids_grandfather")
  993. return 1
  994. async def set_user_deactivated_status(
  995. self, user_id: str, deactivated: bool
  996. ) -> None:
  997. """Set the `deactivated` property for the provided user to the provided value.
  998. Args:
  999. user_id: The ID of the user to set the status for.
  1000. deactivated: The value to set for `deactivated`.
  1001. """
  1002. await self.db_pool.runInteraction(
  1003. "set_user_deactivated_status",
  1004. self.set_user_deactivated_status_txn,
  1005. user_id,
  1006. deactivated,
  1007. )
  1008. def set_user_deactivated_status_txn(self, txn, user_id: str, deactivated: bool):
  1009. self.db_pool.simple_update_one_txn(
  1010. txn=txn,
  1011. table="users",
  1012. keyvalues={"name": user_id},
  1013. updatevalues={"deactivated": 1 if deactivated else 0},
  1014. )
  1015. self._invalidate_cache_and_stream(
  1016. txn, self.get_user_deactivated_status, (user_id,)
  1017. )
  1018. txn.call_after(self.is_guest.invalidate, (user_id,))
  1019. @cached()
  1020. async def is_guest(self, user_id: str) -> bool:
  1021. res = await self.db_pool.simple_select_one_onecol(
  1022. table="users",
  1023. keyvalues={"name": user_id},
  1024. retcol="is_guest",
  1025. allow_none=True,
  1026. desc="is_guest",
  1027. )
  1028. return res if res else False
  1029. class RegistrationStore(StatsStore, RegistrationBackgroundUpdateStore):
  1030. def __init__(self, database: DatabasePool, db_conn: Connection, hs: "HomeServer"):
  1031. super().__init__(database, db_conn, hs)
  1032. self._ignore_unknown_session_error = hs.config.request_token_inhibit_3pid_errors
  1033. self._access_tokens_id_gen = IdGenerator(db_conn, "access_tokens", "id")
  1034. async def add_access_token_to_user(
  1035. self,
  1036. user_id: str,
  1037. token: str,
  1038. device_id: Optional[str],
  1039. valid_until_ms: Optional[int],
  1040. puppets_user_id: Optional[str] = None,
  1041. ) -> int:
  1042. """Adds an access token for the given user.
  1043. Args:
  1044. user_id: The user ID.
  1045. token: The new access token to add.
  1046. device_id: ID of the device to associate with the access token
  1047. valid_until_ms: when the token is valid until. None for no expiry.
  1048. Raises:
  1049. StoreError if there was a problem adding this.
  1050. Returns:
  1051. The token ID
  1052. """
  1053. next_id = self._access_tokens_id_gen.get_next()
  1054. now = self._clock.time_msec()
  1055. await self.db_pool.simple_insert(
  1056. "access_tokens",
  1057. {
  1058. "id": next_id,
  1059. "user_id": user_id,
  1060. "token": token,
  1061. "device_id": device_id,
  1062. "valid_until_ms": valid_until_ms,
  1063. "puppets_user_id": puppets_user_id,
  1064. "last_validated": now,
  1065. },
  1066. desc="add_access_token_to_user",
  1067. )
  1068. return next_id
  1069. def _set_device_for_access_token_txn(self, txn, token: str, device_id: str) -> str:
  1070. old_device_id = self.db_pool.simple_select_one_onecol_txn(
  1071. txn, "access_tokens", {"token": token}, "device_id"
  1072. )
  1073. self.db_pool.simple_update_txn(
  1074. txn, "access_tokens", {"token": token}, {"device_id": device_id}
  1075. )
  1076. self._invalidate_cache_and_stream(txn, self.get_user_by_access_token, (token,))
  1077. return old_device_id
  1078. async def set_device_for_access_token(self, token: str, device_id: str) -> str:
  1079. """Sets the device ID associated with an access token.
  1080. Args:
  1081. token: The access token to modify.
  1082. device_id: The new device ID.
  1083. Returns:
  1084. The old device ID associated with the access token.
  1085. """
  1086. return await self.db_pool.runInteraction(
  1087. "set_device_for_access_token",
  1088. self._set_device_for_access_token_txn,
  1089. token,
  1090. device_id,
  1091. )
  1092. async def register_user(
  1093. self,
  1094. user_id: str,
  1095. password_hash: Optional[str] = None,
  1096. was_guest: bool = False,
  1097. make_guest: bool = False,
  1098. appservice_id: Optional[str] = None,
  1099. create_profile_with_displayname: Optional[str] = None,
  1100. admin: bool = False,
  1101. user_type: Optional[str] = None,
  1102. shadow_banned: bool = False,
  1103. ) -> None:
  1104. """Attempts to register an account.
  1105. Args:
  1106. user_id: The desired user ID to register.
  1107. password_hash: Optional. The password hash for this user.
  1108. was_guest: Whether this is a guest account being upgraded to a
  1109. non-guest account.
  1110. make_guest: True if the the new user should be guest, false to add a
  1111. regular user account.
  1112. appservice_id: The ID of the appservice registering the user.
  1113. create_profile_with_displayname: Optionally create a profile for
  1114. the user, setting their displayname to the given value
  1115. admin: is an admin user?
  1116. user_type: type of user. One of the values from api.constants.UserTypes,
  1117. or None for a normal user.
  1118. shadow_banned: Whether the user is shadow-banned, i.e. they may be
  1119. told their requests succeeded but we ignore them.
  1120. Raises:
  1121. StoreError if the user_id could not be registered.
  1122. """
  1123. await self.db_pool.runInteraction(
  1124. "register_user",
  1125. self._register_user,
  1126. user_id,
  1127. password_hash,
  1128. was_guest,
  1129. make_guest,
  1130. appservice_id,
  1131. create_profile_with_displayname,
  1132. admin,
  1133. user_type,
  1134. shadow_banned,
  1135. )
  1136. def _register_user(
  1137. self,
  1138. txn,
  1139. user_id: str,
  1140. password_hash: Optional[str],
  1141. was_guest: bool,
  1142. make_guest: bool,
  1143. appservice_id: Optional[str],
  1144. create_profile_with_displayname: Optional[str],
  1145. admin: bool,
  1146. user_type: Optional[str],
  1147. shadow_banned: bool,
  1148. ):
  1149. user_id_obj = UserID.from_string(user_id)
  1150. now = int(self._clock.time())
  1151. try:
  1152. if was_guest:
  1153. # Ensure that the guest user actually exists
  1154. # ``allow_none=False`` makes this raise an exception
  1155. # if the row isn't in the database.
  1156. self.db_pool.simple_select_one_txn(
  1157. txn,
  1158. "users",
  1159. keyvalues={"name": user_id, "is_guest": 1},
  1160. retcols=("name",),
  1161. allow_none=False,
  1162. )
  1163. self.db_pool.simple_update_one_txn(
  1164. txn,
  1165. "users",
  1166. keyvalues={"name": user_id, "is_guest": 1},
  1167. updatevalues={
  1168. "password_hash": password_hash,
  1169. "upgrade_ts": now,
  1170. "is_guest": 1 if make_guest else 0,
  1171. "appservice_id": appservice_id,
  1172. "admin": 1 if admin else 0,
  1173. "user_type": user_type,
  1174. "shadow_banned": shadow_banned,
  1175. },
  1176. )
  1177. else:
  1178. self.db_pool.simple_insert_txn(
  1179. txn,
  1180. "users",
  1181. values={
  1182. "name": user_id,
  1183. "password_hash": password_hash,
  1184. "creation_ts": now,
  1185. "is_guest": 1 if make_guest else 0,
  1186. "appservice_id": appservice_id,
  1187. "admin": 1 if admin else 0,
  1188. "user_type": user_type,
  1189. "shadow_banned": shadow_banned,
  1190. },
  1191. )
  1192. except self.database_engine.module.IntegrityError:
  1193. raise StoreError(400, "User ID already taken.", errcode=Codes.USER_IN_USE)
  1194. if self._account_validity.enabled:
  1195. self.set_expiration_date_for_user_txn(txn, user_id)
  1196. if create_profile_with_displayname:
  1197. # set a default displayname serverside to avoid ugly race
  1198. # between auto-joins and clients trying to set displaynames
  1199. #
  1200. # *obviously* the 'profiles' table uses localpart for user_id
  1201. # while everything else uses the full mxid.
  1202. txn.execute(
  1203. "INSERT INTO profiles(user_id, displayname) VALUES (?,?)",
  1204. (user_id_obj.localpart, create_profile_with_displayname),
  1205. )
  1206. if self.hs.config.stats_enabled:
  1207. # we create a new completed user statistics row
  1208. # we don't strictly need current_token since this user really can't
  1209. # have any state deltas before now (as it is a new user), but still,
  1210. # we include it for completeness.
  1211. current_token = self._get_max_stream_id_in_current_state_deltas_txn(txn)
  1212. self._update_stats_delta_txn(
  1213. txn, now, "user", user_id, {}, complete_with_stream_id=current_token
  1214. )
  1215. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  1216. async def user_set_password_hash(
  1217. self, user_id: str, password_hash: Optional[str]
  1218. ) -> None:
  1219. """
  1220. NB. This does *not* evict any cache because the one use for this
  1221. removes most of the entries subsequently anyway so it would be
  1222. pointless. Use flush_user separately.
  1223. """
  1224. def user_set_password_hash_txn(txn):
  1225. self.db_pool.simple_update_one_txn(
  1226. txn, "users", {"name": user_id}, {"password_hash": password_hash}
  1227. )
  1228. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  1229. await self.db_pool.runInteraction(
  1230. "user_set_password_hash", user_set_password_hash_txn
  1231. )
  1232. async def user_set_consent_version(
  1233. self, user_id: str, consent_version: str
  1234. ) -> None:
  1235. """Updates the user table to record privacy policy consent
  1236. Args:
  1237. user_id: full mxid of the user to update
  1238. consent_version: version of the policy the user has consented to
  1239. Raises:
  1240. StoreError(404) if user not found
  1241. """
  1242. def f(txn):
  1243. self.db_pool.simple_update_one_txn(
  1244. txn,
  1245. table="users",
  1246. keyvalues={"name": user_id},
  1247. updatevalues={"consent_version": consent_version},
  1248. )
  1249. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  1250. await self.db_pool.runInteraction("user_set_consent_version", f)
  1251. async def user_set_consent_server_notice_sent(
  1252. self, user_id: str, consent_version: str
  1253. ) -> None:
  1254. """Updates the user table to record that we have sent the user a server
  1255. notice about privacy policy consent
  1256. Args:
  1257. user_id: full mxid of the user to update
  1258. consent_version: version of the policy we have notified the user about
  1259. Raises:
  1260. StoreError(404) if user not found
  1261. """
  1262. def f(txn):
  1263. self.db_pool.simple_update_one_txn(
  1264. txn,
  1265. table="users",
  1266. keyvalues={"name": user_id},
  1267. updatevalues={"consent_server_notice_sent": consent_version},
  1268. )
  1269. self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,))
  1270. await self.db_pool.runInteraction("user_set_consent_server_notice_sent", f)
  1271. async def user_delete_access_tokens(
  1272. self,
  1273. user_id: str,
  1274. except_token_id: Optional[str] = None,
  1275. device_id: Optional[str] = None,
  1276. ) -> List[Tuple[str, int, Optional[str]]]:
  1277. """
  1278. Invalidate access tokens belonging to a user
  1279. Args:
  1280. user_id: ID of user the tokens belong to
  1281. except_token_id: access_tokens ID which should *not* be deleted
  1282. device_id: ID of device the tokens are associated with.
  1283. If None, tokens associated with any device (or no device) will
  1284. be deleted
  1285. Returns:
  1286. A tuple of (token, token id, device id) for each of the deleted tokens
  1287. """
  1288. def f(txn):
  1289. keyvalues = {"user_id": user_id}
  1290. if device_id is not None:
  1291. keyvalues["device_id"] = device_id
  1292. items = keyvalues.items()
  1293. where_clause = " AND ".join(k + " = ?" for k, _ in items)
  1294. values = [v for _, v in items]
  1295. if except_token_id:
  1296. where_clause += " AND id != ?"
  1297. values.append(except_token_id)
  1298. txn.execute(
  1299. "SELECT token, id, device_id FROM access_tokens WHERE %s"
  1300. % where_clause,
  1301. values,
  1302. )
  1303. tokens_and_devices = [(r[0], r[1], r[2]) for r in txn]
  1304. for token, _, _ in tokens_and_devices:
  1305. self._invalidate_cache_and_stream(
  1306. txn, self.get_user_by_access_token, (token,)
  1307. )
  1308. txn.execute("DELETE FROM access_tokens WHERE %s" % where_clause, values)
  1309. return tokens_and_devices
  1310. return await self.db_pool.runInteraction("user_delete_access_tokens", f)
  1311. async def delete_access_token(self, access_token: str) -> None:
  1312. def f(txn):
  1313. self.db_pool.simple_delete_one_txn(
  1314. txn, table="access_tokens", keyvalues={"token": access_token}
  1315. )
  1316. self._invalidate_cache_and_stream(
  1317. txn, self.get_user_by_access_token, (access_token,)
  1318. )
  1319. await self.db_pool.runInteraction("delete_access_token", f)
  1320. async def add_user_pending_deactivation(self, user_id: str) -> None:
  1321. """
  1322. Adds a user to the table of users who need to be parted from all the rooms they're
  1323. in
  1324. """
  1325. await self.db_pool.simple_insert(
  1326. "users_pending_deactivation",
  1327. values={"user_id": user_id},
  1328. desc="add_user_pending_deactivation",
  1329. )
  1330. async def validate_threepid_session(
  1331. self, session_id: str, client_secret: str, token: str, current_ts: int
  1332. ) -> Optional[str]:
  1333. """Attempt to validate a threepid session using a token
  1334. Args:
  1335. session_id: The id of a validation session
  1336. client_secret: A unique string provided by the client to help identify
  1337. this validation attempt
  1338. token: A validation token
  1339. current_ts: The current unix time in milliseconds. Used for checking
  1340. token expiry status
  1341. Raises:
  1342. ThreepidValidationError: if a matching validation token was not found or has
  1343. expired
  1344. Returns:
  1345. A str representing a link to redirect the user to if there is one.
  1346. """
  1347. # Insert everything into a transaction in order to run atomically
  1348. def validate_threepid_session_txn(txn):
  1349. row = self.db_pool.simple_select_one_txn(
  1350. txn,
  1351. table="threepid_validation_session",
  1352. keyvalues={"session_id": session_id},
  1353. retcols=["client_secret", "validated_at"],
  1354. allow_none=True,
  1355. )
  1356. if not row:
  1357. if self._ignore_unknown_session_error:
  1358. # If we need to inhibit the error caused by an incorrect session ID,
  1359. # use None as placeholder values for the client secret and the
  1360. # validation timestamp.
  1361. # It shouldn't be an issue because they're both only checked after
  1362. # the token check, which should fail. And if it doesn't for some
  1363. # reason, the next check is on the client secret, which is NOT NULL,
  1364. # so we don't have to worry about the client secret matching by
  1365. # accident.
  1366. row = {"client_secret": None, "validated_at": None}
  1367. else:
  1368. raise ThreepidValidationError(400, "Unknown session_id")
  1369. retrieved_client_secret = row["client_secret"]
  1370. validated_at = row["validated_at"]
  1371. row = self.db_pool.simple_select_one_txn(
  1372. txn,
  1373. table="threepid_validation_token",
  1374. keyvalues={"session_id": session_id, "token": token},
  1375. retcols=["expires", "next_link"],
  1376. allow_none=True,
  1377. )
  1378. if not row:
  1379. raise ThreepidValidationError(
  1380. 400, "Validation token not found or has expired"
  1381. )
  1382. expires = row["expires"]
  1383. next_link = row["next_link"]
  1384. if retrieved_client_secret != client_secret:
  1385. raise ThreepidValidationError(
  1386. 400, "This client_secret does not match the provided session_id"
  1387. )
  1388. # If the session is already validated, no need to revalidate
  1389. if validated_at:
  1390. return next_link
  1391. if expires <= current_ts:
  1392. raise ThreepidValidationError(
  1393. 400, "This token has expired. Please request a new one"
  1394. )
  1395. # Looks good. Validate the session
  1396. self.db_pool.simple_update_txn(
  1397. txn,
  1398. table="threepid_validation_session",
  1399. keyvalues={"session_id": session_id},
  1400. updatevalues={"validated_at": self._clock.time_msec()},
  1401. )
  1402. return next_link
  1403. # Return next_link if it exists
  1404. return await self.db_pool.runInteraction(
  1405. "validate_threepid_session_txn", validate_threepid_session_txn
  1406. )
  1407. async def start_or_continue_validation_session(
  1408. self,
  1409. medium: str,
  1410. address: str,
  1411. session_id: str,
  1412. client_secret: str,
  1413. send_attempt: int,
  1414. next_link: Optional[str],
  1415. token: str,
  1416. token_expires: int,
  1417. ) -> None:
  1418. """Creates a new threepid validation session if it does not already
  1419. exist and associates a new validation token with it
  1420. Args:
  1421. medium: The medium of the 3PID
  1422. address: The address of the 3PID
  1423. session_id: The id of this validation session
  1424. client_secret: A unique string provided by the client to help
  1425. identify this validation attempt
  1426. send_attempt: The latest send_attempt on this session
  1427. next_link: The link to redirect the user to upon successful validation
  1428. token: The validation token
  1429. token_expires: The timestamp for which after the token will no
  1430. longer be valid
  1431. """
  1432. def start_or_continue_validation_session_txn(txn):
  1433. # Create or update a validation session
  1434. self.db_pool.simple_upsert_txn(
  1435. txn,
  1436. table="threepid_validation_session",
  1437. keyvalues={"session_id": session_id},
  1438. values={"last_send_attempt": send_attempt},
  1439. insertion_values={
  1440. "medium": medium,
  1441. "address": address,
  1442. "client_secret": client_secret,
  1443. },
  1444. )
  1445. # Create a new validation token with this session ID
  1446. self.db_pool.simple_insert_txn(
  1447. txn,
  1448. table="threepid_validation_token",
  1449. values={
  1450. "session_id": session_id,
  1451. "token": token,
  1452. "next_link": next_link,
  1453. "expires": token_expires,
  1454. },
  1455. )
  1456. await self.db_pool.runInteraction(
  1457. "start_or_continue_validation_session",
  1458. start_or_continue_validation_session_txn,
  1459. )
  1460. def find_max_generated_user_id_localpart(cur: Cursor) -> int:
  1461. """
  1462. Gets the localpart of the max current generated user ID.
  1463. Generated user IDs are integers, so we find the largest integer user ID
  1464. already taken and return that.
  1465. """
  1466. # We bound between '@0' and '@a' to avoid pulling the entire table
  1467. # out.
  1468. cur.execute("SELECT name FROM users WHERE '@0' <= name AND name < '@a'")
  1469. regex = re.compile(r"^@(\d+):")
  1470. max_found = 0
  1471. for (user_id,) in cur:
  1472. match = regex.search(user_id)
  1473. if match:
  1474. max_found = max(int(match.group(1)), max_found)
  1475. return max_found