π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Prepare Android for HPKE push notifications (#13805)
aman-pilot335e3d745814
diff --git a/mobile/apps/photos/changes/android-encrypted-push.md b/mobile/apps/photos/changes/android-encrypted-push.mdnew file mode 100644index 0000000000..fc23588e5f--- /dev/null+++ b/mobile/apps/photos/changes/android-encrypted-push.md@@ -0,0 +1 @@+- Added support for receiving encrypted notifications on Android.diff --git a/mobile/apps/photos/integration_test/notification_lifecycle_test.dart b/mobile/apps/photos/integration_test/notification_lifecycle_test.dartnew file mode 100644index 0000000000..5ce1892f82--- /dev/null+++ b/mobile/apps/photos/integration_test/notification_lifecycle_test.dart@@ -0,0 +1,109 @@+import 'dart:convert';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter_local_notifications/flutter_local_notifications.dart';+import 'package:flutter_secure_storage/flutter_secure_storage.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';+import 'package:photos/core/configuration.dart';+import 'package:photos/services/notification_key_service.dart';+import 'package:photos/services/notification_service.dart';+import 'package:photos/src/rust/frb_generated.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();+ const storage = FlutterSecureStorage();+ final notifications = FlutterLocalNotificationsPlugin();+ late SharedPreferences preferences;++ setUpAll(() async {+ await EntePhotosRust.init();+ expect(+ await notifications+ .resolvePlatformSpecificImplementation<+ AndroidFlutterLocalNotificationsPlugin+ >()!+ .areNotificationsEnabled(),+ isTrue,+ reason: 'Grant Android notification permission before running this test',+ );+ });++ setUp(() async {+ preferences = await SharedPreferences.getInstance();+ await preferences.clear();+ await storage.deleteAll();+ await notifications.cancelAll();+ NotificationService.instance.init(preferences);+ });++ tearDown(() async {+ await preferences.clear();+ await storage.deleteAll();+ await notifications.cancelAll();+ });++ testWidgets('overlapping enrollment reuses one persisted private key', (+ tester,+ ) async {+ final keys = await Future.wait(+ List.generate(8, (_) => NotificationKeyService.generateNotificationKey()),+ );+ expect(keys.toSet().length, 1);+ expect(await NotificationKeyService.generateNotificationKey(), keys.first);+ final stored = await storage.readAll();+ expect(stored.length, 1);+ expect(base64Decode(stored.values.single), hasLength(32));++ await storage.deleteAll();+ expect(+ await NotificationKeyService.generateNotificationKey(),+ isNot(keys.first),+ );+ });++ testWidgets('fallback is shown when signed in and suppressed after logout', (+ tester,+ ) async {+ await preferences.setString(Configuration.tokenKey, 'test-session');+ Future<void> receive() =>+ NotificationService.instance.handlePushNotification(+ {'notificationCiphertext': 'invalid'},+ onSync: () async =>+ fail('An undecryptable push must not request sync'),+ );++ await receive();+ await Future<void>.delayed(const Duration(milliseconds: 500));+ expect(await notifications.getActiveNotifications(), hasLength(1));+ await notifications.cancelAll();++ final rootToken = RootIsolateToken.instance!;+ await compute(_clearAccount, rootToken);+ expect(preferences.getString(Configuration.tokenKey), isNotNull);+ await receive();+ await Future<void>.delayed(const Duration(milliseconds: 500));+ expect(await notifications.getActiveNotifications(), isEmpty);+ });++ testWidgets('failed key preparation can be retried after clearing storage', (+ tester,+ ) async {+ await NotificationKeyService.setNotificationPrivateKey(Uint8List(1));+ await expectLater(+ NotificationKeyService.generateNotificationKey(),+ throwsA(anything),+ );+ await storage.deleteAll();+ final publicKey = await NotificationKeyService.generateNotificationKey();+ expect(publicKey, isNotNull);+ });+}++Future<void> _clearAccount(RootIsolateToken rootToken) async {+ BackgroundIsolateBinaryMessenger.ensureInitialized(rootToken);+ await (await SharedPreferences.getInstance()).clear();+ await const FlutterSecureStorage().deleteAll();+}diff --git a/mobile/apps/photos/lib/gateways/push/push_gateway.dart b/mobile/apps/photos/lib/gateways/push/push_gateway.dartindex 58faca4186..a030f5ea0a 100644--- a/mobile/apps/photos/lib/gateways/push/push_gateway.dart+++ b/mobile/apps/photos/lib/gateways/push/push_gateway.dart@@ -9,6 +9,7 @@ class PushGateway {required String fcmToken,required String platform,String? apnsToken,+ String? notificationKey,}) async {await _enteDio.post("/push/token",@@ -16,6 +17,7 @@ class PushGateway {"fcmToken": fcmToken,"platform": platform,"apnsToken": apnsToken,+ "notificationKey": notificationKey,},);}diff --git a/mobile/apps/photos/lib/services/notification_key_service.dart b/mobile/apps/photos/lib/services/notification_key_service.dartnew file mode 100644index 0000000000..14baeb3c33--- /dev/null+++ b/mobile/apps/photos/lib/services/notification_key_service.dart@@ -0,0 +1,59 @@+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:flutter_secure_storage/flutter_secure_storage.dart';+import 'package:photos/src/rust/api/notification_api.dart';+import 'package:photos/src/rust/frb_generated.dart';++class NotificationKeyService {+ static const _storage = FlutterSecureStorage();+ static const _storageKey = 'notification_private_key';+ static Future<String>? _pendingKey;++ static Future<String?> generateNotificationKey() {+ if (!Platform.isAndroid) return Future.value();+ return _pendingKey ??= _getOrCreateNotificationKey().whenComplete(() {+ _pendingKey = null;+ });+ }++ static Future<String> _getOrCreateNotificationKey() async {+ var privateKey = await getNotificationPrivateKey();+ if (privateKey == null) {+ privateKey = generateNotificationPrivateKey();+ await setNotificationPrivateKey(privateKey);+ }+ return base64Encode(getNotificationPublicKey(privateKey: privateKey));+ }++ static Future<Map<String, dynamic>?> decrypt(+ Map<String, dynamic> data,+ ) async {+ final privateKey = await getNotificationPrivateKey();+ if (privateKey == null) return null;+ if (!EntePhotosRust.instance.initialized) {+ await EntePhotosRust.init();+ }+ final plaintext = decryptNotification(+ ciphertext: base64Decode(data['notificationCiphertext'] as String),+ privateKey: privateKey,+ );+ final event = jsonDecode(utf8.decode(plaintext)) as Map<String, dynamic>;+ if (event['eventType'] is! String) return null;+ return event;+ }++ static Future<Uint8List?> getNotificationPrivateKey() async {+ final encoded = await _storage.read(key: _storageKey);+ return encoded == null ? null : base64Decode(encoded);+ }++ static Future<void> setNotificationPrivateKey(Uint8List? privateKey) async {+ if (privateKey == null) {+ await _storage.delete(key: _storageKey);+ } else {+ await _storage.write(key: _storageKey, value: base64Encode(privateKey));+ }+ }+}diff --git a/mobile/apps/photos/lib/services/notification_service.dart b/mobile/apps/photos/lib/services/notification_service.dartindex d1653d2827..f8c30417ad 100644--- a/mobile/apps/photos/lib/services/notification_service.dart+++ b/mobile/apps/photos/lib/services/notification_service.dart@@ -8,6 +8,9 @@ import "package:flutter_timezone/flutter_timezone.dart";import "package:logging/logging.dart";import "package:package_info_plus/package_info_plus.dart";import "package:permission_handler/permission_handler.dart";+import "package:photos/core/configuration.dart";+import "package:photos/services/language_service.dart";+import "package:photos/services/notification_key_service.dart";import "package:photos/services/timezone_aliases.dart";import "package:shared_preferences/shared_preferences.dart";import 'package:timezone/data/latest_10y.dart' as tzdb;@@ -39,6 +42,40 @@ class NotificationService {unawaited(preferences.remove("notification_permission_granted"));}+ Future<void> handlePushNotification(+ Map<String, dynamic> data, {+ required Future<void> Function() onSync,+ }) async {+ if (!data.containsKey('notificationCiphertext')) {+ if (data['action'] == 'sync') await onSync();+ return;+ }+ if (!Platform.isAndroid) return;+ Map<String, dynamic>? event;+ try {+ event = await NotificationKeyService.decrypt(data);+ } catch (_) {+ _logger.warning('Could not decrypt notification');+ }+ if (event == null) {+ await _preferences.reload();+ if (_preferences.getString(Configuration.tokenKey) == null) return;+ if (shouldShowNotificationsForSharedPhotosAndAlbums()) {+ final strings = await LanguageService.locals;+ await showNotification(+ strings.entePhotos,+ strings.notificationNewActivity,+ id: -1,+ );+ }+ return;+ }+ if (event['eventType'] == 'album_shared') {+ _logger.info('Received encrypted album-share push');+ await onSync();+ }+ }+bool timezoneInitialized = false;Future<void> initialize(diff --git a/mobile/apps/photos/lib/services/push_service.dart b/mobile/apps/photos/lib/services/push_service.dartindex f5fe489c56..9b567fa8ca 100644--- a/mobile/apps/photos/lib/services/push_service.dart+++ b/mobile/apps/photos/lib/services/push_service.dart@@ -10,6 +10,8 @@ import 'package:photos/core/constants.dart';import 'package:photos/core/event_bus.dart';import 'package:photos/events/signed_in_event.dart';import 'package:photos/service_locator.dart';+import 'package:photos/services/notification_key_service.dart';+import 'package:photos/services/notification_service.dart';import 'package:photos/services/sync/sync_service.dart';import 'package:photos/utils/bg_task_utils.dart';import 'package:shared_preferences/shared_preferences.dart';@@ -100,10 +102,17 @@ class PushService {}Future<void> _setPushTokenOnServer(String fcmToken, String? apnsToken) async {+ String? notificationKey;+ try {+ notificationKey = await NotificationKeyService.generateNotificationKey();+ } catch (e, s) {+ _logPushError("Could not prepare notification key", e, s);+ }await pushGateway.registerToken(fcmToken: fcmToken,platform: Platform.operatingSystem,apnsToken: apnsToken,+ notificationKey: notificationKey,);}@@ -117,16 +126,11 @@ class PushService {}}- void _handleForegroundPushMessage(RemoteMessage message) {- _logger.info("Message data: ${message.data}");- if (message.notification != null) {- _logger.info(- "Message also contained a notification: ${message.notification}",- );- }- if (shouldSync(message)) {- SyncService.instance.sync();- }+ Future<void> _handleForegroundPushMessage(RemoteMessage message) async {+ await NotificationService.instance.handlePushNotification(+ message.data,+ onSync: () => SyncService.instance.sync(),+ );}static bool shouldSync(Object message) {@@ -140,10 +144,13 @@ class PushService {@pragma('vm:entry-point')Future<void> handleAndroidBackgroundPush(RemoteMessage message) async {- if (!PushService.shouldSync(message)) return;WidgetsFlutterBinding.ensureInitialized();await Firebase.initializeApp().timeout(const Duration(seconds: 10));- await BgTaskUtils.scheduleAndroidBackgroundRefresh().timeout(- const Duration(seconds: 10),+ NotificationService.instance.init(await SharedPreferences.getInstance());+ await NotificationService.instance.handlePushNotification(+ message.data,+ onSync: () => BgTaskUtils.scheduleAndroidBackgroundRefresh().timeout(+ const Duration(seconds: 10),+ ),);}diff --git a/mobile/packages/strings/lib/l10n/arb/strings_en.arb b/mobile/packages/strings/lib/l10n/arb/strings_en.arbindex 74b008d12f..8fc590fde9 100644--- a/mobile/packages/strings/lib/l10n/arb/strings_en.arb+++ b/mobile/packages/strings/lib/l10n/arb/strings_en.arb@@ -2888,6 +2888,7 @@"nothingToCleanUp": "Nothing to clean up","nothingToTidyUpHere": "Nothing to tidy up here","notifications": "Notifications",+ "notificationNewActivity": "New activity","notifyMe": "Notify me","notPersonLabel": "Not {name}?","@notPersonLabel": {diff --git a/rust/bindings/frb/photos/src/api/mod.rs b/rust/bindings/frb/photos/src/api/mod.rsindex 87cebac3e2..6f650a56ec 100644--- a/rust/bindings/frb/photos/src/api/mod.rs+++ b/rust/bindings/frb/photos/src/api/mod.rs@@ -9,6 +9,7 @@ pub mod metadata_api;pub mod ml_db_api;pub mod ml_indexing_api;pub mod motion_photo_api;+pub mod notification_api;pub mod ocr_api;pub mod usearch_api;pub mod vecdb_api;diff --git a/rust/bindings/frb/photos/src/api/notification_api.rs b/rust/bindings/frb/photos/src/api/notification_api.rsnew file mode 100644index 0000000000..2b06704311--- /dev/null+++ b/rust/bindings/frb/photos/src/api/notification_api.rs@@ -0,0 +1,22 @@+use ente_core::crypto::hpke;++const HPKE_INFO: &[u8] = b"ente-push";++#[flutter_rust_bridge::frb(sync)]+pub fn generate_notification_private_key() -> Vec<u8> {+ hpke::SecretKey::generate().as_bytes().to_vec()+}++#[flutter_rust_bridge::frb(sync)]+pub fn get_notification_public_key(private_key: Vec<u8>) -> Result<Vec<u8>, String> {+ let private_key =+ hpke::SecretKey::try_from_slice(&private_key).map_err(|error| error.to_string())?;+ Ok(private_key.public_key().as_bytes().to_vec())+}++#[flutter_rust_bridge::frb(sync)]+pub fn decrypt_notification(ciphertext: Vec<u8>, private_key: Vec<u8>) -> Result<Vec<u8>, String> {+ let private_key =+ hpke::SecretKey::try_from_slice(&private_key).map_err(|error| error.to_string())?;+ hpke::open(&ciphertext, &private_key, HPKE_INFO).map_err(|error| error.to_string())+}