π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Harden Live Photo archive extraction
Neeraj Gupta46cb9f409803
diff --git a/mobile/apps/photos/lib/module/live_photo/archive.dart b/mobile/apps/photos/lib/module/live_photo/archive.dartindex 696de83e14..4ecc6c6352 100644--- a/mobile/apps/photos/lib/module/live_photo/archive.dart+++ b/mobile/apps/photos/lib/module/live_photo/archive.dart@@ -4,18 +4,50 @@ import "package:archive/archive_io.dart";import "package:computer/computer.dart";import "package:path/path.dart";-enum LivePhotoArchivePartType { image, video }+// Live Photo components are already compressed media. This allows generous+// container overhead while preventing a small archive from expanding without+// bound on device storage.+const _maxExpandedArchiveRatio = 20;+const _maxExpandedArchiveOverhead = 16 * 1024 * 1024;+final _livePhotoEntryPattern = RegExp(+ r'^(image|video)(?:\.[A-Za-z0-9]{1,16})?$',+);class LivePhotoArchivePart {- const LivePhotoArchivePart({- required this.type,- required this.fileName,- required this.bytes,- });+ const LivePhotoArchivePart({required this.fileName, required this.file});- final LivePhotoArchivePartType type;final String fileName;- final List<int> bytes;+ final File file;+}++typedef ExtractedLivePhotoArchive = ({+ LivePhotoArchivePart image,+ LivePhotoArchivePart video,+});++class _CappedOutputFileStream extends OutputFileStream {+ _CappedOutputFileStream(String path, this.maxLength)+ : super.withFileHandle(FileHandle(path, mode: FileAccess.write));++ final int maxLength;++ @override+ void writeByte(int value) {+ _checkLength(1);+ super.writeByte(value);+ }++ @override+ void writeBytes(List<int> bytes, {int? length}) {+ _checkLength(length ?? bytes.length);+ super.writeBytes(bytes, length: length);+ }++ void _checkLength(int additionalBytes) {+ if (length + additionalBytes > maxLength) {+ throw const FormatException("Live Photo archive expands beyond limit");+ }+ }}Future<void> _computeLivePhotoArchive(Map<String, dynamic> args) async {@@ -45,29 +77,93 @@ Future<void> createLivePhotoArchive({);}-List<LivePhotoArchivePart> decodeLivePhotoArchive(List<int> bytes) {- final archive = ZipDecoder().decodeBytes(bytes);- final parts = <LivePhotoArchivePart>[];- for (final entry in archive) {- if (!entry.isFile) {- continue;- }- final type = switch (entry.name) {- final name when name.startsWith("image") =>- LivePhotoArchivePartType.image,- final name when name.startsWith("video") =>- LivePhotoArchivePartType.video,- _ => null,- };- if (type != null) {- parts.add(- LivePhotoArchivePart(- type: type,- fileName: entry.name,- bytes: entry.content,- ),+Future<ExtractedLivePhotoArchive> extractLivePhotoArchive({+ required File archiveFile,+ required Directory outputDirectory,+}) async {+ ArchiveFile? imageEntry;+ ArchiveFile? videoEntry;+ final input = InputFileStream(archiveFile.path);+ try {+ ZipDecoder().decodeStream(+ input,+ callback: (entry) {+ if (!entry.isFile || entry.isSymbolicLink) {+ throw const FormatException(+ "Live Photo archives may only contain files",+ );+ }+ final match = _livePhotoEntryPattern.firstMatch(entry.name);+ if (match == null) {+ throw FormatException(+ "Unexpected Live Photo archive entry: ${entry.name}",+ );+ }+ if (match.group(1) == "image") {+ if (imageEntry != null) {+ throw const FormatException(+ "Live Photo archive contains multiple images",+ );+ }+ imageEntry = entry;+ } else {+ if (videoEntry != null) {+ throw const FormatException(+ "Live Photo archive contains multiple videos",+ );+ }+ videoEntry = entry;+ }+ },+ );+ if (imageEntry == null || videoEntry == null) {+ throw const FormatException(+ "Live Photo archive must contain one image and one video",);}++ final archiveSize = await archiveFile.length();+ final maxExpandedSize =+ archiveSize * _maxExpandedArchiveRatio + _maxExpandedArchiveOverhead;+ if (imageEntry!.size + videoEntry!.size > maxExpandedSize) {+ throw const FormatException("Live Photo archive expands beyond limit");+ }++ final image = await _extractPart(+ imageEntry!,+ outputDirectory,+ "image",+ maxExpandedSize,+ );+ final remainingSize = maxExpandedSize - await image.file.length();+ return (+ image: image,+ video: await _extractPart(+ videoEntry!,+ outputDirectory,+ "video",+ remainingSize,+ ),+ );+ } finally {+ await input.close();+ }+}++Future<LivePhotoArchivePart> _extractPart(+ ArchiveFile entry,+ Directory outputDirectory,+ String outputName,+ int maxSize,+) async {+ final file = File(+ join(outputDirectory.path, "$outputName${extension(entry.name)}"),+ );+ final output = _CappedOutputFileStream(file.path, maxSize);+ try {+ entry.writeContent(output);+ } finally {+ await output.close();}- return parts;+ return LivePhotoArchivePart(fileName: entry.name, file: file);}diff --git a/mobile/apps/photos/lib/module/live_photo/download.dart b/mobile/apps/photos/lib/module/live_photo/download.dartindex 376020720f..2e7d08121d 100644--- a/mobile/apps/photos/lib/module/live_photo/download.dart+++ b/mobile/apps/photos/lib/module/live_photo/download.dart@@ -1,7 +1,6 @@import 'dart:io';import 'package:dio/dio.dart';-import 'package:flutter/foundation.dart';import 'package:flutter_cache_manager/flutter_cache_manager.dart';import 'package:flutter_image_compress/flutter_image_compress.dart';import 'package:logging/logging.dart';@@ -22,6 +21,7 @@ Future<LivePhotoFiles?> downloadLivePhotoFiles(bool forGalleryDownload = false,}) async {File? decryptedFile;+ Directory? extractionDirectory;try {decryptedFile = await downloadAndDecrypt(file,@@ -33,60 +33,17 @@ Future<LivePhotoFiles?> downloadLivePhotoFiles(return null;}_logger.info('Decoded zipped live photo from ${decryptedFile.path}');- File? imageFileCache;- File? videoFileCache;- final parts = decodeLivePhotoArchive(await decryptedFile.readAsBytes());- final tempPath = Configuration.instance.getTempDirectory();- for (final part in parts) {- final fileExtension = _fileExtension(part.fileName);- final decodePath = '$tempPath${file.uploadedFileID}${part.fileName}';- if (part.type == LivePhotoArchivePartType.image) {- final imageFile = File(decodePath);- await imageFile.create(recursive: true);- await imageFile.writeAsBytes(part.bytes);- File imageConvertedFile = imageFile;- if (fileExtension == 'unknown' ||- (Platform.isAndroid && fileExtension == 'heic')) {- final compressResult = await FlutterImageCompress.compressAndGetFile(- decodePath,- '$decodePath.jpg',- keepExif: true,- );- await imageFile.delete();- if (compressResult == null) {- throw Exception('Failed to compress file');- }- imageConvertedFile = File(compressResult.path);- }- imageFileCache = await DefaultCacheManager().putFile(- file.downloadUrl,- await imageConvertedFile.readAsBytes(),- eTag: file.downloadUrl,- maxAge: const Duration(days: 365),- fileExtension: fileExtension,- );- await imageConvertedFile.delete();- } else {- final videoFile = File(decodePath);- await videoFile.create(recursive: true);- await videoFile.writeAsBytes(part.bytes);- videoFileCache = await VideoCacheManager.instance.putFileStream(- file.downloadUrl,- videoFile.openRead(),- eTag: file.downloadUrl,- maxAge: const Duration(days: 365),- fileExtension: fileExtension,- );- await videoFile.delete();- }- }- if (imageFileCache != null && videoFileCache != null) {- return (image: imageFileCache, video: videoFileCache);- }- debugPrint(- 'Warning: ${file.tag} either image ${imageFileCache == null} or video ${videoFileCache == null} is missing from remoteLive',+ extractionDirectory = await Directory(+ Configuration.instance.getTempDirectory(),+ ).createTemp('live_photo_${file.uploadedFileID}_');+ final parts = await extractLivePhotoArchive(+ archiveFile: decryptedFile,+ outputDirectory: extractionDirectory,+ );+ return (+ image: await _cacheImagePart(file, parts.image),+ video: await _cacheVideoPart(file, parts.video),);- return null;} catch (error, stackTrace) {_logger.warning('failed to download live photos : ${file.tag}',@@ -98,7 +55,44 @@ Future<LivePhotoFiles?> downloadLivePhotoFiles(if (decryptedFile != null) {await _deleteDecryptedArchive(decryptedFile);}+ if (extractionDirectory != null) {+ await _deleteExtractionDirectory(extractionDirectory);+ }+ }+}++Future<File> _cacheImagePart(EnteFile file, LivePhotoArchivePart part) async {+ final fileExtension = _fileExtension(part.fileName);+ File imageFile = part.file;+ if (fileExtension == 'unknown' ||+ (Platform.isAndroid && fileExtension == 'heic')) {+ final compressResult = await FlutterImageCompress.compressAndGetFile(+ imageFile.path,+ '${imageFile.path}.jpg',+ keepExif: true,+ );+ if (compressResult == null) {+ throw Exception('Failed to compress file');+ }+ imageFile = File(compressResult.path);}+ return DefaultCacheManager().putFileStream(+ file.downloadUrl,+ imageFile.openRead(),+ eTag: file.downloadUrl,+ maxAge: const Duration(days: 365),+ fileExtension: fileExtension,+ );+}++Future<File> _cacheVideoPart(EnteFile file, LivePhotoArchivePart part) {+ return VideoCacheManager.instance.putFileStream(+ file.downloadUrl,+ part.file.openRead(),+ eTag: file.downloadUrl,+ maxAge: const Duration(days: 365),+ fileExtension: _fileExtension(part.fileName),+ );}Future<void> _deleteDecryptedArchive(File file) async {@@ -113,6 +107,18 @@ Future<void> _deleteDecryptedArchive(File file) async {}}+Future<void> _deleteExtractionDirectory(Directory directory) async {+ try {+ await directory.delete(recursive: true);+ } catch (error, stackTrace) {+ _logger.warning(+ 'Failed to delete extracted live photo files',+ error,+ stackTrace,+ );+ }+}+String _fileExtension(String nameOrPath) {try {return extension(nameOrPath).substring(1).toLowerCase();diff --git a/mobile/apps/photos/test/module/live_photo/archive_test.dart b/mobile/apps/photos/test/module/live_photo/archive_test.dartnew file mode 100644index 0000000000..d7b4e9db2e--- /dev/null+++ b/mobile/apps/photos/test/module/live_photo/archive_test.dart@@ -0,0 +1,113 @@+import "dart:io";+import "dart:typed_data";++import "package:archive/archive_io.dart";+import "package:flutter_test/flutter_test.dart";+import "package:path/path.dart";+import "package:photos/module/live_photo/archive.dart";++void main() {+ late Directory tempDirectory;+ late Directory outputDirectory;++ setUp(() async {+ tempDirectory = await Directory.systemTemp.createTemp(+ "live_photo_archive_test_",+ );+ outputDirectory = await Directory(+ join(tempDirectory.path, "output"),+ ).create();+ });++ tearDown(() async {+ await tempDirectory.delete(recursive: true);+ });++ test("extracts one flat image and video entry", () async {+ final archiveFile = await _writeArchive(tempDirectory, [+ ArchiveFile.bytes("image.jpg", [1, 2, 3]),+ ArchiveFile.bytes("video.mov", [4, 5, 6]),+ ]);++ final result = await extractLivePhotoArchive(+ archiveFile: archiveFile,+ outputDirectory: outputDirectory,+ );++ expect(result.image.fileName, "image.jpg");+ expect(await result.image.file.readAsBytes(), [1, 2, 3]);+ expect(result.video.fileName, "video.mov");+ expect(await result.video.file.readAsBytes(), [4, 5, 6]);+ });++ test("rejects entries with paths", () async {+ final archiveFile = await _writeArchive(tempDirectory, [+ ArchiveFile.bytes("image/../../outside.jpg", [1, 2, 3]),+ ArchiveFile.bytes("video.mov", [4, 5, 6]),+ ]);++ await expectLater(+ extractLivePhotoArchive(+ archiveFile: archiveFile,+ outputDirectory: outputDirectory,+ ),+ throwsFormatException,+ );+ expect(outputDirectory.listSync(), isEmpty);+ });++ test("limits the bytes produced by decompression", () async {+ final archive = Archive()+ ..add(ArchiveFile.bytes("image.jpg", Uint8List(18 * 1024 * 1024)))+ ..add(ArchiveFile.bytes("video.mov", [4, 5, 6]));+ final encoded = Uint8List.fromList(ZipEncoder().encode(archive));+ final imageDirectoryEntry = _indexOfSignature(encoded, [+ 0x50,+ 0x4b,+ 0x01,+ 0x02,+ ]);+ // Forge a small declared size while retaining the full deflate stream.+ encoded.buffer.asByteData().setUint32(+ imageDirectoryEntry + 24,+ 1,+ Endian.little,+ );+ final archiveFile = await File(+ join(tempDirectory.path, "forged-size.zip"),+ ).writeAsBytes(encoded);++ await expectLater(+ extractLivePhotoArchive(+ archiveFile: archiveFile,+ outputDirectory: outputDirectory,+ ),+ throwsFormatException,+ );+ });+}++Future<File> _writeArchive(+ Directory directory,+ List<ArchiveFile> entries,+) async {+ final archive = Archive();+ for (final entry in entries) {+ archive.add(entry);+ }+ return File(+ join(directory.path, "live-photo.zip"),+ ).writeAsBytes(ZipEncoder().encode(archive));+}++int _indexOfSignature(Uint8List bytes, List<int> signature) {+ for (var index = 0; index <= bytes.length - signature.length; index++) {+ if (bytes[index] == signature[0] &&+ bytes[index + 1] == signature[1] &&+ bytes[index + 2] == signature[2] &&+ bytes[index + 3] == signature[3]) {+ return index;+ }+ }+ throw StateError("ZIP directory entry not found");+}