Skip to content

Commit fd6ef13

Browse files
[file_selector_android] Surface file-copy failures to Dart instead of crashing (flutter#12107)
`file_selector_android` crashes when a selected file can't be copied to a readable location. `FileSelectorApiImpl.toFileResponse` catches `IOException`/`SecurityException` from `FileUtils.getPathFromCopyOfFileFromUri` and sets the path to `null`, but then still builds a `FileResponse` with that null `path`. Since `path` is non-null in the Pigeon-generated `FileResponse`, this throws — a `NullPointerException` since the move to the Kotlin Pigeon generator (the issue reported it as an `IllegalStateException` on the older Java generator) — so the app crashes instead of surfacing an error. When no path can be produced, `toFileResponse` now returns `null`. The callers already handle that by completing the result with an error (the same `completeWithError("Failed to read file: …")` path they use elsewhere when a file can't be read), so the failure now reaches Dart as a `PlatformException` instead of crashing the app. I kept this scoped to the crash. The issue also suggests moving these branches onto the typed `FileSelectorNativeException` mechanism (like flutter#8184); that would need a Pigeon regeneration and a Dart-facing API change, so I left it out here — happy to do it as a follow-up if that's the preferred direction. The existing test that documented the crash (marked "Remove when fixed") now asserts the failure is surfaced, plus a matching test for the single-file `openFile` path. Fixes flutter#159568 ## Pre-Review Checklist
1 parent d9eee4c commit fd6ef13

4 files changed

Lines changed: 94 additions & 31 deletions

File tree

‎packages/file_selector/file_selector_android/CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
## 0.5.2+9
2+
3+
* Fixes a crash when a selected file cannot be copied to a readable location (for
4+
example, on a `SecurityException`).
5+
16
## 0.5.2+8
27

38
* Bumps the androidx group across 10 directories with 1 update.

‎packages/file_selector/file_selector_android/android/src/main/java/dev/flutter/packages/file_selector_android/FileSelectorApiImpl.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,16 @@ FileResponse toFileResponse(@NonNull Uri uri) {
383383
e.getMessage() == null ? "" : e.getMessage());
384384
}
385385

386+
if (uriPath == null) {
387+
// `getPathFromCopyOfFileFromUri` can fail to produce a path: either by
388+
// throwing (handled above by returning a null `uriPath`) or by returning
389+
// null directly. Return null so the caller surfaces the failure to Dart,
390+
// instead of building a `FileResponse` with a null `path`, which the
391+
// non-null field rejects at runtime.
392+
// See https://github.com/flutter/flutter/issues/159568.
393+
return null;
394+
}
395+
386396
return new FileResponse(uriPath, contentResolver.getType(uri), name, size, bytes, nativeError);
387397
}
388398
}

‎packages/file_selector/file_selector_android/android/src/test/java/dev/flutter/packages/file_selector_android/FileSelectorAndroidPluginTest.java‎

Lines changed: 78 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66

77
import static org.junit.Assert.assertEquals;
88
import static org.junit.Assert.assertNotNull;
9-
import static org.junit.Assert.assertThrows;
109
import static org.junit.Assert.assertTrue;
1110
import static org.mockito.ArgumentMatchers.any;
1211
import static org.mockito.ArgumentMatchers.eq;
12+
import static org.mockito.Mockito.lenient;
1313
import static org.mockito.Mockito.mock;
1414
import static org.mockito.Mockito.mockStatic;
1515
import static org.mockito.Mockito.verify;
@@ -71,7 +71,9 @@ private void mockContentResolver(
7171
when(mockCursor.getInt(1)).thenReturn(size);
7272

7373
when(mockResolver.query(uri, null, null, null, null, null)).thenReturn(mockCursor);
74-
when(mockResolver.getType(uri)).thenReturn(mimeType);
74+
// `getType` is only reached when a `FileResponse` is built, so it is unused by
75+
// the error-path tests; keep it lenient to avoid strict-stubbing warnings.
76+
lenient().when(mockResolver.getType(uri)).thenReturn(mimeType);
7577
when(mockResolver.openInputStream(uri)).thenReturn(mock(InputStream.class));
7678
}
7779

