Skip to content

armgit / ente

Public Imported from GitHub
0

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

Revoke server Cast sessions on stop

Neeraj Gupta5010458b6357
diff --git a/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart b/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart
index 7e468112dc..0e43cf9c6a 100644
--- a/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart
+++ b/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart
@@ -55,13 +55,13 @@ class CastGateway {
return devices.map((session) => CastInfo.fromJson(session)).toList();
}
- Future<void> publishCastPayload(
+ Future<String?> publishCastPayload(
String code,
String castPayload,
int collectionID,
String castToken,
- ) {
- return _enteDio.post(
+ ) async {
+ final response = await _enteDio.post(
"/cast/cast-data",
data: {
"deviceCode": code,
@@ -70,6 +70,9 @@ class CastGateway {
"castToken": castToken,
},
);
+ final data = response.data;
+ final deviceID = data is Map ? data["deviceID"] : null;
+ return deviceID is String && deviceID.isNotEmpty ? deviceID : null;
}
Future<void> revokeAllTokens() async {
@@ -81,7 +84,11 @@ class CastGateway {
}
Future<void> revokeSession(CastInfo session) async {
- await _enteDio.delete("/cast/device-info/${session.deviceID}");
+ await revokeSessionByID(session.deviceID);
+ }
+
+ Future<void> revokeSessionByID(String deviceID) async {
+ await _enteDio.delete("/cast/device-info/$deviceID");
}
}
diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dart
index a1f8107edf..9055b0ec12 100644
--- a/mobile/apps/photos/lib/service_locator.dart
+++ b/mobile/apps/photos/lib/service_locator.dart
@@ -6,6 +6,7 @@ import "package:package_info_plus/package_info_plus.dart";
import "package:photos/core/configuration.dart";
import "package:photos/core/network/endpoint_config.dart";
import "package:photos/gateways/billing/billing_gateway.dart";
+import "package:photos/gateways/cast/cast_gateway.dart";
import "package:photos/gateways/collections/collection_files_gateway.dart";
import "package:photos/gateways/collections/collection_share_gateway.dart";
import "package:photos/gateways/collections/collections_gateway.dart";
@@ -23,6 +24,7 @@ import "package:photos/gateways/users/users_gateway.dart";
import "package:photos/module/download/gallery_download_queue_service.dart";
import "package:photos/module/download/manager.dart";
import "package:photos/services/account/billing_service.dart";
+import "package:photos/services/auto_cast_service.dart";
import "package:photos/services/backup_preference_service.dart";
import "package:photos/services/collections_service.dart";
import "package:photos/services/entity_service.dart";
@@ -101,6 +103,17 @@ CastService get castService {
return _castService!;
}
+AutoCastService? _autoCastService;
+
+AutoCastService get autoCastService {
+ _autoCastService ??= AutoCastService(
+ transport: castService,
+ gateway: CastGateway(ServiceLocator.instance.enteDio),
+ encodePayload: collectionsService.getCastData,
+ );
+ return _autoCastService!;
+}
+
LocalSettings get localSettings => ServiceLocator.instance.localSettings;
BackupSettings get backupSettings => ServiceLocator.instance.backupSettings;
diff --git a/mobile/apps/photos/lib/services/auto_cast_service.dart b/mobile/apps/photos/lib/services/auto_cast_service.dart
new file mode 100644
index 0000000000..7819d0c835
--- /dev/null
+++ b/mobile/apps/photos/lib/services/auto_cast_service.dart
@@ -0,0 +1,104 @@
+import "package:ente_cast/ente_cast.dart";
+import "package:logging/logging.dart";
+import "package:photos/gateways/cast/cast_gateway.dart";
+import "package:photos/models/collection/collection.dart";
+import "package:uuid/uuid.dart";
+
+typedef CastPayloadEncoder =
+ String Function(String castToken, Collection collection, String publicKey);
+
+class AutoCastDeviceNotFoundException implements Exception {
+ const AutoCastDeviceNotFoundException();
+}
+
+class AutoCastService {
+ AutoCastService({
+ required CastService transport,
+ required CastGateway gateway,
+ required CastPayloadEncoder encodePayload,
+ }) : _transport = transport,
+ _gateway = gateway,
+ _encodePayload = encodePayload;
+
+ final CastService _transport;
+ final CastGateway _gateway;
+ final CastPayloadEncoder _encodePayload;
+ final _serverDeviceIDs = <Object, String>{};
+ final _logger = Logger("AutoCastService");
+
+ Future<List<(String, Object)>> searchDevices() => _transport.searchDevices();
+
+ bool isCastingToDevice(Object device) => _transport.isCastingToDevice(device);
+
+ Future<void> connect(Object device, Collection collection) async {
+ final code = await _transport.connectDevice(
+ device,
+ collectionID: collection.id,
+ );
+ try {
+ final publicKey = await _gateway.getPublicKey(code);
+ if (publicKey == null) {
+ throw const AutoCastDeviceNotFoundException();
+ }
+ final castToken = const Uuid().v4();
+ final castPayload = _encodePayload(castToken, collection, publicKey);
+ final deviceID = await _gateway.publishCastPayload(
+ code,
+ castPayload,
+ collection.id,
+ castToken,
+ );
+ if (deviceID == null) {
+ _logger.warning(
+ "Cast server did not return a device ID; stop cannot revoke this "
+ "session remotely",
+ );
+ } else {
+ _serverDeviceIDs[device] = deviceID;
+ }
+ } catch (error, stackTrace) {
+ try {
+ await _transport.stopCastingToDevice(device);
+ } catch (stopError, stopStackTrace) {
+ _logger.warning(
+ "Failed to stop Cast after pairing failed",
+ stopError,
+ stopStackTrace,
+ );
+ }
+ Error.throwWithStackTrace(error, stackTrace);
+ }
+ }
+
+ Future<void> stop(Object device) async {
+ Object? revokeError;
+ StackTrace? revokeStackTrace;
+ final deviceID = _serverDeviceIDs[device];
+ if (deviceID != null) {
+ try {
+ await _gateway.revokeSessionByID(deviceID);
+ _serverDeviceIDs.remove(device);
+ } catch (error, stackTrace) {
+ revokeError = error;
+ revokeStackTrace = stackTrace;
+ }
+ }
+
+ try {
+ await _transport.stopCastingToDevice(device);
+ } catch (error, stackTrace) {
+ if (revokeError == null) {
+ Error.throwWithStackTrace(error, stackTrace);
+ }
+ _logger.warning(
+ "Failed to disconnect the local Cast session",
+ error,
+ stackTrace,
+ );
+ }
+
+ if (revokeError != null) {
+ Error.throwWithStackTrace(revokeError, revokeStackTrace!);
+ }
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart b/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart
index 3bff3b4edd..b0dd8da161 100644
--- a/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart
+++ b/mobile/apps/photos/lib/ui/cast/pair_with_auto.dart
@@ -4,35 +4,15 @@ import "package:ente_components/ente_components.dart";
import "package:flutter/material.dart";
import "package:hugeicons/hugeicons.dart";
import "package:logging/logging.dart";
-import "package:photos/core/network/network.dart";
import "package:photos/gateways/cast/cast_gateway.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/collection/collection.dart";
import "package:photos/service_locator.dart";
+import "package:photos/services/auto_cast_service.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/common/loading_widget.dart";
import "package:photos/ui/notification/toast.dart";
import "package:photos/utils/dialog_util.dart";
-import "package:uuid/uuid.dart";
-
-class _DeviceNotFoundException implements Exception {
- const _DeviceNotFoundException();
-}
-
-Future<void> _pairWithAuto(Collection collection, String code) async {
- final gw = CastGateway(NetworkClient.instance.enteDio);
- final publicKey = await gw.getPublicKey(code);
- if (publicKey == null) {
- throw const _DeviceNotFoundException();
- }
- final castToken = const Uuid().v4();
- final castData = collectionsService.getCastData(
- castToken,
- collection,
- publicKey,
- );
- await gw.publishCastPayload(code, castData, collection.id, castToken);
-}
/// Shows the auto-pairing sheet for Cast devices.
Future<void> showPairWithAutoSheet(
@@ -62,7 +42,7 @@ class _PairWithAutoSheetState extends State<_PairWithAutoSheet> {
@override
void initState() {
super.initState();
- _devices = castService.searchDevices();
+ _devices = autoCastService.searchDevices();
}
@override
@@ -102,7 +82,7 @@ class _PairWithAutoSheetState extends State<_PairWithAutoSheet> {
children: snapshot.data!.map((result) {
final device = result.$2;
final name = result.$1;
- final isCasting = castService.isCastingToDevice(device);
+ final isCasting = autoCastService.isCastingToDevice(device);
final isInProgress = _devicesInProgress.contains(device);
return MenuComponent(
title: name,
@@ -169,28 +149,12 @@ class _PairWithAutoSheetState extends State<_PairWithAutoSheet> {
}
setState(() => _devicesInProgress.add(device));
try {
- final code = await castService.connectDevice(device);
+ await autoCastService.connect(device, widget.collection);
if (!mounted) {
- await castService.stopCastingToDevice(device);
+ await autoCastService.stop(device);
return;
}
- try {
- await _pairWithAuto(widget.collection, code);
- } catch (error, stackTrace) {
- try {
- await castService.stopCastingToDevice(device);
- } catch (stopError, stopStackTrace) {
- _logger.warning(
- "Failed to stop Cast after pairing failed",
- stopError,
- stopStackTrace,
- );
- }
- Error.throwWithStackTrace(error, stackTrace);
- }
- if (mounted) {
- await Navigator.maybePop(context);
- }
+ await Navigator.maybePop(context);
} catch (e, s) {
if (!mounted) return;
await _handleError(e, s);
@@ -218,7 +182,7 @@ class _PairWithAutoSheetState extends State<_PairWithAutoSheet> {
if (!mounted) return;
setState(() => _devicesInProgress.add(device));
try {
- await castService.stopCastingToDevice(device);
+ await autoCastService.stop(device);
} catch (e, s) {
_logger.severe("Failed to stop casting", e, s);
if (!mounted) return;
@@ -247,7 +211,7 @@ class _PairWithAutoSheetState extends State<_PairWithAutoSheet> {
);
return;
}
- if (error is _DeviceNotFoundException) {
+ if (error is AutoCastDeviceNotFoundException) {
showToast(context, l10n.deviceNotFound);
return;
}
diff --git a/mobile/apps/photos/test/services/auto_cast_service_test.dart b/mobile/apps/photos/test/services/auto_cast_service_test.dart
new file mode 100644
index 0000000000..e39f850274
--- /dev/null
+++ b/mobile/apps/photos/test/services/auto_cast_service_test.dart
@@ -0,0 +1,92 @@
+import "package:ente_cast/ente_cast.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/gateways/cast/cast_gateway.dart";
+import "package:photos/models/collection/collection.dart";
+import "package:photos/services/auto_cast_service.dart";
+
+void main() {
+ test("stopping revokes the server session returned while pairing", () async {
+ final transport = _FakeCastService();
+ final gateway = _FakeCastGateway();
+ final service = AutoCastService(
+ transport: transport,
+ gateway: gateway,
+ encodePayload: (_, _, _) => "encrypted-payload",
+ );
+ final device = Object();
+
+ await service.connect(device, _FakeCollection());
+ await service.stop(device);
+
+ expect(gateway.revokedDeviceIDs, ["device-id"]);
+ expect(transport.stoppedDevices, [device]);
+ });
+
+ test(
+ "stopping disconnects the device when server revocation fails",
+ () async {
+ final transport = _FakeCastService();
+ final gateway = _FakeCastGateway();
+ final service = AutoCastService(
+ transport: transport,
+ gateway: gateway,
+ encodePayload: (_, _, _) => "encrypted-payload",
+ );
+ final device = Object();
+ await service.connect(device, _FakeCollection());
+ gateway.revokeError = StateError("revoke failed");
+
+ await expectLater(service.stop(device), throwsStateError);
+
+ expect(gateway.revokedDeviceIDs, ["device-id"]);
+ expect(transport.stoppedDevices, [device]);
+ },
+ );
+}
+
+class _FakeCastService extends Fake implements CastService {
+ final stoppedDevices = <Object>[];
+
+ @override
+ Future<String> connectDevice(Object device, {int? collectionID}) async {
+ return "ABC123";
+ }
+
+ @override
+ Future<void> stopCastingToDevice(Object device) async {
+ stoppedDevices.add(device);
+ }
+}
+
+class _FakeCastGateway extends Fake implements CastGateway {
+ final revokedDeviceIDs = <String>[];
+ Object? revokeError;
+
+ @override
+ Future<String?> getPublicKey(String deviceCode) async {
+ return "public-key";
+ }
+
+ @override
+ Future<String?> publishCastPayload(
+ String code,
+ String castPayload,
+ int collectionID,
+ String castToken,
+ ) async {
+ return "device-id";
+ }
+
+ @override
+ Future<void> revokeSessionByID(String deviceID) async {
+ revokedDeviceIDs.add(deviceID);
+ if (revokeError case final error?) {
+ throw error;
+ }
+ }
+}
+
+class _FakeCollection extends Fake implements Collection {
+ @override
+ int get id => 42;
+}