From 170fb2ebe77cf238cce587fb346df868fd714935 Mon Sep 17 00:00:00 2001 From: ypl <7353755@gmail.com> Date: Mon, 23 Nov 2026 22:26:33 +0200 Subject: [PATCH] fix(ios): retain export sources through deferred UIKit presentation --- .github/workflows/pdf_file_export_ios.yml | 86 +++ integration_test/pdf_file_export_ios_app.dart | 214 +++++++ .../PdfFileExportTests.swift | 597 ++++++++++++++++++ .../PdfFileExportUITests.swift | 108 ++++ ios/Podfile | 3 + ios/Runner.xcodeproj/project.pbxproj | 185 ++++++ .../xcschemes/PdfFileExport.xcscheme | 44 ++ ios/Runner/AppDelegate.swift | 3 + ios/Runner/PdfExportStaging.swift | 172 +++++ ios/Runner/PdfFileExportCoordinator.swift | 261 ++++++++ ios/Runner/PdfFileExportPlugin.swift | 68 ++ tool/pdf_file_export/README.md | 63 ++ tool/pdf_file_export/ios_export_runner.py | 236 +++++++ .../test_ios_export_evidence.py | 111 ++++ .../pdf_file_export/test_ios_export_runner.py | 206 ++++++ tool/pdf_file_export/validate_ios_export.py | 117 ++++ 16 files changed, 2474 insertions(+) create mode 100644 .github/workflows/pdf_file_export_ios.yml create mode 100644 integration_test/pdf_file_export_ios_app.dart create mode 100644 ios/PdfFileExportTests/PdfFileExportTests.swift create mode 100644 ios/PdfFileExportUITests/PdfFileExportUITests.swift create mode 100644 ios/Runner.xcodeproj/xcshareddata/xcschemes/PdfFileExport.xcscheme create mode 100644 ios/Runner/PdfExportStaging.swift create mode 100644 ios/Runner/PdfFileExportCoordinator.swift create mode 100644 ios/Runner/PdfFileExportPlugin.swift create mode 100644 tool/pdf_file_export/README.md create mode 100644 tool/pdf_file_export/ios_export_runner.py create mode 100644 tool/pdf_file_export/test_ios_export_evidence.py create mode 100644 tool/pdf_file_export/test_ios_export_runner.py create mode 100644 tool/pdf_file_export/validate_ios_export.py diff --git a/.github/workflows/pdf_file_export_ios.yml b/.github/workflows/pdf_file_export_ios.yml new file mode 100644 index 0000000000..3c311293fc --- /dev/null +++ b/.github/workflows/pdf_file_export_ios.yml @@ -0,0 +1,86 @@ +name: PDF file export (iOS UIKit and Files) + +on: + pull_request: + paths: + - 'ios/**' + - 'lib/utils/file/mobile_pdf_export_*.dart' + - 'integration_test/pdf_file_export_ios_app.dart' + - 'tool/pdf_file_export/**' + - 'pubspec.yaml' + - 'pubspec.lock' + - '.github/workflows/pdf_file_export_ios.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pdf-file-export-ios-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + gate: + uses: ./.github/workflows/ci_gate.yml + permissions: + contents: read + pull-requests: read + + contracts: + needs: gate + if: needs.gate.outputs.run == 'true' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7.0.1 + - run: python3 -m unittest discover -s tool/pdf_file_export -p 'test_*.py' -v + + ios-export: + name: Real UIKit lifecycle and Files / iOS Simulator + needs: [gate, contracts] + if: needs.gate.outputs.run == 'true' + runs-on: macos-latest + timeout-minutes: 90 + env: + CI: 'true' + BOT: 'true' + FLUTTER_SUPPRESS_ANALYTICS: 'true' + DART_SUPPRESS_ANALYTICS: 'true' + CARGO_NET_GIT_FETCH_WITH_CLI: 'true' + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v7.0.1 + - uses: subosito/flutter-action@v2 + with: + channel: stable + flutter-version: 3.47.7 + cache: false + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-apple-ios-sim,x86_64-apple-ios + - name: Build Runner and execute all native and real Files tests + timeout-minutes: 80 + run: >- + python3 tool/pdf_file_export/ios_export_runner.py + --root "$RUNNER_TEMP/pdf-file-export-ios" + --source "$GITHUB_WORKSPACE" + --commit "$GITHUB_SHA" + - name: Cleanup only the owned Simulator if the runner was interrupted + if: always() + run: >- + python3 tool/pdf_file_export/ios_export_runner.py + --root "$RUNNER_TEMP/pdf-file-export-ios" --cleanup-only + - name: Preserve raw XCTest, source, SDK and Files evidence + if: always() + uses: actions/upload-artifact@v7.0.2 + with: + name: pdf-file-export-ios + if-no-files-found: warn + retention-days: 14 + path: | + ${{ runner.temp }}/pdf-file-export-ios/*.json + ${{ runner.temp }}/pdf-file-export-ios/*.txt + ${{ runner.temp }}/pdf-file-export-ios/*.diff + ${{ runner.temp }}/pdf-file-export-ios/*.log + ${{ runner.temp }}/pdf-file-export-ios/probe/ + ${{ runner.temp }}/pdf-file-export-ios/native.xcresult/ diff --git a/integration_test/pdf_file_export_ios_app.dart b/integration_test/pdf_file_export_ios_app.dart new file mode 100644 index 0000000000..c1f13774f9 --- /dev/null +++ b/integration_test/pdf_file_export_ios_app.dart @@ -0,0 +1,214 @@ +// A test-only app for the real iOS Files picker. It uses the production service. +// Its small generated PDF is a fixture, not the production export generator. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter/material.dart'; +import 'package:otzaria/utils/file/mobile_pdf_export_service.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; + +void main() { + if (!const bool.fromEnvironment('PDF_FILE_EXPORT_IOS_PROBE') || + !Platform.isIOS) { + throw StateError( + 'This entrypoint is only for the iOS PDF export CI probe.', + ); + } + WidgetsFlutterBinding.ensureInitialized(); + runApp(const MaterialApp(home: _ExportProbe())); +} + +/// Native lifetime tests run a real additional engine without a second app UI. +@pragma('vm:entry-point') +void pdfExportHeadlessProbe() {} + +class _ExportProbe extends StatefulWidget { + const _ExportProbe(); + + @override + State<_ExportProbe> createState() => _ExportProbeState(); +} + +class _ExportProbeState extends State<_ExportProbe> { + MobilePdfExportOperation? _operation; + Uint8List? _fixture; + Directory? _destination; + Directory? _evidence; + String _state = 'preparing'; + String _summary = 'not_run'; + + @override + void initState() { + super.initState(); + unawaited(_prepare()); + } + + Future _prepare() async { + try { + final documents = await getApplicationDocumentsDirectory(); + final destination = Directory( + p.join(documents.path, 'OtzariaExportUITest'), + ); + await destination.create(recursive: true); + // This makes the app's already-enabled Files location visible. The + // directory is created only in this dedicated test entrypoint/build. + await File( + p.join(destination.path, 'fixture-location.txt'), + ).writeAsString('Otzaria PDF export UI fixture\n', flush: true); + final evidence = Directory(p.join(documents.path, 'PdfExportEvidence')); + await evidence.create(recursive: true); + final document = pw.Document(); + document.addPage( + pw.Page( + pageFormat: PdfPageFormat.a5, + build: (_) => pw.Column( + children: [ + pw.Text('Otzaria real Files export fixture'), + pw.SizedBox(height: 12), + pw.Container(width: 80, height: 60, color: PdfColors.blue), + ], + ), + ), + ); + final bytes = await document.save(); + _fixture = bytes; + _destination = destination; + _evidence = evidence; + if (mounted) setState(() => _state = 'ready'); + } catch (error) { + if (mounted) { + setState(() { + _state = 'failed'; + _summary = 'prepare: $error'; + }); + } + } + } + + Future _export(String caseName) async { + if (_state != 'ready' || _operation != null) return; + final bytes = _fixture!; + final fileName = 'ios-export-$caseName.pdf'; + String? stagingPath; + setState(() => _state = 'pending'); + final operation = MobilePdfExportService.instance.start( + fileName: fileName, + producer: (path) async { + stagingPath = path; + await File(path).writeAsBytes(bytes, flush: true); + }, + ); + _operation = operation; + try { + final outcome = await operation.result; + final source = stagingPath; + final stagingAbsent = + source != null && !await Directory(p.dirname(source)).exists(); + final expectedDigest = sha256.convert(bytes).toString(); + String? actualDigest; + bool destinationVerified = false; + if (outcome.status == MobilePdfExportStatus.saved && + outcome.documentUri != null) { + final uri = Uri.parse(outcome.documentUri!); + if (uri.scheme == 'file') { + final saved = File.fromUri(uri); + final canonical = await saved.resolveSymbolicLinks(); + final directory = await _destination!.resolveSymbolicLinks(); + actualDigest = sha256.convert(await saved.readAsBytes()).toString(); + destinationVerified = + p.dirname(canonical) == directory && + p.basename(canonical) == outcome.displayName && + actualDigest == expectedDigest; + } + } else if (outcome.status == MobilePdfExportStatus.cancelled) { + destinationVerified = !await File( + p.join(_destination!.path, fileName), + ).exists(); + } + final valid = + destinationVerified && + stagingAbsent && + outcome.cleanupStatus == MobilePdfExportCleanupStatus.notNeeded && + outcome.cleanupError == null && + outcome.residualDocument == null; + final record = { + 'schemaVersion': 1, + 'case': caseName, + 'backend': 'MobilePdfExportService.instance', + 'picker': 'UIDocumentPickerViewController.forExporting.asCopy', + 'outcome': outcome.toMap(), + 'fixtureBytes': bytes.length, + 'expectedSha256': expectedDigest, + 'actualSha256': actualDigest, + 'destinationVerified': destinationVerified, + 'stagingAbsent': stagingAbsent, + 'passed': valid, + }; + await File(p.join(_evidence!.path, '$caseName.json')).writeAsString( + '${const JsonEncoder.withIndent(' ').convert(record)}\n', + flush: true, + ); + if (mounted) { + setState(() { + _state = outcome.status.name; + _summary = + 'validated=$valid;stagingAbsent=$stagingAbsent;status=${outcome.status.name}'; + if (outcome.errorCode != null) { + _summary += ';errorCode=${outcome.errorCode}'; + } + }); + } + } catch (error) { + if (mounted) { + setState(() { + _state = 'failed'; + _summary = 'export: $error'; + }); + } + } + } + + @override + void dispose() { + unawaited(_operation?.cancel()); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('PDF export native test')), + body: Padding( + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Semantics( + identifier: 'export-status', + label: _state, + child: ExcludeSemantics(child: Text('State: $_state')), + ), + Semantics( + identifier: 'export-evidence', + label: _summary, + child: ExcludeSemantics(child: Text(_summary)), + ), + const SizedBox(height: 24), + for (final caseName in ['files-save', 'files-cancel']) + FilledButton( + onPressed: _state == 'ready' ? () => _export(caseName) : null, + child: Text('Export $caseName fixture'), + ), + const Text( + 'Destination: On My iPhone / אוצריא / OtzariaExportUITest', + ), + ], + ), + ), + ); +} diff --git a/ios/PdfFileExportTests/PdfFileExportTests.swift b/ios/PdfFileExportTests/PdfFileExportTests.swift new file mode 100644 index 0000000000..d49061dbd7 --- /dev/null +++ b/ios/PdfFileExportTests/PdfFileExportTests.swift @@ -0,0 +1,597 @@ +import Darwin +import Flutter +import UIKit +import XCTest +@testable import Runner + +/// These tests use real UIKit presentation and real filesystem/engine resources. +/// Delegate callbacks are controlled here; Files UI is tested by PdfFileExportUITests. +@MainActor +final class PdfFileExportTests: XCTestCase { + private var cache: URL! + private var window: UIWindow! + private var originalWindow: UIWindow? + private var presenter: UIViewController! + private var coordinators: [PdfFileExportCoordinator] = [] + private var heldDismissals: [() -> Void] = [] + + override func setUpWithError() throws { + try super.setUpWithError() + continueAfterFailure = false + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + originalWindow = scene.windows.first(where: { $0.isKeyWindow }) + presenter = UIViewController() + window = UIWindow(windowScene: scene) + window.rootViewController = presenter + window.makeKeyAndVisible() + cache = try PdfExportStaging.cachesDirectory().appendingPathComponent("PdfExportTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true) + } + + override func tearDown() async throws { + for coordinator in coordinators { + if let identifier = coordinator.activeOperationID { coordinator.cancel(operationID: identifier) } + } + for completion in heldDismissals { completion() } + heldDismissals.removeAll() + for coordinator in coordinators { + await waitUntil { coordinator.activeOperationID == nil } + } + coordinators.removeAll() + window.isHidden = true + window.rootViewController = nil + window = nil + presenter = nil + originalWindow?.makeKeyAndVisible() + originalWindow = nil + if let cache = cache, FileManager.default.fileExists(atPath: cache.path) { + try FileManager.default.removeItem(at: cache) + } + cache = nil + try await super.tearDown() + } + + func testStagingCleanupPreservesRootAndOtherOperations() throws { + let first = try fixture() + let second = try fixture() + let source = try validate(first) + XCTAssertEqual(try Data(contentsOf: first.url), first.bytes) + XCTAssertNil(source.cleanup()) + XCTAssertNil(source.cleanup()) + XCTAssertFalse(exists(first.directory)) + XCTAssertTrue(exists(first.directory.deletingLastPathComponent())) + XCTAssertEqual(try Data(contentsOf: second.url), second.bytes) + } + + func testInvalidIdentitiesAndSiblingPathsAreNotAdopted() throws { + let file = try fixture() + for identifier in ["", "../outside", String(repeating: "a", count: 31), file.id.uppercased()] { + XCTAssertThrowsError(try PdfExportStaging.validate( + operationID: identifier, sourcePath: file.url.path, fileName: file.name, cachesDirectory: cache + )) + } + for name in ["../outside.pdf", "a/b.pdf", "a\\b.pdf", "bad\0.pdf", "bad\n.pdf"] { + XCTAssertThrowsError(try PdfExportStaging.validate( + operationID: file.id, sourcePath: file.url.path, fileName: name, cachesDirectory: cache + )) + } + let outside = cache.appendingPathComponent("outside.pdf") + try file.bytes.write(to: outside) + XCTAssertThrowsError(try PdfExportStaging.validate( + operationID: file.id, sourcePath: outside.path, fileName: "outside.pdf", cachesDirectory: cache + )) + XCTAssertEqual(try Data(contentsOf: file.url), file.bytes) + XCTAssertEqual(try Data(contentsOf: outside), file.bytes) + + // ICU's $ can match before a final line terminator. A real directory with + // that suffix must not turn the 32-byte identifier contract into a prefix. + for suffix in ["\n", "\r\n", "\u{0085}", "\u{2028}"] { + let identifier = file.id + suffix + let directory = file.directory.deletingLastPathComponent().appendingPathComponent(identifier) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + let source = directory.appendingPathComponent(file.name) + try file.bytes.write(to: source) + XCTAssertThrowsError(try PdfExportStaging.validate( + operationID: identifier, sourcePath: source.path, fileName: file.name, cachesDirectory: cache + )) + XCTAssertEqual(try Data(contentsOf: source), file.bytes) + } + } + + func testSymlinkAndHardlinkSourcesAreNotAdopted() throws { + let file = try fixture() + let outside = cache.appendingPathComponent("outside.pdf") + try FileManager.default.moveItem(at: file.url, to: outside) + try FileManager.default.createSymbolicLink(at: file.url, withDestinationURL: outside) + XCTAssertThrowsError(try validate(file)) + XCTAssertEqual(try Data(contentsOf: outside), file.bytes) + try FileManager.default.removeItem(at: file.url) + try FileManager.default.linkItem(at: outside, to: file.url) + XCTAssertThrowsError(try validate(file)) + XCTAssertEqual(try Data(contentsOf: outside), file.bytes) + } + + func testFifoSourceIsRejectedWithoutWaitingForAWriter() async throws { + let file = try fixture() + try FileManager.default.removeItem(at: file.url) + XCTAssertEqual(mkfifo(file.url.path, 0o600), 0) + let cachesDirectory = try XCTUnwrap(cache) + let finished = expectation(description: "FIFO validation returned") + DispatchQueue.global().async { + let staging = try? PdfExportStaging.validate( + operationID: file.id, sourcePath: file.url.path, fileName: file.name, + cachesDirectory: cachesDirectory + ) + XCTAssertNil(staging) + finished.fulfill() + } + await fulfillment(of: [finished], timeout: 5) + } + + func testRootAndOperationSymlinksAreNotFollowed() throws { + let file = try fixture() + let moved = cache.appendingPathComponent("moved-operation") + try FileManager.default.moveItem(at: file.directory, to: moved) + try FileManager.default.createSymbolicLink(at: file.directory, withDestinationURL: moved) + XCTAssertThrowsError(try validate(file)) + XCTAssertEqual(try Data(contentsOf: moved.appendingPathComponent(file.name)), file.bytes) + try FileManager.default.removeItem(at: file.directory) + try FileManager.default.moveItem(at: moved, to: file.directory) + let root = file.directory.deletingLastPathComponent() + let movedRoot = cache.appendingPathComponent("moved-root") + try FileManager.default.moveItem(at: root, to: movedRoot) + try FileManager.default.createSymbolicLink(at: root, withDestinationURL: movedRoot) + XCTAssertThrowsError(try validate(file)) + XCTAssertEqual(try Data(contentsOf: movedRoot.appendingPathComponent(file.id).appendingPathComponent(file.name)), file.bytes) + } + + func testReplacingOperationDirectoryDoesNotDeleteTheReplacement() throws { + let file = try fixture() + let staging = try validate(file) + let original = cache.appendingPathComponent("original-operation") + try FileManager.default.moveItem(at: file.directory, to: original) + try FileManager.default.createDirectory(at: file.directory, withIntermediateDirectories: false) + let replacement = Data("replacement must survive".utf8) + try replacement.write(to: file.url) + XCTAssertEqual(staging.cleanup(), "staging_cleanup_failed: operation_directory_replaced") + XCTAssertEqual(try Data(contentsOf: file.url), replacement) + XCTAssertEqual(try Data(contentsOf: original.appendingPathComponent(file.name)), file.bytes) + } + + func testCleanupDoesNotRecursivelyRemoveUnexpectedChildren() throws { + let file = try fixture() + let staging = try validate(file) + let extra = file.directory.appendingPathComponent("unowned.txt") + try Data("preserve".utf8).write(to: extra) + XCTAssertNotNil(staging.cleanup()) + XCTAssertTrue(exists(extra)) + XCTAssertFalse(exists(file.url)) + } + + func testReplacingRootRefusesCleanupSoDartCannotDeleteTheReplacement() throws { + let file = try fixture() + let staging = try validate(file) + let root = file.directory.deletingLastPathComponent() + let original = cache.appendingPathComponent("original-root") + try FileManager.default.moveItem(at: root, to: original) + try FileManager.default.createDirectory(at: file.directory, withIntermediateDirectories: true) + let replacement = Data("new root must survive".utf8) + try replacement.write(to: file.url) + XCTAssertEqual(staging.cleanup(), "staging_cleanup_failed: root_replaced") + XCTAssertEqual(try Data(contentsOf: file.url), replacement) + XCTAssertEqual(try Data(contentsOf: original.appendingPathComponent(file.id).appendingPathComponent(file.name)), file.bytes) + } + + func testMissingPresenterIsTerminalAndCleansOnlyItsOwnFile() throws { + let file = try fixture() + let other = try fixture() + let coordinator = makeCoordinator(presenter: { nil }) + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + XCTAssertEqual(replies.values.count, 1) + XCTAssertEqual(replies.values.first?["errorCode"] as? String, "presenter_unavailable") + XCTAssertFalse(exists(file.directory)) + XCTAssertTrue(exists(other.url)) + } + + func testBusyPresenterRejectsExportWithoutDismissingExistingPresentation() async throws { + let existing = UIViewController() + var presented = false + presenter.present(existing, animated: false) { presented = true } + await waitUntil { presented } + let file = try fixture() + let coordinator = makeCoordinator() + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + XCTAssertEqual(replies.values.count, 1) + XCTAssertEqual(replies.values[0]["errorCode"] as? String, "presenter_unavailable") + XCTAssertNil(coordinator.activeOperationID) + XCTAssertFalse(exists(file.directory)) + XCTAssertTrue(presenter.presentedViewController === existing) + var dismissed = false + existing.dismiss(animated: false) { dismissed = true } + await waitUntil { dismissed } + } + + func testCancelAcknowledgementRetainsStagingUntilDismissalCompletion() async throws { + let file = try fixture() + let coordinator = makeCoordinator(holdDismissal: true) + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + let picker = try await presentedPicker(coordinator) + XCTAssertTrue(coordinator.cancel(operationID: file.id)) + XCTAssertTrue(coordinator.cancel(operationID: file.id)) + XCTAssertTrue(replies.values.isEmpty) + XCTAssertTrue(exists(file.url)) + await waitUntil { !self.heldDismissals.isEmpty } + XCTAssertNil(picker.presentingViewController) + XCTAssertTrue(exists(file.url)) + heldDismissals.removeFirst()() + await waitUntil { replies.values.count == 1 } + XCTAssertEqual(replies.values[0]["status"] as? String, "cancelled") + XCTAssertEqual(replies.values[0]["cleanupStatus"] as? String, "notNeeded") + XCTAssertNil(replies.values[0]["residualDocument"]) + XCTAssertFalse(exists(file.directory)) + XCTAssertFalse(coordinator.cancel(operationID: file.id)) + } + + func testCancelDuringPresentationWaitsForThePresentationAndDismissal() async throws { + let deferred = DeferredPresenter() + window.rootViewController = deferred + await waitUntil { deferred.viewIfLoaded?.window === self.window } + let file = try fixture() + let coordinator = makeCoordinator(presenter: { deferred }, holdDismissal: true) + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + let picker = try XCTUnwrap(coordinator.activePicker) + XCTAssertNil(picker.presentingViewController) + XCTAssertFalse(picker.isBeingPresented) + XCTAssertTrue(coordinator.cancel(operationID: file.id)) + XCTAssertTrue(replies.values.isEmpty) + XCTAssertTrue(exists(file.url)) + deferred.continuePresentation() + await waitUntil { !self.heldDismissals.isEmpty } + XCTAssertTrue(replies.values.isEmpty) + XCTAssertTrue(exists(file.url)) + XCTAssertNil(picker.presentingViewController) + heldDismissals.removeFirst()() + await waitUntil { replies.values.count == 1 } + XCTAssertEqual(replies.values[0]["status"] as? String, "cancelled") + XCTAssertNil(picker.presentingViewController) + XCTAssertFalse(exists(file.directory)) + } + + func testSaveAfterCancelAckWinsAndDuplicateCallbacksCannotChangeIt() async throws { + let file = try fixture() + let destination = cache.appendingPathComponent("provider-renamed.pdf") + try file.bytes.write(to: destination) + let coordinator = makeCoordinator(holdDismissal: true) + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + let picker = try await presentedPicker(coordinator) + XCTAssertTrue(coordinator.cancel(operationID: file.id)) + coordinator.documentPicker(picker, didPickDocumentsAt: [destination]) + XCTAssertFalse(coordinator.cancel(operationID: file.id)) + coordinator.documentPickerWasCancelled(picker) + coordinator.documentPicker(picker, didPickDocumentsAt: []) + await waitUntil { !self.heldDismissals.isEmpty } + heldDismissals.removeFirst()() + await waitUntil { replies.values.count == 1 } + let result = replies.values[0] + XCTAssertEqual(result["status"] as? String, "saved") + XCTAssertEqual(result["displayName"] as? String, "provider-renamed.pdf") + XCTAssertEqual(result["documentUri"] as? String, destination.absoluteString) + XCTAssertEqual(result["cleanupStatus"] as? String, "notNeeded") + XCTAssertNil(result["cleanupError"]) + XCTAssertFalse(exists(file.directory)) + XCTAssertEqual(try Data(contentsOf: destination), file.bytes) + coordinator.documentPicker(picker, didPickDocumentsAt: [destination]) + XCTAssertEqual(replies.values.count, 1) + } + + func testSavedResultDoesNotInventAnUnavailableDestinationName() async throws { + let file = try fixture() + let coordinator = makeCoordinator() + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + let picker = try await presentedPicker(coordinator) + coordinator.documentPicker(picker, didPickDocumentsAt: [cache.appendingPathComponent("does-not-exist.pdf")]) + await waitUntil { replies.values.count == 1 } + XCTAssertEqual(replies.values[0]["status"] as? String, "saved") + XCTAssertNil(replies.values[0]["documentUri"]) + XCTAssertNil(replies.values[0]["displayName"]) + } + + func testInvalidProviderResultIsNotRewrittenByLateCancellation() async throws { + let file = try fixture() + let coordinator = makeCoordinator(holdDismissal: true) + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + let picker = try await presentedPicker(coordinator) + coordinator.documentPicker(picker, didPickDocumentsAt: []) + XCTAssertFalse(coordinator.cancel(operationID: file.id)) + coordinator.documentPickerWasCancelled(picker) + XCTAssertTrue(replies.values.isEmpty) + XCTAssertTrue(exists(file.url)) + await waitUntil { !self.heldDismissals.isEmpty } + heldDismissals.removeFirst()() + await waitUntil { replies.values.count == 1 } + XCTAssertEqual(replies.values[0]["status"] as? String, "failed") + XCTAssertEqual(replies.values[0]["errorCode"] as? String, "invalid_picker_result") + XCTAssertFalse(exists(file.directory)) + } + + func testStagingCleanupFailureCannotTurnSavedIntoFailedOrInventResidualDocument() async throws { + let file = try fixture() + let destination = cache.appendingPathComponent("saved.pdf") + try file.bytes.write(to: destination) + let coordinator = makeCoordinator() + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + let picker = try await presentedPicker(coordinator) + let extra = file.directory.appendingPathComponent("unexpected.txt") + try Data("preserve".utf8).write(to: extra) + coordinator.documentPicker(picker, didPickDocumentsAt: [destination]) + await waitUntil { replies.values.count == 1 } + XCTAssertEqual(replies.values[0]["status"] as? String, "saved") + XCTAssertEqual(replies.values[0]["cleanupStatus"] as? String, "notNeeded") + XCTAssertTrue((replies.values[0]["cleanupError"] as? String)?.hasPrefix("staging_cleanup_failed:") == true) + XCTAssertNil(replies.values[0]["residualDocument"]) + XCTAssertTrue(exists(extra)) + XCTAssertEqual(try Data(contentsOf: destination), file.bytes) + } + + func testBusyDuplicateAndStalePickerDoNotReleaseTheCurrentSource() async throws { + let first = try fixture() + let second = try fixture() + let coordinator = makeCoordinator() + let firstReplies = Replies() + start(first, coordinator: coordinator, replies: firstReplies) + let oldPicker = try await presentedPicker(coordinator) + let duplicate = Replies() + start(first, coordinator: coordinator, replies: duplicate) + XCTAssertEqual(duplicate.values.first?["errorCode"] as? String, "duplicate_operation") + XCTAssertTrue(exists(first.url)) + let busy = Replies() + start(second, coordinator: coordinator, replies: busy) + XCTAssertEqual(busy.values.first?["errorCode"] as? String, "export_busy") + XCTAssertFalse(exists(second.directory)) + XCTAssertTrue(exists(first.url)) + coordinator.documentPickerWasCancelled(oldPicker) + await waitUntil { firstReplies.values.count == 1 } + let next = try fixture() + let nextReplies = Replies() + start(next, coordinator: coordinator, replies: nextReplies) + _ = try await presentedPicker(coordinator) + coordinator.documentPickerWasCancelled(oldPicker) + coordinator.documentPicker(oldPicker, didPickDocumentsAt: [first.url]) + XCTAssertTrue(nextReplies.values.isEmpty) + XCTAssertTrue(exists(next.url)) + XCTAssertTrue(coordinator.cancel(operationID: next.id)) + await waitUntil { nextReplies.values.count == 1 } + } + + func testInteractiveDismissalCompletesOnlyAfterUIKitDismissed() async throws { + let file = try fixture() + let coordinator = makeCoordinator() + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + let picker = try await presentedPicker(coordinator) + let presentation = try XCTUnwrap(picker.presentationController) + let finished = expectation(description: "UIKit dismissal") + picker.dismiss(animated: false) { finished.fulfill() } + await fulfillment(of: [finished], timeout: 10) + // Programmatic dismissal does not synthesize the interactive delegate event. + XCTAssertTrue(replies.values.isEmpty) + XCTAssertTrue(exists(file.url)) + coordinator.presentationControllerDidDismiss(presentation) + await waitUntil { replies.values.count == 1 } + XCTAssertEqual(replies.values[0]["status"] as? String, "cancelled") + XCTAssertFalse(exists(file.directory)) + } + + func testSceneDisconnectIsDeliveredByFlutterSceneDelegate() async throws { + let file = try fixture() + let coordinator = makeCoordinator() + let plugin = PdfFileExportPlugin(coordinator: coordinator) + let engine = FlutterEngine(name: "pdf-export-scene", project: nil, allowHeadlessExecution: true) + XCTAssertTrue(engine.run(withEntrypoint: "pdfExportHeadlessProbe")) + let registrar = try XCTUnwrap(engine.registrar(forPlugin: "PdfExportSceneTest")) + registrar.publish(plugin) + registrar.addSceneDelegate(plugin) + let sceneDelegate = FlutterSceneDelegate() + XCTAssertTrue(sceneDelegate.registerSceneLifeCycle(with: engine)) + defer { + sceneDelegate.unregisterSceneLifeCycle(with: engine) + engine.destroyContext() + } + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + _ = try await presentedPicker(coordinator) + let scene = try XCTUnwrap(window.windowScene) + let delegate: UISceneDelegate = sceneDelegate + delegate.sceneDidEnterBackground?(scene) + XCTAssertTrue(exists(file.url)) + XCTAssertTrue(replies.values.isEmpty) + delegate.sceneDidDisconnect?(scene) + await waitUntil { replies.values.count == 1 } + XCTAssertEqual(replies.values[0]["status"] as? String, "cancelled") + XCTAssertFalse(exists(file.directory)) + } + + func testDestroyContextDoesNotReleaseSourceBeforePickerTerminal() async throws { + let file = try fixture() + let coordinator = makeCoordinator() + let plugin = PdfFileExportPlugin(coordinator: coordinator) + let engine = FlutterEngine(name: "pdf-export-destroy", project: nil, allowHeadlessExecution: true) + XCTAssertTrue(engine.run(withEntrypoint: "pdfExportHeadlessProbe")) + let registrar = try XCTUnwrap(engine.registrar(forPlugin: "PdfExportDestroyTest")) + registrar.publish(plugin) + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + let picker = try await presentedPicker(coordinator) + engine.destroyContext() + XCTAssertTrue(replies.values.isEmpty) + XCTAssertTrue(exists(file.url)) + XCTAssertEqual(coordinator.activeOperationID, file.id) + coordinator.documentPickerWasCancelled(picker) + await waitUntil { replies.values.count == 1 } + XCTAssertFalse(exists(file.directory)) + } + + func testActualEngineDeallocationDismissesAndCleansWithoutADartReply() async throws { + let file = try fixture() + let coordinator = makeCoordinator(holdDismissal: true) + let plugin = PdfFileExportPlugin(coordinator: coordinator) + var engine: FlutterEngine? = FlutterEngine(name: "pdf-export-dealloc", project: nil, allowHeadlessExecution: true) + weak var weakEngine = engine + XCTAssertTrue(engine!.run(withEntrypoint: "pdfExportHeadlessProbe")) + let registrar = try XCTUnwrap(engine!.registrar(forPlugin: "PdfExportDeallocTest")) + registrar.publish(plugin) + let replies = Replies() + start(file, coordinator: coordinator, replies: replies) + _ = try await presentedPicker(coordinator) + autoreleasepool { engine = nil } + await waitUntil { weakEngine == nil } + await waitUntil { !self.heldDismissals.isEmpty } + XCTAssertTrue(exists(file.url)) + XCTAssertTrue(replies.values.isEmpty) + heldDismissals.removeFirst()() + await waitUntil { coordinator.activeOperationID == nil } + XCTAssertFalse(exists(file.directory)) + XCTAssertTrue(replies.values.isEmpty) + } + + func testImplicitEngineRegistrationAndMethodContract() async throws { + let root = try XCTUnwrap(originalWindow?.rootViewController as? FlutterViewController) + let engine = try XCTUnwrap(root.engine) + XCTAssertTrue(engine.hasPlugin(PdfFileExportPlugin.pluginKey)) + XCTAssertNotNil(engine.valuePublished(byPlugin: PdfFileExportPlugin.pluginKey) as? PdfFileExportPlugin) + let plugin = PdfFileExportPlugin(coordinator: makeCoordinator()) + let invalidArguments: [[String: Any]] = [ + ["version": true, "operationId": String(repeating: "a", count: 32)], + ["version": 2, "operationId": String(repeating: "a", count: 32)], + ["version": 1, "operationId": "../outside"], + ["version": 1, "operationId": String(repeating: "a", count: 32) + "\n"], + ["version": 1, "operationId": String(repeating: "a", count: 32) + "\r\n"], + ["version": 1, "operationId": String(repeating: "a", count: 32) + "\u{0085}"], + ["version": 1, "operationId": String(repeating: "a", count: 32) + "\u{2028}"], + ] + for arguments in invalidArguments { + var reply: Any? + plugin.handle(FlutterMethodCall(methodName: "cancelExport", arguments: arguments)) { reply = $0 } + XCTAssertEqual((reply as? FlutterError)?.code, "invalid_arguments") + } + var ack: [String: Any]? + let identifier = String(repeating: "a", count: 32) + plugin.handle(FlutterMethodCall(methodName: "cancelExport", arguments: ["version": 1, "operationId": identifier])) { + ack = $0 as? [String: Any] + } + XCTAssertEqual(ack?["operationId"] as? String, identifier) + XCTAssertEqual(ack?["accepted"] as? Bool, false) + } + + private struct Fixture { + let id: String + let name: String + let directory: URL + let url: URL + let bytes: Data + } + + private final class Replies { var values: [[String: Any]] = [] } + + private func fixture() throws -> Fixture { + let identifier = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + let name = "בדיקת-ייצוא.pdf" + let directory = cache.appendingPathComponent(PdfExportStaging.rootName).appendingPathComponent(identifier) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent(name) + let bytes = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 240, height: 320)).pdfData { context in + context.beginPage() + UIColor.blue.setFill() + UIRectFill(CGRect(x: 20, y: 20, width: 80, height: 60)) + ("PDF export ownership" as NSString).draw(at: CGPoint(x: 20, y: 100), withAttributes: [.font: UIFont.systemFont(ofSize: 14)]) + } + try bytes.write(to: url) + return Fixture(id: identifier, name: name, directory: directory, url: url, bytes: bytes) + } + + private func validate(_ file: Fixture) throws -> PdfExportStaging { + try PdfExportStaging.validate(operationID: file.id, sourcePath: file.url.path, fileName: file.name, cachesDirectory: cache) + } + + private func makeCoordinator( + presenter suppliedPresenter: (() -> UIViewController?)? = nil, + holdDismissal: Bool = false + ) -> PdfFileExportCoordinator { + let ownedCache = cache! + let getPresenter = suppliedPresenter ?? { [weak self] in self?.presenter } + let coordinator: PdfFileExportCoordinator + if holdDismissal { + coordinator = PdfFileExportCoordinator(presenter: getPresenter, cachesDirectory: { ownedCache }) { [weak self] picker, completion in + picker.dismiss(animated: false) { self?.heldDismissals.append(completion) } + } + } else { + coordinator = PdfFileExportCoordinator(presenter: getPresenter, cachesDirectory: { ownedCache }) + } + coordinators.append(coordinator) + return coordinator + } + + private func start(_ file: Fixture, coordinator: PdfFileExportCoordinator, replies: Replies) { + coordinator.export(operationID: file.id, sourcePath: file.url.path, fileName: file.name) { value in + print("PDF export terminal: \(value)") + replies.values.append(value) + } + print("PDF export presentation: \(presentationState(coordinator))") + } + + private func presentedPicker(_ coordinator: PdfFileExportCoordinator) async throws -> UIDocumentPickerViewController { + await waitUntil({ + guard let picker = coordinator.activePicker else { return false } + return picker.presentingViewController != nil && !picker.isBeingPresented + }, diagnostics: { self.presentationState(coordinator) }) + let picker = try XCTUnwrap(coordinator.activePicker) + XCTAssertTrue(picker.presentationController?.delegate === coordinator) + return picker + } + + private func presentationState(_ coordinator: PdfFileExportCoordinator) -> String { + let picker = coordinator.activePicker + return [ + "active=\(coordinator.activeOperationID ?? "nil")", + "ownerPresented=\(String(describing: presenter?.presentedViewController))", + "pickerPresenter=\(String(describing: picker?.presentingViewController))", + "pickerPresenting=\(String(describing: picker?.isBeingPresented))", + "pickerWindow=\(picker?.viewIfLoaded?.window != nil)", + ].joined(separator: "; ") + } + + private func waitUntil( + _ condition: @escaping () -> Bool, diagnostics: () -> String = { "" }, + file: StaticString = #filePath, line: UInt = #line + ) async { + let deadline = Date().addingTimeInterval(15) + while !condition() && Date() < deadline { + try? await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertTrue(condition(), "Native condition did not complete before its deadline. \(diagnostics())", file: file, line: line) + } + + private func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) } + + private final class DeferredPresenter: UIViewController { + private var pending: (UIViewController, Bool, (() -> Void)?)? + + override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) { + pending = (viewControllerToPresent, flag, completion) + } + + func continuePresentation() { + guard let (controller, animated, completion) = pending else { return } + pending = nil + super.present(controller, animated: animated, completion: completion) + } + } +} diff --git a/ios/PdfFileExportUITests/PdfFileExportUITests.swift b/ios/PdfFileExportUITests/PdfFileExportUITests.swift new file mode 100644 index 0000000000..0b6f88bdff --- /dev/null +++ b/ios/PdfFileExportUITests/PdfFileExportUITests.swift @@ -0,0 +1,108 @@ +import XCTest + +/// Real Files/provider UI. No delegate callback or platform channel is faked. +final class PdfFileExportUITests: XCTestCase { + private var app: XCUIApplication! + + override func setUpWithError() throws { + try super.setUpWithError() + continueAfterFailure = false + app = XCUIApplication(bundleIdentifier: "com.mendelg.otzaria") + app.launchArguments = ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"] + } + + override func tearDownWithError() throws { + if let app = app { + let screenshot = XCTAttachment(screenshot: app.screenshot()) + screenshot.name = "PDF export final UI" + screenshot.lifetime = .keepAlways + add(screenshot) + app.terminate() + } + app = nil + try super.tearDownWithError() + } + + func testFilesSaveCopiesTheRealServiceFileAndReleasesStaging() { + launch(caseName: "files-save") + app.buttons["Export files-save fixture"].tap() + waitForPicker() + openTestDestination() + let save = app.buttons["Save"].firstMatch + XCTAssertTrue(save.waitForExistence(timeout: 15), app.debugDescription) + XCTAssertTrue(save.isEnabled) + save.tap() + waitForState("saved") + XCTAssertEqual(evidence.label, "validated=true;stagingAbsent=true;status=saved") + } + + func testFilesCancelTerminatesTheRealServiceWithoutCreatingADestination() { + launch(caseName: "files-cancel") + app.buttons["Export files-cancel fixture"].tap() + waitForPicker() + let cancel = app.buttons["Cancel"].firstMatch + if cancel.exists && cancel.isHittable { + cancel.tap() + } else { + let navigation = app.navigationBars["FullDocumentManagerViewControllerNavigationBar"] + XCTAssertTrue(navigation.exists && navigation.isHittable, app.debugDescription) + navigation.swipeDown() + } + waitForState("cancelled") + XCTAssertEqual(evidence.label, "validated=true;stagingAbsent=true;status=cancelled") + } + + private var state: XCUIElement { + app.descendants(matching: .any).matching(identifier: "export-status").firstMatch + } + + private var evidence: XCUIElement { + app.descendants(matching: .any).matching(identifier: "export-evidence").firstMatch + } + + private func launch(caseName: String) { + app.launch() + XCTAssertTrue(state.waitForExistence(timeout: 60), app.debugDescription) + waitForState("ready") + XCTAssertTrue(app.buttons["Export \(caseName) fixture"].isEnabled) + } + + private func waitForPicker() { + let save = app.buttons["Save"].firstMatch + let ready = XCTNSPredicateExpectation( + predicate: NSPredicate(format: "exists == true AND hittable == true"), object: save + ) + XCTAssertEqual(XCTWaiter.wait(for: [ready], timeout: 30), .completed, app.debugDescription) + XCTAssertEqual(state.label, "pending", app.debugDescription) + } + + private func waitForState(_ expected: String) { + let predicate = NSPredicate(format: "label == %@", expected) + let completion = XCTNSPredicateExpectation(predicate: predicate, object: state) + XCTAssertEqual(XCTWaiter.wait(for: [completion], timeout: 60), .completed, app.debugDescription) + XCTAssertTrue(evidence.exists) + } + + private func tapLocation(_ label: String) { + let cell = app.cells.containing(.staticText, identifier: label).firstMatch + if cell.waitForExistence(timeout: 5) { + cell.tap() + return + } + let button = app.buttons[label].firstMatch + XCTAssertTrue(button.waitForExistence(timeout: 10), "Missing Files location \(label)\n\(app.debugDescription)") + button.tap() + } + + private func openTestDestination() { + // A new owned Simulator has no iCloud account. Navigate the actual local + // Files provider; missing locations fail, rather than becoming a mock/skip. + if !app.cells.containing(.staticText, identifier: "On My iPhone").firstMatch.exists { + let browse = app.buttons["Browse"].firstMatch + if browse.waitForExistence(timeout: 5) { browse.tap() } + } + tapLocation("On My iPhone") + tapLocation("אוצריא") + tapLocation("OtzariaExportUITest") + } +} diff --git a/ios/Podfile b/ios/Podfile index 4890558d85..69872878bf 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -34,6 +34,9 @@ target 'Runner' do target 'RunnerTests' do inherit! :search_paths end + target 'PdfFileExportTests' do + inherit! :search_paths + end end post_install do |installer| diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index b5f0f0c700..7fd9060673 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -17,6 +17,12 @@ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; BA234C3CB252557551BDF8A1 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9C2A078294BA1094E2A212D9 /* Pods_Runner.framework */; }; + 4B9DCFAB76C1CF17A18E7180 /* PdfExportStaging.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5802984418B69005C19FCA2 /* PdfExportStaging.swift */; }; + F4CE03A2774C85B72A215038 /* PdfFileExportCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED7A3F013989F7D0D6A9E2F3 /* PdfFileExportCoordinator.swift */; }; + BA76238E3313FBCAF9493E6A /* PdfFileExportPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 29079D3A71123BB1AAE44C99 /* PdfFileExportPlugin.swift */; }; + 491C898E0838DF1CD6423223 /* PdfFileExportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5430BC48F40765E71E3B1E6C /* PdfFileExportTests.swift */; }; + 41591EC1FEC391D208138DFC /* Pods_PdfFileExportTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 70853586B82F13E5D673080C /* Pods_PdfFileExportTests.framework */; }; + A8CCD86529A95DE8CD30AB2C /* PdfFileExportUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75CC5C48B06A64C70B2D49F6 /* PdfFileExportUITests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -27,6 +33,8 @@ remoteGlobalIDString = 97C146ED1CF9000F007C117D; remoteInfo = Runner; }; + 7FC2DF20EDFC780A500C2FFF /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 97C146E61CF9000F007C117D /* Project object */; proxyType = 1; remoteGlobalIDString = 97C146ED1CF9000F007C117D; remoteInfo = Runner; }; + CAA6858629BC8A7802C331FC /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 97C146E61CF9000F007C117D /* Project object */; proxyType = 1; remoteGlobalIDString = 97C146ED1CF9000F007C117D; remoteInfo = Runner; }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -67,6 +75,17 @@ B39408EF8884F84EFDDE3A2B /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; D3515C4BD5307C91A662E519 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F366375BC646E716302163E1 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + A5802984418B69005C19FCA2 /* PdfExportStaging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PdfExportStaging.swift; sourceTree = ""; }; + ED7A3F013989F7D0D6A9E2F3 /* PdfFileExportCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PdfFileExportCoordinator.swift; sourceTree = ""; }; + 29079D3A71123BB1AAE44C99 /* PdfFileExportPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PdfFileExportPlugin.swift; sourceTree = ""; }; + 5430BC48F40765E71E3B1E6C /* PdfFileExportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PdfFileExportTests.swift; sourceTree = ""; }; + DBF471B994E95B4D44F87B3E /* PdfFileExportTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PdfFileExportTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 70853586B82F13E5D673080C /* Pods_PdfFileExportTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = Pods_PdfFileExportTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4BD0A75DC0AEB095D256D782 /* Pods-PdfFileExportTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods-PdfFileExportTests.debug.xcconfig; path = "Target Support Files/Pods-PdfFileExportTests/Pods-PdfFileExportTests.debug.xcconfig"; sourceTree = ""; }; + 6C846A33F32095648A8DC819 /* Pods-PdfFileExportTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods-PdfFileExportTests.release.xcconfig; path = "Target Support Files/Pods-PdfFileExportTests/Pods-PdfFileExportTests.release.xcconfig"; sourceTree = ""; }; + 489102120932C5729BF905D1 /* Pods-PdfFileExportTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods-PdfFileExportTests.profile.xcconfig; path = "Target Support Files/Pods-PdfFileExportTests/Pods-PdfFileExportTests.profile.xcconfig"; sourceTree = ""; }; + 75CC5C48B06A64C70B2D49F6 /* PdfFileExportUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PdfFileExportUITests.swift; sourceTree = ""; }; + 805C2D9D8AF2A2882F345844 /* PdfFileExportUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PdfFileExportUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -87,6 +106,8 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + F09C1E2A3EC694A501223577 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (41591EC1FEC391D208138DFC /* Pods_PdfFileExportTests.framework in Frameworks */,); runOnlyForDeploymentPostprocessing = 0; }; + 0AEDEDDD273CA711FD530193 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -107,6 +128,9 @@ 1C556E81EFFD456323E3074F /* Pods-RunnerTests.debug.xcconfig */, B39408EF8884F84EFDDE3A2B /* Pods-RunnerTests.release.xcconfig */, 719828067DBE7F52C6C9D6A9 /* Pods-RunnerTests.profile.xcconfig */, + 489102120932C5729BF905D1 /* Pods-PdfFileExportTests.profile.xcconfig */, + 6C846A33F32095648A8DC819 /* Pods-PdfFileExportTests.release.xcconfig */, + 4BD0A75DC0AEB095D256D782 /* Pods-PdfFileExportTests.debug.xcconfig */, ); path = Pods; sourceTree = ""; @@ -130,6 +154,8 @@ 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 331C8082294A63A400263BE5 /* RunnerTests */, + BD9B568E2BB0EE82F83ED3E9 /* PdfFileExportUITests */, + C02AD151420F9BAEE8EA5C83 /* PdfFileExportTests */, 6042D8CDE9E71B31FD53C95A /* Pods */, A0AA495CA622AE8D3CB3A138 /* Frameworks */, ); @@ -140,6 +166,8 @@ children = ( 97C146EE1CF9000F007C117D /* Runner.app */, 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + 805C2D9D8AF2A2882F345844 /* PdfFileExportUITests.xctest */, + DBF471B994E95B4D44F87B3E /* PdfFileExportTests.xctest */, ); name = Products; sourceTree = ""; @@ -154,6 +182,9 @@ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 29079D3A71123BB1AAE44C99 /* PdfFileExportPlugin.swift */, + ED7A3F013989F7D0D6A9E2F3 /* PdfFileExportCoordinator.swift */, + A5802984418B69005C19FCA2 /* PdfExportStaging.swift */, 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, ); path = Runner; @@ -164,10 +195,13 @@ children = ( 9C2A078294BA1094E2A212D9 /* Pods_Runner.framework */, D3515C4BD5307C91A662E519 /* Pods_RunnerTests.framework */, + 70853586B82F13E5D673080C /* Pods_PdfFileExportTests.framework */, ); name = Frameworks; sourceTree = ""; }; + C02AD151420F9BAEE8EA5C83 /* PdfFileExportTests */ = {isa = PBXGroup; children = (5430BC48F40765E71E3B1E6C /* PdfFileExportTests.swift */,); path = PdfFileExportTests; sourceTree = ""; }; + BD9B568E2BB0EE82F83ED3E9 /* PdfFileExportUITests */ = {isa = PBXGroup; children = (75CC5C48B06A64C70B2D49F6 /* PdfFileExportUITests.swift */,); path = PdfFileExportUITests; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -215,6 +249,28 @@ productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; }; + 5498E5A505AA24B71D7CE6D8 /* PdfFileExportTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = FDA998FC5015379E07955A9F /* Build configuration list for PBXNativeTarget "PdfFileExportTests" */; + buildPhases = (5A8070DF132A4317D38335D9 /* Sources */, F09C1E2A3EC694A501223577 /* Frameworks */, 57E00F844F1B2FF473F51EE3 /* Resources */,); + buildRules = (); + dependencies = (1E40CCA3B833BC09C814E136 /* PBXTargetDependency */,); + name = PdfFileExportTests; + productName = PdfFileExportTests; + productReference = DBF471B994E95B4D44F87B3E /* PdfFileExportTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + BB1670117695B54FBD8DE3AD /* PdfFileExportUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7E721D23FFF65FBCEB58EB2D /* Build configuration list for PBXNativeTarget "PdfFileExportUITests" */; + buildPhases = (E7A78C3669920903F6A9696B /* Sources */, 0AEDEDDD273CA711FD530193 /* Frameworks */, B48555D81FB20FEECD21DEF2 /* Resources */,); + buildRules = (); + dependencies = (40805D943A3D84DEB9F5B7C4 /* PBXTargetDependency */,); + name = PdfFileExportUITests; + productName = PdfFileExportUITests; + productReference = 805C2D9D8AF2A2882F345844 /* PdfFileExportUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -225,6 +281,8 @@ LastUpgradeCheck = 1510; ORGANIZATIONNAME = ""; TargetAttributes = { + BB1670117695B54FBD8DE3AD = {CreatedOnToolsVersion = 15.0; TestTargetID = 97C146ED1CF9000F007C117D; }; + 5498E5A505AA24B71D7CE6D8 = {CreatedOnToolsVersion = 15.0; TestTargetID = 97C146ED1CF9000F007C117D; }; 331C8080294A63A400263BE5 = { CreatedOnToolsVersion = 14.0; TestTargetID = 97C146ED1CF9000F007C117D; @@ -253,6 +311,8 @@ targets = ( 97C146ED1CF9000F007C117D /* Runner */, 331C8080294A63A400263BE5 /* RunnerTests */, + BB1670117695B54FBD8DE3AD /* PdfFileExportUITests */, + 5498E5A505AA24B71D7CE6D8 /* PdfFileExportTests */, ); }; /* End PBXProject section */ @@ -276,6 +336,8 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 57E00F844F1B2FF473F51EE3 /* Resources */ = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; }; + B48555D81FB20FEECD21DEF2 /* Resources */ = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ @@ -387,10 +449,15 @@ buildActionMask = 2147483647; files = ( 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + BA76238E3313FBCAF9493E6A /* PdfFileExportPlugin.swift in Sources */, + F4CE03A2774C85B72A215038 /* PdfFileExportCoordinator.swift in Sources */, + 4B9DCFAB76C1CF17A18E7180 /* PdfExportStaging.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; + 5A8070DF132A4317D38335D9 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (491C898E0838DF1CD6423223 /* PdfFileExportTests.swift in Sources */,); runOnlyForDeploymentPostprocessing = 0; }; + E7A78C3669920903F6A9696B /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A8CCD86529A95DE8CD30AB2C /* PdfFileExportUITests.swift in Sources */,); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -399,6 +466,8 @@ target = 97C146ED1CF9000F007C117D /* Runner */; targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; }; + 1E40CCA3B833BC09C814E136 /* PBXTargetDependency */ = {isa = PBXTargetDependency; target = 97C146ED1CF9000F007C117D /* Runner */; targetProxy = 7FC2DF20EDFC780A500C2FFF /* PBXContainerItemProxy */; }; + 40805D943A3D84DEB9F5B7C4 /* PBXTargetDependency */ = {isa = PBXTargetDependency; target = 97C146ED1CF9000F007C117D /* Runner */; targetProxy = CAA6858629BC8A7802C331FC /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -698,6 +767,120 @@ }; name = Release; }; + 13B012C1231EF15788DD5A64 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4BD0A75DC0AEB095D256D782 /* Pods-PdfFileExportTests.debug.xcconfig */; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = M5GXX3YXX2; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.mendelg.otzaria.PdfFileExportTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + BUNDLE_LOADER = "$(TEST_HOST)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + EA36B1AA26BC297CBF2DFCDE /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6C846A33F32095648A8DC819 /* Pods-PdfFileExportTests.release.xcconfig */; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = M5GXX3YXX2; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.mendelg.otzaria.PdfFileExportTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + BUNDLE_LOADER = "$(TEST_HOST)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + + }; + name = Release; + }; + 81EA88F2B1C242E6DFBEE2C6 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 489102120932C5729BF905D1 /* Pods-PdfFileExportTests.profile.xcconfig */; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = M5GXX3YXX2; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.mendelg.otzaria.PdfFileExportTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + BUNDLE_LOADER = "$(TEST_HOST)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + + }; + name = Profile; + }; + A09F2BF9F9D7D2B89F11AFF2 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = M5GXX3YXX2; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.mendelg.otzaria.PdfFileExportUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Runner; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + A8A8C0C4E15F0BCBC3A309A6 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = M5GXX3YXX2; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.mendelg.otzaria.PdfFileExportUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Runner; + + }; + name = Release; + }; + 1B39C1631C1F095AC7E69B99 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = M5GXX3YXX2; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.mendelg.otzaria.PdfFileExportUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Runner; + + }; + name = Profile; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -731,6 +914,8 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + FDA998FC5015379E07955A9F /* Build configuration list for PBXNativeTarget "PdfFileExportTests" */ = {isa = XCConfigurationList; buildConfigurations = (13B012C1231EF15788DD5A64 /* Debug */, EA36B1AA26BC297CBF2DFCDE /* Release */, 81EA88F2B1C242E6DFBEE2C6 /* Profile */,); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 7E721D23FFF65FBCEB58EB2D /* Build configuration list for PBXNativeTarget "PdfFileExportUITests" */ = {isa = XCConfigurationList; buildConfigurations = (A09F2BF9F9D7D2B89F11AFF2 /* Debug */, A8A8C0C4E15F0BCBC3A309A6 /* Release */, 1B39C1631C1F095AC7E69B99 /* Profile */,); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/PdfFileExport.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/PdfFileExport.xcscheme new file mode 100644 index 0000000000..fafca3a947 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/PdfFileExport.xcscheme @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index c30b367ec0..a1d721b321 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -11,6 +11,9 @@ import UIKit } func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: PdfFileExportPlugin.pluginKey) { + PdfFileExportPlugin.register(with: registrar) + } GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) } } diff --git a/ios/Runner/PdfExportStaging.swift b/ios/Runner/PdfExportStaging.swift new file mode 100644 index 0000000000..d7d6eede96 --- /dev/null +++ b/ios/Runner/PdfExportStaging.swift @@ -0,0 +1,172 @@ +import Darwin +import Foundation + +/// An exclusive, closed export file owned by one operation, never the PDF cache. +/// Directory descriptors keep cleanup inside the validated child even if a path +/// alias changes while UIKit is using the file. +final class PdfExportStaging { + static let rootName = "otzaria-pdf-exports-v1" + + let operationID: String + let fileName: String + let sourceURL: URL + private let cachesURL: URL + private let rootDescriptor: Int32 + private let directoryDescriptor: Int32 + private let rootIdentity: stat + private let directoryIdentity: stat + private let fileIdentity: stat + private var closed = false + + static func cachesDirectory() throws -> URL { + guard let path = NSSearchPathForDirectoriesInDomains( + .cachesDirectory, .userDomainMask, true + ).first else { + throw SourceError.invalidPath + } + // This is also path_provider_foundation 2.6.0's iOS temporary directory. + return URL(fileURLWithPath: path, isDirectory: true) + .standardizedFileURL.resolvingSymlinksInPath() + } + + static func validate( + operationID: String, sourcePath: String, fileName: String, + cachesDirectory: URL + ) throws -> PdfExportStaging { + guard operationID.utf8.count == 32, + operationID.range(of: "^[0-9a-f]{32}$", options: .regularExpression) != nil, + !fileName.isEmpty, fileName.utf8.count <= 255, + fileName.hasSuffix(".pdf"), fileName != ".pdf", + !fileName.contains("/"), !fileName.contains("\\"), + !fileName.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7f }) + else { throw SourceError.invalidIdentity } + guard sourcePath.hasPrefix("/"), !sourcePath.contains("\0") else { + throw SourceError.invalidPath + } + + let caches = cachesDirectory.standardizedFileURL.resolvingSymlinksInPath() + let expected = caches.appendingPathComponent(rootName, isDirectory: true) + .appendingPathComponent(operationID, isDirectory: true) + .appendingPathComponent(fileName, isDirectory: false) + let supplied = URL(fileURLWithPath: sourcePath).standardizedFileURL + .resolvingSymlinksInPath() + guard supplied == expected else { throw SourceError.invalidPath } + + let cachesFD = open(caches.path, O_RDONLY | O_DIRECTORY | O_CLOEXEC) + guard cachesFD >= 0 else { throw SourceError.unreadableSource } + defer { close(cachesFD) } + let rootFD = openat(cachesFD, rootName, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + guard rootFD >= 0 else { throw SourceError.invalidPath } + var retainRoot = false + defer { if !retainRoot { close(rootFD) } } + let directoryFD = openat( + rootFD, operationID, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC + ) + guard directoryFD >= 0 else { throw SourceError.invalidPath } + var retainDirectory = false + defer { if !retainDirectory { close(directoryFD) } } + // Reject a FIFO without waiting for a writer on the UIKit thread. + let fileFD = openat(directoryFD, fileName, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) + guard fileFD >= 0 else { throw SourceError.unreadableSource } + defer { close(fileFD) } + var rootInformation = stat() + var directoryInformation = stat() + var fileInformation = stat() + guard fstat(rootFD, &rootInformation) == 0, + fstat(directoryFD, &directoryInformation) == 0, + fstat(fileFD, &fileInformation) == 0, + fileInformation.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG), + fileInformation.st_nlink == 1, fileInformation.st_size > 0 + else { throw SourceError.unreadableSource } + retainRoot = true + retainDirectory = true + return PdfExportStaging( + operationID: operationID, fileName: fileName, sourceURL: expected, + cachesURL: caches, + rootDescriptor: rootFD, directoryDescriptor: directoryFD, + rootIdentity: rootInformation, + directoryIdentity: directoryInformation, fileIdentity: fileInformation + ) + } + + private init( + operationID: String, fileName: String, sourceURL: URL, cachesURL: URL, + rootDescriptor: Int32, directoryDescriptor: Int32, + rootIdentity: stat, directoryIdentity: stat, fileIdentity: stat + ) { + self.operationID = operationID + self.fileName = fileName + self.sourceURL = sourceURL + self.cachesURL = cachesURL + self.rootDescriptor = rootDescriptor + self.directoryDescriptor = directoryDescriptor + self.rootIdentity = rootIdentity + self.directoryIdentity = directoryIdentity + self.fileIdentity = fileIdentity + } + + /// Called only after the picker is terminal. No recursive/path-based delete. + /// A competing replacement or an unexpected child is preserved, not swept. + func cleanup() -> String? { + guard !closed else { return nil } + defer { closeDescriptors() } + // Dart also owns a fallback cleanup by pathname. If the visible root was + // replaced, report refusal even though our old descriptors remain safe. + // The shared refusal prefix prevents Dart from deleting the replacement. + let currentCaches = open(cachesURL.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + guard currentCaches >= 0 else { return cleanupFailure("caches_open", errno) } + defer { close(currentCaches) } + var currentRoot = stat() + guard fstatat(currentCaches, Self.rootName, ¤tRoot, AT_SYMLINK_NOFOLLOW) == 0 else { + return cleanupFailure("root_stat", errno) + } + guard sameFile(currentRoot, rootIdentity), + currentRoot.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) + else { return "staging_cleanup_failed: root_replaced" } + var currentDirectory = stat() + if fstatat(rootDescriptor, operationID, ¤tDirectory, AT_SYMLINK_NOFOLLOW) != 0 { + return errno == ENOENT ? nil : cleanupFailure("directory_stat", errno) + } + guard sameFile(currentDirectory, directoryIdentity), + currentDirectory.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) + else { return "staging_cleanup_failed: operation_directory_replaced" } + var currentFile = stat() + if fstatat(directoryDescriptor, fileName, ¤tFile, AT_SYMLINK_NOFOLLOW) == 0 { + guard sameFile(currentFile, fileIdentity), + currentFile.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG) + else { return "staging_cleanup_failed: source_replaced" } + if unlinkat(directoryDescriptor, fileName, 0) != 0 && errno != ENOENT { + return cleanupFailure("source_unlink", errno) + } + } else if errno != ENOENT { + return cleanupFailure("source_stat", errno) + } + if unlinkat(rootDescriptor, operationID, AT_REMOVEDIR) != 0 && errno != ENOENT { + return cleanupFailure("directory_unlink", errno) + } + return nil + } + + private func sameFile(_ left: stat, _ right: stat) -> Bool { + left.st_dev == right.st_dev && left.st_ino == right.st_ino + } + + private func cleanupFailure(_ stage: String, _ code: Int32) -> String { + "staging_cleanup_failed: \(stage) (errno \(code))" + } + + private func closeDescriptors() { + guard !closed else { return } + closed = true + close(directoryDescriptor) + close(rootDescriptor) + } + + deinit { closeDescriptors() } + + enum SourceError: Error { + case invalidIdentity + case invalidPath + case unreadableSource + } +} diff --git a/ios/Runner/PdfFileExportCoordinator.swift b/ios/Runner/PdfFileExportCoordinator.swift new file mode 100644 index 0000000000..cb5fe00d8a --- /dev/null +++ b/ios/Runner/PdfFileExportCoordinator.swift @@ -0,0 +1,261 @@ +import Foundation +import UIKit + +/// UIKit owns the source until a picker callback and dismissal have completed. +/// A cancel acknowledgement is deliberately separate from that terminal result. +final class PdfFileExportCoordinator: NSObject, UIDocumentPickerDelegate, + UIAdaptivePresentationControllerDelegate +{ + typealias Reply = ([String: Any]) -> Void + typealias Dismiss = (UIDocumentPickerViewController, @escaping () -> Void) -> Void + + private final class Operation { + let staging: PdfExportStaging + let picker: UIDocumentPickerViewController + let sceneIdentifier: String? + var reply: Reply? + var presenting = true + var dismissing = false + var finishing = false + var providerTerminal = false + var outcome: Outcome? + + init( + staging: PdfExportStaging, picker: UIDocumentPickerViewController, + sceneIdentifier: String?, reply: @escaping Reply + ) { + self.staging = staging + self.picker = picker + self.sceneIdentifier = sceneIdentifier + self.reply = reply + } + } + + private enum Outcome { + case saved(URL) + case cancelled + case failed(String) + + var saved: Bool { + if case .saved = self { return true } + return false + } + + func result(operationID: String, cleanupError: String?) -> [String: Any] { + var result: [String: Any] = [ + "version": 1, "operationId": operationID, "cleanupStatus": "notNeeded", + ] + switch self { + case .saved(let url): + result["status"] = "saved" + // The delegate confirms completion. Metadata is optional and must come + // from the returned provider URL, never the requested file name. + if url.isFileURL { + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + if let values = try? url.resourceValues(forKeys: [.isRegularFileKey, .nameKey]), + values.isRegularFile == true + { + result["documentUri"] = url.absoluteString + result["displayName"] = values.name + } + } + case .cancelled: + result["status"] = "cancelled" + case .failed(let code): + result["status"] = "failed" + result["errorCode"] = code + } + if let cleanupError = cleanupError { result["cleanupError"] = cleanupError } + return result + } + } + + private let presenter: () -> UIViewController? + private let cachesDirectory: () throws -> URL + private let dismissPicker: Dismiss + private var active: Operation? + private var detached = false + + var activeOperationID: String? { active?.staging.operationID } + var activePicker: UIDocumentPickerViewController? { active?.picker } + + init( + presenter: @escaping () -> UIViewController?, + cachesDirectory: @escaping () throws -> URL = PdfExportStaging.cachesDirectory, + dismissPicker: @escaping Dismiss = PdfFileExportCoordinator.dismiss + ) { + self.presenter = presenter + self.cachesDirectory = cachesDirectory + self.dismissPicker = dismissPicker + } + + func export( + operationID: String, sourcePath: String, fileName: String, + reply: @escaping Reply + ) { + precondition(Thread.isMainThread) + guard active?.staging.operationID != operationID else { + reply(Outcome.failed("duplicate_operation").result(operationID: operationID, cleanupError: nil)) + return + } + let staging: PdfExportStaging + do { + staging = try PdfExportStaging.validate( + operationID: operationID, sourcePath: sourcePath, fileName: fileName, + cachesDirectory: cachesDirectory() + ) + } catch { + reply(Outcome.failed("invalid_source").result(operationID: operationID, cleanupError: nil)) + return + } + guard !detached, active == nil else { + reply(Outcome.failed(detached ? "engine_detached" : "export_busy").result( + operationID: operationID, cleanupError: staging.cleanup() + )) + return + } + guard let owner = presenter(), owner.viewIfLoaded?.window != nil, + owner.presentedViewController == nil, !owner.isBeingDismissed, + !owner.isBeingPresented, owner.transitionCoordinator == nil + else { + reply(Outcome.failed("presenter_unavailable").result( + operationID: operationID, cleanupError: staging.cleanup() + )) + return + } + let picker = UIDocumentPickerViewController(forExporting: [staging.sourceURL], asCopy: true) + picker.allowsMultipleSelection = false + picker.delegate = self + picker.presentationController?.delegate = self + let operation = Operation( + staging: staging, picker: picker, + sceneIdentifier: owner.view.window?.windowScene?.session.persistentIdentifier, + reply: reply + ) + active = operation + // UIKit can attach the picker asynchronously; only its completion ends presentation. + owner.present(picker, animated: true) { [self, operation] in + guard active === operation else { return } + operation.presenting = false + picker.presentationController?.delegate = self + if operation.outcome != nil { dismissAndFinish(operation) } + } + picker.presentationController?.delegate = self + } + + @discardableResult + func cancel(operationID: String) -> Bool { + precondition(Thread.isMainThread) + guard let operation = active, operation.staging.operationID == operationID, + !operation.finishing, !operation.providerTerminal, operation.outcome?.saved != true + else { return false } + operation.outcome = .cancelled + dismissAndFinish(operation) + return true + } + + func detach() { + precondition(Thread.isMainThread) + detached = true + // Do not retain a reply into a dying engine. The dismissal closure retains + // this coordinator independently until native staging cleanup finishes. + active?.reply = nil + if let identifier = activeOperationID { cancel(operationID: identifier) } + } + + func sceneDidDisconnect(_ scene: UIScene) { + precondition(Thread.isMainThread) + if let operation = active, + operation.sceneIdentifier == scene.session.persistentIdentifier + { + cancel(operationID: operation.staging.operationID) + } + } + + func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { + precondition(Thread.isMainThread) + guard let operation = active, operation.picker === controller, + !operation.finishing, !operation.providerTerminal + else { return } + operation.providerTerminal = true + guard urls.count == 1, let destination = urls.first else { + operation.outcome = .failed("invalid_picker_result") + dismissAndFinish(operation) + return + } + // A provider completion received after cancel ACK but before dismissal is + // still a completed save. A later cancel cannot turn it into cancellation. + operation.outcome = .saved(destination) + dismissAndFinish(operation) + } + + func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { + precondition(Thread.isMainThread) + guard let operation = active, operation.picker === controller, + !operation.finishing, !operation.providerTerminal + else { return } + operation.providerTerminal = true + if operation.outcome == nil { operation.outcome = .cancelled } + dismissAndFinish(operation) + } + + func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { + precondition(Thread.isMainThread) + guard let operation = active, + presentationController.presentedViewController === operation.picker, + !operation.finishing + else { return } + operation.presenting = false + operation.providerTerminal = true + if operation.outcome == nil { operation.outcome = .cancelled } + finish(operation) + } + + private func dismissAndFinish(_ operation: Operation) { + guard active === operation, !operation.presenting, !operation.dismissing, + !operation.finishing + else { return } + if operation.picker.presentingViewController == nil && !operation.picker.isBeingDismissed { + finish(operation) + return + } + operation.dismissing = true + dismissPicker(operation.picker) { [self, operation] in + finish(operation) + } + } + + private func finish(_ operation: Operation) { + guard active === operation, !operation.finishing, let outcome = operation.outcome else { return } + guard operation.picker.presentingViewController == nil else { return } + operation.finishing = true + operation.picker.delegate = nil + operation.picker.presentationController?.delegate = nil + // Provider metadata may perform I/O. No UIKit object is touched by this work. + let staging = operation.staging + DispatchQueue.global(qos: .userInitiated).async { [self, operation, staging] in + let result = outcome.result(operationID: staging.operationID, cleanupError: staging.cleanup()) + DispatchQueue.main.async { [self, operation] in + guard active === operation else { return } + let reply = operation.reply + operation.reply = nil + active = nil + reply?(result) + } + } + } + + private static func dismiss(_ picker: UIDocumentPickerViewController, completion: @escaping () -> Void) { + if picker.isBeingDismissed, let transition = picker.transitionCoordinator, + transition.animate(alongsideTransition: nil, completion: { context in + if context.isCancelled { + picker.dismiss(animated: true, completion: completion) + } else { + completion() + } + }) + { return } + picker.dismiss(animated: true, completion: completion) + } +} diff --git a/ios/Runner/PdfFileExportPlugin.swift b/ios/Runner/PdfFileExportPlugin.swift new file mode 100644 index 0000000000..b02e1c0f27 --- /dev/null +++ b/ios/Runner/PdfFileExportPlugin.swift @@ -0,0 +1,68 @@ +import CoreFoundation +import Flutter +import UIKit + +final class PdfFileExportPlugin: NSObject, FlutterPlugin, FlutterSceneLifeCycleDelegate { + static let pluginKey = "OtzariaPdfFileExport" + static let channelName = "otzaria/pdf_file_export" + let coordinator: PdfFileExportCoordinator + + init(coordinator: PdfFileExportCoordinator) { + self.coordinator = coordinator + } + + static func register(with registrar: FlutterPluginRegistrar) { + let coordinator = PdfFileExportCoordinator(presenter: { [weak registrar] in + registrar?.viewController + }) + let plugin = PdfFileExportPlugin(coordinator: coordinator) + let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger()) + registrar.addMethodCallDelegate(plugin, channel: channel) + registrar.addSceneDelegate(plugin) + registrar.publish(plugin) + } + + func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + precondition(Thread.isMainThread) + guard call.method == "exportFile" || call.method == "cancelExport" else { + result(FlutterMethodNotImplemented) + return + } + guard let arguments = call.arguments as? [String: Any], + let version = arguments["version"] as? NSNumber, + CFGetTypeID(version) != CFBooleanGetTypeID(), version.doubleValue == 1, + let identifier = arguments["operationId"] as? String, + identifier.utf8.count == 32, + identifier.range(of: "^[0-9a-f]{32}$", options: .regularExpression) != nil + else { + result(FlutterError(code: "invalid_arguments", message: "Invalid PDF export request.", details: nil)) + return + } + if call.method == "cancelExport" { + result(["operationId": identifier, "accepted": coordinator.cancel(operationID: identifier)]) + return + } + guard let sourcePath = arguments["sourcePath"] as? String, + let fileName = arguments["fileName"] as? String + else { + result(FlutterError(code: "invalid_arguments", message: "Missing PDF export source.", details: nil)) + return + } + coordinator.export(operationID: identifier, sourcePath: sourcePath, fileName: fileName) { value in + result(value) + } + } + + func detachFromEngine(for registrar: FlutterPluginRegistrar) { + let coordinator = self.coordinator + if Thread.isMainThread { + coordinator.detach() + } else { + DispatchQueue.main.async { coordinator.detach() } + } + } + + func sceneDidDisconnect(_ scene: UIScene) { + coordinator.sceneDidDisconnect(scene) + } +} diff --git a/tool/pdf_file_export/README.md b/tool/pdf_file_export/README.md new file mode 100644 index 0000000000..d71e7b7a88 --- /dev/null +++ b/tool/pdf_file_export/README.md @@ -0,0 +1,63 @@ +# בדיקת ייצוא PDF לקובץ ב־iOS + +ה־workflow `PDF file export (iOS UIKit and Files)` בונה את Runner האמיתי עם +Flutter 3.47.7 וה־lockfile של המאגר. הוא מפעיל scheme ייעודי בשם +`PdfFileExport`, ללא שינוי ב־scheme הרגיל או בבדיקות Runner הקיימות. +`flutter build ios --config-only` מכין גם את תלויות CocoaPods ו־SPM לפני Xcode; +אין הרצת `pod install` נוספת מתיקיית המאגר. + +## שתי שכבות הראיה + +- `PdfFileExportTests` משתמש ב־UIKit, במערכת הקבצים ובמנועי Flutter אמיתיים. + הבדיקות שולטות ב־delegate callbacks כדי לבדוק סדר אירועים: ACK לביטול אינו + משחרר את המקור; סיום שמירה מאוחר נשמר; cleanup ממתין לסיום dismissal; ניתוק + scene או מנוע אינו משאיר קובץ בשימוש שנמחק מוקדם. אלה בדיקות חוזה, והן אינן + הוכחה לפעולה של ספק Files. +- `PdfFileExportUITests` מפעיל את הבורר המערכתי עצמו דרך + `MobilePdfExportService.instance`. בדיקה אחת שומרת PDF סינתטי באמצעות + `On My iPhone`, והשנייה מבטלת דרך Cancel או מחוות סגירת ה־sheet במערכת + שאינה מציגה כפתור ביטול. אין החלפה של MethodChannel או של + callback בבדיקות אלה. ה־probe מאמת את SHA-256 של הקובץ שנשמר, את השם והנתיב + שהוחזרו מהיעד ואת פינוי staging לאחר התוצאה הסופית. + +תיקיית `Documents/OtzariaExportUITest` נוצרת רק בכניסת הבדיקה +`integration_test/pdf_file_export_ios_app.dart`. היא משתמשת בחשיפת Files שכבר +מופעלת ב־Info.plist של האפליקציה; הבדיקה אינה מוסיפה הרשאה לגרסת הייצור. +כניסת הבדיקה דורשת גם `PDF_FILE_EXPORT_IOS_PROBE=true` וגם iOS. +התרחיש נבחר באמצעות כפתור מפורש באפליקציית הבדיקה, ואינו תלוי בחשיפת +משתני הסביבה של XCTest ל־Dart. כל תרחיש שומר קבלה נפרדת בשמו. + +## הרצה ובדיקת התוצרים + +במחשב macOS עם Xcode, CocoaPods, Rust וה־SDK המוצמד: + +```sh +python3 tool/pdf_file_export/ios_export_runner.py \ + --source "$PWD" --root "$RUNNER_TEMP/pdf-file-export-ios" \ + --commit "$(git rev-parse HEAD)" +``` + +הכלי מיועד ל־CI ודורש `GITHUB_RUN_ID` ו־`GITHUB_RUN_ATTEMPT` לזיהוי ה־Simulator +שבבעלותו. הוא יוצר מכשיר חדש מתוך runtime של iOS שכבר מותקן, ואינו משנה או +מוחק מכשירי Simulator קיימים. בסיום הוא מאמת שוב את ה־UUID, השם, ה־runtime +והדגם לפני מחיקת המכשיר שלו. לכל פקודה ארוכה יש deadline; timeout נשמר ככישלון. + +התוצר כולל source commit/tree, hashes של קובצי המימוש והבדיקה לפני ואחרי +הבנייה, Flutter/Xcode/host, פקודות וקודי יציאה, לוגי XCTest, `xcresult` ושתי +קבלות JSON של ה־probe. שינויים ש־CocoaPods יוצר בגרף הפרויקט נשמרים בדיפ +נפרד; קוד Swift/Dart וה־pins חייבים להישאר זהים. הארטיפקט אינו כולל את +DerivedData, את container האפליקציה או את קובצי ה־PDF הסינתטיים. + +`validate_ios_export.py` דורש שכל `test...` בשתי מחלקות XCTest הנוכחיות יופיע +פעם אחת כהצלחה, ללא skips או retries שמסתירים כישלון. הוא בודק בנפרד את שתי +קבלות Files, את גרסת ה־SDK ואת הניקוי. summary נכתב רק אחרי שכל אלה עברו. + +בדיקות הכלים עצמן אינן דורשות macOS: + +```sh +python3 -m unittest discover -s tool/pdf_file_export -p 'test_*.py' -v +``` + +הבדיקה מכסה Simulator וספק Files המקומי. היא אינה מחליפה QA במכשיר פיזי, +ב־iCloud או בספק צד שלישי, ואינה מודדת חיסכון כולל בזיכרון. קובץ המקור כבר +קיים בדיסק לפני שהבורר נפתח; ה־channel מעביר נתיב ומטא־נתונים בלבד. diff --git a/tool/pdf_file_export/ios_export_runner.py b/tool/pdf_file_export/ios_export_runner.py new file mode 100644 index 0000000000..0743772b9a --- /dev/null +++ b/tool/pdf_file_export/ios_export_runner.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Build the actual Runner and run native contracts plus the real Files UI. + +Only the Simulator created by this process is shut down/deleted. No PDF or app +container is uploaded: only the two synthetic probe receipts and XCTest output. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import signal +import subprocess +import sys +import threading +import time + +from validate_ios_export import REVIEWED_SOURCES as SOURCE_FILES, validate + + +UUID = re.compile(r"[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}") + + +def output(arguments: list[str], *, timeout: int = 120) -> str: + return subprocess.check_output(arguments, text=True, timeout=timeout).strip() + + +def save(path: Path, value: object) -> None: + path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n") + + +def digest(path: Path) -> str: + with path.open("rb") as handle: + return hashlib.file_digest(handle, "sha256").hexdigest() + + +def run_logged(arguments: list[str], destination: Path, *, timeout: int) -> int: + print(f"Running {destination.stem}", flush=True) + start = time.monotonic() + timed_out = threading.Event() + with destination.open("w") as log: + with subprocess.Popen( + arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) as process: + def stop() -> None: + timed_out.set() + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + + watchdog = threading.Timer(timeout, stop) + watchdog.start() + try: + assert process.stdout is not None + for line in process.stdout: + log.write(line) + log.flush() + sys.stdout.write(line) + sys.stdout.flush() + code = process.wait() + finally: + watchdog.cancel() + save(destination.with_suffix(".command.json"), { + "arguments": arguments, "exitCode": code, + "timedOut": timed_out.is_set(), "durationSeconds": time.monotonic() - start, + }) + if code != 0 or timed_out.is_set(): + raise RuntimeError(f"{destination.stem} failed: exit={code}, timeout={timed_out.is_set()}") + return code + + +def create_simulator(root: Path) -> dict: + runtimes = json.loads(output(["xcrun", "simctl", "list", "-j", "runtimes"]))["runtimes"] + devices = json.loads(output(["xcrun", "simctl", "list", "-j", "devices"]))["devices"] + choices = [] + for runtime in runtimes: + if not runtime.get("isAvailable") or not runtime["identifier"].startswith("com.apple.CoreSimulator.SimRuntime.iOS-"): + continue + for device in devices.get(runtime["identifier"], []): + if device.get("isAvailable") and device.get("deviceTypeIdentifier", "").startswith("com.apple.CoreSimulator.SimDeviceType.iPhone-"): + choices.append((runtime, device)) + if not choices: + raise RuntimeError("No installed iOS runtime with a compatible iPhone; tests were NOT_RUN") + runtime, prototype = max(choices, key=lambda pair: tuple(int(n) for n in pair[0]["version"].split("."))) + name = f"otzaria-pdf-export-{os.environ['GITHUB_RUN_ID']}-{os.environ['GITHUB_RUN_ATTEMPT']}" + identifier = output(["xcrun", "simctl", "create", name, prototype["deviceTypeIdentifier"], runtime["identifier"]]) + if not UUID.fullmatch(identifier): + raise RuntimeError("simctl returned an invalid owned Simulator identifier") + receipt = {"udid": identifier, "name": name, "runtime": runtime, "deviceType": prototype["deviceTypeIdentifier"]} + try: + save(root / "simulator.json", receipt) + except Exception: + # A failed evidence write must not orphan the Simulator just created. + try: + cleanup_simulator(receipt) + except Exception as error: + print(f"Simulator cleanup after receipt failure: {error}", file=sys.stderr) + raise + return receipt + + +def check_owned_simulator(receipt: dict) -> dict | None: + identifier = receipt["udid"] + expected_name = f"otzaria-pdf-export-{os.environ['GITHUB_RUN_ID']}-{os.environ['GITHUB_RUN_ATTEMPT']}" + if not UUID.fullmatch(identifier) or receipt.get("name") != expected_name: + raise RuntimeError("Refusing an invalid Simulator receipt") + devices = json.loads(output(["xcrun", "simctl", "list", "-j", "devices"]))["devices"] + for runtime, entries in devices.items(): + for entry in entries: + if entry["udid"] == identifier: + if runtime != receipt["runtime"]["identifier"] or entry["name"] != receipt["name"] or entry.get("deviceTypeIdentifier") != receipt["deviceType"]: + raise RuntimeError("Owned Simulator identity changed; refusing cleanup") + return entry + return None + + +def cleanup_simulator(receipt: dict) -> None: + entry = check_owned_simulator(receipt) + if entry is None: + return + if entry["state"] == "Booted": + output(["xcrun", "simctl", "shutdown", receipt["udid"]]) + output(["xcrun", "simctl", "delete", receipt["udid"]]) + if check_owned_simulator(receipt) is not None: + raise RuntimeError("Owned Simulator was not deleted") + + +def collect_probe_receipts(root: Path, receipt: dict) -> None: + container = Path(output([ + "xcrun", "simctl", "get_app_container", receipt["udid"], "com.mendelg.otzaria", "data", + ])).resolve(strict=True) + source = container / "Documents" / "PdfExportEvidence" + destination = root / "probe" + destination.mkdir(exist_ok=True) + for name in ("files-save.json", "files-cancel.json"): + path = source / name + if path.is_file() and not path.is_symlink(): + shutil.copyfile(path, destination / name) + + +def run(root: Path, source: Path, commit: str) -> None: + root.mkdir(parents=True, exist_ok=False) + os.chdir(source) + if not re.fullmatch(r"[0-9a-f]{40}", commit) or output(["git", "rev-parse", "HEAD"]) != commit: + raise RuntimeError("Checkout does not match the requested source commit") + status = output(["git", "status", "--porcelain"]) + if status: + raise RuntimeError("The source checkout was dirty before the build") + before = {name: digest(source / name) for name in SOURCE_FILES} + save(root / "source.json", {"commit": commit, "tree": output(["git", "rev-parse", "HEAD^{tree}"]), "filesBefore": before}) + save(root / "flutter.json", json.loads(output(["flutter", "--version", "--machine"]))) + (root / "host.txt").write_text(output(["sw_vers"]) + "\n" + output(["uname", "-a"]) + "\n") + (root / "xcode.txt").write_text(output(["xcodebuild", "-version"]) + "\n") + receipt = create_simulator(root) + primary: BaseException | None = None + try: + output(["xcrun", "simctl", "boot", receipt["udid"]]) + output(["xcrun", "simctl", "bootstatus", receipt["udid"], "-b"], timeout=300) + output(["xcrun", "simctl", "spawn", receipt["udid"], "defaults", "write", "NSGlobalDomain", "AppleLanguages", "-array", "en"]) + run_logged(["flutter", "pub", "get", "--enforce-lockfile"], root / "dependencies.log", timeout=900) + run_logged([ + "flutter", "build", "ios", "--simulator", "--debug", "--config-only", "--no-codesign", "--no-pub", + "--target=integration_test/pdf_file_export_ios_app.dart", "--dart-define=PDF_FILE_EXPORT_IOS_PROBE=true", + ], root / "configure.log", timeout=900) + common = [ + "-workspace", "ios/Runner.xcworkspace", "-scheme", "PdfFileExport", "-configuration", "Debug", + "-sdk", "iphonesimulator", "-destination", f"id={receipt['udid']}", + "-derivedDataPath", str(root / "derived-data"), + "CODE_SIGNING_ALLOWED=NO", "CODE_SIGNING_REQUIRED=NO", "COMPILER_INDEX_STORE_ENABLE=NO", + ] + run_logged(["xcodebuild", "build-for-testing", *common], root / "build.log", timeout=2700) + run_logged([ + "xcodebuild", "test-without-building", *common, + "-parallel-testing-enabled", "NO", + "-test-timeouts-enabled", "YES", "-maximum-test-execution-time-allowance", "180", + "-resultBundlePath", str(root / "native.xcresult"), + "-only-testing:PdfFileExportTests", "-only-testing:PdfFileExportUITests", + ], root / "tests.log", timeout=1800) + except BaseException as error: + primary = error + finally: + try: + after = {name: digest(source / name) for name in SOURCE_FILES} + source_receipt = json.loads((root / "source.json").read_text()) + source_receipt["filesAfter"] = after + save(root / "source.json", source_receipt) + (root / "source-status-after.txt").write_text(output(["git", "status", "--porcelain"]) + "\n") + (root / "generated-project.diff").write_text(output(["git", "diff", "--", "ios"]) + "\n") + if before != after: + raise RuntimeError("Reviewed application/test source or pinned dependencies changed during build") + except Exception as error: + print(f"Source evidence collection failed: {error}", file=sys.stderr) + if primary is None: + primary = error + try: + collect_probe_receipts(root, receipt) + except Exception as error: + print(f"Files evidence collection failed: {error}", file=sys.stderr) + if primary is None: + primary = error + try: + cleanup_simulator(receipt) + save(root / "cleanup.json", {"ownedSimulatorDeleted": True, "udid": receipt["udid"]}) + except Exception as error: + print(f"Simulator cleanup/evidence failed: {error}", file=sys.stderr) + if primary is None: + primary = error + if primary is not None: + raise primary + summary = validate(root, source, commit) + save(root / "summary.json", summary) + print(json.dumps(summary, indent=2), flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source", type=Path, default=Path.cwd()) + parser.add_argument("--commit") + parser.add_argument("--cleanup-only", action="store_true") + arguments = parser.parse_args() + if arguments.cleanup_only: + receipt_path = arguments.root.resolve() / "simulator.json" + if receipt_path.is_file(): + cleanup_simulator(json.loads(receipt_path.read_text())) + else: + if arguments.commit is None: + parser.error("--commit is required for a test run") + run(arguments.root.resolve(), arguments.source.resolve(), arguments.commit) diff --git a/tool/pdf_file_export/test_ios_export_evidence.py b/tool/pdf_file_export/test_ios_export_evidence.py new file mode 100644 index 0000000000..2256121853 --- /dev/null +++ b/tool/pdf_file_export/test_ios_export_evidence.py @@ -0,0 +1,111 @@ +import json +from pathlib import Path +import tempfile +import unittest + +from validate_ios_export import REVIEWED_SOURCES, TEST_SOURCES, sha256, validate + + +class EvidenceTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) / "evidence" + self.source = Path(self.temporary.name) / "source" + (self.root / "probe").mkdir(parents=True) + for name in REVIEWED_SOURCES: + path = self.source / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("fixture\n") + for path in TEST_SOURCES.values(): + (self.source / path).write_text("func testOwnership() {}\n") + self.commit = "a" * 40 + files = {name: sha256(self.source / name) for name in REVIEWED_SOURCES} + self.write("source.json", {"commit": self.commit, "tree": "b" * 40, "filesBefore": files, "filesAfter": files}) + self.write("flutter.json", {"frameworkVersion": "3.47.7", "frameworkRevision": "abaf9c523780a608bd46686fd5e53740a07077f8"}) + for stage, action in (("build", "build-for-testing"), ("tests", "test-without-building")): + self.write(stage + ".command.json", {"exitCode": 0, "timedOut": False, "arguments": ["xcodebuild", action]}) + identifier = "AABBCCDD-1111-2222-3333-123456789012" + self.write("simulator.json", {"udid": identifier, "runtime": {"identifier": "com.apple.CoreSimulator.SimRuntime.iOS-26-0"}}) + self.write("cleanup.json", {"ownedSimulatorDeleted": True, "udid": identifier}) + (self.root / "build.log").write_text("build passed\n") + self.lines = [f"Test Case '-[{suite}.{suite} testOwnership]' passed (0.1 seconds).\n" for suite in TEST_SOURCES] + (self.root / "tests.log").write_text("".join(self.lines)) + for index, (case_name, status) in enumerate((("files-save", "saved"), ("files-cancel", "cancelled"))): + self.write("probe/" + case_name + ".json", { + "schemaVersion": 1, "case": case_name, "backend": "MobilePdfExportService.instance", + "picker": "UIDocumentPickerViewController.forExporting.asCopy", + "passed": True, "destinationVerified": True, "stagingAbsent": True, + "fixtureBytes": 200, "expectedSha256": "c" * 64, + "actualSha256": "c" * 64 if index == 0 else None, + "outcome": {"version": 1, "operationId": str(index) * 32, "status": status, "cleanupStatus": "notNeeded", + "documentUri": "file:///private/app/Documents/saved.pdf" if index == 0 else None, + "displayName": "saved.pdf" if index == 0 else None}, + }) + + def write(self, name, value): + (self.root / name).write_text(json.dumps(value)) + + def update(self, name, change): + value = json.loads((self.root / name).read_text()) + change(value) + self.write(name, value) + + def test_complete_native_and_real_files_evidence_passes(self): + report = validate(self.root, self.source, self.commit) + self.assertEqual(report["nativeContractTests"], 1) + self.assertEqual(report["realFilesUITests"], 1) + self.assertEqual(report["status"], "passed") + + def test_missing_or_skipped_native_case_is_not_success(self): + for log in (self.lines[0], "".join(self.lines).replace("passed", "skipped", 1), "".join(self.lines).replace("passed", "failed", 1)): + with self.subTest(log=log): + (self.root / "tests.log").write_text(log) + with self.assertRaises(ValueError): + validate(self.root, self.source, self.commit) + + def test_retry_cannot_hide_a_failure(self): + (self.root / "tests.log").write_text("".join(self.lines) + self.lines[0]) + with self.assertRaisesRegex(ValueError, "duplicate/retried"): + validate(self.root, self.source, self.commit) + + def test_changed_source_and_sdk_are_rejected(self): + (self.source / REVIEWED_SOURCES[0]).write_text("changed") + with self.assertRaisesRegex(ValueError, "source bytes"): + validate(self.root, self.source, self.commit) + (self.source / REVIEWED_SOURCES[0]).write_text("fixture\n") + self.update("flutter.json", lambda value: value.update(frameworkVersion="newer")) + with self.assertRaisesRegex(ValueError, "Flutter version"): + validate(self.root, self.source, self.commit) + + def test_test_timeout_is_not_a_pass(self): + self.update("tests.command.json", lambda value: value.update(timedOut=True)) + with self.assertRaisesRegex(ValueError, "did not finish"): + validate(self.root, self.source, self.commit) + + def test_saved_bytes_and_verified_name_are_required(self): + self.update("probe/files-save.json", lambda value: value.update(actualSha256="d" * 64)) + with self.assertRaisesRegex(ValueError, "saved bytes"): + validate(self.root, self.source, self.commit) + self.update("probe/files-save.json", lambda value: value.update(actualSha256="c" * 64)) + self.update("probe/files-save.json", lambda value: value["outcome"].update(displayName="requested-but-unverified.pdf")) + with self.assertRaisesRegex(ValueError, "saved name"): + validate(self.root, self.source, self.commit) + + def test_missing_cancel_receipt_is_not_ui_coverage(self): + (self.root / "probe/files-cancel.json").unlink() + with self.assertRaises(FileNotFoundError): + validate(self.root, self.source, self.commit) + + def test_unreleased_staging_and_unknown_cleanup_are_rejected(self): + self.update("probe/files-save.json", lambda value: value.update(stagingAbsent=False)) + with self.assertRaisesRegex(ValueError, "staging is unverified"): + validate(self.root, self.source, self.commit) + self.update("probe/files-save.json", lambda value: value.update(stagingAbsent=True)) + self.update("cleanup.json", lambda value: value.update(ownedSimulatorDeleted=False)) + with self.assertRaisesRegex(ValueError, "Simulator cleanup"): + validate(self.root, self.source, self.commit) + + +if __name__ == "__main__": + unittest.main() diff --git a/tool/pdf_file_export/test_ios_export_runner.py b/tool/pdf_file_export/test_ios_export_runner.py new file mode 100644 index 0000000000..469ccdbbe7 --- /dev/null +++ b/tool/pdf_file_export/test_ios_export_runner.py @@ -0,0 +1,206 @@ +import json +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +import ios_export_runner as runner + + +class RunnerCleanupTests(unittest.TestCase): + def test_native_tests_run_once_without_xcode_repetition_options(self): + with tempfile.TemporaryDirectory() as temporary: + source = Path(temporary).resolve() + (source / "native.swift").write_text("reviewed source") + root = source / "evidence" + commit = "a" * 40 + receipt = {"udid": "12345678-1234-1234-1234-123456789ABC"} + commands = [] + + def output(arguments, **_): + if arguments == ["git", "rev-parse", "HEAD"]: + return commit + if arguments == ["git", "rev-parse", "HEAD^{tree}"]: + return "b" * 40 + if arguments == ["flutter", "--version", "--machine"]: + return "{}" + return "" + + def run_logged(arguments, *_args, **_kwargs): + commands.append(arguments) + if "-test-iterations" in arguments: + if arguments[arguments.index("-test-iterations") + 1] == "1": + raise RuntimeError("Must specify -test-iterations with more than 1 iteration.") + + previous = Path.cwd() + try: + with ( + patch.object(runner, "SOURCE_FILES", ("native.swift",)), + patch.object(runner, "output", side_effect=output), + patch.object(runner, "create_simulator", return_value=receipt), + patch.object(runner, "run_logged", side_effect=run_logged), + patch.object(runner, "collect_probe_receipts"), + patch.object(runner, "cleanup_simulator") as cleanup, + patch.object(runner, "validate", return_value={"status": "passed"}), + ): + runner.run(root, source, commit) + tests = [c for c in commands if c[:2] == ["xcodebuild", "test-without-building"]] + self.assertEqual(len(tests), 1) + self.assertFalse(set(tests[0]) & { + "-test-iterations", "-retry-tests-on-failure", + "-run-tests-until-failure", "-test-repetition-relaunch-enabled", + }) + self.assertEqual(tests[0][tests[0].index("-parallel-testing-enabled") + 1], "NO") + self.assertIn("-only-testing:PdfFileExportTests", tests[0]) + self.assertIn("-only-testing:PdfFileExportUITests", tests[0]) + cleanup.assert_called_once_with(receipt) + finally: + os.chdir(previous) + + def test_flutter_configuration_owns_dependency_installation(self): + with tempfile.TemporaryDirectory() as temporary: + source = Path(temporary).resolve() + (source / "native.swift").write_text("reviewed source") + root = source / "evidence" + commit = "a" * 40 + receipt = {"udid": "12345678-1234-1234-1234-123456789ABC"} + commands = [] + + def output(arguments, **_): + if arguments == ["git", "rev-parse", "HEAD"]: + return commit + if arguments == ["git", "rev-parse", "HEAD^{tree}"]: + return "b" * 40 + if arguments == ["flutter", "--version", "--machine"]: + return "{}" + return "" + + def run_logged(arguments, *_args, **_kwargs): + commands.append(arguments) + if arguments[0] == "pod": + raise RuntimeError("No podspec found for SPM-only sentry_flutter") + + previous = Path.cwd() + try: + with ( + patch.object(runner, "SOURCE_FILES", ("native.swift",)), + patch.object(runner, "output", side_effect=output), + patch.object(runner, "create_simulator", return_value=receipt), + patch.object(runner, "run_logged", side_effect=run_logged), + patch.object(runner, "collect_probe_receipts"), + patch.object(runner, "cleanup_simulator") as cleanup, + patch.object(runner, "validate", return_value={"status": "passed"}), + ): + runner.run(root, source, commit) + configure = next(i for i, c in enumerate(commands) if c[:3] == ["flutter", "build", "ios"]) + build = next(i for i, c in enumerate(commands) if c[:2] == ["xcodebuild", "build-for-testing"]) + self.assertIn("--config-only", commands[configure]) + self.assertLess(configure, build) + self.assertFalse(any(c[0] == "pod" for c in commands)) + cleanup.assert_called_once_with(receipt) + finally: + os.chdir(previous) + + def test_source_evidence_failure_still_cleans_owned_simulator(self): + self._run_with_evidence_failure(primary=None) + + def test_secondary_evidence_failure_preserves_build_failure(self): + self._run_with_evidence_failure(primary=RuntimeError("native build failed")) + + def _run_with_evidence_failure(self, primary): + with tempfile.TemporaryDirectory() as temporary: + source = Path(temporary).resolve() + (source / "native.swift").write_text("reviewed source") + root = source / "evidence" + commit = "a" * 40 + evidence_error = OSError("reviewed source could not be read after build") + receipt = {"udid": "12345678-1234-1234-1234-123456789ABC"} + + def output(arguments, **_): + if arguments == ["git", "rev-parse", "HEAD"]: + return commit + if arguments == ["git", "rev-parse", "HEAD^{tree}"]: + return "b" * 40 + if arguments == ["flutter", "--version", "--machine"]: + return "{}" + return "" + + def run_logged(arguments, *_args, **_kwargs): + if primary is not None and arguments[:2] == ["xcodebuild", "build-for-testing"]: + raise primary + + previous = Path.cwd() + try: + with ( + patch.object(runner, "SOURCE_FILES", ("native.swift",)), + patch.object(runner, "digest", side_effect=["c" * 64, evidence_error]), + patch.object(runner, "output", side_effect=output), + patch.object(runner, "create_simulator", return_value=receipt), + patch.object(runner, "run_logged", side_effect=run_logged), + patch.object(runner, "collect_probe_receipts") as collect, + patch.object(runner, "cleanup_simulator") as cleanup, + patch.object(runner, "validate") as validate, + ): + with self.assertRaises(type(primary or evidence_error)) as caught: + runner.run(root, source, commit) + self.assertIs(caught.exception, primary or evidence_error) + collect.assert_called_once_with(root, receipt) + cleanup.assert_called_once_with(receipt) + validate.assert_not_called() + self.assertTrue(json.loads((root / "cleanup.json").read_text())["ownedSimulatorDeleted"]) + finally: + os.chdir(previous) + + def test_receipt_write_failure_cleans_the_newly_created_simulator(self): + runtime = {"identifier": "com.apple.CoreSimulator.SimRuntime.iOS-26-1", "version": "26.1", "isAvailable": True} + device_type = "com.apple.CoreSimulator.SimDeviceType.iPhone-17" + device = {"deviceTypeIdentifier": device_type, "isAvailable": True} + identifier = "12345678-1234-1234-1234-123456789ABC" + error = OSError("cannot persist receipt") + with ( + patch.dict(os.environ, {"GITHUB_RUN_ID": "123", "GITHUB_RUN_ATTEMPT": "1"}), + patch.object(runner, "output", side_effect=[ + json.dumps({"runtimes": [runtime]}), + json.dumps({"devices": {runtime["identifier"]: [device]}}), + identifier, + ]), + patch.object(runner, "save", side_effect=error), + patch.object(runner, "cleanup_simulator") as cleanup, + ): + with self.assertRaises(OSError) as caught: + runner.create_simulator(Path("unused")) + self.assertIs(caught.exception, error) + cleanup.assert_called_once_with({ + "udid": identifier, "name": "otzaria-pdf-export-123-1", + "runtime": runtime, "deviceType": device_type, + }) + + def test_foreign_simulator_receipt_is_never_deleted(self): + receipt = {"udid": "12345678-1234-1234-1234-123456789ABC", "name": "someone-elses-device"} + with ( + patch.dict(os.environ, {"GITHUB_RUN_ID": "123", "GITHUB_RUN_ATTEMPT": "1"}), + patch.object(runner, "output") as output, + ): + with self.assertRaisesRegex(RuntimeError, "invalid Simulator receipt"): + runner.cleanup_simulator(receipt) + output.assert_not_called() + + def test_changed_simulator_identity_is_never_deleted(self): + identifier = "12345678-1234-1234-1234-123456789ABC" + runtime = "com.apple.CoreSimulator.SimRuntime.iOS-26-1" + device_type = "com.apple.CoreSimulator.SimDeviceType.iPhone-17" + receipt = {"udid": identifier, "name": "otzaria-pdf-export-123-1", "runtime": {"identifier": runtime}, "deviceType": device_type} + with ( + patch.dict(os.environ, {"GITHUB_RUN_ID": "123", "GITHUB_RUN_ATTEMPT": "1"}), + patch.object(runner, "output", return_value=json.dumps({"devices": {runtime: [{ + "udid": identifier, "name": receipt["name"], "deviceTypeIdentifier": "a-different-model", "state": "Booted", + }]}})) as output, + ): + with self.assertRaisesRegex(RuntimeError, "identity changed"): + runner.cleanup_simulator(receipt) + output.assert_called_once_with(["xcrun", "simctl", "list", "-j", "devices"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tool/pdf_file_export/validate_ios_export.py b/tool/pdf_file_export/validate_ios_export.py new file mode 100644 index 0000000000..7243f59a81 --- /dev/null +++ b/tool/pdf_file_export/validate_ios_export.py @@ -0,0 +1,117 @@ +"""Fail closed on missing/skipped XCTest cases or incomplete real Files receipts.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import re +from urllib.parse import unquote, urlsplit + + +REVIEWED_SOURCES = ( + "ios/Runner/AppDelegate.swift", + "ios/Runner/PdfExportStaging.swift", + "ios/Runner/PdfFileExportCoordinator.swift", + "ios/Runner/PdfFileExportPlugin.swift", + "ios/PdfFileExportTests/PdfFileExportTests.swift", + "ios/PdfFileExportUITests/PdfFileExportUITests.swift", + "integration_test/pdf_file_export_ios_app.dart", + "lib/utils/file/mobile_pdf_export_core.dart", + "lib/utils/file/mobile_pdf_export_models.dart", + "lib/utils/file/mobile_pdf_export_service.dart", + "pubspec.yaml", + "pubspec.lock", +) +TEST_SOURCES = { + "PdfFileExportTests": "ios/PdfFileExportTests/PdfFileExportTests.swift", + "PdfFileExportUITests": "ios/PdfFileExportUITests/PdfFileExportUITests.swift", +} +SHA256 = re.compile(r"[0-9a-f]{64}") +CASE = re.compile( + r"Test Case '-\[(?:[^ ]+\.)?(PdfFileExportTests|PdfFileExportUITests) (test\w+)\]' (passed|failed|skipped)\b" +) + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def read(root: Path, name: str) -> dict: + return json.loads((root / name).read_text()) + + +def sha256(path: Path) -> str: + with path.open("rb") as handle: + return hashlib.file_digest(handle, "sha256").hexdigest() + + +def validate(root: Path, source: Path, commit: str) -> dict: + provenance = read(root, "source.json") + require(provenance.get("commit") == commit and bool(re.fullmatch(r"[0-9a-f]{40}", commit)), "source commit mismatch") + require(bool(re.fullmatch(r"[0-9a-f]{40}", provenance.get("tree", ""))), "missing source tree") + before, after = provenance.get("filesBefore", {}), provenance.get("filesAfter", {}) + require(set(before) == set(REVIEWED_SOURCES) and before == after, "reviewed source changed or was not recorded") + require(all(before[name] == sha256(source / name) for name in REVIEWED_SOURCES), "source bytes do not match the checkout") + flutter = read(root, "flutter.json") + require(flutter.get("frameworkVersion") == "3.47.7", "Flutter version changed") + require(flutter.get("frameworkRevision") == "abaf9c523780a608bd46686fd5e53740a07077f8", "Flutter source revision changed") + for stage in ("build", "tests"): + command = read(root, stage + ".command.json") + require(command.get("exitCode") == 0 and command.get("timedOut") is False, f"{stage} did not finish successfully") + require(command.get("arguments", [])[:2] == ["xcodebuild", "build-for-testing" if stage == "build" else "test-without-building"], f"{stage} did not use Xcode") + simulator = read(root, "simulator.json") + cleanup = read(root, "cleanup.json") + require(bool(re.fullmatch(r"[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}", simulator.get("udid", ""))), "missing Simulator identity") + require(simulator.get("runtime", {}).get("identifier", "").startswith("com.apple.CoreSimulator.SimRuntime.iOS-"), "not an iOS Simulator") + require(cleanup.get("ownedSimulatorDeleted") is True and cleanup.get("udid") == simulator["udid"], "owned Simulator cleanup is unverified") + + expected = { + (suite, name) + for suite, path in TEST_SOURCES.items() + for name in re.findall(r"\bfunc (test\w+)\s*\(", (source / path).read_text()) + } + require(all(any(suite == name for suite, _ in expected) for name in TEST_SOURCES), "a native test suite is empty") + observed = {} + for suite, name, result in CASE.findall((root / "tests.log").read_text()): + key = (suite, name) + require(key not in observed, f"duplicate/retried XCTest result: {key}") + observed[key] = result + require(set(observed) == expected, f"XCTest cases missing or unexpected: {expected.symmetric_difference(observed)}") + require(all(value == "passed" for value in observed.values()), "a native test failed or was skipped") + + operation_ids = set() + receipts = {} + for case_name, status in (("files-save", "saved"), ("files-cancel", "cancelled")): + receipt = read(root / "probe", case_name + ".json") + require(receipt.get("schemaVersion") == 1 and receipt.get("case") == case_name, "wrong Files receipt") + require(receipt.get("backend") == "MobilePdfExportService.instance", "Files did not use the real service") + require(receipt.get("picker") == "UIDocumentPickerViewController.forExporting.asCopy", "wrong picker mode") + require(all(receipt.get(key) is True for key in ("passed", "destinationVerified", "stagingAbsent")), "Files output/staging is unverified") + require(type(receipt.get("fixtureBytes")) is int and receipt["fixtureBytes"] > 100, "fixture PDF is missing") + require(bool(SHA256.fullmatch(receipt.get("expectedSha256", ""))), "fixture hash is missing") + outcome = receipt.get("outcome", {}) + require(outcome.get("version") == 1 and outcome.get("status") == status, "wrong terminal Files outcome") + identifier = outcome.get("operationId", "") + require(bool(re.fullmatch(r"[0-9a-f]{32}", identifier)) and identifier not in operation_ids, "operation identity was reused/missing") + operation_ids.add(identifier) + require(outcome.get("cleanupStatus") == "notNeeded" and outcome.get("cleanupError") is None and outcome.get("residualDocument") is None, "Files cleanup evidence is inconsistent") + if status == "saved": + require(receipt.get("actualSha256") == receipt["expectedSha256"], "saved bytes differ from source") + url = urlsplit(outcome.get("documentUri", "")) + require(url.scheme == "file" and bool(url.path), "saved URL was not verified") + require(Path(unquote(url.path)).name == outcome.get("displayName"), "saved name was not verified from the destination") + else: + require(receipt.get("actualSha256") is None and outcome.get("documentUri") is None and outcome.get("displayName") is None, "cancel invented a saved destination") + receipts[case_name] = receipt + return { + "schemaVersion": 1, "status": "passed", "source": provenance, + "flutter": flutter, "simulator": simulator, + "nativeContractTests": sum(suite == "PdfFileExportTests" for suite, _ in expected), + "realFilesUITests": sum(suite == "PdfFileExportUITests" for suite, _ in expected), + "testNames": {suite: sorted(name for observed_suite, name in expected if observed_suite == suite) for suite in TEST_SOURCES}, + "filesReceipts": receipts, + "rawHashes": {name: sha256(root / name) for name in ("build.log", "tests.log", "source.json", "flutter.json", "simulator.json")}, + "scope": "Simulator UIKit lifecycle and local Files provider; not physical-device or third-party-provider QA", + }