From 79fe7b08780705fecf1fd942397575e1ad534c83 Mon Sep 17 00:00:00 2001 From: Christian Pauly Date: Wed, 23 Dec 2020 12:14:16 +0100 Subject: [PATCH] refactor: Replace some magic strings --- lib/encryption/encryption.dart | 11 ++-- lib/encryption/key_manager.dart | 17 +++--- lib/encryption/key_verification_manager.dart | 10 ++-- lib/encryption/ssss.dart | 8 +-- lib/encryption/utils/key_verification.dart | 63 +++++++++++--------- lib/matrix_api/model/event_types.dart | 12 ++++ 6 files changed, 72 insertions(+), 49 deletions(-) diff --git a/lib/encryption/encryption.dart b/lib/encryption/encryption.dart index ba5effd2..9fe95ff2 100644 --- a/lib/encryption/encryption.dart +++ b/lib/encryption/encryption.dart @@ -84,12 +84,13 @@ class Encryption { } Future handleToDeviceEvent(ToDeviceEvent event) async { - if (event.type == 'm.room_key') { + if (event.type == EventTypes.RoomKey) { // a new room key. We need to handle this asap, before other // events in /sync are handled await keyManager.handleToDeviceEvent(event); } - if (['m.room_key_request', 'm.forwarded_room_key'].contains(event.type)) { + if ([EventTypes.RoomKeyRequest, EventTypes.ForwardedRoomKey] + .contains(event.type)) { // "just" room key request things. We don't need these asap, so we handle // them in the background unawaited(runInRoot(() => keyManager.handleToDeviceEvent(event))); @@ -115,7 +116,7 @@ class Encryption { return; } if (update.eventType.startsWith('m.key.verification.') || - (update.eventType == 'm.room.message' && + (update.eventType == EventTypes.Message && (update.content['content']['msgtype'] is String) && update.content['content']['msgtype'] .startsWith('m.key.verification.'))) { @@ -214,12 +215,12 @@ class Encryption { 'type': EventTypes.Encrypted, }; decryptedPayload['content']['body'] = exception.toString(); - decryptedPayload['content']['msgtype'] = 'm.bad.encrypted'; + decryptedPayload['content']['msgtype'] = MessageTypes.BadEncrypted; decryptedPayload['content']['can_request_session'] = true; } else { decryptedPayload = { 'content': { - 'msgtype': 'm.bad.encrypted', + 'msgtype': MessageTypes.BadEncrypted, 'body': exception.toString(), }, 'type': EventTypes.Encrypted, diff --git a/lib/encryption/key_manager.dart b/lib/encryption/key_manager.dart index dbd75e27..69340cb9 100644 --- a/lib/encryption/key_manager.dart +++ b/lib/encryption/key_manager.dart @@ -376,7 +376,7 @@ class KeyManager { } // send out the key await client.sendToDeviceEncrypted( - devicesToReceive, 'm.room_key', rawSession); + devicesToReceive, EventTypes.RoomKey, rawSession); } } catch (e, s) { Logs().e( @@ -461,7 +461,8 @@ class KeyManager { key: client.userID, ); try { - await client.sendToDeviceEncrypted(deviceKeys, 'm.room_key', rawSession); + await client.sendToDeviceEncrypted( + deviceKeys, EventTypes.RoomKey, rawSession); await storeOutboundGroupSession(roomId, sess); _outboundGroupSessions[roomId] = sess; } catch (e, s) { @@ -642,7 +643,7 @@ class KeyManager { final userList = await room.requestParticipants(); await client.sendToDevicesOfUserIds( userList.map((u) => u.id).toSet(), - 'm.room_key_request', + EventTypes.RoomKeyRequest, { 'action': 'request', 'body': { @@ -736,7 +737,7 @@ class KeyManager { /// Handle an incoming to_device event that is related to key sharing Future handleToDeviceEvent(ToDeviceEvent event) async { - if (event.type == 'm.room_key_request') { + if (event.type == EventTypes.RoomKeyRequest) { if (!(event.content['request_id'] is String)) { return; // invalid event } @@ -822,7 +823,7 @@ class KeyManager { request.canceled = true; incomingShareRequests.remove(request.requestId); } - } else if (event.type == 'm.forwarded_room_key') { + } else if (event.type == EventTypes.ForwardedRoomKey) { // we *received* an incoming key request if (event.encryptedContent == null) { return; // event wasn't encrypted, this is a security risk @@ -879,11 +880,11 @@ class KeyManager { data[device.userId][device.deviceId] = sendToDeviceMessage; } await client.sendToDevice( - 'm.room_key_request', + EventTypes.RoomKeyRequest, client.generateUniqueTransactionId(), data, ); - } else if (event.type == 'm.room_key') { + } else if (event.type == EventTypes.RoomKey) { if (event.encryptedContent == null) { return; // the event wasn't encrypted, this is a security risk; } @@ -974,7 +975,7 @@ class RoomKeyRequest extends ToDeviceEvent { // send the actual reply of the key back to the requester await keyManager.client.sendToDeviceEncrypted( [requestingDevice], - 'm.forwarded_room_key', + EventTypes.ForwardedRoomKey, message, ); keyManager.incomingShareRequests.remove(request.requestId); diff --git a/lib/encryption/key_verification_manager.dart b/lib/encryption/key_verification_manager.dart index 7a599304..e452a036 100644 --- a/lib/encryption/key_verification_manager.dart +++ b/lib/encryption/key_verification_manager.dart @@ -55,7 +55,7 @@ class KeyVerificationManager { } Future handleToDeviceEvent(ToDeviceEvent event) async { - if (!event.type.startsWith('m.key.verification') || + if (!event.type.startsWith('m.key.verification.') || client.verificationMethods.isEmpty) { return; } @@ -66,11 +66,11 @@ class KeyVerificationManager { } if (_requests.containsKey(transactionId)) { // make sure that new requests can't come from ourself - if (!{'m.key.verification.request'}.contains(event.type)) { + if (!{EventTypes.KeyVerificationRequest}.contains(event.type)) { await _requests[transactionId].handlePayload(event.type, event.content); } } else { - if (!{'m.key.verification.request', 'm.key.verification.start'} + if (!{EventTypes.KeyVerificationRequest, EventTypes.KeyVerificationStart} .contains(event.type)) { return; // we can only start on these } @@ -97,7 +97,7 @@ class KeyVerificationManager { client.verificationMethods.isEmpty) { return; } - if (type == 'm.key.verification.request') { + if (type == EventTypes.KeyVerificationRequest) { event['content']['timestamp'] = event['origin_server_ts']; } @@ -118,7 +118,7 @@ class KeyVerificationManager { _requests.remove(transactionId); } } else if (event['sender'] != client.userID) { - if (!{'m.key.verification.request', 'm.key.verification.start'} + if (!{EventTypes.KeyVerificationRequest, EventTypes.KeyVerificationStart} .contains(type)) { return; // we can only start on these } diff --git a/lib/encryption/ssss.dart b/lib/encryption/ssss.dart index ecec05cd..9c4a3eef 100644 --- a/lib/encryption/ssss.dart +++ b/lib/encryption/ssss.dart @@ -408,7 +408,7 @@ class SSSS { devices: devices, ); pendingShareRequests[requestId] = request; - await client.sendToDeviceEncrypted(devices, 'm.secret.request', { + await client.sendToDeviceEncrypted(devices, EventTypes.SecretRequest, { 'action': 'request', 'requesting_device_id': client.deviceID, 'request_id': requestId, @@ -438,7 +438,7 @@ class SSSS { } Future handleToDeviceEvent(ToDeviceEvent event) async { - if (event.type == 'm.secret.request') { + if (event.type == EventTypes.SecretRequest) { // got a request to share a secret Logs().i('[SSSS] Received sharing request...'); if (event.sender != client.userID || @@ -468,12 +468,12 @@ class SSSS { Logs().i('[SSSS] Replying with secret for ${type}'); await client.sendToDeviceEncrypted( [device], - 'm.secret.send', + EventTypes.SecretSend, { 'request_id': event.content['request_id'], 'secret': secret, }); - } else if (event.type == 'm.secret.send') { + } else if (event.type == EventTypes.SecretSend) { // receiving a secret we asked for Logs().i('[SSSS] Received shared secret...'); if (event.sender != client.userID || diff --git a/lib/encryption/utils/key_verification.dart b/lib/encryption/utils/key_verification.dart index 4b9546aa..cc6f9872 100644 --- a/lib/encryption/utils/key_verification.dart +++ b/lib/encryption/utils/key_verification.dart @@ -176,7 +176,7 @@ class KeyVerification { } Future sendStart() async { - await send('m.key.verification.request', { + await send(EventTypes.KeyVerificationRequest, { 'methods': knownVerificationMethods, if (room == null) 'timestamp': DateTime.now().millisecondsSinceEpoch, }); @@ -214,7 +214,7 @@ class KeyVerification { try { var thisLastStep = lastStep; switch (type) { - case 'm.key.verification.request': + case EventTypes.KeyVerificationRequest: _deviceId ??= payload['from_device']; transactionId ??= eventId ?? payload['transaction_id']; // verify the timestamp @@ -253,7 +253,7 @@ class KeyVerification { }; makePayload(cancelPayload); await client.sendToDeviceEncrypted( - devices, 'm.key.verification.cancel', cancelPayload); + devices, EventTypes.KeyVerificationCancel, cancelPayload); } _deviceId ??= payload['from_device']; possibleMethods = @@ -271,7 +271,7 @@ class KeyVerification { await method.sendStart(); setState(KeyVerificationState.waitingAccept); break; - case 'm.key.verification.start': + case EventTypes.KeyVerificationStart: _deviceId ??= payload['from_device']; transactionId ??= eventId ?? payload['transaction_id']; if (method != null) { @@ -288,7 +288,7 @@ class KeyVerification { // the other start won, let's hand off startedVerification = false; // it is now as if they started thisLastStep = lastStep = - 'm.key.verification.request'; // we fake the last step + EventTypes.KeyVerificationRequest; // we fake the last step method.dispose(); // in case anything got created already } } else { @@ -297,7 +297,8 @@ class KeyVerification { return; } } - if (!(await verifyLastStep(['m.key.verification.request', null]))) { + if (!(await verifyLastStep( + [EventTypes.KeyVerificationRequest, null]))) { return; // abort } if (!knownVerificationMethods.contains(payload['method'])) { @@ -324,10 +325,10 @@ class KeyVerification { await method.handlePayload(type, payload); } break; - case 'm.key.verification.done': + case EventTypes.KeyVerificationDone: // do nothing break; - case 'm.key.verification.cancel': + case EventTypes.KeyVerificationCancel: canceled = true; canceledCode = payload['code']; canceledReason = payload['reason']; @@ -390,19 +391,21 @@ class KeyVerification { /// called when the user accepts an incoming verification Future acceptVerification() async { - if (!(await verifyLastStep( - ['m.key.verification.request', 'm.key.verification.start']))) { + if (!(await verifyLastStep([ + EventTypes.KeyVerificationRequest, + EventTypes.KeyVerificationStart + ]))) { return; } setState(KeyVerificationState.waitingAccept); - if (lastStep == 'm.key.verification.request') { + if (lastStep == EventTypes.KeyVerificationRequest) { // we need to send a ready event await send('m.key.verification.ready', { 'methods': possibleMethods, }); } else { // we need to send an accept event - await method.handlePayload('m.key.verification.start', startPaylaod); + await method.handlePayload(EventTypes.KeyVerificationStart, startPaylaod); } } @@ -411,8 +414,10 @@ class KeyVerification { if (isDone) { return; } - if (!(await verifyLastStep( - ['m.key.verification.request', 'm.key.verification.start']))) { + if (!(await verifyLastStep([ + EventTypes.KeyVerificationRequest, + EventTypes.KeyVerificationStart + ]))) { return; } await cancel('m.user'); @@ -511,7 +516,7 @@ class KeyVerification { // we do it in the background, thus no await needed here unawaited(maybeRequestSSSSSecrets()); } - await send('m.key.verification.done', {}); + await send(EventTypes.KeyVerificationDone, {}); var askingSSSS = false; if (encryption.crossSigning.enabled && @@ -555,7 +560,7 @@ class KeyVerification { Future cancel([String code = 'm.unknown', bool quiet = false]) async { if (!quiet && (deviceId != null || room != null)) { - await send('m.key.verification.cancel', { + await send(EventTypes.KeyVerificationCancel, { 'reason': code, 'code': code, }); @@ -584,7 +589,7 @@ class KeyVerification { Logs().i('[Key Verification] Sending type ${type}: ' + payload.toString()); if (room != null) { Logs().i('[Key Verification] Sending to ${userId} in room ${room.id}...'); - if ({'m.key.verification.request'}.contains(type)) { + if ({EventTypes.KeyVerificationRequest}.contains(type)) { payload['msgtype'] = type; payload['to'] = userId; payload['body'] = @@ -599,7 +604,7 @@ class KeyVerification { } else { Logs().i('[Key Verification] Sending to ${userId} device ${deviceId}...'); if (deviceId == '*') { - if ({'m.key.verification.request'}.contains(type)) { + if ({EventTypes.KeyVerificationRequest}.contains(type)) { await client.sendToDevicesOfUserIds({userId}, type, payload); } else { Logs().e( @@ -685,9 +690,11 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod { Future handlePayload(String type, Map payload) async { try { switch (type) { - case 'm.key.verification.start': - if (!(await request.verifyLastStep( - ['m.key.verification.request', 'm.key.verification.start']))) { + case EventTypes.KeyVerificationStart: + if (!(await request.verifyLastStep([ + EventTypes.KeyVerificationRequest, + EventTypes.KeyVerificationStart + ]))) { return; // abort } if (!validateStart(payload)) { @@ -696,7 +703,7 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod { } await _sendAccept(); break; - case 'm.key.verification.accept': + case EventTypes.KeyVerificationAccept: if (!(await request.verifyLastStep(['m.key.verification.ready']))) { return; } @@ -707,12 +714,14 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod { await _sendKey(); break; case 'm.key.verification.key': - if (!(await request.verifyLastStep( - ['m.key.verification.accept', 'm.key.verification.start']))) { + if (!(await request.verifyLastStep([ + EventTypes.KeyVerificationAccept, + EventTypes.KeyVerificationStart + ]))) { return; } _handleKey(payload); - if (request.lastStep == 'm.key.verification.start') { + if (request.lastStep == EventTypes.KeyVerificationStart) { // we need to send our key await _sendKey(); } else { @@ -766,7 +775,7 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod { request.makePayload(payload); // We just store the canonical json in here for later verification startCanonicalJson = String.fromCharCodes(canonicalJson.encode(payload)); - await request.send('m.key.verification.start', payload); + await request.send(EventTypes.KeyVerificationStart, payload); } @override @@ -805,7 +814,7 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod { Future _sendAccept() async { sas = olm.SAS(); commitment = _makeCommitment(sas.get_pubkey(), startCanonicalJson); - await request.send('m.key.verification.accept', { + await request.send(EventTypes.KeyVerificationAccept, { 'method': type, 'key_agreement_protocol': keyAgreementProtocol, 'hash': hash, diff --git a/lib/matrix_api/model/event_types.dart b/lib/matrix_api/model/event_types.dart index cbd4cd00..36b63a7d 100644 --- a/lib/matrix_api/model/event_types.dart +++ b/lib/matrix_api/model/event_types.dart @@ -17,6 +17,7 @@ */ abstract class EventTypes { + // Room timeline and state event types static const String Message = 'm.room.message'; static const String Sticker = 'm.sticker'; static const String Reaction = 'm.reaction'; @@ -42,6 +43,17 @@ abstract class EventTypes { static const String CallHangup = 'm.call.hangup'; static const String Unknown = 'm.unknown'; + // To device event types + static const String RoomKey = 'm.room_key'; + static const String ForwardedRoomKey = 'm.forwarded_room_key'; + static const String RoomKeyRequest = 'm.room_key_request'; + static const String KeyVerificationRequest = 'm.key.verification.request'; + static const String KeyVerificationStart = 'm.key.verification.start'; + static const String KeyVerificationDone = 'm.key.verification.done'; + static const String KeyVerificationCancel = 'm.key.verification.cancel'; + static const String KeyVerificationAccept = 'm.key.verification.accept'; + static const String SecretRequest = 'm.secret.request'; + static const String SecretSend = 'm.secret.send'; static const String CrossSigningSelfSigning = 'm.cross_signing.self_signing'; static const String CrossSigningUserSigning = 'm.cross_signing.user_signing'; static const String CrossSigningMasterKey = 'm.cross_signing.master';