From 1c91b3d4862babf5838848c251fa1bb558d6dc05 Mon Sep 17 00:00:00 2001 From: Krille Date: Thu, 19 Oct 2023 16:44:27 +0200 Subject: [PATCH] feat: Add methods to load all room keys from online key backup This makes it possible to load and sync all room keys right after the bootstrap if the app wants to do this. --- lib/encryption/key_manager.dart | 25 +++++++++++++++++++++ test/encryption/online_key_backup_test.dart | 24 ++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/lib/encryption/key_manager.dart b/lib/encryption/key_manager.dart index 435d16673..2184e6084 100644 --- a/lib/encryption/key_manager.dart +++ b/lib/encryption/key_manager.dart @@ -667,6 +667,31 @@ class KeyManager { } } + /// Loads and stores all keys from the online key backup. This may take a + /// while for older and big accounts. + Future loadAllKeys() async { + final info = await getRoomKeysBackupInfo(); + final ret = await client.getRoomKeys(info.version); + await loadFromResponse(ret); + } + + /// Loads all room keys for a single room and stores them. This may take a + /// while for older and big rooms. + Future loadAllKeysFromRoom(String roomId) async { + final info = await getRoomKeysBackupInfo(); + final ret = await client.getRoomKeysByRoomId(roomId, info.version); + final keys = RoomKeys.fromJson({ + 'rooms': { + roomId: { + 'sessions': ret.sessions.map((k, s) => MapEntry(k, s.toJson())), + }, + }, + }); + await loadFromResponse(keys); + } + + /// Loads a single key for the specified room from the online key backup + /// and stores it. Future loadSingleKey(String roomId, String sessionId) async { final info = await getRoomKeysBackupInfo(); final ret = diff --git a/test/encryption/online_key_backup_test.dart b/test/encryption/online_key_backup_test.dart index 124b19324..5183259b8 100644 --- a/test/encryption/online_key_backup_test.dart +++ b/test/encryption/online_key_backup_test.dart @@ -72,6 +72,30 @@ void main() { true); }); + test('Load all Room Keys', () async { + if (!olmEnabled) return; + const roomId = '!726s6s6q:example.com'; + const sessionId = 'ciM/JWTPrmiWPPZNkRLDPQYf9AW/I46bxyLSr+Bx5oU'; + await client.encryption!.keyManager.loadAllKeysFromRoom(roomId); + expect( + client.encryption!.keyManager + .getInboundGroupSession(roomId, sessionId) != + null, + true); + }); + + test('Load all Keys', () async { + if (!olmEnabled) return; + const roomId = '!726s6s6q:example.com'; + const sessionId = 'ciM/JWTPrmiWPPZNkRLDPQYf9AW/I46bxyLSr+Bx5oU'; + await client.encryption!.keyManager.loadAllKeys(); + expect( + client.encryption!.keyManager + .getInboundGroupSession(roomId, sessionId) != + null, + true); + }); + test('upload key', () async { if (!olmEnabled) return; final session = olm.OutboundGroupSession();