diff --git a/docs/adr/0106-root-isolate-attachment-upload-authentication.md b/docs/adr/0106-root-isolate-attachment-upload-authentication.md index 0f6024459..39ff43660 100644 --- a/docs/adr/0106-root-isolate-attachment-upload-authentication.md +++ b/docs/adr/0106-root-isolate-attachment-upload-authentication.md @@ -15,10 +15,10 @@ Mobile attachment uploads ran in a worker isolate with a separate `DioClient`, O - `FileUploader` uses the root `DioClient`; attachment uploads do not initialize Hive or native authentication from a worker isolate. - Each file still streams on its own asynchronous socket and progress stream. - A 401 retry rebuilds its consumed body from a file path or retained bytes. -- On mobile the retry replays the original `RequestOptions` via `Dio.fetch`, so `onSendProgress`, `CancelToken`, timeouts and response type survive the refresh. Web keeps the legacy `Dio.request` path because it is already correct there and this fix must not change its execution path. +- On mobile the retry replays the original `RequestOptions` via `Dio.fetch`, so `onSendProgress`, `CancelToken`, timeouts and response type survive the refresh. Web keeps its existing `Dio.request` path: this fix is scoped to the mobile isolate regression and must not change a working platform. - Merging the previously separate web and isolate code paths cost web its structural guarantee of never touching `dart:io`, so `FileUploader` treats an attachment as byte-backed whenever it runs on web. - Charset detection reads at most 256 KiB, because it only needs a prefix and the root isolate must not materialise a whole text attachment. -- An attachment with neither a file path nor bytes raises `MissingAttachmentSourceException` rather than silently uploading an empty body. +- An attachment with neither a file path nor bytes raises `MissingAttachmentSourceException`, both when the request is built and when a mobile replay body cannot be rebuilt, rather than silently uploading an empty body. - Charset detection runs after the server stored the blob, so a probe failure degrades to an unknown charset instead of discarding a completed upload. ## Consequences @@ -29,4 +29,6 @@ Mobile attachment uploads ran in a worker isolate with a separate `DioClient`, O - The upload path no longer opens Hive from a worker isolate. - `NetworkBindings` owns `FileUploader` and `HtmlAnalyzer`; `NetworkIsolateBindings` no longer registers upload dependencies. - `CancelToken` now reaches Dio on mobile, so cancelling aborts the request instead of letting it upload the whole file and only marking the UI as cancelled. +- Rebuilding an `Options` for the retry drops `onSendProgress` and `CancelToken`, so on web a replayed upload still freezes its progress chip and ignores cancellation. This is pre-existing behaviour and out of scope for this ADR. +- `flutter_charset_detector` is a native plugin, so `getCharsetFromBytes` falls back to UTF-8 under `flutter test` and no unit test can assert a real charset. Unit tests cover the sampled bytes only; that the bounded sample classifies a large non-UTF8 attachment the same way an unbounded read would needs on-device validation. - Physical iOS validation remains required. diff --git a/lib/features/login/data/network/interceptors/authorization_interceptors.dart b/lib/features/login/data/network/interceptors/authorization_interceptors.dart index 7d2a1739e..e4d3e4799 100644 --- a/lib/features/login/data/network/interceptors/authorization_interceptors.dart +++ b/lib/features/login/data/network/interceptors/authorization_interceptors.dart @@ -22,6 +22,7 @@ import 'package:tmail_ui_user/features/login/data/network/authentication_client/ import 'package:tmail_ui_user/features/login/domain/exceptions/oauth_authorization_error.dart'; import 'package:tmail_ui_user/features/login/domain/extensions/oidc_configuration_extensions.dart'; import 'package:tmail_ui_user/features/upload/data/network/file_uploader.dart'; +import 'package:tmail_ui_user/features/upload/domain/exceptions/upload_exception.dart'; import 'package:tmail_ui_user/main/exceptions/remote/authentication_exception.dart'; import 'package:tmail_ui_user/main/utils/ios_sharing_manager.dart'; @@ -645,33 +646,52 @@ class AuthorizationInterceptors extends QueuedInterceptorsWrapper { if (extraInRequest.containsKey(FileUploader.uploadAttachmentExtraKey)) { log('AuthorizationInterceptors::_retryRequest: ' 'Retry upload request with TokenId = ${_token?.tokenIdHash}'); - final uploadExtra = - extraInRequest[FileUploader.uploadAttachmentExtraKey]; + return _retryUploadRequest( + retryDio, + requestOptions, + extraInRequest[FileUploader.uploadAttachmentExtraKey], + ); + } - if (PlatformInfo.isMobile) { - // `copyWith` falls back to the original body when the rebuilt one is - // null, and that body is already consumed. Assign it explicitly so an - // unrebuildable upload fails plainly instead of replaying a dead stream. - final replayOptions = requestOptions.copyWith() - ..data = _getDataUploadRequest(uploadExtra); - return retryDio.fetch(replayOptions); + log('AuthorizationInterceptors::_retryRequest: ' + 'Retry request with TokenId = ${_token?.tokenIdHash}'); + return retryDio.fetch(requestOptions); + } + + /// The failed attempt already consumed the body stream, so a replay has to + /// rebuild it from the file path or the retained bytes. + Future _retryUploadRequest( + Dio retryDio, + RequestOptions requestOptions, + dynamic uploadExtra, + ) { + if (PlatformInfo.isMobile) { + final uploadBody = _getDataUploadRequest(uploadExtra); + + // Without a rebuilt body the replay would send an empty one, so fail + // plainly instead of storing a zero-byte blob under the attachment's name. + if (uploadBody == null) { + throw const MissingAttachmentSourceException(); } - return retryDio.request( - requestOptions.path, - data: _getDataUploadRequest(uploadExtra), - queryParameters: requestOptions.queryParameters, - options: Options( - method: requestOptions.method, - headers: requestOptions.headers, - extra: requestOptions.extra, - ), - ); - } else { - log('AuthorizationInterceptors::_retryRequest: ' - 'Retry request with TokenId = ${_token?.tokenIdHash}'); - return retryDio.fetch(requestOptions); + // Replaying the original options keeps `onSendProgress`, `CancelToken`, + // the timeouts and the response type, all of which rebuilding an + // `Options` from scratch drops. + return retryDio.fetch(requestOptions.copyWith(data: uploadBody)); } + + // Web keeps the retry path it already had. It works today, and this fix is + // scoped to the mobile isolate regression. + return retryDio.request( + requestOptions.path, + data: _getDataUploadRequest(uploadExtra), + queryParameters: requestOptions.queryParameters, + options: Options( + method: requestOptions.method, + headers: requestOptions.headers, + extra: requestOptions.extra, + ), + ); } /// Creates a separate Dio instance without interceptors for retry requests. diff --git a/test/features/interceptor/authorization_interceptor_upload_retry_test.dart b/test/features/interceptor/authorization_interceptor_upload_retry_test.dart index 2d0974f38..d85608a19 100644 --- a/test/features/interceptor/authorization_interceptor_upload_retry_test.dart +++ b/test/features/interceptor/authorization_interceptor_upload_retry_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -19,6 +20,7 @@ import 'package:tmail_ui_user/features/login/data/network/authentication_client/ import 'package:tmail_ui_user/features/login/data/network/interceptors/authorization_interceptors.dart'; import 'package:tmail_ui_user/features/login/domain/extensions/oidc_configuration_extensions.dart'; import 'package:tmail_ui_user/features/upload/data/network/file_uploader.dart'; +import 'package:tmail_ui_user/features/upload/domain/exceptions/upload_exception.dart'; import 'package:tmail_ui_user/main/utils/ios_sharing_manager.dart'; import '../../fixtures/account_fixtures.dart'; @@ -91,6 +93,41 @@ void main() { return server; } + /// Rejects the first request with 401, then reads the replay's body and holds + /// the response open, so a test can cancel while the replay awaits its reply. + Future startReplayStallingServer({ + required Completer replayStarted, + required Completer releaseReplay, + }) async { + var requestCount = 0; + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) async { + await request.drain(); + requestCount++; + if (requestCount == 1) { + request.response.statusCode = HttpStatus.unauthorized; + request.response.headers.contentType = ContentType.json; + request.response.write(jsonEncode({'error': 'unauthorized'})); + await request.response.close(); + return; + } + if (!replayStarted.isCompleted) { + replayStarted.complete(); + } + await releaseReplay.future; + request.response.headers.contentType = ContentType.json; + request.response.write(jsonEncode({'uploaded': true})); + await request.response.close(); + }); + addTearDown(() async { + if (!releaseReplay.isCompleted) { + releaseReplay.complete(); + } + await server.close(force: true); + }); + return server; + } + Dio buildUploadDio() { final dio = Dio(BaseOptions(headers: { HttpHeaders.acceptHeader: DioClient.jmapHeader, @@ -134,7 +171,12 @@ void main() { return dio; } - Options uploadOptions(List sourceBytes) => Options( + /// Mirrors the byte-backed request `FileUploader` builds. `contentLength` is + /// what makes Dio emit send progress, so it is opt-in per test. + Options uploadOptions(List sourceBytes, {bool withContentLength = false}) => Options( + headers: withContentLength + ? {HttpHeaders.contentLengthHeader: sourceBytes.length} + : null, extra: { FileUploader.uploadAttachmentExtraKey: { FileUploader.streamDataExtraKey: @@ -200,6 +242,34 @@ void main() { ); } + /// Uploads [body] through one 401 + refresh cycle and returns the `count == + /// total` send-progress events observed across the original and the replay. + Future> completedProgressAcrossReplay({ + required Stream> body, + required Options options, + }) async { + final receivedBodies = >[]; + final authorizationHeaders = []; + final server = await startUploadServer(receivedBodies, authorizationHeaders); + final dio = buildUploadDio(); + final completedProgressEvents = []; + + final response = await dio.post( + 'http://${server.address.address}:${server.port}/upload/account-id', + data: body, + options: options, + onSendProgress: (count, total) { + if (count == total) { + completedProgressEvents.add(count); + } + }, + ).timeout(const Duration(seconds: 30)); + + expect(response.statusCode, HttpStatus.ok); + expect(receivedBodies.length, 2); + return completedProgressEvents; + } + test('replays concurrent attachment uploads on mobile after one shared token refresh', () async { final receivedBodies = >[]; final authorizationHeaders = []; @@ -258,31 +328,19 @@ void main() { ); }); - test('keeps reporting upload progress on the mobile replay after 401', () async { + // The replay must keep the original `onSendProgress`, otherwise the attachment + // chip freezes at the progress reached before the 401. + test('keeps reporting progress on a file-backed mobile replay after 401', () async { final sourceBytes = List.generate(4096, (index) => index % 256); final file = await createTempUploadFile(sourceBytes); - final receivedBodies = >[]; - final authorizationHeaders = []; - final server = await startUploadServer(receivedBodies, authorizationHeaders); - final dio = buildUploadDio(); - final completedProgressEvents = []; - final response = await dio.post( - 'http://${server.address.address}:${server.port}/upload/account-id', - data: file.openRead(), - options: filePathUploadOptions(file.path, sourceBytes.length), - onSendProgress: (count, total) { - if (count == total) { - completedProgressEvents.add(count); - } - }, - ).timeout(const Duration(seconds: 30)); - - expect(response.statusCode, HttpStatus.ok); - expect(receivedBodies.length, 2); - // The replay must keep the original `onSendProgress`, otherwise the - // attachment chip freezes at the progress reached before the 401. - expect(completedProgressEvents, [sourceBytes.length, sourceBytes.length]); + expect( + await completedProgressAcrossReplay( + body: file.openRead(), + options: filePathUploadOptions(file.path, sourceBytes.length), + ), + [sourceBytes.length, sourceBytes.length], + ); }); test('replays the attachment body on web after 401 through the legacy retry path', () async { @@ -340,18 +398,79 @@ void main() { final dio = buildUploadDio(); // Malformed extras: neither a path nor a stream, so the replay body is null. - // It must not silently resend the already-consumed original stream. - final response = await dio.post( - 'http://${server.address.address}:${server.port}/upload/account-id', - data: Stream>.value(sourceBytes), - options: Options( - extra: { - FileUploader.uploadAttachmentExtraKey: {}, - }, - ), - ).timeout(const Duration(seconds: 30)); + // The already-consumed original stream cannot be resent, and sending no body + // at all would store a zero-byte blob under the attachment's name. + await expectLater( + dio.post( + 'http://${server.address.address}:${server.port}/upload/account-id', + data: Stream>.value(sourceBytes), + options: Options( + extra: { + FileUploader.uploadAttachmentExtraKey: {}, + }, + ), + ).timeout(const Duration(seconds: 30)), + throwsA(isA().having( + (exception) => exception.error, + 'error', + isA(), + )), + ); - expect(response.statusCode, HttpStatus.ok); - expect(receivedBodies, [sourceBytes, isEmpty]); + // Only the original request reached the server; no empty replay followed it. + expect(receivedBodies, [sourceBytes]); + }); + + // A mobile attachment with bytes but no file path (Drive, inline image) + // replays from streamData and must report progress like a file-backed one. + test('keeps reporting progress on a byte-backed mobile replay after 401', () async { + final sourceBytes = List.generate(4096, (index) => index % 256); + + expect( + await completedProgressAcrossReplay( + body: BodyBytesStream.fromBytes(Uint8List.fromList(sourceBytes)), + options: uploadOptions(sourceBytes, withContentLength: true), + ), + [sourceBytes.length, sourceBytes.length], + ); + }); + + // Cancels once the replay is in flight awaiting its response, not mid-body. + // Both phases abort through the same `cancelFuture.whenComplete(request.abort)` + // in `IOHttpClientAdapter`, reading the same `options.cancelToken`, so this + // covers the regression: whether the replay carries the token at all. Forcing + // a mid-body abort would need a multi-MB payload to defeat socket buffers and + // would buy no extra discrimination. + test('aborts the in-flight mobile replay when the upload CancelToken is cancelled', () async { + final sourceBytes = List.generate(4096, (index) => index % 256); + final replayStarted = Completer(); + final releaseReplay = Completer(); + final server = await startReplayStallingServer( + replayStarted: replayStarted, + releaseReplay: releaseReplay, + ); + final dio = buildUploadDio(); + final cancelToken = CancelToken(); + + final uploadFuture = dio.post( + 'http://${server.address.address}:${server.port}/upload/account-id', + data: BodyBytesStream.fromBytes(Uint8List.fromList(sourceBytes)), + options: uploadOptions(sourceBytes), + cancelToken: cancelToken, + ); + + await replayStarted.future.timeout(const Duration(seconds: 30)); + cancelToken.cancel(); + + // Without the token on the replay, nothing aborts it and the upload hangs on + // the stalled server until the timeout fires instead of reporting `cancel`. + await expectLater( + uploadFuture.timeout(const Duration(seconds: 30)), + throwsA(isA().having( + (exception) => exception.type, + 'type', + DioExceptionType.cancel, + )), + ); }); } diff --git a/test/features/upload/data/network/file_uploader_test.dart b/test/features/upload/data/network/file_uploader_test.dart index e4bf52192..b56a33094 100644 --- a/test/features/upload/data/network/file_uploader_test.dart +++ b/test/features/upload/data/network/file_uploader_test.dart @@ -96,20 +96,21 @@ void main() { return server; } - Future uploadTextFileFromDisk({ + Future uploadTextBytesFromDisk({ required String fileName, - required String content, + required List bytes, required List> receivedBodies, + FileUtils? fileUtils, }) async { final directory = await Directory.systemTemp.createTemp('charset-upload-'); addTearDown(() async { await directory.delete(recursive: true); }); final file = File('${directory.path}/$fileName'); - await file.writeAsString(content); + await file.writeAsBytes(bytes); final server = await startRecordingUploadServer(receivedBodies); - return FileUploader(DioClient(Dio()), FileUtils()).uploadAttachment( + return FileUploader(DioClient(Dio()), fileUtils ?? FileUtils()).uploadAttachment( UploadTaskId('upload-$fileName'), FileInfo( fileName: fileName, @@ -263,7 +264,10 @@ void main() { final receivedBodies = >[]; final server = await startRecordingUploadServer(receivedBodies); - final attachment = await FileUploader(DioClient(Dio()), FileUtils()).uploadAttachment( + final attachment = await FileUploader( + DioClient(Dio()), + _RecordingFileUtils('Shift_JIS'), + ).uploadAttachment( const UploadTaskId('upload-web-charset'), FileInfo( fileName: 'note.txt', @@ -274,8 +278,7 @@ void main() { Uri.parse('http://${server.address.address}:${server.port}/upload/account-id'), ).timeout(const Duration(seconds: 30)); - expect(attachment.charset, isNotNull); - expect(attachment.charset, attachment.charset!.toLowerCase()); + expect(attachment.charset, 'shift_jis'); }); test('throws MissingAttachmentSourceException when there is no body source', () async { @@ -299,29 +302,38 @@ void main() { const content = 'hello charset'; final receivedBodies = >[]; - final attachment = await uploadTextFileFromDisk( + final attachment = await uploadTextBytesFromDisk( fileName: 'note.txt', - content: content, + bytes: utf8.encode(content), receivedBodies: receivedBodies, + fileUtils: _RecordingFileUtils('Shift_JIS'), ); - expect(attachment.charset, isNotNull); + expect(attachment.charset, 'shift_jis'); expect(receivedBodies.single, utf8.encode(content)); }); - test('bounds the charset probe without truncating the uploaded file', () async { - // Comfortably past the 256 KiB charset sample bound. - final content = 'charset detection line\n' * 40000; + test('probes exactly the first 256 KiB of an oversized text attachment', () async { + const sampleMaxBytes = 256 * 1024; + final bytes = Uint8List.fromList( + List.generate(sampleMaxBytes + 4096, (index) => 0x41 + (index % 26))); + final fileUtils = _RecordingFileUtils('Windows-1251'); final receivedBodies = >[]; - final attachment = await uploadTextFileFromDisk( - fileName: 'big.txt', - content: content, + final attachment = await uploadTextBytesFromDisk( + fileName: 'oversized.txt', + bytes: bytes, receivedBodies: receivedBodies, + fileUtils: fileUtils, ); - expect(attachment.charset, isNotNull); - expect(receivedBodies.single.length, utf8.encode(content).length); + // The probe reads a bounded prefix so the root isolate never materialises a + // whole text attachment, and it reads that prefix from the start of it. + expect(fileUtils.probedSamples.single, bytes.sublist(0, sampleMaxBytes)); + // Bounding the probe must not shorten what is uploaded, and the detected + // charset must still reach the attachment. + expect(receivedBodies.single.length, bytes.length); + expect(attachment.charset, 'windows-1251'); }); test('leaves the charset unset for a non text/plain attachment', () async { @@ -359,7 +371,8 @@ void main() { releaseResponse: releaseResponse, ); - final uploadFuture = FileUploader(DioClient(Dio()), FileUtils()).uploadAttachment( + final fileUtils = _RecordingFileUtils('Shift_JIS'); + final uploadFuture = FileUploader(DioClient(Dio()), fileUtils).uploadAttachment( const UploadTaskId('upload-charset-gone'), FileInfo( fileName: 'note.txt', @@ -381,5 +394,24 @@ void main() { // with an unknown charset rather than the upload reporting a failure. expect(attachment.name, 'note.txt'); expect(attachment.charset, isNull); + // The failure has to come from reading the vanished file, not from the + // detector: the sample never got far enough to be probed. + expect(fileUtils.probedSamples, isEmpty); }); } + +/// The real detector is a native federated plugin, so `CharsetDetector.autoDecode` +/// throws in the VM and `FileUtils` silently falls back to UTF-8. Recording the +/// bytes it is handed is the only way a unit test can observe what was sampled. +class _RecordingFileUtils extends FileUtils { + _RecordingFileUtils(this._charset); + + final String _charset; + final List probedSamples = []; + + @override + Future getCharsetFromBytes(Uint8List bytes) async { + probedSamples.add(bytes); + return _charset; + } +}