Skip to content

Commit c030532

Browse files
committed
Create one-off scheduled task to delete old OTKs
To work around the fact that, pre-#17903, our database may have old one-time-keys that the clients have long thrown away the private keys for, we want to delete OTKs that look like they came from libolm. To spread the load a bit, without holding up other background database updates, we use a scheduled task to do the work.
1 parent e80dad5 commit c030532

File tree

5 files changed

+114
-0
lines changed

5 files changed

+114
-0
lines changed

changelog.d/17934.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add a one-off task to delete old one-time-keys, to guard against us having old OTKs in the database that the client has long forgotten about.

synapse/handlers/e2e_keys.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939
from synapse.types import (
4040
JsonDict,
4141
JsonMapping,
42+
ScheduledTask,
43+
TaskStatus,
4244
UserID,
4345
get_domain_from_id,
4446
get_verify_key_from_cross_signing_key,
@@ -70,6 +72,7 @@ def __init__(self, hs: "HomeServer"):
7072
self.is_mine = hs.is_mine
7173
self.clock = hs.get_clock()
7274
self._worker_lock_handler = hs.get_worker_locks_handler()
75+
self._task_scheduler = hs.get_task_scheduler()
7376

7477
federation_registry = hs.get_federation_registry()
7578

@@ -116,6 +119,10 @@ def __init__(self, hs: "HomeServer"):
116119
hs.config.experimental.msc3984_appservice_key_query
117120
)
118121

122+
self._task_scheduler.register_action(
123+
self._delete_old_one_time_keys_task, "delete_old_otks"
124+
)
125+
119126
@trace
120127
@cancellable
121128
async def query_devices(
@@ -1574,6 +1581,34 @@ async def has_different_keys(self, user_id: str, body: JsonDict) -> bool:
15741581
return True
15751582
return False
15761583

1584+
async def _delete_old_one_time_keys_task(
1585+
self, task: ScheduledTask
1586+
) -> Tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
1587+
"""Scheduler task to delete old one time keys.
1588+
1589+
Until Synapse 1.119, Synapse used to issue one-time-keys in a random order, leading to the possibility
1590+
that it could still have old OTKs that the client has dropped. This task is scheduled exactly once
1591+
by a database schema delta file, and it clears out old one-time-keys that look like they came from libolm.
1592+
"""
1593+
user = task.result.get("from_user", "") if task.result else ""
1594+
while True:
1595+
user, rowcount = await self.store.delete_old_otks_for_one_user(user)
1596+
if user is None:
1597+
# We're done!
1598+
return TaskStatus.COMPLETE, None, None
1599+
1600+
logger.debug("Deleted %i old one-time-keys for user '%s'", rowcount, user)
1601+
1602+
# Store our progress
1603+
await self._task_scheduler.update_task(task.id, result={"from_user": user})
1604+
1605+
# Sleep a little before doing the next user.
1606+
#
1607+
# matrix.org has about 15M users in the e2e_one_time_keys_json table
1608+
# (comprising 20M devices). We want this to take about a week, so we need
1609+
# to do 25 per second.
1610+
await self.clock.sleep(0.04)
1611+
15771612

15781613
def _check_cross_signing_key(
15791614
key: JsonDict, user_id: str, key_type: str, signing_key: Optional[VerifyKey] = None

synapse/storage/databases/main/end_to_end_keys.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1453,6 +1453,46 @@ def impl(txn: LoggingTransaction) -> Tuple[bool, Optional[int]]:
14531453
impl,
14541454
)
14551455

1456+
async def delete_old_otks_for_one_user(self, after_user_id: str) -> Tuple[Optional[str], int]:
1457+
"""Deletes old OTKs belonging to one user.
1458+
1459+
Returns:
1460+
`(user, rows)`, where:
1461+
* `user` is the user ID of the updated user, or None if we are don
1462+
* `rows` is the number of deleted rows
1463+
"""
1464+
def impl(txn: LoggingTransaction) -> Tuple[Optional[str], int]:
1465+
# Find the next user
1466+
txn.execute(
1467+
"""
1468+
SELECT user_id FROM e2e_one_time_keys_json WHERE user_id > ? LIMIT 1
1469+
""",
1470+
(after_user_id,),
1471+
)
1472+
row = txn.fetchone()
1473+
if not row:
1474+
# We're done!
1475+
return None, 0
1476+
(user_id,) = row
1477+
1478+
# Delete any old OTKs belonging to that user.
1479+
#
1480+
# We only actually consider OTKs whose key ID is 6 characters long. These
1481+
# keys were likely made by libolm rather than Vodozemac; libolm only kept
1482+
# 100 private OTKs, so was far more vulnerable than Vodozemac to throwing
1483+
# away keys prematurely.
1484+
txn.execute(
1485+
"""
1486+
DELETE FROM e2e_one_time_keys_json
1487+
WHERE user_id = ? AND ts_added_ms < ? AND length(key_id) = 6
1488+
""",
1489+
(user_id, self._clock.time_msec() - (7 * 24 * 3600 * 1000)),
1490+
)
1491+
1492+
return user_id, txn.rowcount
1493+
1494+
return await self.db_pool.runInteraction("delete_old_otks_for_one_user", impl)
1495+
14561496

14571497
class EndToEndKeyStore(EndToEndKeyWorkerStore, SQLBaseStore):
14581498
def __init__(
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
--
2+
-- This file is licensed under the Affero General Public License (AGPL) version 3.
3+
--
4+
-- Copyright (C) 2024 New Vector, Ltd
5+
--
6+
-- This program is free software: you can redistribute it and/or modify
7+
-- it under the terms of the GNU Affero General Public License as
8+
-- published by the Free Software Foundation, either version 3 of the
9+
-- License, or (at your option) any later version.
10+
--
11+
-- See the GNU Affero General Public License for more details:
12+
-- <https://www.gnu.org/licenses/agpl-3.0.html>.
13+
14+
-- Until Synapse 1.119, Synapse used to issue one-time-keys in a random order, leading to the possibility
15+
-- that it could still have old OTKs that the client has dropped.
16+
--
17+
-- We create a scheduled task which will drop old OTKs, to flush them out.
18+
INSERT INTO scheduled_tasks(id, action, status, timestamp)
19+
VALUES ('delete_old_otks_task', 'delete_old_otks', 'scheduled', extract(epoch from current_timestamp) * 1000);
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
--
2+
-- This file is licensed under the Affero General Public License (AGPL) version 3.
3+
--
4+
-- Copyright (C) 2024 New Vector, Ltd
5+
--
6+
-- This program is free software: you can redistribute it and/or modify
7+
-- it under the terms of the GNU Affero General Public License as
8+
-- published by the Free Software Foundation, either version 3 of the
9+
-- License, or (at your option) any later version.
10+
--
11+
-- See the GNU Affero General Public License for more details:
12+
-- <https://www.gnu.org/licenses/agpl-3.0.html>.
13+
14+
-- Until Synapse 1.119, Synapse used to issue one-time-keys in a random order, leading to the possibility
15+
-- that it could still have old OTKs that the client has dropped.
16+
--
17+
-- We create a scheduled task which will drop old OTKs, to flush them out.
18+
INSERT INTO scheduled_tasks(id, action, status, timestamp)
19+
VALUES ('delete_old_otks_task', 'delete_old_otks', 'scheduled', strftime('%s', 'now') * 1000);

0 commit comments

Comments
 (0)