Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

440 строки
16 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 New Vector Ltd
  3. # Copyright 2019 Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from canonicaljson import json
  17. from twisted.internet import defer
  18. from synapse.api.errors import StoreError
  19. from synapse.logging.opentracing import log_kv, trace
  20. from synapse.storage._base import SQLBaseStore, db_to_json
  21. class EndToEndRoomKeyStore(SQLBaseStore):
  22. @defer.inlineCallbacks
  23. def update_e2e_room_key(self, user_id, version, room_id, session_id, room_key):
  24. """Replaces the encrypted E2E room key for a given session in a given backup
  25. Args:
  26. user_id(str): the user whose backup we're setting
  27. version(str): the version ID of the backup we're updating
  28. room_id(str): the ID of the room whose keys we're setting
  29. session_id(str): the session whose room_key we're setting
  30. room_key(dict): the room_key being set
  31. Raises:
  32. StoreError
  33. """
  34. yield self.db_pool.simple_update_one(
  35. table="e2e_room_keys",
  36. keyvalues={
  37. "user_id": user_id,
  38. "version": version,
  39. "room_id": room_id,
  40. "session_id": session_id,
  41. },
  42. updatevalues={
  43. "first_message_index": room_key["first_message_index"],
  44. "forwarded_count": room_key["forwarded_count"],
  45. "is_verified": room_key["is_verified"],
  46. "session_data": json.dumps(room_key["session_data"]),
  47. },
  48. desc="update_e2e_room_key",
  49. )
  50. @defer.inlineCallbacks
  51. def add_e2e_room_keys(self, user_id, version, room_keys):
  52. """Bulk add room keys to a given backup.
  53. Args:
  54. user_id (str): the user whose backup we're adding to
  55. version (str): the version ID of the backup for the set of keys we're adding to
  56. room_keys (iterable[(str, str, dict)]): the keys to add, in the form
  57. (roomID, sessionID, keyData)
  58. """
  59. values = []
  60. for (room_id, session_id, room_key) in room_keys:
  61. values.append(
  62. {
  63. "user_id": user_id,
  64. "version": version,
  65. "room_id": room_id,
  66. "session_id": session_id,
  67. "first_message_index": room_key["first_message_index"],
  68. "forwarded_count": room_key["forwarded_count"],
  69. "is_verified": room_key["is_verified"],
  70. "session_data": json.dumps(room_key["session_data"]),
  71. }
  72. )
  73. log_kv(
  74. {
  75. "message": "Set room key",
  76. "room_id": room_id,
  77. "session_id": session_id,
  78. "room_key": room_key,
  79. }
  80. )
  81. yield self.db_pool.simple_insert_many(
  82. table="e2e_room_keys", values=values, desc="add_e2e_room_keys"
  83. )
  84. @trace
  85. @defer.inlineCallbacks
  86. def get_e2e_room_keys(self, user_id, version, room_id=None, session_id=None):
  87. """Bulk get the E2E room keys for a given backup, optionally filtered to a given
  88. room, or a given session.
  89. Args:
  90. user_id (str): the user whose backup we're querying
  91. version (str): the version ID of the backup for the set of keys we're querying
  92. room_id (str): Optional. the ID of the room whose keys we're querying, if any.
  93. If not specified, we return the keys for all the rooms in the backup.
  94. session_id (str): Optional. the session whose room_key we're querying, if any.
  95. If specified, we also require the room_id to be specified.
  96. If not specified, we return all the keys in this version of
  97. the backup (or for the specified room)
  98. Returns:
  99. A deferred list of dicts giving the session_data and message metadata for
  100. these room keys.
  101. """
  102. try:
  103. version = int(version)
  104. except ValueError:
  105. return {"rooms": {}}
  106. keyvalues = {"user_id": user_id, "version": version}
  107. if room_id:
  108. keyvalues["room_id"] = room_id
  109. if session_id:
  110. keyvalues["session_id"] = session_id
  111. rows = yield self.db_pool.simple_select_list(
  112. table="e2e_room_keys",
  113. keyvalues=keyvalues,
  114. retcols=(
  115. "user_id",
  116. "room_id",
  117. "session_id",
  118. "first_message_index",
  119. "forwarded_count",
  120. "is_verified",
  121. "session_data",
  122. ),
  123. desc="get_e2e_room_keys",
  124. )
  125. sessions = {"rooms": {}}
  126. for row in rows:
  127. room_entry = sessions["rooms"].setdefault(row["room_id"], {"sessions": {}})
  128. room_entry["sessions"][row["session_id"]] = {
  129. "first_message_index": row["first_message_index"],
  130. "forwarded_count": row["forwarded_count"],
  131. # is_verified must be returned to the client as a boolean
  132. "is_verified": bool(row["is_verified"]),
  133. "session_data": db_to_json(row["session_data"]),
  134. }
  135. return sessions
  136. def get_e2e_room_keys_multi(self, user_id, version, room_keys):
  137. """Get multiple room keys at a time. The difference between this function and
  138. get_e2e_room_keys is that this function can be used to retrieve
  139. multiple specific keys at a time, whereas get_e2e_room_keys is used for
  140. getting all the keys in a backup version, all the keys for a room, or a
  141. specific key.
  142. Args:
  143. user_id (str): the user whose backup we're querying
  144. version (str): the version ID of the backup we're querying about
  145. room_keys (dict[str, dict[str, iterable[str]]]): a map from
  146. room ID -> {"session": [session ids]} indicating the session IDs
  147. that we want to query
  148. Returns:
  149. Deferred[dict[str, dict[str, dict]]]: a map of room IDs to session IDs to room key
  150. """
  151. return self.db_pool.runInteraction(
  152. "get_e2e_room_keys_multi",
  153. self._get_e2e_room_keys_multi_txn,
  154. user_id,
  155. version,
  156. room_keys,
  157. )
  158. @staticmethod
  159. def _get_e2e_room_keys_multi_txn(txn, user_id, version, room_keys):
  160. if not room_keys:
  161. return {}
  162. where_clauses = []
  163. params = [user_id, version]
  164. for room_id, room in room_keys.items():
  165. sessions = list(room["sessions"])
  166. if not sessions:
  167. continue
  168. params.append(room_id)
  169. params.extend(sessions)
  170. where_clauses.append(
  171. "(room_id = ? AND session_id IN (%s))"
  172. % (",".join(["?" for _ in sessions]),)
  173. )
  174. # check if we're actually querying something
  175. if not where_clauses:
  176. return {}
  177. sql = """
  178. SELECT room_id, session_id, first_message_index, forwarded_count,
  179. is_verified, session_data
  180. FROM e2e_room_keys
  181. WHERE user_id = ? AND version = ? AND (%s)
  182. """ % (
  183. " OR ".join(where_clauses)
  184. )
  185. txn.execute(sql, params)
  186. ret = {}
  187. for row in txn:
  188. room_id = row[0]
  189. session_id = row[1]
  190. ret.setdefault(room_id, {})
  191. ret[room_id][session_id] = {
  192. "first_message_index": row[2],
  193. "forwarded_count": row[3],
  194. "is_verified": row[4],
  195. "session_data": db_to_json(row[5]),
  196. }
  197. return ret
  198. def count_e2e_room_keys(self, user_id, version):
  199. """Get the number of keys in a backup version.
  200. Args:
  201. user_id (str): the user whose backup we're querying
  202. version (str): the version ID of the backup we're querying about
  203. """
  204. return self.db_pool.simple_select_one_onecol(
  205. table="e2e_room_keys",
  206. keyvalues={"user_id": user_id, "version": version},
  207. retcol="COUNT(*)",
  208. desc="count_e2e_room_keys",
  209. )
  210. @trace
  211. @defer.inlineCallbacks
  212. def delete_e2e_room_keys(self, user_id, version, room_id=None, session_id=None):
  213. """Bulk delete the E2E room keys for a given backup, optionally filtered to a given
  214. room or a given session.
  215. Args:
  216. user_id(str): the user whose backup we're deleting from
  217. version(str): the version ID of the backup for the set of keys we're deleting
  218. room_id(str): Optional. the ID of the room whose keys we're deleting, if any.
  219. If not specified, we delete the keys for all the rooms in the backup.
  220. session_id(str): Optional. the session whose room_key we're querying, if any.
  221. If specified, we also require the room_id to be specified.
  222. If not specified, we delete all the keys in this version of
  223. the backup (or for the specified room)
  224. Returns:
  225. A deferred of the deletion transaction
  226. """
  227. keyvalues = {"user_id": user_id, "version": int(version)}
  228. if room_id:
  229. keyvalues["room_id"] = room_id
  230. if session_id:
  231. keyvalues["session_id"] = session_id
  232. yield self.db_pool.simple_delete(
  233. table="e2e_room_keys", keyvalues=keyvalues, desc="delete_e2e_room_keys"
  234. )
  235. @staticmethod
  236. def _get_current_version(txn, user_id):
  237. txn.execute(
  238. "SELECT MAX(version) FROM e2e_room_keys_versions "
  239. "WHERE user_id=? AND deleted=0",
  240. (user_id,),
  241. )
  242. row = txn.fetchone()
  243. if not row:
  244. raise StoreError(404, "No current backup version")
  245. return row[0]
  246. def get_e2e_room_keys_version_info(self, user_id, version=None):
  247. """Get info metadata about a version of our room_keys backup.
  248. Args:
  249. user_id(str): the user whose backup we're querying
  250. version(str): Optional. the version ID of the backup we're querying about
  251. If missing, we return the information about the current version.
  252. Raises:
  253. StoreError: with code 404 if there are no e2e_room_keys_versions present
  254. Returns:
  255. A deferred dict giving the info metadata for this backup version, with
  256. fields including:
  257. version(str)
  258. algorithm(str)
  259. auth_data(object): opaque dict supplied by the client
  260. etag(int): tag of the keys in the backup
  261. """
  262. def _get_e2e_room_keys_version_info_txn(txn):
  263. if version is None:
  264. this_version = self._get_current_version(txn, user_id)
  265. else:
  266. try:
  267. this_version = int(version)
  268. except ValueError:
  269. # Our versions are all ints so if we can't convert it to an integer,
  270. # it isn't there.
  271. raise StoreError(404, "No row found")
  272. result = self.db_pool.simple_select_one_txn(
  273. txn,
  274. table="e2e_room_keys_versions",
  275. keyvalues={"user_id": user_id, "version": this_version, "deleted": 0},
  276. retcols=("version", "algorithm", "auth_data", "etag"),
  277. )
  278. result["auth_data"] = db_to_json(result["auth_data"])
  279. result["version"] = str(result["version"])
  280. if result["etag"] is None:
  281. result["etag"] = 0
  282. return result
  283. return self.db_pool.runInteraction(
  284. "get_e2e_room_keys_version_info", _get_e2e_room_keys_version_info_txn
  285. )
  286. @trace
  287. def create_e2e_room_keys_version(self, user_id, info):
  288. """Atomically creates a new version of this user's e2e_room_keys store
  289. with the given version info.
  290. Args:
  291. user_id(str): the user whose backup we're creating a version
  292. info(dict): the info about the backup version to be created
  293. Returns:
  294. A deferred string for the newly created version ID
  295. """
  296. def _create_e2e_room_keys_version_txn(txn):
  297. txn.execute(
  298. "SELECT MAX(version) FROM e2e_room_keys_versions WHERE user_id=?",
  299. (user_id,),
  300. )
  301. current_version = txn.fetchone()[0]
  302. if current_version is None:
  303. current_version = "0"
  304. new_version = str(int(current_version) + 1)
  305. self.db_pool.simple_insert_txn(
  306. txn,
  307. table="e2e_room_keys_versions",
  308. values={
  309. "user_id": user_id,
  310. "version": new_version,
  311. "algorithm": info["algorithm"],
  312. "auth_data": json.dumps(info["auth_data"]),
  313. },
  314. )
  315. return new_version
  316. return self.db_pool.runInteraction(
  317. "create_e2e_room_keys_version_txn", _create_e2e_room_keys_version_txn
  318. )
  319. @trace
  320. def update_e2e_room_keys_version(
  321. self, user_id, version, info=None, version_etag=None
  322. ):
  323. """Update a given backup version
  324. Args:
  325. user_id(str): the user whose backup version we're updating
  326. version(str): the version ID of the backup version we're updating
  327. info (dict): the new backup version info to store. If None, then
  328. the backup version info is not updated
  329. version_etag (Optional[int]): etag of the keys in the backup. If
  330. None, then the etag is not updated
  331. """
  332. updatevalues = {}
  333. if info is not None and "auth_data" in info:
  334. updatevalues["auth_data"] = json.dumps(info["auth_data"])
  335. if version_etag is not None:
  336. updatevalues["etag"] = version_etag
  337. if updatevalues:
  338. return self.db_pool.simple_update(
  339. table="e2e_room_keys_versions",
  340. keyvalues={"user_id": user_id, "version": version},
  341. updatevalues=updatevalues,
  342. desc="update_e2e_room_keys_version",
  343. )
  344. @trace
  345. def delete_e2e_room_keys_version(self, user_id, version=None):
  346. """Delete a given backup version of the user's room keys.
  347. Doesn't delete their actual key data.
  348. Args:
  349. user_id(str): the user whose backup version we're deleting
  350. version(str): Optional. the version ID of the backup version we're deleting
  351. If missing, we delete the current backup version info.
  352. Raises:
  353. StoreError: with code 404 if there are no e2e_room_keys_versions present,
  354. or if the version requested doesn't exist.
  355. """
  356. def _delete_e2e_room_keys_version_txn(txn):
  357. if version is None:
  358. this_version = self._get_current_version(txn, user_id)
  359. if this_version is None:
  360. raise StoreError(404, "No current backup version")
  361. else:
  362. this_version = version
  363. self.db_pool.simple_delete_txn(
  364. txn,
  365. table="e2e_room_keys",
  366. keyvalues={"user_id": user_id, "version": this_version},
  367. )
  368. return self.db_pool.simple_update_one_txn(
  369. txn,
  370. table="e2e_room_keys_versions",
  371. keyvalues={"user_id": user_id, "version": this_version},
  372. updatevalues={"deleted": 1},
  373. )
  374. return self.db_pool.runInteraction(
  375. "delete_e2e_room_keys_version", _delete_e2e_room_keys_version_txn
  376. )