Enable database encryption for new logins on Nightly/PR builds. (#2328)

- Slightly reworks where the pusher client ID is generated.
This commit is contained in:
Doug
2024-01-12 16:45:59 +00:00
committed by GitHub
parent d475c9c63b
commit 01f42546e1
20 changed files with 147 additions and 60 deletions
@@ -21,11 +21,18 @@ import MatrixRustSDK
class AuthenticationServiceProxy: AuthenticationServiceProxyProtocol {
private let authenticationService: AuthenticationService
private let userSessionStore: UserSessionStoreProtocol
private let passphrase: String?
private let homeserverSubject: CurrentValueSubject<LoginHomeserver, Never>
var homeserver: CurrentValuePublisher<LoginHomeserver, Never> { homeserverSubject.asCurrentValuePublisher() }
init(userSessionStore: UserSessionStoreProtocol, appSettings: AppSettings) {
init(userSessionStore: UserSessionStoreProtocol, encryptionKeyProvider: EncryptionKeyProviderProtocol, appSettings: AppSettings) {
let passphrase = appSettings.isDevelopmentBuild ? encryptionKeyProvider.generateKey().base64EncodedString() : nil
if passphrase != nil {
MXLog.info("Testing database encryption in development build.")
}
self.passphrase = passphrase
self.userSessionStore = userSessionStore
homeserverSubject = .init(LoginHomeserver(address: appSettings.defaultHomeserverAddress,
@@ -41,7 +48,7 @@ class AuthenticationServiceProxy: AuthenticationServiceProxyProtocol {
staticRegistrations: appSettings.oidcStaticRegistrations.mapKeys { $0.absoluteString })
authenticationService = AuthenticationService(basePath: userSessionStore.baseDirectory.path,
passphrase: nil,
passphrase: passphrase,
userAgent: UserAgentBuilder.makeASCIIUserAgent(),
oidcConfiguration: oidcConfiguration,
customSlidingSyncProxy: appSettings.slidingSyncProxyURL?.absoluteString,
@@ -138,7 +145,7 @@ class AuthenticationServiceProxy: AuthenticationServiceProxyProtocol {
// MARK: - Private
private func userSession(for client: Client) async -> Result<UserSessionProtocol, AuthenticationServiceError> {
switch await userSessionStore.userSession(for: client) {
switch await userSessionStore.userSession(for: client, passphrase: passphrase) {
case .success(let clientProxy):
return .success(clientProxy)
case .failure:
@@ -15,9 +15,9 @@
//
import Combine
import Foundation
import CryptoKit
import MatrixRustSDK
import UIKit
import SwiftUI
class ClientProxy: ClientProxyProtocol {
private let client: ClientProtocol
@@ -159,14 +159,22 @@ class ClientProxy: ClientProxyProtocol {
client.homeserver()
}
var restorationToken: RestorationToken? {
var session: Session? {
do {
return try RestorationToken(session: client.session())
return try client.session()
} catch {
MXLog.error("Failed retrieving restore token with error: \(error)")
MXLog.error("Failed retrieving the client's session with error: \(error)")
return nil
}
}
private(set) lazy var pusherNotificationClientIdentifier: String? = {
// NOTE: The result is stored as part of the restoration token. Any changes
// here would require a migration to correctly match incoming notifications.
guard let data = userID.data(using: .utf8) else { return nil }
let digest = SHA256.hash(data: data)
return digest.compactMap { String(format: "%02x", $0) }.joined()
}()
func startSync() {
guard !hasEncounteredAuthError else {
@@ -79,11 +79,13 @@ protocol ClientProxyProtocol: AnyObject, MediaLoaderProtocol {
var homeserver: String { get }
var session: Session? { get }
var userDisplayName: CurrentValuePublisher<String?, Never> { get }
var userAvatarURL: CurrentValuePublisher<URL?, Never> { get }
var restorationToken: RestorationToken? { get }
var pusherNotificationClientIdentifier: String? { get }
var roomSummaryProvider: RoomSummaryProviderProtocol? { get }
@@ -26,7 +26,8 @@ class MockClientProxy: ClientProxyProtocol {
let userID: String
let deviceID: String?
let homeserver = ""
let restorationToken: RestorationToken? = nil
let session: Session? = nil
let pusherNotificationClientIdentifier: String? = nil
var roomSummaryProvider: RoomSummaryProviderProtocol? = MockRoomSummaryProvider()
@@ -0,0 +1,26 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import CryptoKit
import Foundation
struct EncryptionKeyProvider: EncryptionKeyProviderProtocol {
func generateKey() -> Data {
SymmetricKey(size: .bits256).withUnsafeBytes { bytes in
Data(Array(bytes))
}
}
}
@@ -0,0 +1,21 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
protocol EncryptionKeyProviderProtocol {
func generateKey() -> Data
}
@@ -113,7 +113,14 @@ class KeychainController: KeychainControllerProtocol {
func saveSessionInKeychain(session: Session) {
MXLog.info("Saving session changes in the keychain.")
let restorationToken = RestorationToken(session: session)
guard let oldToken = restorationTokenForUsername(session.userId) else {
MXLog.error("Failed retrieving the restoration token for \(session.userId)")
fatalError("Something has gone mega wrong, all bets are off.")
}
let restorationToken = RestorationToken(session: session,
passphrase: oldToken.passphrase,
pusherNotificationClientIdentifier: oldToken.pusherNotificationClientIdentifier)
setRestorationToken(restorationToken, forUsername: session.userId)
}
@@ -127,7 +127,7 @@ final class NotificationManager: NSObject, NotificationManagerProtocol {
let defaultPayload = APNSPayload(aps: APSInfo(mutableContent: 1,
alert: APSAlert(locKey: "Notification",
locArgs: [])),
pusherNotificationClientIdentifier: clientProxy.restorationToken?.pusherNotificationClientIdentifier)
pusherNotificationClientIdentifier: clientProxy.pusherNotificationClientIdentifier)
let configuration = try await PusherConfiguration(identifiers: .init(pushkey: deviceToken.base64EncodedString(),
appId: appSettings.pusherAppId),
@@ -14,24 +14,13 @@
// limitations under the License.
//
import CryptoKit
import Foundation
import MatrixRustSDK
struct RestorationToken: Codable, Equatable {
let session: MatrixRustSDK.Session
let passphrase: String?
let pusherNotificationClientIdentifier: String?
init(session: MatrixRustSDK.Session) {
self.session = session
if let data = session.userId.data(using: .utf8) {
let digest = SHA256.hash(data: data)
pusherNotificationClientIdentifier = digest.compactMap { String(format: "%02x", $0) }.joined()
} else {
pusherNotificationClientIdentifier = nil
}
}
}
extension MatrixRustSDK.Session: Codable {
@@ -68,13 +68,21 @@ class UserSessionStore: UserSessionStoreProtocol {
}
}
func userSession(for client: Client) async -> Result<UserSessionProtocol, UserSessionStoreError> {
switch await setupProxyForClient(client) {
case .success(let clientProxy):
func userSession(for client: Client, passphrase: String?) async -> Result<UserSessionProtocol, UserSessionStoreError> {
do {
let session = try client.session()
let userID = try client.userId()
let clientProxy = await setupProxyForClient(client)
keychainController.setRestorationToken(RestorationToken(session: session,
passphrase: passphrase,
pusherNotificationClientIdentifier: clientProxy.pusherNotificationClientIdentifier),
forUsername: userID)
return .success(buildUserSessionWithClient(clientProxy))
case .failure(let error):
} catch {
MXLog.error("Failed creating user session with error: \(error)")
return .failure(error)
return .failure(.failedSettingUpSession)
}
}
@@ -104,10 +112,14 @@ class UserSessionStore: UserSessionStoreProtocol {
}
private func restorePreviousLogin(_ credentials: KeychainCredentials) async -> Result<ClientProxyProtocol, UserSessionStoreError> {
if credentials.restorationToken.passphrase != nil {
MXLog.info("Restoring client with encrypted store.")
}
let builder = ClientBuilder()
.basePath(path: baseDirectory.path)
.username(username: credentials.userID)
.homeserverUrl(url: credentials.restorationToken.session.homeserverUrl)
.passphrase(passphrase: credentials.restorationToken.passphrase)
.userAgent(userAgent: UserAgentBuilder.makeASCIIUserAgent())
.enableCrossProcessRefreshLock(processId: InfoPlistReader.main.bundleIdentifier,
sessionDelegate: keychainController)
@@ -119,30 +131,18 @@ class UserSessionStore: UserSessionStoreProtocol {
try client.restoreSession(session: credentials.restorationToken.session)
return client
}
return await setupProxyForClient(client)
return await .success(setupProxyForClient(client))
} catch {
MXLog.error("Failed restoring login with error: \(error)")
return .failure(.failedRestoringLogin)
}
}
private func setupProxyForClient(_ client: Client) async -> Result<ClientProxyProtocol, UserSessionStoreError> {
do {
let session = try client.session()
let userID = try client.userId()
keychainController.setRestorationToken(RestorationToken(session: session), forUsername: userID)
} catch {
MXLog.error("Failed setting up user session with error: \(error)")
return .failure(.failedSettingUpSession)
}
let clientProxy = await ClientProxy(client: client,
backgroundTaskService: backgroundTaskService,
appSettings: ServiceLocator.shared.settings,
networkMonitor: ServiceLocator.shared.networkMonitor)
return .success(clientProxy)
private func setupProxyForClient(_ client: Client) async -> ClientProxyProtocol {
await ClientProxy(client: client,
backgroundTaskService: backgroundTaskService,
appSettings: ServiceLocator.shared.settings,
networkMonitor: ServiceLocator.shared.networkMonitor)
}
private func deleteSessionDirectory(for userID: String) {
@@ -42,8 +42,8 @@ protocol UserSessionStoreProtocol {
/// Restores an existing user session.
func restoreUserSession() async -> Result<UserSessionProtocol, UserSessionStoreError>
/// Creates a user session for a new client from the SDK.
func userSession(for client: Client) async -> Result<UserSessionProtocol, UserSessionStoreError>
/// Creates a user session for a new client from the SDK along with the passphrase used for the data stores.
func userSession(for client: Client, passphrase: String?) async -> Result<UserSessionProtocol, UserSessionStoreError>
/// Logs out of the specified session.
func logout(userSession: UserSessionProtocol)