Skip to content

Commit

Permalink
Merge pull request matrix-org#1772 from matrix-org/andy/deprecate_crypto
Browse files Browse the repository at this point in the history
Deprecate MXLegacyCrypto
  • Loading branch information
Anderas authored Apr 19, 2023
2 parents edc99aa + 485490e commit db75814
Show file tree
Hide file tree
Showing 15 changed files with 96 additions and 348 deletions.
12 changes: 2 additions & 10 deletions MatrixSDK/Background/MXBackgroundSyncService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
) {
Expand All @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion MatrixSDK/Crypto/CrossSigning/MXCrossSigningV2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
Expand Down
29 changes: 0 additions & 29 deletions MatrixSDK/Crypto/MXCrypto.m
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,6 @@ @implementation MXLegacyCrypto
__block id<MXCrypto> 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, ^{

Expand All @@ -180,29 +174,6 @@ + (void)initializeCryptoWithMatrixSession:(MXSession *)mxSession
complete:(void (^)(id<MXCrypto> 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<MXCrypto> 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);
Expand Down
12 changes: 11 additions & 1 deletion MatrixSDK/Crypto/MXCryptoV2Factory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
}
6 changes: 0 additions & 6 deletions MatrixSDK/Data/EventTimeline/Room/MXRoomEventTimeline.m
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,6 @@ - (void)initialiseState:(NSArray<MXEvent *> *)stateEvents

- (void)destroy
{
[room.mxSession resetReplayAttackCheckInTimeline:_timelineId];

if (httpOperation)
{
// Cancel the current server request
Expand Down Expand Up @@ -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];

Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,6 @@ public class MXThreadEventTimeline: NSObject, MXEventTimeline {
}

public func destroy() {
thread.session?.resetReplayAttackCheck(inTimeline: timelineId)

removeAllListeners()

currentHttpOperation?.cancel()
Expand Down Expand Up @@ -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)

Expand All @@ -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()
Expand Down
28 changes: 0 additions & 28 deletions MatrixSDK/Data/MXRoom.m
Original file line number Diff line number Diff line change
Expand Up @@ -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<void (^)(NSError *)> *pendingMembersFailureBlocks;

/**
The manager for sharing keys of messages with invited users
*/
MXSharedHistoryKeyManager *sharedHistoryKeyManager;
}
@end

Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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<MXEventsEnumerator> enumerator = [self enumeratorForStoredMessagesWithTypeIn:@[kMXEventTypeStringRoomMessage]];
[sharedHistoryKeyManager shareMessageKeysWithUserId:userId
messageEnumerator:enumerator
limit:numberOfSharedMessage];
}

- (MXHTTPOperation*)inviteUserByEmail:(NSString*)email
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
Expand Down
31 changes: 4 additions & 27 deletions MatrixSDK/MXSDKOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<MXCryptoV2MigrationDelegate> cryptoMigrationDelegate;

/**
Enable symmetric room key backups
Expand All @@ -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
9 changes: 1 addition & 8 deletions MatrixSDK/MXSDKOptions.m
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 0 additions & 8 deletions MatrixSDK/MXSession.h
Original file line number Diff line number Diff line change
Expand Up @@ -1596,14 +1596,6 @@ typedef void (^MXOnBackgroundSyncFail)(NSError *error);
inTimeline:(NSString*)timeline
onComplete:(void (^)(NSArray<MXEvent*> *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.
Expand Down
Loading

0 comments on commit db75814

Please sign in to comment.