registration.py 58 KB

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