@@ -214,36 +216,25 @@ public void openFilesReturnsSuccessfully() throws FileNotFoundException {
214216
}
215217
}
216218

217-
// This test was created when error handling was moved from FileUtils.java to
218-
// FileSelectorApiImpl.java
219-
// in https://github.com/flutter/packages/pull/8184, so as to maintain the existing test.
220-
// The behavior is actually an error case and should be fixed,
221-
// see: https://github.com/flutter/flutter/issues/159568.
222-
// Remove when fixed!
219+
// Regression test for https://github.com/flutter/flutter/issues/159568: a
220+
// `SecurityException` while copying a selected file must be surfaced to Dart
221+
// as a failed result, rather than crashing by building a `FileResponse` with a
222+
// null `path` (which the non-null `path` field rejects at runtime).
223223
@SuppressWarnings({"rawtypes", "unchecked"})
224224
@Test
225-
public void
226-
openFileThrowsNullPointerException_whenSecurityExceptionInGetPathFromCopyOfFileFromUri()
227-
throws FileNotFoundException {
225+
public void openFilesCompletesWithError_whenSecurityExceptionInGetPathFromCopyOfFileFromUri()
226+
throws FileNotFoundException {
228227

229228
try (MockedStatic<FileUtils> mockedFileUtils = mockStatic(FileUtils.class)) {
230229

231230
final ContentResolver mockContentResolver = mock(ContentResolver.class);
232231

233232
final Uri mockUri = mock(Uri.class);
234-
final String mockUriPath = "some/path/";
235233
mockedFileUtils
236234
.when(() -> FileUtils.getPathFromCopyOfFileFromUri(any(Context.class), eq(mockUri)))
237235
.thenThrow(SecurityException.class);
238236
mockContentResolver(mockContentResolver, mockUri, "filename", 30, "text/plain");
239237

240-
final Uri mockUri2 = mock(Uri.class);
241-
final String mockUri2Path = "some/other/path/";
242-
mockedFileUtils
243-
.when(() -> FileUtils.getPathFromCopyOfFileFromUri(any(Context.class), eq(mockUri2)))
244-
.thenAnswer((Answer<String>) invocation -> mockUri2Path);
245-
mockContentResolver(mockContentResolver, mockUri2, "filename2", 40, "image/jpg");
246-
247238
when(mockObjectFactory.newIntent(Intent.ACTION_OPEN_DOCUMENT)).thenReturn(mockIntent);
248239
when(mockObjectFactory.newDataInputStream(any())).thenReturn(mock(DataInputStream.class));
249240
when(mockActivity.getContentResolver()).thenReturn(mockContentResolver);
@@ -254,11 +245,15 @@ public void openFilesReturnsSuccessfully() throws FileNotFoundException {
254245
mockObjectFactory,
255246
(version) -> Build.VERSION.SDK_INT >= version);
256247

248+
final boolean[] callbackCalled = new boolean[1];
249+
final Throwable[] failure = new Throwable[1];
257250
fileSelectorApi.openFiles(
258251
null,
259252
new FileTypes(Collections.emptyList(), Collections.emptyList()),
260253
ResultCompat.asCompatCallback(
261254
(reply) -> {
255+
callbackCalled[0] = true;
256+
failure[0] = reply.exceptionOrNull();
262257
return null;
263258
}));
264259
verify(mockIntent).addCategory(Intent.CATEGORY_OPENABLE);
@@ -272,24 +267,77 @@ public void openFilesReturnsSuccessfully() throws FileNotFoundException {
272267

273268
final Intent resultMockIntent = mock(Intent.class);
274269
final ClipData mockClipData = mock(ClipData.class);
275-
when(mockClipData.getItemCount()).thenReturn(2);
270+
when(mockClipData.getItemCount()).thenReturn(1);
276271

277272
final ClipData.Item mockClipDataItem = mock(ClipData.Item.class);
278273
when(mockClipDataItem.getUri()).thenReturn(mockUri);
279274
when(mockClipData.getItemAt(0)).thenReturn(mockClipDataItem);
280275

281-
final ClipData.Item mockClipDataItem2 = mock(ClipData.Item.class);
282-
when(mockClipDataItem2.getUri()).thenReturn(mockUri2);
283-
when(mockClipData.getItemAt(1)).thenReturn(mockClipDataItem2);
284-
285276
when(resultMockIntent.getClipData()).thenReturn(mockClipData);
286277

287-
assertThrows(
288-
NullPointerException.class,
289-
() ->
290-
listenerArgumentCaptor
291-
.getValue()
292-
.onActivityResult(222, Activity.RESULT_OK, resultMockIntent));
278+
// Previously this threw a NullPointerException (see #159568); it must now
279+
// complete the callback with a failure instead of crashing.
280+
listenerArgumentCaptor.getValue().onActivityResult(222, Activity.RESULT_OK, resultMockIntent);
281+
282+
assertTrue(callbackCalled[0]);
283+
assertNotNull(failure[0]);
284+
assertTrue(failure[0].getMessage().contains("Failed to read file"));
285+
}
286+
}
287+
288+
// Regression test for https://github.com/flutter/flutter/issues/159568: the
289+
// single-file `openFile` path must likewise surface a copy failure to Dart
290+
// instead of crashing.
291+
@SuppressWarnings({"rawtypes", "unchecked"})
292+
@Test
293+
public void openFileCompletesWithError_whenSecurityExceptionInGetPathFromCopyOfFileFromUri()
294+
throws FileNotFoundException {
295+
296+
try (MockedStatic<FileUtils> mockedFileUtils = mockStatic(FileUtils.class)) {
297+
298+
final ContentResolver mockContentResolver = mock(ContentResolver.class);
299+
300+
final Uri mockUri = mock(Uri.class);
301+
mockedFileUtils
302+
.when(() -> FileUtils.getPathFromCopyOfFileFromUri(any(Context.class), eq(mockUri)))
303+
.thenThrow(SecurityException.class);
304+
mockContentResolver(mockContentResolver, mockUri, "filename", 30, "text/plain");
305+
306+
when(mockObjectFactory.newIntent(Intent.ACTION_OPEN_DOCUMENT)).thenReturn(mockIntent);
307+
when(mockObjectFactory.newDataInputStream(any())).thenReturn(mock(DataInputStream.class));
308+
when(mockActivity.getContentResolver()).thenReturn(mockContentResolver);
309+
when(mockActivityBinding.getActivity()).thenReturn(mockActivity);
310+
final FileSelectorApiImpl fileSelectorApi =
311+
new FileSelectorApiImpl(
312+
mockActivityBinding,
313+
mockObjectFactory,
314+
(version) -> Build.VERSION.SDK_INT >= version);
315+
316+
final boolean[] callbackCalled = new boolean[1];
317+
final Throwable[] failure = new Throwable[1];
318+
fileSelectorApi.openFile(
319+
null,
320+
new FileTypes(Collections.emptyList(), Collections.emptyList()),
321+
ResultCompat.asCompatCallback(
322+
(reply) -> {
323+
callbackCalled[0] = true;
324+
failure[0] = reply.exceptionOrNull();
325+
return null;
326+
}));
327+
328+
verify(mockActivity).startActivityForResult(mockIntent, 221);
329+
330+
final ArgumentCaptor<PluginRegistry.ActivityResultListener> listenerArgumentCaptor =
331+
ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class);
332+
verify(mockActivityBinding).addActivityResultListener(listenerArgumentCaptor.capture());
333+
334+
final Intent resultMockIntent = mock(Intent.class);
335+
when(resultMockIntent.getData()).thenReturn(mockUri);
336+
listenerArgumentCaptor.getValue().onActivityResult(221, Activity.RESULT_OK, resultMockIntent);
337+
338+
assertTrue(callbackCalled[0]);
339+
assertNotNull(failure[0]);
340+
assertTrue(failure[0].getMessage().contains("Failed to read file"));
293341
}
294342
}
295343

‎packages/file_selector/file_selector_android/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: file_selector_android
22
description: Android implementation of the file_selector package.
33
repository: https://github.com/flutter/packages/tree/main/packages/file_selector/file_selector_android
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22
5-
version: 0.5.2+8
5+
version: 0.5.2+9
66

77
environment:
88
sdk: ^3.12.0

0 commit comments

Comments
 (0)