Skip to content

Commit

Permalink
Merge pull request matrix-org#1770 from matrix-org/andy/crypto_sdk
Browse files Browse the repository at this point in the history
Enable Crypto SDK by default
  • Loading branch information
Anderas committed Apr 19, 2023
2 parents d72008e + db75814 commit 98e7c1c
Show file tree
Hide file tree
Showing 43 changed files with 855 additions and 1,253 deletions.
86 changes: 0 additions & 86 deletions .github/workflows/ci-crypto-tests.yml

This file was deleted.

134 changes: 86 additions & 48 deletions MatrixSDK.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,6 @@
<TestPlanReference
reference = "container:MatrixSDKTests/TestPlans/UnitTestsWithSanitizers.xctestplan">
</TestPlanReference>
<TestPlanReference
reference = "container:MatrixSDKTests/TestPlans/CryptoTests.xctestplan">
</TestPlanReference>
<TestPlanReference
reference = "container:MatrixSDKTests/TestPlans/AllWorkingTests.xctestplan">
</TestPlanReference>
Expand Down
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().cryptoSDKFeature?.needsVerificationUpgrade = false
MXSDKOptions.sharedInstance().cryptoMigrationDelegate?.needsVerificationUpgrade = false
}

log.debug("Cross signing state refreshed, new state: \(state)")
Expand Down
22 changes: 0 additions & 22 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,22 +174,6 @@ + (void)initializeCryptoWithMatrixSession:(MXSession *)mxSession
complete:(void (^)(id<MXCrypto> crypto, NSError *error))complete
{
#ifdef MX_CRYPTO

// Each time we construct the crypto module (app launch, login etc) we have a chance to try to enable
// the newer SDK crypto module, if it is available for this particular user.
[MXSDKOptions.sharedInstance.cryptoSDKFeature enableIfAvailableForUserId:mxSession.myUserId];
if (MXSDKOptions.sharedInstance.enableCryptoSDK)
{
[MXCryptoV2Factory.shared buildCryptoWithSession:mxSession
migrationProgress:migrationProgress
success:^(id<MXCrypto> crypto) {
complete(crypto, nil); }
failure:^(NSError *error) {
complete(nil, error);
}];
return;
}

[self initalizeLegacyCryptoWithMatrixSession:mxSession complete:complete];
#else
complete(nil);
Expand Down
27 changes: 26 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 All @@ -28,6 +38,21 @@ import Foundation
.deprecated3
}

@objc public func hasCryptoData(for session: MXSession!) -> Bool {
guard let userId = session?.myUserId else {
log.error("Missing required dependencies")
return false
}

do {
let url = try MXCryptoMachineStore.storeURL(for: userId)
return FileManager.default.fileExists(atPath: url.path)
} catch {
log.error("Failed creating url for user", context: error)
return false
}
}

@objc public func buildCrypto(
session: MXSession!,
migrationProgress: ((Double) -> Void)?,
Expand Down Expand Up @@ -124,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().cryptoSDKFeature?.needsVerificationUpgrade = true
MXSDKOptions.sharedInstance().cryptoMigrationDelegate?.needsVerificationUpgrade = true
}
}
}
50 changes: 0 additions & 50 deletions MatrixSDK/Crypto/MXCryptoV2Feature.swift

This file was deleted.

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
Loading

0 comments on commit 98e7c1c

Please sign in to comment.