Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CryptoV2 changes #1622

Merged
merged 3 commits into from
Oct 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion MatrixSDK.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Pod::Spec.new do |s|

# Experimental / NOT production-ready Rust-based crypto library
s.subspec 'CryptoSDK' do |ss|
ss.dependency 'MatrixSDKCrypto', '0.1.4', :configurations => ["DEBUG"]
ss.dependency 'MatrixSDKCrypto', '0.1.5', :configurations => ["DEBUG"]
end

end
10 changes: 8 additions & 2 deletions MatrixSDK.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -500,8 +500,8 @@
32AF9285240EA2430008A0FD /* MXSecretShareRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 32AF9282240EA2430008A0FD /* MXSecretShareRequest.h */; };
32AF9286240EA2430008A0FD /* MXSecretShareRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 32AF9283240EA2430008A0FD /* MXSecretShareRequest.m */; };
32AF9287240EA2430008A0FD /* MXSecretShareRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 32AF9283240EA2430008A0FD /* MXSecretShareRequest.m */; };
32AF928A240EA3880008A0FD /* MXSecretShareSend.h in Headers */ = {isa = PBXBuildFile; fileRef = 32AF9288240EA3880008A0FD /* MXSecretShareSend.h */; };
32AF928B240EA3880008A0FD /* MXSecretShareSend.h in Headers */ = {isa = PBXBuildFile; fileRef = 32AF9288240EA3880008A0FD /* MXSecretShareSend.h */; };
32AF928A240EA3880008A0FD /* MXSecretShareSend.h in Headers */ = {isa = PBXBuildFile; fileRef = 32AF9288240EA3880008A0FD /* MXSecretShareSend.h */; settings = {ATTRIBUTES = (Public, ); }; };
32AF928B240EA3880008A0FD /* MXSecretShareSend.h in Headers */ = {isa = PBXBuildFile; fileRef = 32AF9288240EA3880008A0FD /* MXSecretShareSend.h */; settings = {ATTRIBUTES = (Public, ); }; };
32AF928C240EA3880008A0FD /* MXSecretShareSend.m in Sources */ = {isa = PBXBuildFile; fileRef = 32AF9289240EA3880008A0FD /* MXSecretShareSend.m */; };
32AF928D240EA3880008A0FD /* MXSecretShareSend.m in Sources */ = {isa = PBXBuildFile; fileRef = 32AF9289240EA3880008A0FD /* MXSecretShareSend.m */; };
32AF928F24110ADD0008A0FD /* MXSecretShareManager_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 32AF928E24110ADD0008A0FD /* MXSecretShareManager_Private.h */; };
Expand Down Expand Up @@ -1941,6 +1941,8 @@
ED8F1D3C2885BB2D00F897E7 /* MXCryptoProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED8F1D3A2885BB2D00F897E7 /* MXCryptoProtocols.swift */; };
EDA2CDD628F5C4230088ACE7 /* MXQRCodeTransactionV2UnitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDA2CDD528F5C4230088ACE7 /* MXQRCodeTransactionV2UnitTests.swift */; };
EDA2CDD728F5C4230088ACE7 /* MXQRCodeTransactionV2UnitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDA2CDD528F5C4230088ACE7 /* MXQRCodeTransactionV2UnitTests.swift */; };
EDA69340290BA92E00223252 /* MXCryptoMachineUnitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDA6933F290BA92E00223252 /* MXCryptoMachineUnitTests.swift */; };
EDA69341290BA92E00223252 /* MXCryptoMachineUnitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDA6933F290BA92E00223252 /* MXCryptoMachineUnitTests.swift */; };
EDAAC41928E2FCFE00DD89B5 /* MXCryptoSecretStoreV2.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDAAC41828E2FCFE00DD89B5 /* MXCryptoSecretStoreV2.swift */; };
EDAAC41A28E2FCFE00DD89B5 /* MXCryptoSecretStoreV2.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDAAC41828E2FCFE00DD89B5 /* MXCryptoSecretStoreV2.swift */; };
EDAAC41C28E30F3C00DD89B5 /* (null) in Headers */ = {isa = PBXBuildFile; settings = {ATTRIBUTES = (Public, ); }; };
Expand Down Expand Up @@ -3059,6 +3061,7 @@
ED8F1D332885ADE200F897E7 /* MXCryptoProtocolStubs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXCryptoProtocolStubs.swift; sourceTree = "<group>"; };
ED8F1D3A2885BB2D00F897E7 /* MXCryptoProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MXCryptoProtocols.swift; sourceTree = "<group>"; };
EDA2CDD528F5C4230088ACE7 /* MXQRCodeTransactionV2UnitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXQRCodeTransactionV2UnitTests.swift; sourceTree = "<group>"; };
EDA6933F290BA92E00223252 /* MXCryptoMachineUnitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXCryptoMachineUnitTests.swift; sourceTree = "<group>"; };
EDAAC41228E2F86800DD89B5 /* MXCryptoSecretStore.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MXCryptoSecretStore.h; sourceTree = "<group>"; };
EDAAC41828E2FCFE00DD89B5 /* MXCryptoSecretStoreV2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXCryptoSecretStoreV2.swift; sourceTree = "<group>"; };
EDAAC42328E3177000DD89B5 /* MXRecoveryServiceDependencies.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MXRecoveryServiceDependencies.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -5320,6 +5323,7 @@
isa = PBXGroup;
children = (
ED8F1D332885ADE200F897E7 /* MXCryptoProtocolStubs.swift */,
EDA6933F290BA92E00223252 /* MXCryptoMachineUnitTests.swift */,
ED2DD11B286C4F3E00F06731 /* MXCryptoRequestsUnitTests.swift */,
ED8F1D312885AC5700F897E7 /* Device+Stub.swift */,
);
Expand Down Expand Up @@ -7155,6 +7159,7 @@
32832B5E1BCC048300241108 /* MXStoreNoStoreTests.m in Sources */,
A816247C25F60C7700A46F05 /* MXDeviceListOperationsPoolUnitTests.swift in Sources */,
B1660F1C260A20B900C3AA12 /* MXSpaceServiceTest.swift in Sources */,
EDA69340290BA92E00223252 /* MXCryptoMachineUnitTests.swift in Sources */,
ED35652C281150310002BF6A /* MXOlmInboundGroupSessionUnitTests.swift in Sources */,
32C9B71823E81A1C00C6F30A /* MXCrossSigningVerificationTests.m in Sources */,
323C5A081A70E53500FB0549 /* MXToolsUnitTests.m in Sources */,
Expand Down Expand Up @@ -7786,6 +7791,7 @@
32C9B71923E81A1C00C6F30A /* MXCrossSigningVerificationTests.m in Sources */,
B1E09A1D2397FCE90057C069 /* MXCryptoKeyVerificationTests.m in Sources */,
B1E09A472397FD990057C069 /* MXEventScanStoreUnitTests.m in Sources */,
EDA69341290BA92E00223252 /* MXCryptoMachineUnitTests.swift in Sources */,
ED35652D281150310002BF6A /* MXOlmInboundGroupSessionUnitTests.swift in Sources */,
B1E09A3D2397FD820057C069 /* MXStoreFileStoreTests.m in Sources */,
32CEEF3E23AD134A0039BA98 /* MXCrossSigningTests.m in Sources */,
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 @@ -121,7 +121,7 @@ class MXCrossSigningV2: NSObject, MXCrossSigning {

Task {
do {
try await crossSigning.downloadKeys(users: [crossSigning.userId])
try await crossSigning.updateTrackedUsers(users: [crossSigning.userId])
myUserCrossSigningKeys = infoSource.crossSigningInfo(userId: crossSigning.userId)

log.debug("Cross signing state refreshed")
Expand Down
64 changes: 35 additions & 29 deletions MatrixSDK/Crypto/CryptoMachine/MXCryptoMachine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -163,13 +163,17 @@ extension MXCryptoMachine: MXCryptoSyncing {
unusedFallbackKeys: unusedFallbackKeys
)

guard let json = MXTools.deserialiseJSONString(result) as? [AnyHashable: Any] else {
log.error("Result cannot be serialized", context: [
guard
let json = MXTools.deserialiseJSONString(result) as? [Any],
let toDevice = MXToDeviceSyncResponse(fromJSON: ["events": json])
else {
log.failure("Result cannot be serialized", context: [
"result": result
])
return MXToDeviceSyncResponse()
}
return MXToDeviceSyncResponse(fromJSON: json)

return toDevice
}

func processOutgoingRequests() async throws {
Expand Down Expand Up @@ -312,10 +316,32 @@ extension MXCryptoMachine: MXCryptoUserIdentitySource {
}
}

func downloadKeys(users: [String]) async throws {
try await handleRequest(
.keysQuery(requestId: UUID().uuidString, users: users)
)
func isUserTracked(userId: String) -> Bool {
do {
return try machine.isUserTracked(userId: userId)
} catch {
log.error("Failed checking user tracking")
return false
}
}

func updateTrackedUsers(users: [String]) async throws {
machine.updateTrackedUsers(users: users)
try await withThrowingTaskGroup(of: Void.self) { [weak self] group in
guard let self = self else { return }

for request in try machine.outgoingRequests() {
guard case .keysQuery = request else {
continue
}

group.addTask {
try await self.handleRequest(request)
}
}

try await group.waitForAll()
}
}

func manuallyVerifyUser(userId: String) async throws {
Expand Down Expand Up @@ -353,9 +379,8 @@ extension MXCryptoMachine: MXCryptoRoomEventEncrypting {
func encryptRoomEvent(
content: [AnyHashable : Any],
roomId: String,
eventType: String,
users: [String]
) async throws -> [String : Any] {
eventType: String
) throws -> [String : Any] {
guard let content = MXTools.serialiseJSONObject(content) else {
throw Error.cannotSerialize
}
Expand Down Expand Up @@ -424,25 +449,6 @@ extension MXCryptoMachine: MXCryptoRoomEventEncrypting {

// MARK: - Private

private func updateTrackedUsers(users: [String]) async throws {
machine.updateTrackedUsers(users: users)
try await withThrowingTaskGroup(of: Void.self) { [weak self] group in
guard let self = self else { return }

for request in try machine.outgoingRequests() {
guard case .keysQuery = request else {
continue
}

group.addTask {
try await self.handleRequest(request)
}
}

try await group.waitForAll()
}
}

private func getMissingSessions(users: [String]) async throws {
guard
let request = try machine.getMissingSessions(users: users),
Expand Down
5 changes: 3 additions & 2 deletions MatrixSDK/Crypto/CryptoMachine/MXCryptoProtocols.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ protocol MXCryptoDevicesSource: MXCryptoIdentity {
protocol MXCryptoUserIdentitySource: MXCryptoIdentity {
func userIdentity(userId: String) -> UserIdentity?
func isUserVerified(userId: String) -> Bool
func downloadKeys(users: [String]) async throws
func isUserTracked(userId: String) -> Bool
func updateTrackedUsers(users: [String]) async throws
func manuallyVerifyUser(userId: String) async throws
func manuallyVerifyDevice(userId: String, deviceId: String) async throws
func setLocalTrust(userId: String, deviceId: String, trust: LocalTrust) throws
Expand All @@ -61,7 +62,7 @@ protocol MXCryptoUserIdentitySource: MXCryptoIdentity {
/// Event encryption and decryption
protocol MXCryptoRoomEventEncrypting: MXCryptoIdentity {
func shareRoomKeysIfNecessary(roomId: String, users: [String], settings: EncryptionSettings) async throws
func encryptRoomEvent(content: [AnyHashable: Any], roomId: String, eventType: String, users: [String]) async throws -> [String: Any]
func encryptRoomEvent(content: [AnyHashable: Any], roomId: String, eventType: String) throws -> [String: Any]
func decryptRoomEvent(_ event: MXEvent) -> MXEventDecryptionResult
func requestRoomKey(event: MXEvent) async throws
func discardRoomKey(roomId: String)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ extension MXEventDecryptionResult {
senderCurve25519Key = event.senderCurve25519Key
claimedEd25519Key = event.claimedEd25519Key
forwardingCurve25519KeyChain = event.forwardingCurve25519Chain
isUntrusted = event.verificationState == VerificationState.untrusted
}
}

Expand Down
10 changes: 7 additions & 3 deletions MatrixSDK/Crypto/Devices/Data/MXCryptoDeviceWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,13 @@ import MatrixSDKCrypto
deviceId = device.deviceId
algorithms = device.algorithms
keys = device.keys
unsignedData = [
"device_display_name": device.displayName as Any
]
if let displayName = device.displayName {
unsignedData = [
"device_display_name": displayName
]
} else {
unsignedData = [:]
}

let status: MXDeviceVerification
if device.isBlocked {
Expand Down
14 changes: 7 additions & 7 deletions MatrixSDK/Crypto/KeyBackup/MXKeyBackup.m
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ - (void)checkAndStartKeyBackup
} failure:^(NSError * _Nonnull error) {
MXStrongifyAndReturnIfNil(self);

MXLogDebug(@"[MXKeyBackup] checkAndStartKeyBackup: Failed to get current version: %@", error);
MXLogErrorDetails(@"[MXKeyBackup] checkAndStartKeyBackup: Failed to get current version", error);
self.state = MXKeyBackupStateUnknown;
}];
}
Expand Down Expand Up @@ -270,7 +270,7 @@ - (void)sendKeyBackup
} failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);

MXLogDebug(@"[MXKeyBackup] sendKeyBackup: backupRoomKeysSuccess failed. Error: %@", error);
MXLogErrorDetails(@"[MXKeyBackup] sendKeyBackup: backupRoomKeysSuccess failed", error);

void (^backupAllGroupSessionsFailure)(NSError *error) = self->backupAllGroupSessionsFailure;

Expand Down Expand Up @@ -304,7 +304,7 @@ - (void)requestPrivateKeys:(void (^)(void))onComplete
[self restoreKeyBackupAutomaticallyWithPrivateKey:onComplete];

} failure:^(NSError * _Nonnull error) {
MXLogDebug(@"[MXKeyBackup] requestPrivateKeys. Error for requestPrivateKeys: %@", error);
MXLogErrorDetails(@"[MXKeyBackup] requestPrivateKeys. Error for requestPrivateKeys", error);
onComplete();
}];
}
Expand All @@ -323,15 +323,15 @@ - (void)restoreKeyBackupAutomaticallyWithPrivateKey:(void (^)(void))onComplete
[self restoreKeyBackupAutomaticallyWithPrivateKey:onComplete];
}
} failure:^(NSError * _Nonnull error) {
MXLogDebug(@"[MXKeyBackup] restoreKeyBackupAutomatically: Cannot fetch backup version. Error: %@", error);
MXLogErrorDetails(@"[MXKeyBackup] restoreKeyBackupAutomatically: Cannot fetch backup version", error);
}];
return;
}

// Check private keys
if (!self.engine.hasValidPrivateKey)
if (![self.engine hasValidPrivateKeyForKeyBackupVersion:self.keyBackupVersion])
{
MXLogDebug(@"[MXKeyBackup] restoreKeyBackupAutomatically. Error: No valid private key");
MXLogError(@"[MXKeyBackup] restoreKeyBackupAutomatically. Error: No valid private key");
onComplete();
return;
}
Expand All @@ -343,7 +343,7 @@ - (void)restoreKeyBackupAutomaticallyWithPrivateKey:(void (^)(void))onComplete
onComplete();

} failure:^(NSError * _Nonnull error) {
MXLogDebug(@"[MXKeyBackup] restoreKeyBackupAutomatically. Error for restoreKeyBackup: %@", error);
MXLogErrorDetails(@"[MXKeyBackup] restoreKeyBackupAutomatically. Error for restoreKeyBackup", error);
onComplete();
}];
}
Expand Down
7 changes: 6 additions & 1 deletion MatrixSDK/Crypto/MXCrypto.h
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ extern NSString *const MXDeviceListDidUpdateUsersDevicesNotification;
*/
@protocol MXCrypto <NSObject>

