diff --git a/MatrixSDK/Background/MXBackgroundSyncService.swift b/MatrixSDK/Background/MXBackgroundSyncService.swift index 5fe4e5abfb..efb2ad4d1f 100644 --- a/MatrixSDK/Background/MXBackgroundSyncService.swift +++ b/MatrixSDK/Background/MXBackgroundSyncService.swift @@ -67,7 +67,6 @@ public enum MXBackgroundSyncServiceError: Error { /// - Parameter credentials: account credentials public init( withCredentials credentials: MXCredentials, - isCryptoSDKEnabled: Bool = false, persistTokenDataHandler: MXRestClientPersistTokenDataHandler? = nil, unauthenticatedHandler: MXRestClientUnauthenticatedHandler? = nil ) { @@ -90,16 +89,9 @@ public enum MXBackgroundSyncServiceError: Error { self.restClient = restClient store = MXBackgroundStore(withCredentials: credentials) - // We can flush any crypto data if our sync response store is empty - let resetBackgroundCryptoStore = syncResponseStoreManager.syncToken() == nil - if isCryptoSDKEnabled { - MXLog.debug("[MXBackgroundSyncService] init: constructing crypto v2") - crypto = MXBackgroundCryptoV2(credentials: credentials, restClient: restClient) - } else { - MXLog.debug("[MXBackgroundSyncService] init: constructing legacy crypto") - crypto = MXLegacyBackgroundCrypto(credentials: credentials, resetBackgroundCryptoStore: resetBackgroundCryptoStore) - } + MXLog.debug("[MXBackgroundSyncService] init: constructing crypto") + crypto = MXBackgroundCryptoV2(credentials: credentials, restClient: restClient) pushRulesManager = MXBackgroundPushRulesManager(withCredentials: credentials) MXLog.debug("[MXBackgroundSyncService] init complete") diff --git a/MatrixSDK/Crypto/CrossSigning/MXCrossSigningV2.swift b/MatrixSDK/Crypto/CrossSigning/MXCrossSigningV2.swift index 92eadb8cfb..e8ab628c8f 100644 --- a/MatrixSDK/Crypto/CrossSigning/MXCrossSigningV2.swift +++ b/MatrixSDK/Crypto/CrossSigning/MXCrossSigningV2.swift @@ -126,7 +126,7 @@ class MXCrossSigningV2: NSObject, MXCrossSigning { // If we are considered verified, there is no need for a verification upgrade // after migrating from legacy crypto if myUserCrossSigningKeys?.trustLevel.isVerified == true { - MXSDKOptions.sharedInstance().needsVerificationUpgrade = false + MXSDKOptions.sharedInstance().cryptoMigrationDelegate?.needsVerificationUpgrade = false } log.debug("Cross signing state refreshed, new state: \(state)") diff --git a/MatrixSDK/Crypto/MXCrypto.m b/MatrixSDK/Crypto/MXCrypto.m index 9cf0f2511a..fc599496f7 100644 --- a/MatrixSDK/Crypto/MXCrypto.m +++ b/MatrixSDK/Crypto/MXCrypto.m @@ -156,12 +156,6 @@ @implementation MXLegacyCrypto __block id crypto; #ifdef MX_CRYPTO - if (MXSDKOptions.sharedInstance.enableCryptoSDK) - { - MXLogFailure(@"[MXCrypto] createCryptoWithMatrixSession: Crypto V2 should not be created directly, use initializeCryptoWithMatrixSession instead"); - return nil; - } - dispatch_queue_t cryptoQueue = [MXLegacyCrypto dispatchQueueForUser:mxSession.matrixRestClient.credentials.userId]; dispatch_sync(cryptoQueue, ^{ @@ -180,29 +174,6 @@ + (void)initializeCryptoWithMatrixSession:(MXSession *)mxSession complete:(void (^)(id crypto, NSError *error))complete { #ifdef MX_CRYPTO - - if (MXSDKOptions.sharedInstance.enableCryptoSDK) - { - BOOL enableCrypto = [MXSDKOptions sharedInstance].enableCryptoWhenStartingMXSession || [MXCryptoV2Factory.shared hasCryptoDataFor:mxSession]; - if (enableCrypto) - { - [MXCryptoV2Factory.shared buildCryptoWithSession:mxSession - migrationProgress:migrationProgress - success:^(id crypto) { - complete(crypto, nil); } - failure:^(NSError *error) { - complete(nil, error); - }]; - } - else - { - dispatch_async(dispatch_get_main_queue(), ^{ - complete(nil, nil); - }); - } - return; - } - [self initalizeLegacyCryptoWithMatrixSession:mxSession complete:complete]; #else complete(nil); diff --git a/MatrixSDK/Crypto/MXCryptoV2Factory.swift b/MatrixSDK/Crypto/MXCryptoV2Factory.swift index 1843f49fc0..d910a1dc7a 100644 --- a/MatrixSDK/Crypto/MXCryptoV2Factory.swift +++ b/MatrixSDK/Crypto/MXCryptoV2Factory.swift @@ -16,6 +16,16 @@ import Foundation +/// Delegate for migrating account data from legacy crypto to rust-based Crypto SDK +@objc public protocol MXCryptoV2MigrationDelegate { + + /// Flag indicating whether this account requires a re-verification after migrating to Crypto SDK + /// + /// This flag is set to true if the legacy account is considered verified but the rust account + /// does not consider the migrated data secure enough, as it applies stricter security conditions. + var needsVerificationUpgrade: Bool { get set } +} + @objc public class MXCryptoV2Factory: NSObject { enum Error: Swift.Error { case cryptoNotAvailable @@ -139,7 +149,7 @@ import Foundation // unless the rust-based crypto already considers the current session to be verified given // the migration data log.debug("Needs verification upgrade") - MXSDKOptions.sharedInstance().needsVerificationUpgrade = true + MXSDKOptions.sharedInstance().cryptoMigrationDelegate?.needsVerificationUpgrade = true } } } diff --git a/MatrixSDK/Data/EventTimeline/Room/MXRoomEventTimeline.m b/MatrixSDK/Data/EventTimeline/Room/MXRoomEventTimeline.m index cf9dabcaad..300ab9934a 100644 --- a/MatrixSDK/Data/EventTimeline/Room/MXRoomEventTimeline.m +++ b/MatrixSDK/Data/EventTimeline/Room/MXRoomEventTimeline.m @@ -142,8 +142,6 @@ - (void)initialiseState:(NSArray *)stateEvents - (void)destroy { - [room.mxSession resetReplayAttackCheckInTimeline:_timelineId]; - if (httpOperation) { // Cancel the current server request @@ -190,8 +188,6 @@ - (BOOL)canPaginate:(MXTimelineDirection)direction - (void)resetPagination { - [room.mxSession resetReplayAttackCheckInTimeline:_timelineId]; - // Reset the back state to the current room state backState = [[MXRoomState alloc] initBackStateWith:_state]; @@ -203,8 +199,6 @@ - (MXHTTPOperation *)resetPaginationAroundInitialEventWithLimit:(NSUInteger)limi { NSParameterAssert(success); NSAssert(_initialEventId, @"[MXRoomEventTimeline] resetPaginationAroundInitialEventWithLimit cannot be called on live timeline"); - - [room.mxSession resetReplayAttackCheckInTimeline:_timelineId]; // Reset the store if (!store.isPermanent) diff --git a/MatrixSDK/Data/EventTimeline/Thread/MXThreadEventTimeline.swift b/MatrixSDK/Data/EventTimeline/Thread/MXThreadEventTimeline.swift index b5fada9a90..f3b0c1e380 100644 --- a/MatrixSDK/Data/EventTimeline/Thread/MXThreadEventTimeline.swift +++ b/MatrixSDK/Data/EventTimeline/Thread/MXThreadEventTimeline.swift @@ -99,8 +99,6 @@ public class MXThreadEventTimeline: NSObject, MXEventTimeline { } public func destroy() { - thread.session?.resetReplayAttackCheck(inTimeline: timelineId) - removeAllListeners() currentHttpOperation?.cancel() @@ -132,8 +130,6 @@ public class MXThreadEventTimeline: NSObject, MXEventTimeline { } public func resetPagination() { - thread.session?.resetReplayAttackCheck(inTimeline: timelineId) - // Reset store pagination storeMessagesEnumerator = store.messagesEnumerator(forRoom: thread.roomId) @@ -150,8 +146,6 @@ public class MXThreadEventTimeline: NSObject, MXEventTimeline { fatalError("[MXThreadEventTimeline][\(timelineId)] resetPaginationAroundInitialEventWithLimit cannot be called on live timeline") } - thread.session?.resetReplayAttackCheck(inTimeline: timelineId) - // Reset the store if !store.isPermanent { store.deleteAllData() diff --git a/MatrixSDK/Data/MXRoom.m b/MatrixSDK/Data/MXRoom.m index 020af712d3..b626989f0b 100644 --- a/MatrixSDK/Data/MXRoom.m +++ b/MatrixSDK/Data/MXRoom.m @@ -82,11 +82,6 @@ The list of room operations (sending of text, images...) that must be sent FIFO queue of failure blocks waiting for [self members:]. */ NSMutableArray *pendingMembersFailureBlocks; - - /** - The manager for sharing keys of messages with invited users - */ - MXSharedHistoryKeyManager *sharedHistoryKeyManager; } @end @@ -123,14 +118,6 @@ - (id)initWithRoomId:(NSString *)roomId matrixSession:(MXSession *)mxSession2 an { _roomId = roomId; mxSession = mxSession2; - - if ([mxSession.crypto isKindOfClass:[MXLegacyCrypto class]]) - { - MXMegolmDecryption *decryption = [[MXMegolmDecryption alloc] initWithCrypto:mxSession.crypto]; - sharedHistoryKeyManager = [[MXSharedHistoryKeyManager alloc] initWithRoomId:roomId - crypto:mxSession.crypto - service:decryption]; - } if (store) { @@ -1977,24 +1964,9 @@ - (MXHTTPOperation*)inviteUser:(NSString*)userId success:(void (^)(void))success failure:(void (^)(NSError *error))failure { - if (MXSDKOptions.sharedInstance.enableRoomSharedHistoryOnInvite) - { - [self shareRoomKeysWith:userId]; - } return [mxSession.matrixRestClient inviteUser:userId toRoom:self.roomId success:success failure:failure]; } -- (void)shareRoomKeysWith:(NSString *)userId -{ - // The value of 20 is arbitrary and imprecise, we merely want to ensure that when a user is invited to a room - // they are able to read any immediately preciding messages that may be relevant to the invite. - NSInteger numberOfSharedMessage = 20; - id enumerator = [self enumeratorForStoredMessagesWithTypeIn:@[kMXEventTypeStringRoomMessage]]; - [sharedHistoryKeyManager shareMessageKeysWithUserId:userId - messageEnumerator:enumerator - limit:numberOfSharedMessage]; -} - - (MXHTTPOperation*)inviteUserByEmail:(NSString*)email success:(void (^)(void))success failure:(void (^)(NSError *error))failure diff --git a/MatrixSDK/MXSDKOptions.h b/MatrixSDK/MXSDKOptions.h index 422a8c6617..e4f82bdba1 100644 --- a/MatrixSDK/MXSDKOptions.h +++ b/MatrixSDK/MXSDKOptions.h @@ -48,7 +48,7 @@ typedef NS_ENUM(NSUInteger, MXCallTransferType) NS_ASSUME_NONNULL_BEGIN -@protocol MXBackgroundModeHandler, MXCryptoV2Feature; +@protocol MXBackgroundModeHandler, MXCryptoV2MigrationDelegate; /** SDK options that can be set at the launch time. @@ -204,26 +204,11 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic) BOOL enableRoomSharedHistoryOnInvite; /** - Use the newer rust-based `MatrixCryptoSDK` instead of the legacy `MatrixSDK`'s internal crypto module. + The delegate for migrating account data from legacy crypto to rust-based Crypto SDK - @remark YES by default - */ -@property (nonatomic) BOOL enableCryptoSDK; - -/** - Flag indicating whether this account requires a re-verification after migrating to Crypto SDK - - This flag is set to true if the legacy account is considered verified but the rust account - does not consider the migrated data secure enough, as it applies stricter security conditions. - - @remark NO by default. - */ -@property (nonatomic) BOOL needsVerificationUpgrade; - -/** - The text-based identifier for the crypto module being used (e.g. native vs rust) + By default, nil. */ -@property (nonatomic, readonly) NSString *cryptoModuleId; +@property (nonatomic, nullable, weak) id cryptoMigrationDelegate; /** Enable symmetric room key backups @@ -239,14 +224,6 @@ NS_ASSUME_NONNULL_BEGIN */ @property (nonatomic) BOOL enableNewClientInformationFeature; -/** - Enable the calculating and display of progress during session startup, incl store migration, - syncing and response processing. - - @remark YES by default - */ -@property (nonatomic) BOOL enableStartupProgress; - @end NS_ASSUME_NONNULL_END diff --git a/MatrixSDK/MXSDKOptions.m b/MatrixSDK/MXSDKOptions.m index e1cc0fa19f..d1f9f103ab 100644 --- a/MatrixSDK/MXSDKOptions.m +++ b/MatrixSDK/MXSDKOptions.m @@ -54,21 +54,14 @@ - (instancetype)init _authEnableRefreshTokens = NO; _enableThreads = NO; _enableRoomSharedHistoryOnInvite = NO; - _enableCryptoSDK = YES; - _needsVerificationUpgrade = NO; _enableSymmetricBackup = NO; _enableNewClientInformationFeature = NO; - _enableStartupProgress = YES; + _cryptoMigrationDelegate = nil; } return self; } -- (NSString *)cryptoModuleId -{ - return self.enableCryptoSDK ? @"rust" : @"native"; -} - - (void)setRoomListDataManagerClass:(Class)roomListDataManagerClass { // Sanity check diff --git a/MatrixSDK/MXSession.h b/MatrixSDK/MXSession.h index a9ce329a02..bfcb723119 100644 --- a/MatrixSDK/MXSession.h +++ b/MatrixSDK/MXSession.h @@ -1596,14 +1596,6 @@ typedef void (^MXOnBackgroundSyncFail)(NSError *error); inTimeline:(NSString*)timeline onComplete:(void (^)(NSArray *failedEvents))onComplete; -/** - Reset replay attack data for the given timeline. - - @param timeline the id of the timeline. - */ -- (void)resetReplayAttackCheckInTimeline:(NSString*)timeline; - - #pragma mark - Global events listeners /** Register a global listener to events related to the current session. diff --git a/MatrixSDK/MXSession.m b/MatrixSDK/MXSession.m index 051b41d122..2942cc4b36 100644 --- a/MatrixSDK/MXSession.m +++ b/MatrixSDK/MXSession.m @@ -312,10 +312,7 @@ - (id)initWithMatrixRestClient:(MXRestClient*)mxRestClient _homeserverCapabilitiesService = [[MXHomeserverCapabilitiesService alloc] initWithSession: self]; [_homeserverCapabilitiesService updateWithCompletion:nil]; - if (MXSDKOptions.sharedInstance.enableStartupProgress) - { - _startupProgress = [[MXSessionStartupProgress alloc] init]; - } + _startupProgress = [[MXSessionStartupProgress alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDidDecryptEvent:) name:kMXEventDidDecryptNotification object:nil]; @@ -398,24 +395,12 @@ -(void)setStore:(id)store success:(void (^)(void))onStoreDataReady fail // Check if the user has enabled crypto MXWeakify(self); - [MXLegacyCrypto initializeCryptoWithMatrixSession:self migrationProgress:^(double progress) { - if (MXSDKOptions.sharedInstance.enableStartupProgress) - { - [self.startupProgress updateProgressForStage:MXSessionStartupStageStoreMigration progress:progress]; - } + [self initializeCryptoWithProgress:^(double progress) { + [self.startupProgress updateProgressForStage:MXSessionStartupStageStoreMigration progress:progress]; - } complete:^(id crypto, NSError *error) { + } success:^(id crypto) { MXStrongifyAndReturnIfNil(self); - if (!crypto && error) - { - if (failure) - { - failure(error); - } - return; - } - self->_crypto = crypto; // Sanity check: The session may be closed before the end of this operation. @@ -539,6 +524,11 @@ -(void)setStore:(id)store success:(void (^)(void))onStoreDataReady fail // The SDK client can use this data onStoreDataReady(); } + } failure:^(NSError *error) { + if (failure) + { + failure(error); + } }]; } failure:^(NSError *error) { @@ -551,6 +541,34 @@ -(void)setStore:(id)store success:(void (^)(void))onStoreDataReady fail }]; } +- (void)initializeCryptoWithProgress:(void (^)(double))progress + success:(void (^)(id crypto))success + failure:(void (^)(NSError *error))failure +{ + BOOL enableCrypto = [MXSDKOptions sharedInstance].enableCryptoWhenStartingMXSession || [MXCryptoV2Factory.shared hasCryptoDataFor:self]; + if (!enableCrypto) + { + MXLogWarning(@"[MXSession] initializeCrypto: Not starting crypto automatically due to SDK settings"); + dispatch_async(dispatch_get_main_queue(), ^{ + success(nil); + }); + return; + } + + [MXCryptoV2Factory.shared buildCryptoWithSession:self + migrationProgress:progress + success:^(id crypto) { + + MXLogDebug(@"[MXSession] initializeCrypto: Successfully initialized crypto module"); + success(crypto); + + } failure:^(NSError *error) { + + MXLogErrorDetails(@"[MXSession] initializeCrypto: Error initialized crypto module", error); + failure(error); + }]; +} + - (void)setRoomListDataManager:(id)roomListDataManager { NSParameterAssert(_roomListDataManager == nil); @@ -574,7 +592,7 @@ - (void)handleSyncResponse:(MXSyncResponse *)syncResponse // Check whether this is the initial sync BOOL isInitialSync = !self.isEventStreamInitialised; - [self handleCryptoSyncResponse:syncResponse onComplete:^{ + [self handleCryptoEventsInSyncResponse:syncResponse onComplete:^{ dispatch_group_t dispatchGroup = dispatch_group_create(); @@ -591,7 +609,7 @@ - (void)handleSyncResponse:(MXSyncResponse *)syncResponse void(^dispatch_group_leave_with_progress)(dispatch_group_t) = ^(dispatch_group_t dispatchGroup) { dispatch_group_leave(dispatchGroup); - if (MXSDKOptions.sharedInstance.enableStartupProgress && progress) + if (progress) { progress([self.startupProgress overallProgressForStep:completedRooms totalCount:totalRooms progress:1]); completedRooms += 1; @@ -778,30 +796,6 @@ - (void)handleSyncResponse:(MXSyncResponse *)syncResponse // Sync point: wait that all rooms in the /sync response have been loaded // and their /sync response has been processed dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{ - - // Legacy crypto requires that we deal with device list changes, OTKs etc at the end of the sync loop. - // This will be removed altogether with `MXLegacyCrypto` - if ([self.crypto isKindOfClass:[MXLegacyCrypto class]]) - { - // Handle device list updates - if (syncResponse.deviceLists) - { - [(MXLegacyCrypto *)self.crypto handleDeviceListsChanges:syncResponse.deviceLists]; - } - - // Handle one_time_keys_count - if (syncResponse.deviceOneTimeKeysCount) - { - [(MXLegacyCrypto *)self.crypto handleDeviceOneTimeKeysCount:syncResponse.deviceOneTimeKeysCount]; - } - - [(MXLegacyCrypto *)self.crypto handleDeviceUnusedFallbackKeys:syncResponse.unusedFallbackKeys]; - - // Tell the crypto module to do its processing - [(MXLegacyCrypto *)self.crypto onSyncCompleted:self.store.eventStreamToken - nextSyncToken:syncResponse.nextBatch - catchingUp:self.catchingUp]; - } // Update live event stream token MXLogDebug(@"[MXSession] Next sync token: %@", syncResponse.nextBatch); @@ -1458,7 +1452,7 @@ - (void)serverSyncWithServerTimeout:(NSUInteger)serverTimeout setPresence:(NSString*)setPresence { // We only want to report sync progress when doing initial sync - BOOL shoulReportStartupProgress = MXSDKOptions.sharedInstance.enableStartupProgress && !self.isEventStreamInitialised; + BOOL shoulReportStartupProgress = !self.isEventStreamInitialised; if (shoulReportStartupProgress) { // There is no way to track percentage progress when syncing with the server, so we always use 0% @@ -1994,7 +1988,6 @@ - (void)handleAccountData:(NSDictionary*)accountDataUpdate } } - [self validateAccountData]; self.store.userAccountData = _accountData.accountData; // Trigger a global notification for the account data update @@ -2007,27 +2000,6 @@ - (void)handleAccountData:(NSDictionary*)accountDataUpdate } } -/** - Private method to validate local account data and report any potential state corruption - */ -- (void)validateAccountData -{ - if (![self.crypto isKindOfClass:[MXLegacyCrypto class]]) - { - return; - } - - // Detecting an issue in legacy crypto where more than one valid SSSS key is present on the client - // https://github.com/vector-im/element-ios/issues/4569 - NSInteger keysCount = ((MXLegacyCrypto *)self.crypto).secretStorage.numberOfValidKeys; - if (keysCount > 1) - { - MXLogErrorDetails(@"[MXSession] validateAccountData: Detected multiple valid SSSS keys, should only have one at most", @{ - @"count": @(keysCount) - }); - } -} - - (void)updateSummaryDirectUserIdForRooms:(NSSet *)roomIds { // If the initial sync response is not processed enough, rooms is not yet mounted. @@ -2052,95 +2024,15 @@ - (void)updateSummaryDirectUserIdForRooms:(NSSet *)roomIds } } -// Temporary junction to deal with sync response depending on the variant of crypto -// that cannot be easily hidden behind a protocol. Legacy implementation will eventually -// be fully removed. -- (void)handleCryptoSyncResponse:(MXSyncResponse *)syncResponse - onComplete:(void (^)(void))onComplete +- (void)handleCryptoEventsInSyncResponse:(MXSyncResponse *)syncResponse onComplete:(void (^)(void))onComplete { - if (!self.crypto || [self.crypto isKindOfClass:[MXLegacyCrypto class]]) - { - // Legacy crypto requires pre-processed to-device events before everything else to make future decryptions work - [self handleToDeviceEvents:syncResponse.toDevice.events onComplete:onComplete]; - } - else - { - // New and all future crypto modules can handle the entire sync response in full - [self.crypto handleSyncResponse:syncResponse onComplete:onComplete]; - } -} - -- (void)handleToDeviceEvents:(NSArray *)events onComplete:(void (^)(void))onComplete -{ - NSMutableArray *supportedEvents = [NSMutableArray arrayWithCapacity:events.count]; - for (MXEvent *event in events) - { - if ([MXTools isSupportedToDeviceEvent:event]) - { - MXLogDebug(@"[MXSession] handleToDeviceEvents: Processing new to-device event msgid: %@", event.content[kMXToDeviceMessageId]) - [supportedEvents addObject:event]; - } - } - - if (supportedEvents.count == 0) + if (!self.crypto) { onComplete(); return; } - [self decryptEvents:supportedEvents inTimeline:nil onComplete:^(NSArray *failedEvents) { - dispatch_group_t dispatchGroup = dispatch_group_create(); - - for (MXEvent *event in supportedEvents) - { - if (!event.decryptionError) - { - MXLogDebug(@"[MXSession] handleToDeviceEvents: Received new to-device event `%@` from `%@` msgid: %@", event.type, event.sender, event.wireContent[kMXToDeviceMessageId]) - dispatch_group_enter(dispatchGroup); - [self handleToDeviceEvent:event onComplete:^{ - dispatch_group_leave(dispatchGroup); - }]; - } - else - { - MXLogDebug(@"[MXSession] handleToDeviceEvents: Warning: Unable to decrypt to-device event: %@\nError: %@", event.wireContent[kMXMessageBodyKey], event.decryptionError); - } - } - - dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{ - onComplete(); - }); - }]; -} - -- (void)handleToDeviceEvent:(MXEvent *)event onComplete:(void (^)(void))onComplete -{ - void (^onHandleToDeviceEventDone)(void) = ^(void) { - [[NSNotificationCenter defaultCenter] postNotificationName:kMXSessionOnToDeviceEventNotification - object:self - userInfo:@{ - kMXSessionNotificationEventKey: event - }]; - - onComplete(); - }; - - switch (event.eventType) - { - case MXEventTypeRoomKey: - { - if ([_crypto isKindOfClass:[MXLegacyCrypto class]]) - { - [(MXLegacyCrypto *)_crypto handleRoomKeyEvent:event onComplete:onHandleToDeviceEventDone]; - } - break; - } - - default: - onHandleToDeviceEventDone(); - break; - } - [_eventStreamService dispatchOnLiveToDeviceWithEvent:event]; + [self.crypto handleSyncResponse:syncResponse onComplete:onComplete]; } /** @@ -2221,17 +2113,10 @@ - (void)handleBackgroundSyncCacheIfRequiredWithCompletion:(void (^)(void))comple [asyncTaskQueue asyncWithExecute:^(void (^ taskCompleted)(void)) { [syncResponseStoreManager mergedSyncResponseFromSyncResponseIds:outdatedSyncResponseIds completion:^(MXCachedSyncResponse * _Nullable outdatedCachedSyncResponse) { - if (outdatedCachedSyncResponse) - { - [self handleOutdatedSyncResponse:outdatedCachedSyncResponse.syncResponse - completion:^{ - taskCompleted(); - }]; - } - else - { + // There is no need to handle `outdatedCachedSyncResponse` manually anymore, ignoring the result + dispatch_async(dispatch_get_main_queue(), ^{ taskCompleted(); - } + }); }]; }]; @@ -2280,26 +2165,6 @@ - (void)handleBackgroundSyncCacheIfRequiredWithCompletion:(void (^)(void))comple }]; } -- (void)handleOutdatedSyncResponse:(MXSyncResponse *)syncResponse - completion:(void (^)(void))completion -{ - MXLogDebug(@"[MXSession] handleOutdatedSyncResponse: %tu joined rooms, %tu invited rooms, %tu left rooms, %tu toDevice events.", syncResponse.rooms.join.count, syncResponse.rooms.invite.count, syncResponse.rooms.leave.count, syncResponse.toDevice.events.count); - - if (!self.crypto || [self.crypto isKindOfClass:[MXLegacyCrypto class]]) - { - // Legacy crypto requires pre-processed to-device events before everything else to make future decryptions work - [self handleToDeviceEvents:syncResponse.toDevice.events onComplete:completion]; - } - else - { - // Only legacy crypto requires different DBs for foreground and background processes, other crypto modules - // write to a single DB in both processes, so there is no need to replay outdated sync response - dispatch_async(dispatch_get_main_queue(), ^{ - completion(); - }); - } -} - #pragma mark - Options - (void)enableVoIPWithCallStack:(id)callStack { @@ -2315,32 +2180,38 @@ - (void)enableCrypto:(BOOL)enableCrypto success:(void (^)(void))success failure: if (enableCrypto && !_crypto) { - NSError *error; - _crypto = [MXLegacyCrypto createCryptoWithMatrixSession:self error:&error]; - if (!_crypto && error) - { - if (failure) + MXWeakify(self); + [MXCryptoV2Factory.shared buildCryptoWithSession:self + migrationProgress:nil + success:^(id crypto) { + + MXLogDebug(@"[MXSession] enableCrypto: Successfully initialized crypto module"); + MXStrongifyAndReturnIfNil(self); + self->_crypto = crypto; + + if (self->_state == MXSessionStateRunning) { - failure(error); + [self startCrypto:success failure:failure]; } - return; - } - - if (_state == MXSessionStateRunning) - { - [self startCrypto:success failure:failure]; - } - else - { - MXLogDebug(@"[MXSesion] enableCrypto: crypto module will be start later (MXSession.state: %@)", [MXTools readableSessionState:_state]); + else + { + MXLogDebug(@"[MXSesion] enableCrypto: crypto module will be start later (MXSession.state: %@)", [MXTools readableSessionState:self->_state]); - if (success) + if (success) + { + dispatch_async(dispatch_get_main_queue(), ^{ + success(); + }); + } + } + + } failure:^(NSError *error) { + MXLogErrorDetails(@"[MXSession] enableCrypto: Error initialized crypto module", error); + if (failure) { - dispatch_async(dispatch_get_main_queue(), ^{ - success(); - }); + failure(error); } - } + }]; } else if (!enableCrypto && _crypto) { @@ -3415,7 +3286,7 @@ - (void)fixRoomsSummariesLastMessageWithMaxServerPaginationCount:(NSUInteger)max __block NSInteger completedRooms = 0; void(^dispatch_group_leave_with_progress)(dispatch_group_t) = ^(dispatch_group_t dispatchGroup) { dispatch_group_leave(dispatchGroup); - if (MXSDKOptions.sharedInstance.enableStartupProgress && progress) + if (progress) { progress([self.startupProgress overallProgressForStep:completedRooms totalCount:self.rooms.count progress:1]); completedRooms += 1; @@ -5056,14 +4927,6 @@ - (void)decryptEvents:(NSArray *)events } } -- (void)resetReplayAttackCheckInTimeline:(NSString*)timeline -{ - if ([_crypto isKindOfClass:[MXLegacyCrypto class]]) - { - [(MXLegacyCrypto *)_crypto resetReplayAttackCheckInTimeline:timeline]; - } -} - // Called when an event finally got decrypted after a late room key reception - (void)onDidDecryptEvent:(NSNotification *)notification { diff --git a/MatrixSDKTests/MXCryptoKeyVerificationTests.m b/MatrixSDKTests/MXCryptoKeyVerificationTests.m index cb8f68918d..c803b60442 100644 --- a/MatrixSDKTests/MXCryptoKeyVerificationTests.m +++ b/MatrixSDKTests/MXCryptoKeyVerificationTests.m @@ -455,12 +455,6 @@ - (void)testVerificationByToDeviceRequestCancellation success:^(id requestFromAliceDevice1POV) { // -> The other device list should have been computed well - if (MXSDKOptions.sharedInstance.enableCryptoSDK) - { - XCTFail(@"This test uses `MXKeyVerificationByToDeviceRequest` which is only compatible with Crypto V1. Replace assertions to make it compatible with V2 as well"); - [expectation fulfill]; - return; - } MXKeyVerificationByToDeviceRequest *toDeviceRequestFromAliceDevice1POV = (MXKeyVerificationByToDeviceRequest*)requestFromAliceDevice1POV; XCTAssertNotNil(toDeviceRequestFromAliceDevice1POV.requestedOtherDeviceIds); NSSet *expectedRequestedDevices = [NSSet setWithArray:@[aliceSession2DeviceId, aliceSession3DeviceId]]; diff --git a/MatrixSDKTests/MXCryptoTests.m b/MatrixSDKTests/MXCryptoTests.m index d300fa9e72..36b50f5138 100644 --- a/MatrixSDKTests/MXCryptoTests.m +++ b/MatrixSDKTests/MXCryptoTests.m @@ -111,18 +111,15 @@ - (void)testEnableCrypto XCTAssertNil(mxSession.crypto, @"Crypto is disabled by default"); - XCTAssertFalse([mxSession.legacyCrypto.store.class hasDataForCredentials:mxSession.matrixRestClient.credentials]); - + MXKeyProvider.sharedInstance.delegate = [[MXKeyProviderStub alloc] init]; [mxSession enableCrypto:YES success:^{ + MXKeyProvider.sharedInstance.delegate = nil; XCTAssert(mxSession.crypto); - XCTAssert([mxSession.legacyCrypto.store.class hasDataForCredentials:mxSession.matrixRestClient.credentials]); [mxSession enableCrypto:NO success:^{ XCTAssertNil(mxSession.crypto); - XCTAssertFalse([mxSession.legacyCrypto.store.class hasDataForCredentials:mxSession.matrixRestClient.credentials], @"Crypto data must have been trashed"); - [expectation fulfill]; } failure:^(NSError *error) { @@ -152,7 +149,6 @@ - (void)testMXSDKOptionsEnableCryptoWhenOpeningMXSession [mxSession enableCrypto:NO success:^{ XCTAssertNil(mxSession.crypto); - [expectation fulfill]; } failure:^(NSError *error) { diff --git a/MatrixSDKTests/TestPlans/AllWorkingTests.xctestplan b/MatrixSDKTests/TestPlans/AllWorkingTests.xctestplan index 61e671924d..711f37fbce 100644 --- a/MatrixSDKTests/TestPlans/AllWorkingTests.xctestplan +++ b/MatrixSDKTests/TestPlans/AllWorkingTests.xctestplan @@ -82,7 +82,6 @@ "MXCryptoTests\/testDiscardAndRestoreOlmOutboundKey", "MXCryptoTests\/testDownloadKeysForUserWithNoDevice", "MXCryptoTests\/testDownloadKeysWithUnreachableHS", - "MXCryptoTests\/testEnableCrypto", "MXCryptoTests\/testEnableEncryptionAfterNonCryptedMessages", "MXCryptoTests\/testEncryptionAlgorithmChange", "MXCryptoTests\/testEnsureSingleOlmSession", diff --git a/changelog.d/pr-1772.change b/changelog.d/pr-1772.change new file mode 100644 index 0000000000..7b85c1e3aa --- /dev/null +++ b/changelog.d/pr-1772.change @@ -0,0 +1 @@ +Crypto: Deprecate MXLegacyCrypto