end_to_end_keys.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import collections
  16. import twisted.internet.defer
  17. from ._base import SQLBaseStore
  18. class EndToEndKeyStore(SQLBaseStore):
  19. def set_e2e_device_keys(self, user_id, device_id, time_now, json_bytes):
  20. return self._simple_upsert(
  21. table="e2e_device_keys_json",
  22. keyvalues={
  23. "user_id": user_id,
  24. "device_id": device_id,
  25. },
  26. values={
  27. "ts_added_ms": time_now,
  28. "key_json": json_bytes,
  29. }
  30. )
  31. def get_e2e_device_keys(self, query_list):
  32. """Fetch a list of device keys.
  33. Args:
  34. query_list(list): List of pairs of user_ids and device_ids.
  35. Returns:
  36. Dict mapping from user-id to dict mapping from device_id to
  37. dict containing "key_json", "device_display_name".
  38. """
  39. if not query_list:
  40. return {}
  41. return self.runInteraction(
  42. "get_e2e_device_keys", self._get_e2e_device_keys_txn, query_list
  43. )
  44. def _get_e2e_device_keys_txn(self, txn, query_list):
  45. query_clauses = []
  46. query_params = []
  47. for (user_id, device_id) in query_list:
  48. query_clause = "k.user_id = ?"
  49. query_params.append(user_id)
  50. if device_id:
  51. query_clause += " AND k.device_id = ?"
  52. query_params.append(device_id)
  53. query_clauses.append(query_clause)
  54. sql = (
  55. "SELECT k.user_id, k.device_id, "
  56. " d.display_name AS device_display_name, "
  57. " k.key_json"
  58. " FROM e2e_device_keys_json k"
  59. " LEFT JOIN devices d ON d.user_id = k.user_id"
  60. " AND d.device_id = k.device_id"
  61. " WHERE %s"
  62. ) % (
  63. " OR ".join("(" + q + ")" for q in query_clauses)
  64. )
  65. txn.execute(sql, query_params)
  66. rows = self.cursor_to_dict(txn)
  67. result = collections.defaultdict(dict)
  68. for row in rows:
  69. result[row["user_id"]][row["device_id"]] = row
  70. return result
  71. def add_e2e_one_time_keys(self, user_id, device_id, time_now, key_list):
  72. def _add_e2e_one_time_keys(txn):
  73. for (algorithm, key_id, json_bytes) in key_list:
  74. self._simple_upsert_txn(
  75. txn, table="e2e_one_time_keys_json",
  76. keyvalues={
  77. "user_id": user_id,
  78. "device_id": device_id,
  79. "algorithm": algorithm,
  80. "key_id": key_id,
  81. },
  82. values={
  83. "ts_added_ms": time_now,
  84. "key_json": json_bytes,
  85. }
  86. )
  87. return self.runInteraction(
  88. "add_e2e_one_time_keys", _add_e2e_one_time_keys
  89. )
  90. def count_e2e_one_time_keys(self, user_id, device_id):
  91. """ Count the number of one time keys the server has for a device
  92. Returns:
  93. Dict mapping from algorithm to number of keys for that algorithm.
  94. """
  95. def _count_e2e_one_time_keys(txn):
  96. sql = (
  97. "SELECT algorithm, COUNT(key_id) FROM e2e_one_time_keys_json"
  98. " WHERE user_id = ? AND device_id = ?"
  99. " GROUP BY algorithm"
  100. )
  101. txn.execute(sql, (user_id, device_id))
  102. result = {}
  103. for algorithm, key_count in txn.fetchall():
  104. result[algorithm] = key_count
  105. return result
  106. return self.runInteraction(
  107. "count_e2e_one_time_keys", _count_e2e_one_time_keys
  108. )
  109. def claim_e2e_one_time_keys(self, query_list):
  110. """Take a list of one time keys out of the database"""
  111. def _claim_e2e_one_time_keys(txn):
  112. sql = (
  113. "SELECT key_id, key_json FROM e2e_one_time_keys_json"
  114. " WHERE user_id = ? AND device_id = ? AND algorithm = ?"
  115. " LIMIT 1"
  116. )
  117. result = {}
  118. delete = []
  119. for user_id, device_id, algorithm in query_list:
  120. user_result = result.setdefault(user_id, {})
  121. device_result = user_result.setdefault(device_id, {})
  122. txn.execute(sql, (user_id, device_id, algorithm))
  123. for key_id, key_json in txn.fetchall():
  124. device_result[algorithm + ":" + key_id] = key_json
  125. delete.append((user_id, device_id, algorithm, key_id))
  126. sql = (
  127. "DELETE FROM e2e_one_time_keys_json"
  128. " WHERE user_id = ? AND device_id = ? AND algorithm = ?"
  129. " AND key_id = ?"
  130. )
  131. for user_id, device_id, algorithm, key_id in delete:
  132. txn.execute(sql, (user_id, device_id, algorithm, key_id))
  133. return result
  134. return self.runInteraction(
  135. "claim_e2e_one_time_keys", _claim_e2e_one_time_keys
  136. )
  137. @twisted.internet.defer.inlineCallbacks
  138. def delete_e2e_keys_by_device(self, user_id, device_id):
  139. yield self._simple_delete(
  140. table="e2e_device_keys_json",
  141. keyvalues={"user_id": user_id, "device_id": device_id},
  142. desc="delete_e2e_device_keys_by_device"
  143. )
  144. yield self._simple_delete(
  145. table="e2e_one_time_keys_json",
  146. keyvalues={"user_id": user_id, "device_id": device_id},
  147. desc="delete_e2e_one_time_keys_by_device"
  148. )