/**
Version of the crypto module being used
*/
@property (nonatomic, readonly) NSString *version;

/**
Curve25519 key for the account.
*/
Expand Down Expand Up @@ -205,7 +210,7 @@ extern NSString *const MXDeviceListDidUpdateUsersDevicesNotification;
/**
Handle the sync response that may contain crypto-related events
*/
- (void)handleSyncResponse:(MXSyncResponse *)syncResponse;
- (void)handleSyncResponse:(MXSyncResponse *)syncResponse onComplete:(void (^)(void))onComplete;

#pragma mark - Cross-signing / Local trust

Expand Down
22 changes: 19 additions & 3 deletions MatrixSDK/Crypto/MXCrypto.m
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,24 @@ @implementation MXLegacyCrypto
+ (void)checkCryptoWithMatrixSession:(MXSession*)mxSession complete:(void (^)(id<MXCrypto> crypto))complete
{
#ifdef MX_CRYPTO

#if DEBUG
id<MXCrypto> cryptoV2 = [self createCryptoV2IfAvailableWithSession:mxSession];
if (cryptoV2) {
if (cryptoV2)
{
complete(cryptoV2);
return;
}
#endif

[self checkLegacyCryptoWithMatrixSession:mxSession complete:complete];
#else
complete(nil);
#endif
}

+ (void)checkLegacyCryptoWithMatrixSession:(MXSession*)mxSession complete:(void (^)(id<MXCrypto> crypto))complete
{
#ifdef MX_CRYPTO

MXLogDebug(@"[MXCrypto] checkCryptoWithMatrixSession for %@", mxSession.matrixRestClient.credentials.userId);

Expand Down Expand Up @@ -909,11 +919,12 @@ - (void)handleDeviceUnusedFallbackKeys:(NSArray<NSString *> *)deviceFallbackKeys
#endif
}

- (void)handleSyncResponse:(MXSyncResponse *)syncResponse
- (void)handleSyncResponse:(MXSyncResponse *)syncResponse onComplete:(void (^)(void))onComplete
{
// Not implemented, the default `MXCrypto` instead uses more specific functions
// such as `handleRoomKeyEvent` and `handleDeviceUnusedFallbackKeys`. The method
// is possibly used by `MXCrypto` subclasses.
onComplete();
}

- (void)onSyncCompleted:(NSString *)oldSyncToken nextSyncToken:(NSString *)nextSyncToken catchingUp:(BOOL)catchingUp
Expand Down Expand Up @@ -1404,6 +1415,11 @@ - (void)resetDeviceKeys
#endif
}

- (NSString *)version
{
return [NSString stringWithFormat:@"OLM %@", self.olmVersion];
}

- (NSString *)deviceCurve25519Key
{
#ifdef MX_CRYPTO
Expand Down
Loading