e2e_room_keys.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. 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
  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.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.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.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": row["is_verified"],
  132. "session_data": json.loads(row["session_data"]),
  133. }
  134. return sessions
  135. def get_e2e_room_keys_multi(self, user_id, version, room_keys):
  136. """Get multiple room keys at a time. The difference between this function and
  137. get_e2e_room_keys is that this function can be used to retrieve
  138. multiple specific keys at a time, whereas get_e2e_room_keys is used for
  139. getting all the keys in a backup version, all the keys for a room, or a
  140. specific key.
  141. Args:
  142. user_id (str): the user whose backup we're querying
  143. version (str): the version ID of the backup we're querying about
  144. room_keys (dict[str, dict[str, iterable[str]]]): a map from
  145. room ID -> {"session": [session ids]} indicating the session IDs
  146. that we want to query
  147. Returns:
  148. Deferred[dict[str, dict[str, dict]]]: a map of room IDs to session IDs to room key
  149. """
  150. return self.db.runInteraction(
  151. "get_e2e_room_keys_multi",
  152. self._get_e2e_room_keys_multi_txn,
  153. user_id,
  154. version,
  155. room_keys,
  156. )
  157. @staticmethod
  158. def _get_e2e_room_keys_multi_txn(txn, user_id, version, room_keys):
  159. if not room_keys:
  160. return {}
  161. where_clauses = []
  162. params = [user_id, version]
  163. for room_id, room in room_keys.items():
  164. sessions = list(room["sessions"])
  165. if not sessions:
  166. continue
  167. params.append(room_id)
  168. params.extend(sessions)
  169. where_clauses.append(
  170. "(room_id = ? AND session_id IN (%s))"
  171. % (",".join(["?" for _ in sessions]),)
  172. )
  173. # check if we're actually querying something
  174. if not where_clauses:
  175. return {}
  176. sql = """
  177. SELECT room_id, session_id, first_message_index, forwarded_count,
  178. is_verified, session_data
  179. FROM e2e_room_keys
  180. WHERE user_id = ? AND version = ? AND (%s)
  181. """ % (
  182. " OR ".join(where_clauses)
  183. )
  184. txn.execute(sql, params)
  185. ret = {}
  186. for row in txn:
  187. room_id = row[0]
  188. session_id = row[1]
  189. ret.setdefault(room_id, {})
  190. ret[room_id][session_id] = {
  191. "first_message_index": row[2],
  192. "forwarded_count": row[3],
  193. "is_verified": row[4],
  194. "session_data": json.loads(row[5]),
  195. }
  196. return ret
  197. def count_e2e_room_keys(self, user_id, version):
  198. """Get the number of keys in a backup version.
  199. Args:
  200. user_id (str): the user whose backup we're querying
  201. version (str): the version ID of the backup we're querying about
  202. """
  203. return self.db.simple_select_one_onecol(
  204. table="e2e_room_keys",
  205. keyvalues={"user_id": user_id, "version": version},
  206. retcol="COUNT(*)",
  207. desc="count_e2e_room_keys",
  208. )
  209. @trace
  210. @defer.inlineCallbacks
  211. def delete_e2e_room_keys(self, user_id, version, room_id=None, session_id=None):
  212. """Bulk delete the E2E room keys for a given backup, optionally filtered to a given
  213. room or a given session.
  214. Args:
  215. user_id(str): the user whose backup we're deleting from
  216. version(str): the version ID of the backup for the set of keys we're deleting
  217. room_id(str): Optional. the ID of the room whose keys we're deleting, if any.
  218. If not specified, we delete the keys for all the rooms in the backup.
  219. session_id(str): Optional. the session whose room_key we're querying, if any.
  220. If specified, we also require the room_id to be specified.
  221. If not specified, we delete all the keys in this version of
  222. the backup (or for the specified room)
  223. Returns:
  224. A deferred of the deletion transaction
  225. """
  226. keyvalues = {"user_id": user_id, "version": int(version)}
  227. if room_id:
  228. keyvalues["room_id"] = room_id
  229. if session_id:
  230. keyvalues["session_id"] = session_id
  231. yield self.db.simple_delete(
  232. table="e2e_room_keys", keyvalues=keyvalues, desc="delete_e2e_room_keys"
  233. )
  234. @staticmethod
  235. def _get_current_version(txn, user_id):
  236. txn.execute(
  237. "SELECT MAX(version) FROM e2e_room_keys_versions "
  238. "WHERE user_id=? AND deleted=0",
  239. (user_id,),
  240. )
  241. row = txn.fetchone()
  242. if not row:
  243. raise StoreError(404, "No current backup version")
  244. return row[0]
  245. def get_e2e_room_keys_version_info(self, user_id, version=None):
  246. """Get info metadata about a version of our room_keys backup.
  247. Args:
  248. user_id(str): the user whose backup we're querying
  249. version(str): Optional. the version ID of the backup we're querying about
  250. If missing, we return the information about the current version.
  251. Raises:
  252. StoreError: with code 404 if there are no e2e_room_keys_versions present
  253. Returns:
  254. A deferred dict giving the info metadata for this backup version, with
  255. fields including:
  256. version(str)
  257. algorithm(str)
  258. auth_data(object): opaque dict supplied by the client
  259. etag(int): tag of the keys in the backup
  260. """
  261. def _get_e2e_room_keys_version_info_txn(txn):
  262. if version is None:
  263. this_version = self._get_current_version(txn, user_id)
  264. else:
  265. try:
  266. this_version = int(version)
  267. except ValueError:
  268. # Our versions are all ints so if we can't convert it to an integer,
  269. # it isn't there.
  270. raise StoreError(404, "No row found")
  271. result = self.db.simple_select_one_txn(
  272. txn,
  273. table="e2e_room_keys_versions",
  274. keyvalues={"user_id": user_id, "version": this_version, "deleted": 0},
  275. retcols=("version", "algorithm", "auth_data", "etag"),
  276. )
  277. result["auth_data"] = json.loads(result["auth_data"])
  278. result["version"] = str(result["version"])
  279. if result["etag"] is None:
  280. result["etag"] = 0
  281. return result
  282. return self.db.runInteraction(
  283. "get_e2e_room_keys_version_info", _get_e2e_room_keys_version_info_txn
  284. )
  285. @trace
  286. def create_e2e_room_keys_version(self, user_id, info):
  287. """Atomically creates a new version of this user's e2e_room_keys store
  288. with the given version info.
  289. Args:
  290. user_id(str): the user whose backup we're creating a version
  291. info(dict): the info about the backup version to be created
  292. Returns:
  293. A deferred string for the newly created version ID
  294. """
  295. def _create_e2e_room_keys_version_txn(txn):
  296. txn.execute(
  297. "SELECT MAX(version) FROM e2e_room_keys_versions WHERE user_id=?",
  298. (user_id,),
  299. )
  300. current_version = txn.fetchone()[0]
  301. if current_version is None:
  302. current_version = "0"
  303. new_version = str(int(current_version) + 1)
  304. self.db.simple_insert_txn(
  305. txn,
  306. table="e2e_room_keys_versions",
  307. values={
  308. "user_id": user_id,
  309. "version": new_version,
  310. "algorithm": info["algorithm"],
  311. "auth_data": json.dumps(info["auth_data"]),
  312. },
  313. )
  314. return new_version
  315. return self.db.runInteraction(
  316. "create_e2e_room_keys_version_txn", _create_e2e_room_keys_version_txn
  317. )
  318. @trace
  319. def update_e2e_room_keys_version(
  320. self, user_id, version, info=None, version_etag=None
  321. ):
  322. """Update a given backup version
  323. Args:
  324. user_id(str): the user whose backup version we're updating
  325. version(str): the version ID of the backup version we're updating
  326. info (dict): the new backup version info to store. If None, then
  327. the backup version info is not updated
  328. version_etag (Optional[int]): etag of the keys in the backup. If
  329. None, then the etag is not updated
  330. """
  331. updatevalues = {}
  332. if info is not None and "auth_data" in info:
  333. updatevalues["auth_data"] = json.dumps(info["auth_data"])
  334. if version_etag is not None:
  335. updatevalues["etag"] = version_etag
  336. if updatevalues:
  337. return self.db.simple_update(
  338. table="e2e_room_keys_versions",
  339. keyvalues={"user_id": user_id, "version": version},
  340. updatevalues=updatevalues,
  341. desc="update_e2e_room_keys_version",
  342. )
  343. @trace
  344. def delete_e2e_room_keys_version(self, user_id, version=None):
  345. """Delete a given backup version of the user's room keys.
  346. Doesn't delete their actual key data.
  347. Args:
  348. user_id(str): the user whose backup version we're deleting
  349. version(str): Optional. the version ID of the backup version we're deleting
  350. If missing, we delete the current backup version info.
  351. Raises:
  352. StoreError: with code 404 if there are no e2e_room_keys_versions present,
  353. or if the version requested doesn't exist.
  354. """
  355. def _delete_e2e_room_keys_version_txn(txn):
  356. if version is None:
  357. this_version = self._get_current_version(txn, user_id)
  358. if this_version is None:
  359. raise StoreError(404, "No current backup version")
  360. else:
  361. this_version = version
  362. self.db.simple_delete_txn(
  363. txn,
  364. table="e2e_room_keys",
  365. keyvalues={"user_id": user_id, "version": this_version},
  366. )
  367. return self.db.simple_update_one_txn(
  368. txn,
  369. table="e2e_room_keys_versions",
  370. keyvalues={"user_id": user_id, "version": this_version},
  371. updatevalues={"deleted": 1},
  372. )
  373. return self.db.runInteraction(
  374. "delete_e2e_room_keys_version", _delete_e2e_room_keys_version_txn
  375. )