fix: Fix style issues

This commit is contained in:
PapaTutuWawa 2023-06-15 21:20:24 +02:00
parent da11e60f79
commit b0bba4fe82
8 changed files with 92 additions and 42 deletions

View File

@ -251,7 +251,11 @@ class OmemoDoubleRatchet {
/// If the computed HMAC does not match the HMAC in [message], returns /// If the computed HMAC does not match the HMAC in [message], returns
/// [InvalidMessageHMACError]. If it matches, returns the decrypted /// [InvalidMessageHMACError]. If it matches, returns the decrypted
/// payload. /// payload.
Future<Result<OmemoError, List<int>>> _decrypt(OMEMOAuthenticatedMessage message, List<int> ciphertext, List<int> mk) async { Future<Result<OmemoError, List<int>>> _decrypt(
OMEMOAuthenticatedMessage message,
List<int> ciphertext,
List<int> mk,
) async {
final keys = await deriveEncryptionKeys(mk, encryptHkdfInfoString); final keys = await deriveEncryptionKeys(mk, encryptHkdfInfoString);
final hmacInput = concat([sessionAd, message.message]); final hmacInput = concat([sessionAd, message.message]);
@ -260,7 +264,8 @@ class OmemoDoubleRatchet {
return Result(InvalidMessageHMACError()); return Result(InvalidMessageHMACError());
} }
final plaintext = await aes256CbcDecrypt(ciphertext, keys.encryptionKey, keys.iv); final plaintext =
await aes256CbcDecrypt(ciphertext, keys.encryptionKey, keys.iv);
if (plaintext.isType<MalformedCiphertextError>()) { if (plaintext.isType<MalformedCiphertextError>()) {
return Result(plaintext.get<MalformedCiphertextError>()); return Result(plaintext.get<MalformedCiphertextError>());
} }
@ -273,7 +278,10 @@ class OmemoDoubleRatchet {
/// ///
/// If the decryption is successful, returns the plaintext payload. If an error occurs, like /// If the decryption is successful, returns the plaintext payload. If an error occurs, like
/// an [InvalidMessageHMACError], that is returned instead. /// an [InvalidMessageHMACError], that is returned instead.
Future<Result<OmemoError, List<int>?>> _trySkippedMessageKeys(OMEMOAuthenticatedMessage message, OMEMOMessage header) async { Future<Result<OmemoError, List<int>?>> _trySkippedMessageKeys(
OMEMOAuthenticatedMessage message,
OMEMOMessage header,
) async {
final key = SkippedKey( final key = SkippedKey(
OmemoPublicKey.fromBytes(header.dhPub, KeyPairType.x25519), OmemoPublicKey.fromBytes(header.dhPub, KeyPairType.x25519),
header.n, header.n,
@ -292,7 +300,9 @@ class OmemoDoubleRatchet {
/// ///
/// If everything goes well, returns the plaintext payload. If an error occurs, that /// If everything goes well, returns the plaintext payload. If an error occurs, that
/// is returned instead. /// is returned instead.
Future<Result<OmemoError, List<int>>> ratchetDecrypt(OMEMOAuthenticatedMessage message) async { Future<Result<OmemoError, List<int>>> ratchetDecrypt(
OMEMOAuthenticatedMessage message,
) async {
final header = OMEMOMessage.fromBuffer(message.message); final header = OMEMOMessage.fromBuffer(message.message);
// Try skipped keys // Try skipped keys
@ -343,10 +353,10 @@ class OmemoDoubleRatchet {
// Fill-in the header and serialize it here so we do it only once // Fill-in the header and serialize it here so we do it only once
final header = OMEMOMessage() final header = OMEMOMessage()
..dhPub = await dhs.pk.getBytes() ..dhPub = await dhs.pk.getBytes()
..pn = pn ..pn = pn
..n = ns ..n = ns
..ciphertext = ciphertext; ..ciphertext = ciphertext;
final headerBytes = header.writeToBuffer(); final headerBytes = header.writeToBuffer();
// Increment the send counter // Increment the send counter

View File

@ -1,8 +1,6 @@
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:omemo_dart/src/errors.dart';
import 'package:omemo_dart/src/omemo/encrypted_key.dart'; import 'package:omemo_dart/src/omemo/encrypted_key.dart';
import 'package:omemo_dart/src/omemo/errors.dart'; import 'package:omemo_dart/src/omemo/errors.dart';
import 'package:omemo_dart/src/omemo/ratchet_map_key.dart';
@immutable @immutable
class EncryptionResult { class EncryptionResult {

View File

@ -1,5 +1,4 @@
import 'dart:async'; import 'dart:async';
import 'dart:collection';
import 'dart:convert'; import 'dart:convert';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:cryptography/cryptography.dart'; import 'package:cryptography/cryptography.dart';
@ -143,7 +142,8 @@ class OmemoManager {
/// Returns a list of new bundles, that may be empty. /// Returns a list of new bundles, that may be empty.
Future<List<OmemoBundle>> _fetchNewOmemoBundles(String jid) async { Future<List<OmemoBundle>> _fetchNewOmemoBundles(String jid) async {
// Do we have to request the device list or are we already up-to-date? // Do we have to request the device list or are we already up-to-date?
if (!_deviceListRequested.containsKey(jid) || !_deviceList.containsKey(jid)) { if (!_deviceListRequested.containsKey(jid) ||
!_deviceList.containsKey(jid)) {
final newDeviceList = await fetchDeviceListImpl(jid); final newDeviceList = await fetchDeviceListImpl(jid);
if (newDeviceList != null) { if (newDeviceList != null) {
// Figure out what bundles we must fetch // Figure out what bundles we must fetch
@ -190,11 +190,17 @@ class OmemoManager {
return bundles; return bundles;
} }
Future<void> _maybeSendEmptyMessage(RatchetMapKey key, bool created, bool replaced) async { Future<void> _maybeSendEmptyMessage(
RatchetMapKey key,
bool created,
bool replaced,
) async {
final ratchet = _ratchetMap[key]!; final ratchet = _ratchetMap[key]!;
if (ratchet.acknowledged) { if (ratchet.acknowledged) {
// The ratchet is acknowledged // The ratchet is acknowledged
_log.finest('Checking whether to heartbeat to ${key.jid}, ratchet.nr (${ratchet.nr}) >= 53: ${ratchet.nr >= 53}, created: $created, replaced: $replaced'); _log.finest(
'Checking whether to heartbeat to ${key.jid}, ratchet.nr (${ratchet.nr}) >= 53: ${ratchet.nr >= 53}, created: $created, replaced: $replaced',
);
if (ratchet.nr >= 53 || created || replaced) { if (ratchet.nr >= 53 || created || replaced) {
await sendEmptyOmemoMessageImpl( await sendEmptyOmemoMessageImpl(
await _onOutgoingStanzaImpl( await _onOutgoingStanzaImpl(
@ -230,7 +236,9 @@ class OmemoManager {
); );
} }
Future<DecryptionResult> _onIncomingStanzaImpl(OmemoIncomingStanza stanza) async { Future<DecryptionResult> _onIncomingStanzaImpl(
OmemoIncomingStanza stanza,
) async {
// Find the correct key for our device // Find the correct key for our device
final deviceId = await getDeviceId(); final deviceId = await getDeviceId();
final key = stanza.keys.firstWhereOrNull((key) => key.rid == deviceId); final key = stanza.keys.firstWhereOrNull((key) => key.rid == deviceId);
@ -242,7 +250,8 @@ class OmemoManager {
} }
// Check how we should process the message // Check how we should process the message
final ratchetKey = RatchetMapKey(stanza.bareSenderJid, stanza.senderDeviceId); final ratchetKey =
RatchetMapKey(stanza.bareSenderJid, stanza.senderDeviceId);
var processAsKex = key.kex; var processAsKex = key.kex;
if (key.kex && _ratchetMap.containsKey(ratchetKey)) { if (key.kex && _ratchetMap.containsKey(ratchetKey)) {
final ratchet = _ratchetMap[ratchetKey]!; final ratchet = _ratchetMap[ratchetKey]!;
@ -369,7 +378,11 @@ class OmemoManager {
} }
// Send the hearbeat, if we have to // Send the hearbeat, if we have to
await _maybeSendEmptyMessage(ratchetKey, true, _ratchetMap.containsKey(ratchetKey)); await _maybeSendEmptyMessage(
ratchetKey,
true,
_ratchetMap.containsKey(ratchetKey),
);
return DecryptionResult( return DecryptionResult(
result.get<String?>(), result.get<String?>(),
@ -380,7 +393,8 @@ class OmemoManager {
if (!_ratchetMap.containsKey(ratchetKey)) { if (!_ratchetMap.containsKey(ratchetKey)) {
// TODO: Check if we recently failed to build a session with the device // TODO: Check if we recently failed to build a session with the device
// This causes omemo_dart to build a session with the device. // This causes omemo_dart to build a session with the device.
if (!_deviceList[stanza.bareSenderJid]!.contains(stanza.senderDeviceId)) { if (!_deviceList[stanza.bareSenderJid]!
.contains(stanza.senderDeviceId)) {
_deviceList[stanza.bareSenderJid]!.add(stanza.senderDeviceId); _deviceList[stanza.bareSenderJid]!.add(stanza.senderDeviceId);
} }
await _sendOmemoHeartbeat(stanza.bareSenderJid); await _sendOmemoHeartbeat(stanza.bareSenderJid);
@ -397,10 +411,14 @@ class OmemoManager {
// Correctly decode the message // Correctly decode the message
OMEMOAuthenticatedMessage authMessage; OMEMOAuthenticatedMessage authMessage;
if (key.kex) { if (key.kex) {
_log.finest('Extracting OMEMOAuthenticatedMessage from OMEMOKeyExchange'); _log.finest(
authMessage = OMEMOKeyExchange.fromBuffer(base64Decode(key.value)).message; 'Extracting OMEMOAuthenticatedMessage from OMEMOKeyExchange',
);
authMessage =
OMEMOKeyExchange.fromBuffer(base64Decode(key.value)).message;
} else { } else {
authMessage = OMEMOAuthenticatedMessage.fromBuffer(base64Decode(key.value)); authMessage =
OMEMOAuthenticatedMessage.fromBuffer(base64Decode(key.value));
} }
final keyAndHmac = await ratchet.ratchetDecrypt(authMessage); final keyAndHmac = await ratchet.ratchetDecrypt(authMessage);
@ -459,7 +477,9 @@ class OmemoManager {
); );
} }
Future<EncryptionResult> _onOutgoingStanzaImpl(OmemoOutgoingStanza stanza) async { Future<EncryptionResult> _onOutgoingStanzaImpl(
OmemoOutgoingStanza stanza,
) async {
// Encrypt the payload, if we have any // Encrypt the payload, if we have any
final List<int> payloadKey; final List<int> payloadKey;
final List<int> ciphertext; final List<int> ciphertext;
@ -545,7 +565,9 @@ class OmemoManager {
_eventStreamController.add( _eventStreamController.add(
RatchetsAddedEvent( RatchetsAddedEvent(
Map<RatchetMapKey, OmemoDoubleRatchet>.fromEntries( Map<RatchetMapKey, OmemoDoubleRatchet>.fromEntries(
addedRatchetKeys.map((key) => MapEntry(key, _ratchetMap[key]!)).toList(), addedRatchetKeys
.map((key) => MapEntry(key, _ratchetMap[key]!))
.toList(),
), ),
), ),
); );
@ -728,7 +750,9 @@ class OmemoManager {
Future<void> _ratchetAcknowledged(String jid, int device) async { Future<void> _ratchetAcknowledged(String jid, int device) async {
final ratchetKey = RatchetMapKey(jid, device); final ratchetKey = RatchetMapKey(jid, device);
if (!_ratchetMap.containsKey(ratchetKey)) { if (!_ratchetMap.containsKey(ratchetKey)) {
_log.warning('Cannot mark $jid:$device as acknowledged as the ratchet does not exist'); _log.warning(
'Cannot mark $jid:$device as acknowledged as the ratchet does not exist',
);
} else { } else {
// Commit // Commit
final ratchet = _ratchetMap[ratchetKey]!..acknowledged = true; final ratchet = _ratchetMap[ratchetKey]!..acknowledged = true;
@ -750,7 +774,9 @@ class OmemoManager {
} }
/// Same as [getFingerprintsForJid], but without acquiring the lock for [jid]. /// Same as [getFingerprintsForJid], but without acquiring the lock for [jid].
Future<List<DeviceFingerprint>?> _getFingerprintsForJidImpl(String jid) async { Future<List<DeviceFingerprint>?> _getFingerprintsForJidImpl(
String jid,
) async {
// Check if we know of the JID. // Check if we know of the JID.
if (!_deviceList.containsKey(jid)) { if (!_deviceList.containsKey(jid)) {
return null; return null;

View File

@ -87,7 +87,10 @@ class RatchetAccessQueue {
}); });
} }
Future<T> synchronized<T>(List<String> jids, Future<T> Function() function) async { Future<T> synchronized<T>(
List<String> jids,
Future<T> Function() function,
) async {
await enterCriticalSection(jids); await enterCriticalSection(jids);
final result = await function(); final result = await function();
await leaveCriticalSection(jids); await leaveCriticalSection(jids);

View File

@ -71,7 +71,8 @@ Future<List<int>> kdf(List<int> km) async {
/// Alice builds a session with Bob using his bundle [bundle] and Alice's identity key /// Alice builds a session with Bob using his bundle [bundle] and Alice's identity key
/// pair [ik]. /// pair [ik].
Future<Result<InvalidKeyExchangeSignatureError, X3DHAliceResult>> x3dhFromBundle( Future<Result<InvalidKeyExchangeSignatureError, X3DHAliceResult>>
x3dhFromBundle(
OmemoBundle bundle, OmemoBundle bundle,
OmemoKeyPair ik, OmemoKeyPair ik,
) async { ) async {

View File

@ -203,7 +203,7 @@ void main() {
// Alice now sends 52 messages that Bob decrypts // Alice now sends 52 messages that Bob decrypts
for (var i = 0; i < 52; i++) { for (var i = 0; i < 52; i++) {
Logger.root.finest('${i+1}/52'); Logger.root.finest('${i + 1}/52');
final aliceResultLoop = await aliceManager.onOutgoingStanza( final aliceResultLoop = await aliceManager.onOutgoingStanza(
OmemoOutgoingStanza( OmemoOutgoingStanza(
[bobJid], [bobJid],
@ -934,7 +934,10 @@ void main() {
expect(aliceResult.isSuccess(2), isFalse); expect(aliceResult.isSuccess(2), isFalse);
expect(aliceResult.deviceEncryptionErrors[cocoJid]!.length, 1); expect(aliceResult.deviceEncryptionErrors[cocoJid]!.length, 1);
expect(aliceResult.deviceEncryptionErrors[cocoJid]!.first.error, const TypeMatcher<NoKeyMaterialAvailableError>(),); expect(
aliceResult.deviceEncryptionErrors[cocoJid]!.first.error,
const TypeMatcher<NoKeyMaterialAvailableError>(),
);
// Bob decrypts it // Bob decrypts it
final bobResult = await bobManager.onIncomingStanza( final bobResult = await bobManager.onIncomingStanza(
@ -1243,7 +1246,10 @@ void main() {
Logger.root.info('Removing all ratchets for $bobJid'); Logger.root.info('Removing all ratchets for $bobJid');
await aliceManager.removeAllRatchets(bobJid); await aliceManager.removeAllRatchets(bobJid);
expect(aliceManager.getRatchet(RatchetMapKey(bobJid, bobDevice.id)), isNull); expect(
aliceManager.getRatchet(RatchetMapKey(bobJid, bobDevice.id)),
isNull,
);
// Alice prepares an empty OMEMO message // Alice prepares an empty OMEMO message
await aliceManager.sendOmemoHeartbeat(bobJid); await aliceManager.sendOmemoHeartbeat(bobJid);

View File

@ -1,9 +1,12 @@
import 'dart:async'; import 'dart:async';
import 'package:omemo_dart/src/omemo/queue.dart'; import 'package:omemo_dart/src/omemo/queue.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
Future<void> testMethod(RatchetAccessQueue queue, List<String> data, int duration) async { Future<void> testMethod(
RatchetAccessQueue queue,
List<String> data,
int duration,
) async {
await queue.enterCriticalSection(data); await queue.enterCriticalSection(data);
await Future<void>.delayed(Duration(seconds: duration)); await Future<void>.delayed(Duration(seconds: duration));
@ -48,7 +51,10 @@ void main() {
expect(queue.runningOperations.length, 4); expect(queue.runningOperations.length, 4);
expect( expect(
queue.runningOperations.containsAll([ queue.runningOperations.containsAll([
'a', 'b', 'c', 'd', 'a',
'b',
'c',
'd',
]), ]),
isTrue, isTrue,
); );