Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][photos] Add iOS notification keychain foundation (#13892)

aman-pilot175dda1c84fc
diff --git a/mobile/apps/photos/ios/NotificationServiceExtension/NotificationKeyStore.swift b/mobile/apps/photos/ios/NotificationServiceExtension/NotificationKeyStore.swift
new file mode 100644
index 0000000000..40a3ca63ce
--- /dev/null
+++ b/mobile/apps/photos/ios/NotificationServiceExtension/NotificationKeyStore.swift
@@ -0,0 +1,94 @@
+import Foundation
+import Security
+
+struct NotificationRecipient: Codable {
+ let schemaVersion: Int
+ let privateKey: String
+
+ var isValid: Bool {
+ schemaVersion == 1 && Data(base64Encoded: privateKey)?.count == 32
+ }
+}
+
+enum NotificationKeyStore {
+ static let accessGroup = "group.io.ente.frame.NotificationServiceExtension"
+ static let service = "io.ente.frame.notifications"
+ #if DEBUG
+ static let account = "recipient.debug"
+ #else
+ static let account = "recipient"
+ #endif
+
+ enum StoreError: Error {
+ case keychain(OSStatus)
+ case invalidRecord
+ case unsupportedVersion
+ }
+
+ static var preferences: UserDefaults { UserDefaults(suiteName: accessGroup)! }
+ private static var resetPendingKey: String { "\(account).resetPending" }
+ private static var preparedKey: String { "flutter.\(account).notificationKeyPrepared" }
+
+ private static var query: [String: Any] {
+ [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrAccessGroup as String: accessGroup,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ kSecAttrSynchronizable as String: false]
+ }
+
+ static func read() throws -> NotificationRecipient? {
+ guard !preferences.bool(forKey: resetPendingKey) else { return nil }
+ var query = query
+ query[kSecReturnData as String] = true
+ query[kSecMatchLimit as String] = kSecMatchLimitOne
+ var result: CFTypeRef?
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
+ if status == errSecItemNotFound { return nil }
+ guard status == errSecSuccess else { throw StoreError.keychain(status) }
+ guard let data = result as? Data else { throw StoreError.invalidRecord }
+ let record = try JSONDecoder().decode(NotificationRecipient.self, from: data)
+ guard record.schemaVersion == 1 else { throw StoreError.unsupportedVersion }
+ guard record.isValid else { throw StoreError.invalidRecord }
+ return record
+ }
+
+ static func readForPreparation() throws -> NotificationRecipient? {
+ if preferences.bool(forKey: resetPendingKey) || !UserDefaults.standard.bool(forKey: preparedKey) {
+ try clear()
+ }
+ do {
+ return try read()
+ } catch StoreError.invalidRecord {
+ return nil
+ } catch is DecodingError {
+ return nil
+ }
+ }
+
+ static func write(privateKey: String) throws {
+ let record = NotificationRecipient(schemaVersion: 1, privateKey: privateKey)
+ guard record.isValid else { throw StoreError.invalidRecord }
+ _ = try readForPreparation()
+ let data = try JSONEncoder().encode(record)
+ var status = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary)
+ if status == errSecItemNotFound {
+ var attributes = query
+ attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ attributes[kSecValueData as String] = data
+ status = SecItemAdd(attributes as CFDictionary, nil)
+ }
+ guard status == errSecSuccess else { throw StoreError.keychain(status) }
+ UserDefaults.standard.set(true, forKey: preparedKey)
+ }
+
+ static func clear() throws {
+ UserDefaults.standard.removeObject(forKey: preparedKey)
+ preferences.set(true, forKey: resetPendingKey)
+ let status = SecItemDelete(query as CFDictionary)
+ guard status == errSecSuccess || status == errSecItemNotFound else {
+ throw StoreError.keychain(status)
+ }
+ preferences.removeObject(forKey: resetPendingKey)
+ }
+}
diff --git a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
index 4f780b98fd..39d82cec70 100644
--- a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
+++ b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
@@ -7,6 +7,8 @@
objects = {
/* Begin PBXBuildFile section */
+ A17E00000000000000000011 /* NotificationKeyStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A17E00000000000000000001 /* NotificationKeyStore.swift */; };
+ A17E00000000000000000010 /* NotificationKeyPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = A17E00000000000000000000 /* NotificationKeyPlugin.swift */; };
ABB487F057701138D27F550A /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DB627F0726BF9EB1E87E584 /* SceneDelegate.swift */; };
0856877A9F80F9E052DBFDB4 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F82DAEEB9A7D9FD00E0FFA1E /* Pods_Runner.framework */; };
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
@@ -92,6 +94,8 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
+ A17E00000000000000000001 /* NotificationKeyStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "../NotificationServiceExtension/NotificationKeyStore.swift"; sourceTree = "<group>"; };
+ A17E00000000000000000000 /* NotificationKeyPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NotificationKeyPlugin.swift"; sourceTree = "<group>"; };
6DB627F0726BF9EB1E87E584 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
@@ -318,6 +322,8 @@
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
+ A17E00000000000000000001 /* NotificationKeyStore.swift */,
+ A17E00000000000000000000 /* NotificationKeyPlugin.swift */,
6DB627F0726BF9EB1E87E584 /* SceneDelegate.swift */,
57EEDBC4E19D917C19BF4545 /* ForegroundHeartbeat.swift */,
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
@@ -865,6 +871,8 @@
buildActionMask = 2147483647;
files = (
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
+ A17E00000000000000000011 /* NotificationKeyStore.swift in Sources */,
+ A17E00000000000000000010 /* NotificationKeyPlugin.swift in Sources */,
ABB487F057701138D27F550A /* SceneDelegate.swift in Sources */,
6DA601B38B4BCCD1C4BB0E25 /* ForegroundHeartbeat.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
@@ -1337,6 +1345,7 @@
SWIFT_ENABLE_EXPLICIT_MODULES = NO;
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
diff --git a/mobile/apps/photos/ios/Runner/AppDelegate.swift b/mobile/apps/photos/ios/Runner/AppDelegate.swift
index fe26d62a48..167a751b6b 100644
--- a/mobile/apps/photos/ios/Runner/AppDelegate.swift
+++ b/mobile/apps/photos/ios/Runner/AppDelegate.swift
@@ -58,7 +58,10 @@ import workmanager_apple
startupTrace.measure("app.backgroundManager.install") {
BackgroundManagerPlugin.install(
isEnabled: { Self.shouldUseNativeBackgroundManager() },
- registrant: { registry in GeneratedPluginRegistrant.register(with: registry) }
+ registrant: { registry in
+ GeneratedPluginRegistrant.register(with: registry)
+ NotificationKeyPlugin.register(in: registry)
+ }
)
}
BackgroundManagerPlugin.registerTask(
@@ -68,6 +71,7 @@ import workmanager_apple
WorkmanagerPlugin.setPluginRegistrantCallback { registry in
BackgroundStartupTrace(scope: "workmanager").measure("task.plugins") {
GeneratedPluginRegistrant.register(with: registry)
+ NotificationKeyPlugin.register(in: registry)
}
}
startupTrace.measure("app.workmanager.register") {
@@ -87,6 +91,7 @@ import workmanager_apple
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
startupTrace.measure("app.plugins") {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
+ NotificationKeyPlugin.register(in: engineBridge.pluginRegistry)
}
}
diff --git a/mobile/apps/photos/ios/Runner/NotificationKeyPlugin.swift b/mobile/apps/photos/ios/Runner/NotificationKeyPlugin.swift
new file mode 100644
index 0000000000..b71a75241f
--- /dev/null
+++ b/mobile/apps/photos/ios/Runner/NotificationKeyPlugin.swift
@@ -0,0 +1,54 @@
+import Flutter
+import Foundation
+
+final class NotificationKeyPlugin: NSObject, FlutterPlugin {
+ private static let queue = DispatchQueue(label: "io.ente.frame.notifications.keys")
+
+ static func register(in registry: FlutterPluginRegistry) {
+ if let registrar = registry.registrar(forPlugin: "NotificationKeyPlugin") {
+ register(with: registrar)
+ }
+ }
+
+ static func register(with registrar: FlutterPluginRegistrar) {
+ let channel = FlutterMethodChannel(name: NotificationKeyStore.service, binaryMessenger: registrar.messenger())
+ registrar.addMethodCallDelegate(NotificationKeyPlugin(), channel: channel)
+ }
+
+ func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ Self.queue.async {
+ do {
+ let arguments = call.arguments as? [String: Any] ?? [:]
+ if call.method == "getPrivateKey" || call.method == "setPrivateKey" {
+ guard let token = arguments["sessionToken"] as? String,
+ UserDefaults.standard.string(forKey: "flutter.token") == token else {
+ throw NotificationKeyStore.StoreError.invalidRecord
+ }
+ }
+ let response: Any?
+ switch call.method {
+ case "getPrivateKey":
+ let recipient = try NotificationKeyStore.readForPreparation()
+ response = recipient?.privateKey
+ case "setPrivateKey":
+ guard let privateKey = arguments["privateKey"] as? String else {
+ throw NotificationKeyStore.StoreError.invalidRecord
+ }
+ try NotificationKeyStore.write(privateKey: privateKey)
+ response = nil
+ case "clear":
+ try NotificationKeyStore.clear()
+ response = nil
+ default:
+ DispatchQueue.main.async { result(FlutterMethodNotImplemented) }
+ return
+ }
+ DispatchQueue.main.async { result(response) }
+ } catch {
+ DispatchQueue.main.async {
+ result(FlutterError(code: "notification_key_store", message: "\(error)", details: nil))
+ }
+ }
+ }
+ }
+}
diff --git a/mobile/apps/photos/ios/Runner/Runner.entitlements b/mobile/apps/photos/ios/Runner/Runner.entitlements
index e59f36fb63..2b402e140e 100644
--- a/mobile/apps/photos/ios/Runner/Runner.entitlements
+++ b/mobile/apps/photos/ios/Runner/Runner.entitlements
@@ -18,6 +18,7 @@
<array>
<string>group.io.ente.frame.EnteMemoryWidget</string>
<string>group.io.ente.frame.ShareExtension</string>
+ <string>group.io.ente.frame.NotificationServiceExtension</string>
</array>
<key>com.apple.developer.kernel.increased-memory-limit</key>
<true/>
diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dart
index 8d5edf0948..0cf84558c6 100644
--- a/mobile/apps/photos/lib/core/configuration.dart
+++ b/mobile/apps/photos/lib/core/configuration.dart
@@ -50,6 +50,7 @@ import "package:photos/services/machine_learning/ml_run_control.dart";
import "package:photos/services/machine_learning/ml_service.dart";
import "package:photos/services/machine_learning/similar_images_service.dart";
import "package:photos/services/memory_share_service.dart";
+import 'package:photos/services/notification_key_service.dart';
import "package:photos/services/notification_service.dart";
import 'package:photos/services/photos_contacts_service.dart';
import 'package:photos/services/search_service.dart';
@@ -148,6 +149,9 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
// https://github.com/mogol/flutter_secure_storage/issues/541
if (e is PlatformException) {
final PlatformException error = e;
+ if (error.code == 'notification_key_store') {
+ rethrow;
+ }
final bool isBadPaddingError =
error.toString().contains('BadPaddingException') ||
(error.message ?? '').contains('BadPaddingException');
@@ -212,6 +216,9 @@ class Configuration implements LockScreenHost, AccountDeletionHost {
}
}
+ if (Platform.isIOS) {
+ await NotificationKeyService.setNotificationPrivateKey(null);
+ }
await _clearTempFolderOnLogout();
await _preferences.clear();
diff --git a/mobile/apps/photos/lib/services/notification_key_service.dart b/mobile/apps/photos/lib/services/notification_key_service.dart
index 14baeb3c33..0b8e9d7309 100644
--- a/mobile/apps/photos/lib/services/notification_key_service.dart
+++ b/mobile/apps/photos/lib/services/notification_key_service.dart
@@ -1,12 +1,14 @@
import 'dart:convert';
import 'dart:io';
-import 'dart:typed_data';
+import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
+import 'package:photos/core/configuration.dart';
import 'package:photos/src/rust/api/notification_api.dart';
import 'package:photos/src/rust/frb_generated.dart';
class NotificationKeyService {
+ static const _channel = MethodChannel('io.ente.frame.notifications');
static const _storage = FlutterSecureStorage();
static const _storageKey = 'notification_private_key';
static Future<String>? _pendingKey;
@@ -19,10 +21,15 @@ class NotificationKeyService {
}
static Future<String> _getOrCreateNotificationKey() async {
- var privateKey = await getNotificationPrivateKey();
+ final sessionToken = Platform.isIOS
+ ? Configuration.instance.getToken()
+ : null;
+ var privateKey = await getNotificationPrivateKey(
+ sessionToken: sessionToken,
+ );
if (privateKey == null) {
privateKey = generateNotificationPrivateKey();
- await setNotificationPrivateKey(privateKey);
+ await setNotificationPrivateKey(privateKey, sessionToken: sessionToken);
}
return base64Encode(getNotificationPublicKey(privateKey: privateKey));
}
@@ -44,12 +51,32 @@ class NotificationKeyService {
return event;
}
- static Future<Uint8List?> getNotificationPrivateKey() async {
- final encoded = await _storage.read(key: _storageKey);
+ static Future<Uint8List?> getNotificationPrivateKey({
+ String? sessionToken,
+ }) async {
+ final encoded = Platform.isIOS
+ ? await _channel.invokeMethod<String>('getPrivateKey', {
+ 'sessionToken': sessionToken ?? Configuration.instance.getToken(),
+ })
+ : await _storage.read(key: _storageKey);
return encoded == null ? null : base64Decode(encoded);
}
- static Future<void> setNotificationPrivateKey(Uint8List? privateKey) async {
+ static Future<void> setNotificationPrivateKey(
+ Uint8List? privateKey, {
+ String? sessionToken,
+ }) async {
+ if (Platform.isIOS) {
+ if (privateKey == null) {
+ await _channel.invokeMethod<void>('clear');
+ } else {
+ await _channel.invokeMethod<void>('setPrivateKey', {
+ 'sessionToken': sessionToken ?? Configuration.instance.getToken(),
+ 'privateKey': base64Encode(privateKey),
+ });
+ }
+ return;
+ }
if (privateKey == null) {
await _storage.delete(key: _storageKey);
} else {