Merge branch 'krille/magicstrings' into 'main'

refactor: Replace some magic strings

See merge request famedly/famedlysdk!584
This commit is contained in:
Christian Pauly 2020-12-23 11:28:43 +00:00
commit bce0c1d485
6 changed files with 72 additions and 49 deletions

View File

@ -84,12 +84,13 @@ class Encryption {
} }
Future<void> handleToDeviceEvent(ToDeviceEvent event) async { Future<void> 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 // a new room key. We need to handle this asap, before other
// events in /sync are handled // events in /sync are handled
await keyManager.handleToDeviceEvent(event); 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 // "just" room key request things. We don't need these asap, so we handle
// them in the background // them in the background
unawaited(runInRoot(() => keyManager.handleToDeviceEvent(event))); unawaited(runInRoot(() => keyManager.handleToDeviceEvent(event)));
@ -115,7 +116,7 @@ class Encryption {
return; return;
} }
if (update.eventType.startsWith('m.key.verification.') || 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'] is String) &&
update.content['content']['msgtype'] update.content['content']['msgtype']
.startsWith('m.key.verification.'))) { .startsWith('m.key.verification.'))) {
@ -214,12 +215,12 @@ class Encryption {
'type': EventTypes.Encrypted, 'type': EventTypes.Encrypted,
}; };
decryptedPayload['content']['body'] = exception.toString(); decryptedPayload['content']['body'] = exception.toString();
decryptedPayload['content']['msgtype'] = 'm.bad.encrypted'; decryptedPayload['content']['msgtype'] = MessageTypes.BadEncrypted;
decryptedPayload['content']['can_request_session'] = true; decryptedPayload['content']['can_request_session'] = true;
} else { } else {
decryptedPayload = { decryptedPayload = {
'content': <String, dynamic>{ 'content': <String, dynamic>{
'msgtype': 'm.bad.encrypted', 'msgtype': MessageTypes.BadEncrypted,
'body': exception.toString(), 'body': exception.toString(),
}, },
'type': EventTypes.Encrypted, 'type': EventTypes.Encrypted,

View File

@ -376,7 +376,7 @@ class KeyManager {
} }
// send out the key // send out the key
await client.sendToDeviceEncrypted( await client.sendToDeviceEncrypted(
devicesToReceive, 'm.room_key', rawSession); devicesToReceive, EventTypes.RoomKey, rawSession);
} }
} catch (e, s) { } catch (e, s) {
Logs().e( Logs().e(
@ -461,7 +461,8 @@ class KeyManager {
key: client.userID, key: client.userID,
); );
try { try {
await client.sendToDeviceEncrypted(deviceKeys, 'm.room_key', rawSession); await client.sendToDeviceEncrypted(
deviceKeys, EventTypes.RoomKey, rawSession);
await storeOutboundGroupSession(roomId, sess); await storeOutboundGroupSession(roomId, sess);
_outboundGroupSessions[roomId] = sess; _outboundGroupSessions[roomId] = sess;
} catch (e, s) { } catch (e, s) {
@ -642,7 +643,7 @@ class KeyManager {
final userList = await room.requestParticipants(); final userList = await room.requestParticipants();
await client.sendToDevicesOfUserIds( await client.sendToDevicesOfUserIds(
userList.map<String>((u) => u.id).toSet(), userList.map<String>((u) => u.id).toSet(),
'm.room_key_request', EventTypes.RoomKeyRequest,
{ {
'action': 'request', 'action': 'request',
'body': { 'body': {
@ -736,7 +737,7 @@ class KeyManager {
/// Handle an incoming to_device event that is related to key sharing /// Handle an incoming to_device event that is related to key sharing
Future<void> handleToDeviceEvent(ToDeviceEvent event) async { Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
if (event.type == 'm.room_key_request') { if (event.type == EventTypes.RoomKeyRequest) {
if (!(event.content['request_id'] is String)) { if (!(event.content['request_id'] is String)) {
return; // invalid event return; // invalid event
} }
@ -822,7 +823,7 @@ class KeyManager {
request.canceled = true; request.canceled = true;
incomingShareRequests.remove(request.requestId); incomingShareRequests.remove(request.requestId);
} }
} else if (event.type == 'm.forwarded_room_key') { } else if (event.type == EventTypes.ForwardedRoomKey) {
// we *received* an incoming key request // we *received* an incoming key request
if (event.encryptedContent == null) { if (event.encryptedContent == null) {
return; // event wasn't encrypted, this is a security risk return; // event wasn't encrypted, this is a security risk
@ -879,11 +880,11 @@ class KeyManager {
data[device.userId][device.deviceId] = sendToDeviceMessage; data[device.userId][device.deviceId] = sendToDeviceMessage;
} }
await client.sendToDevice( await client.sendToDevice(
'm.room_key_request', EventTypes.RoomKeyRequest,
client.generateUniqueTransactionId(), client.generateUniqueTransactionId(),
data, data,
); );
} else if (event.type == 'm.room_key') { } else if (event.type == EventTypes.RoomKey) {
if (event.encryptedContent == null) { if (event.encryptedContent == null) {
return; // the event wasn't encrypted, this is a security risk; 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 // send the actual reply of the key back to the requester
await keyManager.client.sendToDeviceEncrypted( await keyManager.client.sendToDeviceEncrypted(
[requestingDevice], [requestingDevice],
'm.forwarded_room_key', EventTypes.ForwardedRoomKey,
message, message,
); );
keyManager.incomingShareRequests.remove(request.requestId); keyManager.incomingShareRequests.remove(request.requestId);

View File

@ -55,7 +55,7 @@ class KeyVerificationManager {
} }
Future<void> handleToDeviceEvent(ToDeviceEvent event) async { Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
if (!event.type.startsWith('m.key.verification') || if (!event.type.startsWith('m.key.verification.') ||
client.verificationMethods.isEmpty) { client.verificationMethods.isEmpty) {
return; return;
} }
@ -66,11 +66,11 @@ class KeyVerificationManager {
} }
if (_requests.containsKey(transactionId)) { if (_requests.containsKey(transactionId)) {
// make sure that new requests can't come from ourself // 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); await _requests[transactionId].handlePayload(event.type, event.content);
} }
} else { } else {
if (!{'m.key.verification.request', 'm.key.verification.start'} if (!{EventTypes.KeyVerificationRequest, EventTypes.KeyVerificationStart}
.contains(event.type)) { .contains(event.type)) {
return; // we can only start on these return; // we can only start on these
} }
@ -97,7 +97,7 @@ class KeyVerificationManager {
client.verificationMethods.isEmpty) { client.verificationMethods.isEmpty) {
return; return;
} }
if (type == 'm.key.verification.request') { if (type == EventTypes.KeyVerificationRequest) {
event['content']['timestamp'] = event['origin_server_ts']; event['content']['timestamp'] = event['origin_server_ts'];
} }
@ -118,7 +118,7 @@ class KeyVerificationManager {
_requests.remove(transactionId); _requests.remove(transactionId);
} }
} else if (event['sender'] != client.userID) { } else if (event['sender'] != client.userID) {
if (!{'m.key.verification.request', 'm.key.verification.start'} if (!{EventTypes.KeyVerificationRequest, EventTypes.KeyVerificationStart}
.contains(type)) { .contains(type)) {
return; // we can only start on these return; // we can only start on these
} }

View File

@ -408,7 +408,7 @@ class SSSS {
devices: devices, devices: devices,
); );
pendingShareRequests[requestId] = request; pendingShareRequests[requestId] = request;
await client.sendToDeviceEncrypted(devices, 'm.secret.request', { await client.sendToDeviceEncrypted(devices, EventTypes.SecretRequest, {
'action': 'request', 'action': 'request',
'requesting_device_id': client.deviceID, 'requesting_device_id': client.deviceID,
'request_id': requestId, 'request_id': requestId,
@ -438,7 +438,7 @@ class SSSS {
} }
Future<void> handleToDeviceEvent(ToDeviceEvent event) async { Future<void> handleToDeviceEvent(ToDeviceEvent event) async {
if (event.type == 'm.secret.request') { if (event.type == EventTypes.SecretRequest) {
// got a request to share a secret // got a request to share a secret
Logs().i('[SSSS] Received sharing request...'); Logs().i('[SSSS] Received sharing request...');
if (event.sender != client.userID || if (event.sender != client.userID ||
@ -468,12 +468,12 @@ class SSSS {
Logs().i('[SSSS] Replying with secret for ${type}'); Logs().i('[SSSS] Replying with secret for ${type}');
await client.sendToDeviceEncrypted( await client.sendToDeviceEncrypted(
[device], [device],
'm.secret.send', EventTypes.SecretSend,
{ {
'request_id': event.content['request_id'], 'request_id': event.content['request_id'],
'secret': secret, 'secret': secret,
}); });
} else if (event.type == 'm.secret.send') { } else if (event.type == EventTypes.SecretSend) {
// receiving a secret we asked for // receiving a secret we asked for
Logs().i('[SSSS] Received shared secret...'); Logs().i('[SSSS] Received shared secret...');
if (event.sender != client.userID || if (event.sender != client.userID ||

View File

@ -176,7 +176,7 @@ class KeyVerification {
} }
Future<void> sendStart() async { Future<void> sendStart() async {
await send('m.key.verification.request', { await send(EventTypes.KeyVerificationRequest, {
'methods': knownVerificationMethods, 'methods': knownVerificationMethods,
if (room == null) 'timestamp': DateTime.now().millisecondsSinceEpoch, if (room == null) 'timestamp': DateTime.now().millisecondsSinceEpoch,
}); });
@ -214,7 +214,7 @@ class KeyVerification {
try { try {
var thisLastStep = lastStep; var thisLastStep = lastStep;
switch (type) { switch (type) {
case 'm.key.verification.request': case EventTypes.KeyVerificationRequest:
_deviceId ??= payload['from_device']; _deviceId ??= payload['from_device'];
transactionId ??= eventId ?? payload['transaction_id']; transactionId ??= eventId ?? payload['transaction_id'];
// verify the timestamp // verify the timestamp
@ -253,7 +253,7 @@ class KeyVerification {
}; };
makePayload(cancelPayload); makePayload(cancelPayload);
await client.sendToDeviceEncrypted( await client.sendToDeviceEncrypted(
devices, 'm.key.verification.cancel', cancelPayload); devices, EventTypes.KeyVerificationCancel, cancelPayload);
} }
_deviceId ??= payload['from_device']; _deviceId ??= payload['from_device'];
possibleMethods = possibleMethods =
@ -271,7 +271,7 @@ class KeyVerification {
await method.sendStart(); await method.sendStart();
setState(KeyVerificationState.waitingAccept); setState(KeyVerificationState.waitingAccept);
break; break;
case 'm.key.verification.start': case EventTypes.KeyVerificationStart:
_deviceId ??= payload['from_device']; _deviceId ??= payload['from_device'];
transactionId ??= eventId ?? payload['transaction_id']; transactionId ??= eventId ?? payload['transaction_id'];
if (method != null) { if (method != null) {
@ -288,7 +288,7 @@ class KeyVerification {
// the other start won, let's hand off // the other start won, let's hand off
startedVerification = false; // it is now as if they started startedVerification = false; // it is now as if they started
thisLastStep = lastStep = 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 method.dispose(); // in case anything got created already
} }
} else { } else {
@ -297,7 +297,8 @@ class KeyVerification {
return; return;
} }
} }
if (!(await verifyLastStep(['m.key.verification.request', null]))) { if (!(await verifyLastStep(
[EventTypes.KeyVerificationRequest, null]))) {
return; // abort return; // abort
} }
if (!knownVerificationMethods.contains(payload['method'])) { if (!knownVerificationMethods.contains(payload['method'])) {
@ -324,10 +325,10 @@ class KeyVerification {
await method.handlePayload(type, payload); await method.handlePayload(type, payload);
} }
break; break;
case 'm.key.verification.done': case EventTypes.KeyVerificationDone:
// do nothing // do nothing
break; break;
case 'm.key.verification.cancel': case EventTypes.KeyVerificationCancel:
canceled = true; canceled = true;
canceledCode = payload['code']; canceledCode = payload['code'];
canceledReason = payload['reason']; canceledReason = payload['reason'];
@ -390,19 +391,21 @@ class KeyVerification {
/// called when the user accepts an incoming verification /// called when the user accepts an incoming verification
Future<void> acceptVerification() async { Future<void> acceptVerification() async {
if (!(await verifyLastStep( if (!(await verifyLastStep([
['m.key.verification.request', 'm.key.verification.start']))) { EventTypes.KeyVerificationRequest,
EventTypes.KeyVerificationStart
]))) {
return; return;
} }
setState(KeyVerificationState.waitingAccept); setState(KeyVerificationState.waitingAccept);
if (lastStep == 'm.key.verification.request') { if (lastStep == EventTypes.KeyVerificationRequest) {
// we need to send a ready event // we need to send a ready event
await send('m.key.verification.ready', { await send('m.key.verification.ready', {
'methods': possibleMethods, 'methods': possibleMethods,
}); });
} else { } else {
// we need to send an accept event // 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) { if (isDone) {
return; return;
} }
if (!(await verifyLastStep( if (!(await verifyLastStep([
['m.key.verification.request', 'm.key.verification.start']))) { EventTypes.KeyVerificationRequest,
EventTypes.KeyVerificationStart
]))) {
return; return;
} }
await cancel('m.user'); await cancel('m.user');
@ -511,7 +516,7 @@ class KeyVerification {
// we do it in the background, thus no await needed here // we do it in the background, thus no await needed here
unawaited(maybeRequestSSSSSecrets()); unawaited(maybeRequestSSSSSecrets());
} }
await send('m.key.verification.done', {}); await send(EventTypes.KeyVerificationDone, {});
var askingSSSS = false; var askingSSSS = false;
if (encryption.crossSigning.enabled && if (encryption.crossSigning.enabled &&
@ -555,7 +560,7 @@ class KeyVerification {
Future<void> cancel([String code = 'm.unknown', bool quiet = false]) async { Future<void> cancel([String code = 'm.unknown', bool quiet = false]) async {
if (!quiet && (deviceId != null || room != null)) { if (!quiet && (deviceId != null || room != null)) {
await send('m.key.verification.cancel', { await send(EventTypes.KeyVerificationCancel, {
'reason': code, 'reason': code,
'code': code, 'code': code,
}); });
@ -584,7 +589,7 @@ class KeyVerification {
Logs().i('[Key Verification] Sending type ${type}: ' + payload.toString()); Logs().i('[Key Verification] Sending type ${type}: ' + payload.toString());
if (room != null) { if (room != null) {
Logs().i('[Key Verification] Sending to ${userId} in room ${room.id}...'); 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['msgtype'] = type;
payload['to'] = userId; payload['to'] = userId;
payload['body'] = payload['body'] =
@ -599,7 +604,7 @@ class KeyVerification {
} else { } else {
Logs().i('[Key Verification] Sending to ${userId} device ${deviceId}...'); Logs().i('[Key Verification] Sending to ${userId} device ${deviceId}...');
if (deviceId == '*') { if (deviceId == '*') {
if ({'m.key.verification.request'}.contains(type)) { if ({EventTypes.KeyVerificationRequest}.contains(type)) {
await client.sendToDevicesOfUserIds({userId}, type, payload); await client.sendToDevicesOfUserIds({userId}, type, payload);
} else { } else {
Logs().e( Logs().e(
@ -685,9 +690,11 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod {
Future<void> handlePayload(String type, Map<String, dynamic> payload) async { Future<void> handlePayload(String type, Map<String, dynamic> payload) async {
try { try {
switch (type) { switch (type) {
case 'm.key.verification.start': case EventTypes.KeyVerificationStart:
if (!(await request.verifyLastStep( if (!(await request.verifyLastStep([
['m.key.verification.request', 'm.key.verification.start']))) { EventTypes.KeyVerificationRequest,
EventTypes.KeyVerificationStart
]))) {
return; // abort return; // abort
} }
if (!validateStart(payload)) { if (!validateStart(payload)) {
@ -696,7 +703,7 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod {
} }
await _sendAccept(); await _sendAccept();
break; break;
case 'm.key.verification.accept': case EventTypes.KeyVerificationAccept:
if (!(await request.verifyLastStep(['m.key.verification.ready']))) { if (!(await request.verifyLastStep(['m.key.verification.ready']))) {
return; return;
} }
@ -707,12 +714,14 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod {
await _sendKey(); await _sendKey();
break; break;
case 'm.key.verification.key': case 'm.key.verification.key':
if (!(await request.verifyLastStep( if (!(await request.verifyLastStep([
['m.key.verification.accept', 'm.key.verification.start']))) { EventTypes.KeyVerificationAccept,
EventTypes.KeyVerificationStart
]))) {
return; return;
} }
_handleKey(payload); _handleKey(payload);
if (request.lastStep == 'm.key.verification.start') { if (request.lastStep == EventTypes.KeyVerificationStart) {
// we need to send our key // we need to send our key
await _sendKey(); await _sendKey();
} else { } else {
@ -766,7 +775,7 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod {
request.makePayload(payload); request.makePayload(payload);
// We just store the canonical json in here for later verification // We just store the canonical json in here for later verification
startCanonicalJson = String.fromCharCodes(canonicalJson.encode(payload)); startCanonicalJson = String.fromCharCodes(canonicalJson.encode(payload));
await request.send('m.key.verification.start', payload); await request.send(EventTypes.KeyVerificationStart, payload);
} }
@override @override
@ -805,7 +814,7 @@ class _KeyVerificationMethodSas extends _KeyVerificationMethod {
Future<void> _sendAccept() async { Future<void> _sendAccept() async {
sas = olm.SAS(); sas = olm.SAS();
commitment = _makeCommitment(sas.get_pubkey(), startCanonicalJson); commitment = _makeCommitment(sas.get_pubkey(), startCanonicalJson);
await request.send('m.key.verification.accept', { await request.send(EventTypes.KeyVerificationAccept, {
'method': type, 'method': type,
'key_agreement_protocol': keyAgreementProtocol, 'key_agreement_protocol': keyAgreementProtocol,
'hash': hash, 'hash': hash,

View File

@ -17,6 +17,7 @@
*/ */
abstract class EventTypes { abstract class EventTypes {
// Room timeline and state event types
static const String Message = 'm.room.message'; static const String Message = 'm.room.message';
static const String Sticker = 'm.sticker'; static const String Sticker = 'm.sticker';
static const String Reaction = 'm.reaction'; static const String Reaction = 'm.reaction';
@ -42,6 +43,17 @@ abstract class EventTypes {
static const String CallHangup = 'm.call.hangup'; static const String CallHangup = 'm.call.hangup';
static const String Unknown = 'm.unknown'; 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 CrossSigningSelfSigning = 'm.cross_signing.self_signing';
static const String CrossSigningUserSigning = 'm.cross_signing.user_signing'; static const String CrossSigningUserSigning = 'm.cross_signing.user_signing';
static const String CrossSigningMasterKey = 'm.cross_signing.master'; static const String CrossSigningMasterKey = 'm.cross_signing.master';