LCOV - code coverage report
Current view: top level - lib/encryption - key_manager.dart (source / functions) Hit Total Coverage
Test: merged.info Lines: 477 550 86.7 %
Date: 2024-05-13 12:56:47 Functions: 0 0 -

          Line data    Source code
       1             : /*
       2             :  *   Famedly Matrix SDK
       3             :  *   Copyright (C) 2019, 2020, 2021 Famedly GmbH
       4             :  *
       5             :  *   This program is free software: you can redistribute it and/or modify
       6             :  *   it under the terms of the GNU Affero General Public License as
       7             :  *   published by the Free Software Foundation, either version 3 of the
       8             :  *   License, or (at your option) any later version.
       9             :  *
      10             :  *   This program is distributed in the hope that it will be useful,
      11             :  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
      12             :  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
      13             :  *   GNU Affero General Public License for more details.
      14             :  *
      15             :  *   You should have received a copy of the GNU Affero General Public License
      16             :  *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
      17             :  */
      18             : 
      19             : import 'dart:async';
      20             : import 'dart:convert';
      21             : 
      22             : import 'package:collection/collection.dart';
      23             : import 'package:olm/olm.dart' as olm;
      24             : 
      25             : import 'package:matrix/encryption/encryption.dart';
      26             : import 'package:matrix/encryption/utils/base64_unpadded.dart';
      27             : import 'package:matrix/encryption/utils/outbound_group_session.dart';
      28             : import 'package:matrix/encryption/utils/session_key.dart';
      29             : import 'package:matrix/encryption/utils/stored_inbound_group_session.dart';
      30             : import 'package:matrix/matrix.dart';
      31             : import 'package:matrix/src/utils/run_in_root.dart';
      32             : 
      33             : const megolmKey = EventTypes.MegolmBackup;
      34             : 
      35             : class KeyManager {
      36             :   final Encryption encryption;
      37             : 
      38          72 :   Client get client => encryption.client;
      39             :   final outgoingShareRequests = <String, KeyManagerKeyShareRequest>{};
      40             :   final incomingShareRequests = <String, KeyManagerKeyShareRequest>{};
      41             :   final _inboundGroupSessions = <String, Map<String, SessionKey>>{};
      42             :   final _outboundGroupSessions = <String, OutboundGroupSession>{};
      43             :   final Set<String> _loadedOutboundGroupSessions = <String>{};
      44             :   final Set<String> _requestedSessionIds = <String>{};
      45             : 
      46          24 :   KeyManager(this.encryption) {
      47          73 :     encryption.ssss.setValidator(megolmKey, (String secret) async {
      48           1 :       final keyObj = olm.PkDecryption();
      49             :       try {
      50           1 :         final info = await getRoomKeysBackupInfo(false);
      51           2 :         if (info.algorithm !=
      52             :             BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2) {
      53             :           return false;
      54             :         }
      55           3 :         return keyObj.init_with_private_key(base64decodeUnpadded(secret)) ==
      56           2 :             info.authData['public_key'];
      57             :       } catch (_) {
      58             :         return false;
      59             :       } finally {
      60           1 :         keyObj.free();
      61             :       }
      62             :     });
      63          73 :     encryption.ssss.setCacheCallback(megolmKey, (String secret) {
      64             :       // we got a megolm key cached, clear our requested keys and try to re-decrypt
      65             :       // last events
      66           2 :       _requestedSessionIds.clear();
      67           3 :       for (final room in client.rooms) {
      68           1 :         final lastEvent = room.lastEvent;
      69             :         if (lastEvent != null &&
      70           2 :             lastEvent.type == EventTypes.Encrypted &&
      71           0 :             lastEvent.content['can_request_session'] == true) {
      72           0 :           final sessionId = lastEvent.content.tryGet<String>('session_id');
      73           0 :           final senderKey = lastEvent.content.tryGet<String>('sender_key');
      74             :           if (sessionId != null && senderKey != null) {
      75           0 :             maybeAutoRequest(
      76           0 :               room.id,
      77             :               sessionId,
      78             :               senderKey,
      79             :             );
      80             :           }
      81             :         }
      82             :       }
      83             :     });
      84             :   }
      85             : 
      86          92 :   bool get enabled => encryption.ssss.isSecret(megolmKey);
      87             : 
      88             :   /// clear all cached inbound group sessions. useful for testing
      89           4 :   void clearInboundGroupSessions() {
      90           8 :     _inboundGroupSessions.clear();
      91             :   }
      92             : 
      93          23 :   Future<void> setInboundGroupSession(
      94             :     String roomId,
      95             :     String sessionId,
      96             :     String senderKey,
      97             :     Map<String, dynamic> content, {
      98             :     bool forwarded = false,
      99             :     Map<String, String>? senderClaimedKeys,
     100             :     bool uploaded = false,
     101             :     Map<String, Map<String, int>>? allowedAtIndex,
     102             :   }) async {
     103          23 :     final senderClaimedKeys_ = senderClaimedKeys ?? <String, String>{};
     104          23 :     final allowedAtIndex_ = allowedAtIndex ?? <String, Map<String, int>>{};
     105          46 :     final userId = client.userID;
     106           0 :     if (userId == null) return Future.value();
     107             : 
     108          23 :     if (!senderClaimedKeys_.containsKey('ed25519')) {
     109          46 :       final device = client.getUserDeviceKeysByCurve25519Key(senderKey);
     110           5 :       if (device != null && device.ed25519Key != null) {
     111          10 :         senderClaimedKeys_['ed25519'] = device.ed25519Key!;
     112             :       }
     113             :     }
     114          23 :     final oldSession = getInboundGroupSession(
     115             :       roomId,
     116             :       sessionId,
     117             :     );
     118          46 :     if (content['algorithm'] != AlgorithmTypes.megolmV1AesSha2) {
     119             :       return;
     120             :     }
     121             :     late olm.InboundGroupSession inboundGroupSession;
     122             :     try {
     123          23 :       inboundGroupSession = olm.InboundGroupSession();
     124             :       if (forwarded) {
     125           6 :         inboundGroupSession.import_session(content['session_key']);
     126             :       } else {
     127          46 :         inboundGroupSession.create(content['session_key']);
     128             :       }
     129             :     } catch (e, s) {
     130           0 :       inboundGroupSession.free();
     131           0 :       Logs().e('[LibOlm] Could not create new InboundGroupSession', e, s);
     132           0 :       return Future.value();
     133             :     }
     134          23 :     final newSession = SessionKey(
     135             :       content: content,
     136             :       inboundGroupSession: inboundGroupSession,
     137          23 :       indexes: {},
     138             :       roomId: roomId,
     139             :       sessionId: sessionId,
     140             :       key: userId,
     141             :       senderKey: senderKey,
     142             :       senderClaimedKeys: senderClaimedKeys_,
     143             :       allowedAtIndex: allowedAtIndex_,
     144             :     );
     145             :     final oldFirstIndex =
     146           2 :         oldSession?.inboundGroupSession?.first_known_index() ?? 0;
     147          46 :     final newFirstIndex = newSession.inboundGroupSession!.first_known_index();
     148             :     if (oldSession == null ||
     149           1 :         newFirstIndex < oldFirstIndex ||
     150           1 :         (oldFirstIndex == newFirstIndex &&
     151           3 :             newSession.forwardingCurve25519KeyChain.length <
     152           2 :                 oldSession.forwardingCurve25519KeyChain.length)) {
     153             :       // use new session
     154           1 :       oldSession?.dispose();
     155             :     } else {
     156             :       // we are gonna keep our old session
     157           1 :       newSession.dispose();
     158             :       return;
     159             :     }
     160             : 
     161             :     final roomInboundGroupSessions =
     162          69 :         _inboundGroupSessions[roomId] ??= <String, SessionKey>{};
     163          23 :     roomInboundGroupSessions[sessionId] = newSession;
     164          92 :     if (!client.isLogged() || client.encryption == null) {
     165             :       return;
     166             :     }
     167          46 :     final storeFuture = client.database
     168          23 :         ?.storeInboundGroupSession(
     169             :       roomId,
     170             :       sessionId,
     171          23 :       inboundGroupSession.pickle(userId),
     172          23 :       json.encode(content),
     173          46 :       json.encode({}),
     174          23 :       json.encode(allowedAtIndex_),
     175             :       senderKey,
     176          23 :       json.encode(senderClaimedKeys_),
     177             :     )
     178          46 :         .then((_) async {
     179          92 :       if (!client.isLogged() || client.encryption == null) {
     180             :         return;
     181             :       }
     182             :       if (uploaded) {
     183           2 :         await client.database
     184           1 :             ?.markInboundGroupSessionAsUploaded(roomId, sessionId);
     185             :       }
     186             :     });
     187          46 :     final room = client.getRoomById(roomId);
     188             :     if (room != null) {
     189             :       // attempt to decrypt the last event
     190           6 :       final event = room.lastEvent;
     191             :       if (event != null &&
     192          12 :           event.type == EventTypes.Encrypted &&
     193           3 :           event.content['session_id'] == sessionId) {
     194           2 :         final decrypted = encryption.decryptRoomEventSync(roomId, event);
     195           2 :         if (decrypted.type != EventTypes.Encrypted) {
     196             :           // No need to persist it as the lastEvent is persisted in the sync
     197             :           // right after processing to-device messages:
     198           1 :           room.lastEvent = decrypted;
     199             :         }
     200             :       }
     201             :       // and finally broadcast the new session
     202          12 :       room.onSessionKeyReceived.add(sessionId);
     203             :     }
     204             : 
     205           0 :     return storeFuture ?? Future.value();
     206             :   }
     207             : 
     208          23 :   SessionKey? getInboundGroupSession(String roomId, String sessionId) {
     209          50 :     final sess = _inboundGroupSessions[roomId]?[sessionId];
     210             :     if (sess != null) {
     211           8 :       if (sess.sessionId != sessionId && sess.sessionId.isNotEmpty) {
     212             :         return null;
     213             :       }
     214             :       return sess;
     215             :     }
     216             :     return null;
     217             :   }
     218             : 
     219             :   /// Attempt auto-request for a key
     220           2 :   void maybeAutoRequest(
     221             :     String roomId,
     222             :     String sessionId,
     223             :     String? senderKey, {
     224             :     bool tryOnlineBackup = true,
     225             :     bool onlineKeyBackupOnly = true,
     226             :   }) {
     227           4 :     final room = client.getRoomById(roomId);
     228           2 :     final requestIdent = '$roomId|$sessionId';
     229             :     if (room != null &&
     230           2 :         !_requestedSessionIds.contains(requestIdent) &&
     231           2 :         !client.isUnknownSession) {
     232             :       // do e2ee recovery
     233           0 :       _requestedSessionIds.add(requestIdent);
     234             : 
     235           0 :       runInRoot(() async => request(
     236             :             room,
     237             :             sessionId,
     238             :             senderKey,
     239             :             tryOnlineBackup: tryOnlineBackup,
     240             :             onlineKeyBackupOnly: onlineKeyBackupOnly,
     241             :           ));
     242             :     }
     243             :   }
     244             : 
     245             :   /// Loads an inbound group session
     246           6 :   Future<SessionKey?> loadInboundGroupSession(
     247             :       String roomId, String sessionId) async {
     248          15 :     final sess = _inboundGroupSessions[roomId]?[sessionId];
     249             :     if (sess != null) {
     250           6 :       if (sess.sessionId != sessionId && sess.sessionId.isNotEmpty) {
     251             :         return null; // session_id does not match....better not do anything
     252             :       }
     253             :       return sess; // nothing to do
     254             :     }
     255             :     final session =
     256          15 :         await client.database?.getInboundGroupSession(roomId, sessionId);
     257             :     if (session == null) return null;
     258           4 :     final userID = client.userID;
     259             :     if (userID == null) return null;
     260           2 :     final dbSess = SessionKey.fromDb(session, userID);
     261             :     final roomInboundGroupSessions =
     262           6 :         _inboundGroupSessions[roomId] ??= <String, SessionKey>{};
     263           2 :     if (!dbSess.isValid ||
     264           4 :         dbSess.sessionId.isEmpty ||
     265           4 :         dbSess.sessionId != sessionId) {
     266             :       return null;
     267             :     }
     268           2 :     roomInboundGroupSessions[sessionId] = dbSess;
     269             :     return sess;
     270             :   }
     271             : 
     272           4 :   Map<String, Map<String, bool>> _getDeviceKeyIdMap(
     273             :       List<DeviceKeys> deviceKeys) {
     274           4 :     final deviceKeyIds = <String, Map<String, bool>>{};
     275           7 :     for (final device in deviceKeys) {
     276           3 :       final deviceId = device.deviceId;
     277             :       if (deviceId == null) {
     278           0 :         Logs().w('[KeyManager] ignoring device without deviceid');
     279             :         continue;
     280             :       }
     281           9 :       final userDeviceKeyIds = deviceKeyIds[device.userId] ??= <String, bool>{};
     282           6 :       userDeviceKeyIds[deviceId] = !device.encryptToDevice;
     283             :     }
     284             :     return deviceKeyIds;
     285             :   }
     286             : 
     287             :   /// clear all cached inbound group sessions. useful for testing
     288           3 :   void clearOutboundGroupSessions() {
     289           6 :     _outboundGroupSessions.clear();
     290             :   }
     291             : 
     292             :   /// Clears the existing outboundGroupSession but first checks if the participating
     293             :   /// devices have been changed. Returns false if the session has not been cleared because
     294             :   /// it wasn't necessary. Otherwise returns true.
     295           4 :   Future<bool> clearOrUseOutboundGroupSession(String roomId,
     296             :       {bool wipe = false, bool use = true}) async {
     297           8 :     final room = client.getRoomById(roomId);
     298           4 :     final sess = getOutboundGroupSession(roomId);
     299           2 :     if (room == null || sess == null || sess.outboundGroupSession == null) {
     300             :       return true;
     301             :     }
     302             : 
     303             :     if (!wipe) {
     304             :       // first check if it needs to be rotated
     305             :       final encryptionContent =
     306           2 :           room.getState(EventTypes.Encryption)?.parsedRoomEncryptionContent;
     307           1 :       final maxMessages = encryptionContent?.rotationPeriodMsgs ?? 100;
     308           1 :       final maxAge = encryptionContent?.rotationPeriodMs ??
     309             :           604800000; // default of one week
     310           2 :       if ((sess.sentMessages ?? maxMessages) >= maxMessages ||
     311           1 :           sess.creationTime
     312           2 :               .add(Duration(milliseconds: maxAge))
     313           2 :               .isBefore(DateTime.now())) {
     314             :         wipe = true;
     315             :       }
     316             :     }
     317             : 
     318           2 :     final inboundSess = await loadInboundGroupSession(
     319           6 :         room.id, sess.outboundGroupSession!.session_id());
     320             :     if (inboundSess == null) {
     321             :       wipe = true;
     322             :     }
     323             : 
     324             :     if (!wipe) {
     325             :       // next check if the devices in the room changed
     326           1 :       final devicesToReceive = <DeviceKeys>[];
     327           1 :       final newDeviceKeys = await room.getUserDeviceKeys();
     328           1 :       final newDeviceKeyIds = _getDeviceKeyIdMap(newDeviceKeys);
     329             :       // first check for user differences
     330           3 :       final oldUserIds = Set.from(sess.devices.keys);
     331           2 :       final newUserIds = Set.from(newDeviceKeyIds.keys);
     332           2 :       if (oldUserIds.difference(newUserIds).isNotEmpty) {
     333             :         // a user left the room, we must wipe the session
     334             :         wipe = true;
     335             :       } else {
     336           1 :         final newUsers = newUserIds.difference(oldUserIds);
     337           1 :         if (newUsers.isNotEmpty) {
     338             :           // new user! Gotta send the megolm session to them
     339             :           devicesToReceive
     340           5 :               .addAll(newDeviceKeys.where((d) => newUsers.contains(d.userId)));
     341             :         }
     342             :         // okay, now we must test all the individual user devices, if anything new got blocked
     343             :         // or if we need to send to any new devices.
     344             :         // for this it is enough if we iterate over the old user Ids, as the new ones already have the needed keys in the list.
     345             :         // we also know that all the old user IDs appear in the old one, else we have already wiped the session
     346           2 :         for (final userId in oldUserIds) {
     347           2 :           final oldBlockedDevices = sess.devices.containsKey(userId)
     348           4 :               ? Set.from(sess.devices[userId]!.entries
     349           3 :                   .where((e) => e.value)
     350           1 :                   .map((e) => e.key))
     351             :               : <String>{};
     352           1 :           final newBlockedDevices = newDeviceKeyIds.containsKey(userId)
     353           2 :               ? Set.from(newDeviceKeyIds[userId]!
     354           1 :                   .entries
     355           3 :                   .where((e) => e.value)
     356           3 :                   .map((e) => e.key))
     357             :               : <String>{};
     358             :           // we don't really care about old devices that got dropped (deleted), we only care if new ones got added and if new ones got blocked
     359             :           // check if new devices got blocked
     360           2 :           if (newBlockedDevices.difference(oldBlockedDevices).isNotEmpty) {
     361             :             wipe = true;
     362             :             break;
     363             :           }
     364             :           // and now add all the new devices!
     365           2 :           final oldDeviceIds = sess.devices.containsKey(userId)
     366           4 :               ? Set.from(sess.devices[userId]!.entries
     367           3 :                   .where((e) => !e.value)
     368           3 :                   .map((e) => e.key))
     369             :               : <String>{};
     370           1 :           final newDeviceIds = newDeviceKeyIds.containsKey(userId)
     371           2 :               ? Set.from(newDeviceKeyIds[userId]!
     372           1 :                   .entries
     373           3 :                   .where((e) => !e.value)
     374           3 :                   .map((e) => e.key))
     375             :               : <String>{};
     376             : 
     377             :           // check if a device got removed
     378           2 :           if (oldDeviceIds.difference(newDeviceIds).isNotEmpty) {
     379             :             wipe = true;
     380             :             break;
     381             :           }
     382             : 
     383             :           // check if any new devices need keys
     384           1 :           final newDevices = newDeviceIds.difference(oldDeviceIds);
     385           1 :           if (newDeviceIds.isNotEmpty) {
     386           2 :             devicesToReceive.addAll(newDeviceKeys.where(
     387           5 :                 (d) => d.userId == userId && newDevices.contains(d.deviceId)));
     388             :           }
     389             :         }
     390             :       }
     391             : 
     392             :       if (!wipe) {
     393             :         if (!use) {
     394             :           return false;
     395             :         }
     396             :         // okay, we use the outbound group session!
     397           1 :         sess.devices = newDeviceKeyIds;
     398           1 :         final rawSession = <String, dynamic>{
     399             :           'algorithm': AlgorithmTypes.megolmV1AesSha2,
     400           1 :           'room_id': room.id,
     401           2 :           'session_id': sess.outboundGroupSession!.session_id(),
     402           2 :           'session_key': sess.outboundGroupSession!.session_key(),
     403             :         };
     404             :         try {
     405           3 :           devicesToReceive.removeWhere((k) => !k.encryptToDevice);
     406           1 :           if (devicesToReceive.isNotEmpty) {
     407             :             // update allowedAtIndex
     408           2 :             for (final device in devicesToReceive) {
     409           4 :               inboundSess!.allowedAtIndex[device.userId] ??= <String, int>{};
     410           3 :               if (!inboundSess.allowedAtIndex[device.userId]!
     411           2 :                       .containsKey(device.curve25519Key) ||
     412           0 :                   inboundSess.allowedAtIndex[device.userId]![
     413           0 :                           device.curve25519Key]! >
     414           0 :                       sess.outboundGroupSession!.message_index()) {
     415             :                 inboundSess
     416           5 :                         .allowedAtIndex[device.userId]![device.curve25519Key!] =
     417           2 :                     sess.outboundGroupSession!.message_index();
     418             :               }
     419             :             }
     420           3 :             await client.database?.updateInboundGroupSessionAllowedAtIndex(
     421           2 :                 json.encode(inboundSess!.allowedAtIndex),
     422           1 :                 room.id,
     423           2 :                 sess.outboundGroupSession!.session_id());
     424             :             // send out the key
     425           2 :             await client.sendToDeviceEncryptedChunked(
     426             :                 devicesToReceive, EventTypes.RoomKey, rawSession);
     427             :           }
     428             :         } catch (e, s) {
     429           0 :           Logs().e(
     430             :               '[LibOlm] Unable to re-send the session key at later index to new devices',
     431             :               e,
     432             :               s);
     433             :         }
     434             :         return false;
     435             :       }
     436             :     }
     437           2 :     sess.dispose();
     438           4 :     _outboundGroupSessions.remove(roomId);
     439           6 :     await client.database?.removeOutboundGroupSession(roomId);
     440             :     return true;
     441             :   }
     442             : 
     443             :   /// Store an outbound group session in the database
     444           4 :   Future<void> storeOutboundGroupSession(
     445             :       String roomId, OutboundGroupSession sess) async {
     446           8 :     final userID = client.userID;
     447             :     if (userID == null) return;
     448          12 :     await client.database?.storeOutboundGroupSession(
     449             :         roomId,
     450           8 :         sess.outboundGroupSession!.pickle(userID),
     451           8 :         json.encode(sess.devices),
     452           8 :         sess.creationTime.millisecondsSinceEpoch);
     453             :   }
     454             : 
     455             :   final Map<String, Future<OutboundGroupSession>>
     456             :       _pendingNewOutboundGroupSessions = {};
     457             : 
     458             :   /// Creates an outbound group session for a given room id
     459           4 :   Future<OutboundGroupSession> createOutboundGroupSession(String roomId) async {
     460           8 :     final sess = _pendingNewOutboundGroupSessions[roomId];
     461             :     if (sess != null) {
     462             :       return sess;
     463             :     }
     464           8 :     final newSess = _pendingNewOutboundGroupSessions[roomId] =
     465           4 :         _createOutboundGroupSession(roomId);
     466             : 
     467             :     try {
     468             :       await newSess;
     469             :     } finally {
     470           4 :       _pendingNewOutboundGroupSessions
     471          12 :           .removeWhere((_, value) => value == newSess);
     472             :     }
     473             : 
     474             :     return newSess;
     475             :   }
     476             : 
     477             :   /// Prepares an outbound group session for a given room ID. That is, load it from
     478             :   /// the database, cycle it if needed and create it if absent.
     479           1 :   Future<void> prepareOutboundGroupSession(String roomId) async {
     480           1 :     if (getOutboundGroupSession(roomId) == null) {
     481           0 :       await loadOutboundGroupSession(roomId);
     482             :     }
     483           1 :     await clearOrUseOutboundGroupSession(roomId, use: false);
     484           1 :     if (getOutboundGroupSession(roomId) == null) {
     485           1 :       await createOutboundGroupSession(roomId);
     486             :     }
     487             :   }
     488             : 
     489           4 :   Future<OutboundGroupSession> _createOutboundGroupSession(
     490             :       String roomId) async {
     491           4 :     await clearOrUseOutboundGroupSession(roomId, wipe: true);
     492           8 :     await client.firstSyncReceived;
     493           8 :     final room = client.getRoomById(roomId);
     494             :     if (room == null) {
     495           0 :       throw Exception(
     496           0 :           'Tried to create a megolm session in a non-existing room ($roomId)!');
     497             :     }
     498           8 :     final userID = client.userID;
     499             :     if (userID == null) {
     500           0 :       throw Exception(
     501             :           'Tried to create a megolm session without being logged in!');
     502             :     }
     503             : 
     504           4 :     final deviceKeys = await room.getUserDeviceKeys();
     505           4 :     final deviceKeyIds = _getDeviceKeyIdMap(deviceKeys);
     506          10 :     deviceKeys.removeWhere((k) => !k.encryptToDevice);
     507           4 :     final outboundGroupSession = olm.OutboundGroupSession();
     508             :     try {
     509           4 :       outboundGroupSession.create();
     510             :     } catch (e, s) {
     511           0 :       outboundGroupSession.free();
     512           0 :       Logs().e('[LibOlm] Unable to create new outboundGroupSession', e, s);
     513             :       rethrow;
     514             :     }
     515           4 :     final rawSession = <String, dynamic>{
     516             :       'algorithm': AlgorithmTypes.megolmV1AesSha2,
     517           4 :       'room_id': room.id,
     518           4 :       'session_id': outboundGroupSession.session_id(),
     519           4 :       'session_key': outboundGroupSession.session_key(),
     520             :     };
     521           4 :     final allowedAtIndex = <String, Map<String, int>>{};
     522           7 :     for (final device in deviceKeys) {
     523           3 :       if (!device.isValid) {
     524           0 :         Logs().e('Skipping invalid device');
     525             :         continue;
     526             :       }
     527           9 :       allowedAtIndex[device.userId] ??= <String, int>{};
     528          12 :       allowedAtIndex[device.userId]![device.curve25519Key!] =
     529           3 :           outboundGroupSession.message_index();
     530             :     }
     531           4 :     await setInboundGroupSession(
     532          12 :         roomId, rawSession['session_id'], encryption.identityKey!, rawSession,
     533             :         allowedAtIndex: allowedAtIndex);
     534           4 :     final sess = OutboundGroupSession(
     535             :       devices: deviceKeyIds,
     536           4 :       creationTime: DateTime.now(),
     537             :       outboundGroupSession: outboundGroupSession,
     538             :       key: userID,
     539             :     );
     540             :     try {
     541           8 :       await client.sendToDeviceEncryptedChunked(
     542             :           deviceKeys, EventTypes.RoomKey, rawSession);
     543           4 :       await storeOutboundGroupSession(roomId, sess);
     544           8 :       _outboundGroupSessions[roomId] = sess;
     545             :     } catch (e, s) {
     546           0 :       Logs().e(
     547             :           '[LibOlm] Unable to send the session key to the participating devices',
     548             :           e,
     549             :           s);
     550           0 :       sess.dispose();
     551             :       rethrow;
     552             :     }
     553             :     return sess;
     554             :   }
     555             : 
     556             :   /// Get an outbound group session for a room id
     557           4 :   OutboundGroupSession? getOutboundGroupSession(String roomId) {
     558           8 :     return _outboundGroupSessions[roomId];
     559             :   }
     560             : 
     561             :   /// Load an outbound group session from database
     562           3 :   Future<void> loadOutboundGroupSession(String roomId) async {
     563           6 :     final database = client.database;
     564           6 :     final userID = client.userID;
     565           6 :     if (_loadedOutboundGroupSessions.contains(roomId) ||
     566           6 :         _outboundGroupSessions.containsKey(roomId) ||
     567             :         database == null ||
     568             :         userID == null) {
     569             :       return; // nothing to do
     570             :     }
     571           6 :     _loadedOutboundGroupSessions.add(roomId);
     572           3 :     final sess = await database.getOutboundGroupSession(
     573             :       roomId,
     574             :       userID,
     575             :     );
     576           1 :     if (sess == null || !sess.isValid) {
     577             :       return;
     578             :     }
     579           2 :     _outboundGroupSessions[roomId] = sess;
     580             :   }
     581             : 
     582          23 :   Future<bool> isCached() async {
     583          46 :     await client.accountDataLoading;
     584          23 :     if (!enabled) {
     585             :       return false;
     586             :     }
     587          46 :     await client.userDeviceKeysLoading;
     588          69 :     return (await encryption.ssss.getCached(megolmKey)) != null;
     589             :   }
     590             : 
     591             :   GetRoomKeysVersionCurrentResponse? _roomKeysVersionCache;
     592             :   DateTime? _roomKeysVersionCacheDate;
     593             : 
     594           5 :   Future<GetRoomKeysVersionCurrentResponse> getRoomKeysBackupInfo(
     595             :       [bool useCache = true]) async {
     596           5 :     if (_roomKeysVersionCache != null &&
     597           3 :         _roomKeysVersionCacheDate != null &&
     598             :         useCache &&
     599           1 :         DateTime.now()
     600           2 :             .subtract(Duration(minutes: 5))
     601           2 :             .isBefore(_roomKeysVersionCacheDate!)) {
     602           1 :       return _roomKeysVersionCache!;
     603             :     }
     604          15 :     _roomKeysVersionCache = await client.getRoomKeysVersionCurrent();
     605          10 :     _roomKeysVersionCacheDate = DateTime.now();
     606           5 :     return _roomKeysVersionCache!;
     607             :   }
     608             : 
     609           1 :   Future<void> loadFromResponse(RoomKeys keys) async {
     610           1 :     if (!(await isCached())) {
     611             :       return;
     612             :     }
     613             :     final privateKey =
     614           4 :         base64decodeUnpadded((await encryption.ssss.getCached(megolmKey))!);
     615           1 :     final decryption = olm.PkDecryption();
     616           1 :     final info = await getRoomKeysBackupInfo();
     617             :     String backupPubKey;
     618             :     try {
     619           1 :       backupPubKey = decryption.init_with_private_key(privateKey);
     620             : 
     621           2 :       if (info.algorithm != BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2 ||
     622           3 :           info.authData['public_key'] != backupPubKey) {
     623             :         return;
     624             :       }
     625           3 :       for (final roomEntry in keys.rooms.entries) {
     626           1 :         final roomId = roomEntry.key;
     627           4 :         for (final sessionEntry in roomEntry.value.sessions.entries) {
     628           1 :           final sessionId = sessionEntry.key;
     629           1 :           final session = sessionEntry.value;
     630           1 :           final sessionData = session.sessionData;
     631             :           Map<String, Object?>? decrypted;
     632             :           try {
     633           2 :             decrypted = json.decode(decryption.decrypt(
     634           1 :                 sessionData['ephemeral'] as String,
     635           1 :                 sessionData['mac'] as String,
     636           1 :                 sessionData['ciphertext'] as String));
     637             :           } catch (e, s) {
     638           0 :             Logs().e('[LibOlm] Error decrypting room key', e, s);
     639             :           }
     640           1 :           final senderKey = decrypted?.tryGet<String>('sender_key');
     641             :           if (decrypted != null && senderKey != null) {
     642           1 :             decrypted['session_id'] = sessionId;
     643           1 :             decrypted['room_id'] = roomId;
     644           1 :             await setInboundGroupSession(
     645             :                 roomId, sessionId, senderKey, decrypted,
     646             :                 forwarded: true,
     647             :                 senderClaimedKeys: decrypted
     648           1 :                         .tryGetMap<String, String>('sender_claimed_keys') ??
     649           0 :                     <String, String>{},
     650             :                 uploaded: true);
     651             :           }
     652             :         }
     653             :       }
     654             :     } finally {
     655           1 :       decryption.free();
     656             :     }
     657             :   }
     658             : 
     659             :   /// Loads and stores all keys from the online key backup. This may take a
     660             :   /// while for older and big accounts.
     661           1 :   Future<void> loadAllKeys() async {
     662           1 :     final info = await getRoomKeysBackupInfo();
     663           3 :     final ret = await client.getRoomKeys(info.version);
     664           1 :     await loadFromResponse(ret);
     665             :   }
     666             : 
     667             :   /// Loads all room keys for a single room and stores them. This may take a
     668             :   /// while for older and big rooms.
     669           1 :   Future<void> loadAllKeysFromRoom(String roomId) async {
     670           1 :     final info = await getRoomKeysBackupInfo();
     671           3 :     final ret = await client.getRoomKeysByRoomId(roomId, info.version);
     672           2 :     final keys = RoomKeys.fromJson({
     673           1 :       'rooms': {
     674           1 :         roomId: {
     675           5 :           'sessions': ret.sessions.map((k, s) => MapEntry(k, s.toJson())),
     676             :         },
     677             :       },
     678             :     });
     679           1 :     await loadFromResponse(keys);
     680             :   }
     681             : 
     682             :   /// Loads a single key for the specified room from the online key backup
     683             :   /// and stores it.
     684           1 :   Future<void> loadSingleKey(String roomId, String sessionId) async {
     685           1 :     final info = await getRoomKeysBackupInfo();
     686             :     final ret =
     687           3 :         await client.getRoomKeyBySessionId(roomId, sessionId, info.version);
     688           2 :     final keys = RoomKeys.fromJson({
     689           1 :       'rooms': {
     690           1 :         roomId: {
     691           1 :           'sessions': {
     692           1 :             sessionId: ret.toJson(),
     693             :           },
     694             :         },
     695             :       },
     696             :     });
     697           1 :     await loadFromResponse(keys);
     698             :   }
     699             : 
     700             :   /// Request a certain key from another device
     701           3 :   Future<void> request(
     702             :     Room room,
     703             :     String sessionId,
     704             :     String? senderKey, {
     705             :     bool tryOnlineBackup = true,
     706             :     bool onlineKeyBackupOnly = false,
     707             :   }) async {
     708           2 :     if (tryOnlineBackup && await isCached()) {
     709             :       // let's first check our online key backup store thingy...
     710           2 :       final hadPreviously = getInboundGroupSession(room.id, sessionId) != null;
     711             :       try {
     712           2 :         await loadSingleKey(room.id, sessionId);
     713             :       } catch (err, stacktrace) {
     714           0 :         if (err is MatrixException && err.errcode == 'M_NOT_FOUND') {
     715           0 :           Logs().i(
     716             :               '[KeyManager] Key not in online key backup, requesting it from other devices...');
     717             :         } else {
     718           0 :           Logs().e('[KeyManager] Failed to access online key backup', err,
     719             :               stacktrace);
     720             :         }
     721             :       }
     722             :       // TODO: also don't request from others if we have an index of 0 now
     723             :       if (!hadPreviously &&
     724           2 :           getInboundGroupSession(room.id, sessionId) != null) {
     725             :         return; // we managed to load the session from online backup, no need to care about it now
     726             :       }
     727             :     }
     728             :     if (onlineKeyBackupOnly) {
     729             :       return; // we only want to do the online key backup
     730             :     }
     731             :     try {
     732             :       // while we just send the to-device event to '*', we still need to save the
     733             :       // devices themself to know where to send the cancel to after receiving a reply
     734           2 :       final devices = await room.getUserDeviceKeys();
     735           4 :       final requestId = client.generateUniqueTransactionId();
     736           2 :       final request = KeyManagerKeyShareRequest(
     737             :         requestId: requestId,
     738             :         devices: devices,
     739             :         room: room,
     740             :         sessionId: sessionId,
     741             :       );
     742           2 :       final userList = await room.requestParticipants();
     743           4 :       await client.sendToDevicesOfUserIds(
     744           6 :         userList.map<String>((u) => u.id).toSet(),
     745             :         EventTypes.RoomKeyRequest,
     746           2 :         {
     747             :           'action': 'request',
     748           2 :           'body': {
     749           2 :             'algorithm': AlgorithmTypes.megolmV1AesSha2,
     750           4 :             'room_id': room.id,
     751           2 :             'session_id': sessionId,
     752           2 :             if (senderKey != null) 'sender_key': senderKey,
     753             :           },
     754             :           'request_id': requestId,
     755           4 :           'requesting_device_id': client.deviceID,
     756             :         },
     757             :       );
     758           6 :       outgoingShareRequests[request.requestId] = request;
     759             :     } catch (e, s) {
     760           0 :       Logs().e('[Key Manager] Sending key verification request failed', e, s);
     761             :     }
     762             :   }
     763             : 
     764             :   Future<void>? _uploadingFuture;
     765             : 
     766          24 :   void startAutoUploadKeys() {
     767         144 :     _uploadKeysOnSync = encryption.client.onSync.stream.listen(
     768          48 :         (_) async => uploadInboundGroupSessions(skipIfInProgress: true));
     769             :   }
     770             : 
     771             :   /// This task should be performed after sync processing but should not block
     772             :   /// the sync. To make sure that it never gets executed multiple times, it is
     773             :   /// skipped when an upload task is already in progress. Set `skipIfInProgress`
     774             :   /// to `false` to await the pending upload task instead.
     775          24 :   Future<void> uploadInboundGroupSessions(
     776             :       {bool skipIfInProgress = false}) async {
     777          48 :     final database = client.database;
     778          48 :     final userID = client.userID;
     779             :     if (database == null || userID == null) {
     780             :       return;
     781             :     }
     782             : 
     783             :     // Make sure to not run in parallel
     784          23 :     if (_uploadingFuture != null) {
     785             :       if (skipIfInProgress) return;
     786             :       try {
     787           0 :         await _uploadingFuture;
     788             :       } finally {
     789             :         // shouldn't be necessary, since it will be unset already by the other process that started it, but just to be safe, also unset the future here
     790           0 :         _uploadingFuture = null;
     791             :       }
     792             :     }
     793             : 
     794          23 :     Future<void> uploadInternal() async {
     795             :       try {
     796          46 :         await client.userDeviceKeysLoading;
     797             : 
     798          23 :         if (!(await isCached())) {
     799             :           return; // we can't backup anyways
     800             :         }
     801           5 :         final dbSessions = await database.getInboundGroupSessionsToUpload();
     802           5 :         if (dbSessions.isEmpty) {
     803             :           return; // nothing to do
     804             :         }
     805             :         final privateKey =
     806          20 :             base64decodeUnpadded((await encryption.ssss.getCached(megolmKey))!);
     807             :         // decryption is needed to calculate the public key and thus see if the claimed information is in fact valid
     808           5 :         final decryption = olm.PkDecryption();
     809           5 :         final info = await getRoomKeysBackupInfo(false);
     810             :         String backupPubKey;
     811             :         try {
     812           5 :           backupPubKey = decryption.init_with_private_key(privateKey);
     813             : 
     814          10 :           if (info.algorithm !=
     815             :                   BackupAlgorithm.mMegolmBackupV1Curve25519AesSha2 ||
     816          15 :               info.authData['public_key'] != backupPubKey) {
     817           1 :             decryption.free();
     818             :             return;
     819             :           }
     820           4 :           final args = GenerateUploadKeysArgs(
     821             :             pubkey: backupPubKey,
     822           4 :             dbSessions: <DbInboundGroupSessionBundle>[],
     823             :             userId: userID,
     824             :           );
     825             :           // we need to calculate verified beforehand, as else we pass a closure to an isolate
     826             :           // with 500 keys they do, however, noticably block the UI, which is why we give brief async suspentions in here
     827             :           // so that the event loop can progress
     828             :           var i = 0;
     829           8 :           for (final dbSession in dbSessions) {
     830             :             final device =
     831          12 :                 client.getUserDeviceKeysByCurve25519Key(dbSession.senderKey);
     832          12 :             args.dbSessions.add(DbInboundGroupSessionBundle(
     833             :               dbSession: dbSession,
     834           4 :               verified: device?.verified ?? false,
     835             :             ));
     836           4 :             i++;
     837           4 :             if (i > 10) {
     838           0 :               await Future.delayed(Duration(milliseconds: 1));
     839             :               i = 0;
     840             :             }
     841             :           }
     842             :           final roomKeys =
     843          12 :               await client.nativeImplementations.generateUploadKeys(args);
     844          16 :           Logs().i('[Key Manager] Uploading ${dbSessions.length} room keys...');
     845             :           // upload the payload...
     846          12 :           await client.putRoomKeys(info.version, roomKeys);
     847             :           // and now finally mark all the keys as uploaded
     848             :           // no need to optimze this, as we only run it so seldomly and almost never with many keys at once
     849           8 :           for (final dbSession in dbSessions) {
     850           4 :             await database.markInboundGroupSessionAsUploaded(
     851           8 :                 dbSession.roomId, dbSession.sessionId);
     852             :           }
     853             :         } finally {
     854           5 :           decryption.free();
     855             :         }
     856             :       } catch (e, s) {
     857           2 :         Logs().e('[Key Manager] Error uploading room keys', e, s);
     858             :       }
     859             :     }
     860             : 
     861          46 :     _uploadingFuture = uploadInternal();
     862             :     try {
     863          23 :       await _uploadingFuture;
     864             :     } finally {
     865          23 :       _uploadingFuture = null;
     866             :     }
     867             :   }
     868             : 
     869             :   /// Handle an incoming to_device event that is related to key sharing
     870          23 :   Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
     871          46 :     if (event.type == EventTypes.RoomKeyRequest) {
     872           3 :       if (event.content['request_id'] is! String) {
     873             :         return; // invalid event
     874             :       }
     875           3 :       if (event.content['action'] == 'request') {
     876             :         // we are *receiving* a request
     877           2 :         Logs().i(
     878           4 :             '[KeyManager] Received key sharing request from ${event.sender}:${event.content['requesting_device_id']}...');
     879           2 :         if (!event.content.containsKey('body')) {
     880           2 :           Logs().w('[KeyManager] No body, doing nothing');
     881             :           return; // no body
     882             :         }
     883           2 :         final body = event.content.tryGetMap<String, Object?>('body');
     884             :         if (body == null) {
     885           0 :           Logs().w('[KeyManager] Wrong type for body, doing nothing');
     886             :           return; // wrong type for body
     887             :         }
     888           1 :         final roomId = body.tryGet<String>('room_id');
     889             :         if (roomId == null) {
     890           0 :           Logs().w(
     891             :               '[KeyManager] Wrong type for room_id or no room_id, doing nothing');
     892             :           return; // wrong type for roomId or no roomId found
     893             :         }
     894           4 :         final device = client.userDeviceKeys[event.sender]
     895           4 :             ?.deviceKeys[event.content['requesting_device_id']];
     896             :         if (device == null) {
     897           2 :           Logs().w('[KeyManager] Device not found, doing nothing');
     898             :           return; // device not found
     899             :         }
     900           4 :         if (device.userId == client.userID &&
     901           4 :             device.deviceId == client.deviceID) {
     902           0 :           Logs().i('[KeyManager] Request is by ourself, ignoring');
     903             :           return; // ignore requests by ourself
     904             :         }
     905           2 :         final room = client.getRoomById(roomId);
     906             :         if (room == null) {
     907           2 :           Logs().i('[KeyManager] Unknown room, ignoring');
     908             :           return; // unknown room
     909             :         }
     910           1 :         final sessionId = body.tryGet<String>('session_id');
     911             :         if (sessionId == null) {
     912           0 :           Logs().w(
     913             :               '[KeyManager] Wrong type for session_id or no session_id, doing nothing');
     914             :           return; // wrong type for session_id
     915             :         }
     916             :         // okay, let's see if we have this session at all
     917           2 :         final session = await loadInboundGroupSession(room.id, sessionId);
     918             :         if (session == null) {
     919           2 :           Logs().i('[KeyManager] Unknown session, ignoring');
     920             :           return; // we don't have this session anyways
     921             :         }
     922           3 :         if (event.content['request_id'] is! String) {
     923           0 :           Logs().w(
     924             :               '[KeyManager] Wrong type for request_id or no request_id, doing nothing');
     925             :           return; // wrong type for request_id
     926             :         }
     927           1 :         final request = KeyManagerKeyShareRequest(
     928           2 :           requestId: event.content.tryGet<String>('request_id')!,
     929           1 :           devices: [device],
     930             :           room: room,
     931             :           sessionId: sessionId,
     932             :         );
     933           3 :         if (incomingShareRequests.containsKey(request.requestId)) {
     934           0 :           Logs().i('[KeyManager] Already processed this request, ignoring');
     935             :           return; // we don't want to process one and the same request multiple times
     936             :         }
     937           3 :         incomingShareRequests[request.requestId] = request;
     938             :         final roomKeyRequest =
     939           1 :             RoomKeyRequest.fromToDeviceEvent(event, this, request);
     940           4 :         if (device.userId == client.userID &&
     941           1 :             device.verified &&
     942           1 :             !device.blocked) {
     943           2 :           Logs().i('[KeyManager] All checks out, forwarding key...');
     944             :           // alright, we can forward the key
     945           1 :           await roomKeyRequest.forwardKey();
     946           1 :         } else if (device.encryptToDevice &&
     947           1 :             session.allowedAtIndex
     948           2 :                     .tryGet<Map<String, Object?>>(device.userId)
     949           2 :                     ?.tryGet(device.curve25519Key!) !=
     950             :                 null) {
     951             :           // if we know the user may see the message, then we can just forward the key.
     952             :           // we do not need to check if the device is verified, just if it is not blocked,
     953             :           // as that is the logic we already initially try to send out the room keys.
     954             :           final index =
     955           5 :               session.allowedAtIndex[device.userId]![device.curve25519Key]!;
     956           2 :           Logs().i(
     957           1 :               '[KeyManager] Valid foreign request, forwarding key at index $index...');
     958           1 :           await roomKeyRequest.forwardKey(index);
     959             :         } else {
     960           1 :           Logs()
     961           1 :               .i('[KeyManager] Asking client, if the key should be forwarded');
     962           2 :           client.onRoomKeyRequest
     963           1 :               .add(roomKeyRequest); // let the client handle this
     964             :         }
     965           0 :       } else if (event.content['action'] == 'request_cancellation') {
     966             :         // we got told to cancel an incoming request
     967           0 :         if (!incomingShareRequests.containsKey(event.content['request_id'])) {
     968             :           return; // we don't know this request anyways
     969             :         }
     970             :         // alright, let's just cancel this request
     971           0 :         final request = incomingShareRequests[event.content['request_id']]!;
     972           0 :         request.canceled = true;
     973           0 :         incomingShareRequests.remove(request.requestId);
     974             :       }
     975          46 :     } else if (event.type == EventTypes.ForwardedRoomKey) {
     976             :       // we *received* an incoming key request
     977           1 :       final encryptedContent = event.encryptedContent;
     978             :       if (encryptedContent == null) {
     979           2 :         Logs().w(
     980             :           'Ignoring an unencrypted forwarded key from a to device message',
     981           1 :           event.toJson(),
     982             :         );
     983             :         return;
     984             :       }
     985           4 :       final request = outgoingShareRequests.values.firstWhereOrNull((r) =>
     986           5 :           r.room.id == event.content['room_id'] &&
     987           4 :           r.sessionId == event.content['session_id']);
     988           1 :       if (request == null || request.canceled) {
     989             :         return; // no associated request found or it got canceled
     990             :       }
     991           3 :       final device = request.devices.firstWhereOrNull((d) =>
     992           3 :           d.userId == event.sender &&
     993           3 :           d.curve25519Key == encryptedContent['sender_key']);
     994             :       if (device == null) {
     995             :         return; // someone we didn't send our request to replied....better ignore this
     996             :       }
     997             :       // we add the sender key to the forwarded key chain
     998           3 :       if (event.content['forwarding_curve25519_key_chain'] is! List) {
     999           0 :         event.content['forwarding_curve25519_key_chain'] = <String>[];
    1000             :       }
    1001           2 :       (event.content['forwarding_curve25519_key_chain'] as List)
    1002           2 :           .add(encryptedContent['sender_key']);
    1003           3 :       if (event.content['sender_claimed_ed25519_key'] is! String) {
    1004           0 :         Logs().w('sender_claimed_ed255519_key has wrong type');
    1005             :         return; // wrong type
    1006             :       }
    1007             :       // TODO: verify that the keys work to decrypt a message
    1008             :       // alright, all checks out, let's go ahead and store this session
    1009           4 :       await setInboundGroupSession(request.room.id, request.sessionId,
    1010           2 :           device.curve25519Key!, event.content,
    1011             :           forwarded: true,
    1012           1 :           senderClaimedKeys: {
    1013           2 :             'ed25519': event.content['sender_claimed_ed25519_key'] as String,
    1014             :           });
    1015           2 :       request.devices.removeWhere(
    1016           7 :           (k) => k.userId == device.userId && k.deviceId == device.deviceId);
    1017           3 :       outgoingShareRequests.remove(request.requestId);
    1018             :       // send cancel to all other devices
    1019           2 :       if (request.devices.isEmpty) {
    1020             :         return; // no need to send any cancellation
    1021             :       }
    1022             :       // Send with send-to-device messaging
    1023           1 :       final sendToDeviceMessage = {
    1024             :         'action': 'request_cancellation',
    1025           1 :         'request_id': request.requestId,
    1026           2 :         'requesting_device_id': client.deviceID,
    1027             :       };
    1028           1 :       final data = <String, Map<String, Map<String, dynamic>>>{};
    1029           2 :       for (final device in request.devices) {
    1030           3 :         final userData = data[device.userId] ??= {};
    1031           2 :         userData[device.deviceId!] = sendToDeviceMessage;
    1032             :       }
    1033           2 :       await client.sendToDevice(
    1034             :         EventTypes.RoomKeyRequest,
    1035           2 :         client.generateUniqueTransactionId(),
    1036             :         data,
    1037             :       );
    1038          46 :     } else if (event.type == EventTypes.RoomKey) {
    1039          46 :       Logs().v(
    1040          69 :           '[KeyManager] Received room key with session ${event.content['session_id']}');
    1041          23 :       final encryptedContent = event.encryptedContent;
    1042             :       if (encryptedContent == null) {
    1043           2 :         Logs().v('[KeyManager] not encrypted, ignoring...');
    1044             :         return; // the event wasn't encrypted, this is a security risk;
    1045             :       }
    1046          46 :       final roomId = event.content.tryGet<String>('room_id');
    1047          46 :       final sessionId = event.content.tryGet<String>('session_id');
    1048             :       if (roomId == null || sessionId == null) {
    1049           0 :         Logs().w(
    1050             :             'Either room_id or session_id are not the expected type or missing');
    1051             :         return;
    1052             :       }
    1053          92 :       final sender_ed25519 = client.userDeviceKeys[event.sender]
    1054           4 :           ?.deviceKeys[event.content['requesting_device_id']]?.ed25519Key;
    1055             :       if (sender_ed25519 != null) {
    1056           0 :         event.content['sender_claimed_ed25519_key'] = sender_ed25519;
    1057             :       }
    1058          46 :       Logs().v('[KeyManager] Keeping room key');
    1059          23 :       await setInboundGroupSession(
    1060          46 :           roomId, sessionId, encryptedContent['sender_key'], event.content,
    1061             :           forwarded: false);
    1062             :     }
    1063             :   }
    1064             : 
    1065             :   StreamSubscription<SyncUpdate>? _uploadKeysOnSync;
    1066             : 
    1067          21 :   void dispose() {
    1068             :     // ignore: discarded_futures
    1069          42 :     _uploadKeysOnSync?.cancel();
    1070          45 :     for (final sess in _outboundGroupSessions.values) {
    1071           3 :       sess.dispose();
    1072             :     }
    1073          62 :     for (final entries in _inboundGroupSessions.values) {
    1074          40 :       for (final sess in entries.values) {
    1075          20 :         sess.dispose();
    1076             :       }
    1077             :     }
    1078             :   }
    1079             : }
    1080             : 
    1081             : class KeyManagerKeyShareRequest {
    1082             :   final String requestId;
    1083             :   final List<DeviceKeys> devices;
    1084             :   final Room room;
    1085             :   final String sessionId;
    1086             :   bool canceled;
    1087             : 
    1088           2 :   KeyManagerKeyShareRequest(
    1089             :       {required this.requestId,
    1090             :       List<DeviceKeys>? devices,
    1091             :       required this.room,
    1092             :       required this.sessionId,
    1093             :       this.canceled = false})
    1094           0 :       : devices = devices ?? [];
    1095             : }
    1096             : 
    1097             : class RoomKeyRequest extends ToDeviceEvent {
    1098             :   KeyManager keyManager;
    1099             :   KeyManagerKeyShareRequest request;
    1100             : 
    1101           1 :   RoomKeyRequest.fromToDeviceEvent(
    1102             :       ToDeviceEvent toDeviceEvent, this.keyManager, this.request)
    1103           1 :       : super(
    1104           1 :             sender: toDeviceEvent.sender,
    1105           1 :             content: toDeviceEvent.content,
    1106           1 :             type: toDeviceEvent.type);
    1107             : 
    1108           3 :   Room get room => request.room;
    1109             : 
    1110           4 :   DeviceKeys get requestingDevice => request.devices.first;
    1111             : 
    1112           1 :   Future<void> forwardKey([int? index]) async {
    1113           2 :     if (request.canceled) {
    1114           0 :       keyManager.incomingShareRequests.remove(request.requestId);
    1115             :       return; // request is canceled, don't send anything
    1116             :     }
    1117           1 :     final room = this.room;
    1118             :     final session =
    1119           5 :         await keyManager.loadInboundGroupSession(room.id, request.sessionId);
    1120           1 :     if (session?.inboundGroupSession == null) {
    1121           0 :       Logs().v("[KeyManager] Not forwarding key we don't have");
    1122             :       return;
    1123             :     }
    1124             : 
    1125           2 :     final message = session!.content.copy();
    1126           1 :     message['forwarding_curve25519_key_chain'] =
    1127           2 :         List<String>.from(session.forwardingCurve25519KeyChain);
    1128             : 
    1129           2 :     if (session.senderKey.isNotEmpty) {
    1130           2 :       message['sender_key'] = session.senderKey;
    1131             :     }
    1132           1 :     message['sender_claimed_ed25519_key'] =
    1133           2 :         session.senderClaimedKeys['ed25519'] ??
    1134           2 :             (session.forwardingCurve25519KeyChain.isEmpty
    1135           3 :                 ? keyManager.encryption.fingerprintKey
    1136             :                 : null);
    1137           3 :     message['session_key'] = session.inboundGroupSession!.export_session(
    1138           2 :         index ?? session.inboundGroupSession!.first_known_index());
    1139             :     // send the actual reply of the key back to the requester
    1140           3 :     await keyManager.client.sendToDeviceEncrypted(
    1141           2 :       [requestingDevice],
    1142             :       EventTypes.ForwardedRoomKey,
    1143             :       message,
    1144             :     );
    1145           5 :     keyManager.incomingShareRequests.remove(request.requestId);
    1146             :   }
    1147             : }
    1148             : 
    1149             : /// you would likely want to use [NativeImplementations] and
    1150             : /// [Client.nativeImplementations] instead
    1151           4 : RoomKeys generateUploadKeysImplementation(GenerateUploadKeysArgs args) {
    1152           4 :   final enc = olm.PkEncryption();
    1153             :   try {
    1154           8 :     enc.set_recipient_key(args.pubkey);
    1155             :     // first we generate the payload to upload all the session keys in this chunk
    1156           8 :     final roomKeys = RoomKeys(rooms: {});
    1157           8 :     for (final dbSession in args.dbSessions) {
    1158          12 :       final sess = SessionKey.fromDb(dbSession.dbSession, args.userId);
    1159           4 :       if (!sess.isValid) {
    1160             :         continue;
    1161             :       }
    1162             :       // create the room if it doesn't exist
    1163             :       final roomKeyBackup =
    1164          20 :           roomKeys.rooms[sess.roomId] ??= RoomKeyBackup(sessions: {});
    1165             :       // generate the encrypted content
    1166           4 :       final payload = <String, dynamic>{
    1167             :         'algorithm': AlgorithmTypes.megolmV1AesSha2,
    1168           4 :         'forwarding_curve25519_key_chain': sess.forwardingCurve25519KeyChain,
    1169           4 :         'sender_key': sess.senderKey,
    1170           4 :         'sender_claimed_keys': sess.senderClaimedKeys,
    1171           4 :         'session_key': sess.inboundGroupSession!
    1172          12 :             .export_session(sess.inboundGroupSession!.first_known_index()),
    1173             :       };
    1174             :       // encrypt the content
    1175           8 :       final encrypted = enc.encrypt(json.encode(payload));
    1176             :       // fetch the device, if available...
    1177             :       //final device = args.client.getUserDeviceKeysByCurve25519Key(sess.senderKey);
    1178             :       // aaaand finally add the session key to our payload
    1179          16 :       roomKeyBackup.sessions[sess.sessionId] = KeyBackupData(
    1180           8 :         firstMessageIndex: sess.inboundGroupSession!.first_known_index(),
    1181           8 :         forwardedCount: sess.forwardingCurve25519KeyChain.length,
    1182           4 :         isVerified: dbSession.verified, //device?.verified ?? false,
    1183           4 :         sessionData: {
    1184           4 :           'ephemeral': encrypted.ephemeral,
    1185           4 :           'ciphertext': encrypted.ciphertext,
    1186           4 :           'mac': encrypted.mac,
    1187             :         },
    1188             :       );
    1189             :     }
    1190           4 :     enc.free();
    1191             :     return roomKeys;
    1192             :   } catch (e, s) {
    1193           0 :     Logs().e('[Key Manager] Error generating payload', e, s);
    1194           0 :     enc.free();
    1195             :     rethrow;
    1196             :   }
    1197             : }
    1198             : 
    1199             : class DbInboundGroupSessionBundle {
    1200           4 :   DbInboundGroupSessionBundle(
    1201             :       {required this.dbSession, required this.verified});
    1202             : 
    1203           0 :   factory DbInboundGroupSessionBundle.fromJson(Map<dynamic, dynamic> json) =>
    1204           0 :       DbInboundGroupSessionBundle(
    1205             :         dbSession:
    1206           0 :             StoredInboundGroupSession.fromJson(Map.from(json['dbSession'])),
    1207           0 :         verified: json['verified'],
    1208             :       );
    1209             : 
    1210           0 :   Map<String, Object> toJson() => {
    1211           0 :         'dbSession': dbSession.toJson(),
    1212           0 :         'verified': verified,
    1213             :       };
    1214             :   StoredInboundGroupSession dbSession;
    1215             :   bool verified;
    1216             : }
    1217             : 
    1218             : class GenerateUploadKeysArgs {
    1219           4 :   GenerateUploadKeysArgs(
    1220             :       {required this.pubkey, required this.dbSessions, required this.userId});
    1221             : 
    1222           0 :   factory GenerateUploadKeysArgs.fromJson(Map<dynamic, dynamic> json) =>
    1223           0 :       GenerateUploadKeysArgs(
    1224           0 :         pubkey: json['pubkey'],
    1225           0 :         dbSessions: (json['dbSessions'] as Iterable)
    1226           0 :             .map((e) => DbInboundGroupSessionBundle.fromJson(e))
    1227           0 :             .toList(),
    1228           0 :         userId: json['userId'],
    1229             :       );
    1230             : 
    1231           0 :   Map<String, Object> toJson() => {
    1232           0 :         'pubkey': pubkey,
    1233           0 :         'dbSessions': dbSessions.map((e) => e.toJson()).toList(),
    1234           0 :         'userId': userId,
    1235             :       };
    1236             : 
    1237             :   String pubkey;
    1238             :   List<DbInboundGroupSessionBundle> dbSessions;
    1239             :   String userId;
    1240             : }

Generated by: LCOV version 1.14