summaryrefslogtreecommitdiff
path: root/hostsidetests/appsecurity/test-apps/MediaStorageApp/src/com/android/cts/mediastorageapp/MediaStorageTest.java
blob: 48172303f0193b82d800a2ed7ca4e1faac0c5a6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.cts.mediastorageapp;

import static com.android.compatibility.common.util.SystemUtil.runShellCommand;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import android.app.Activity;
import android.app.Instrumentation;
import android.app.PendingIntent;
import android.app.RecoverableSecurityException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.FileUtils;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiSelector;

import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;

import com.android.cts.mediastorageapp.MediaStoreUtils.PendingParams;
import com.android.cts.mediastorageapp.MediaStoreUtils.PendingSession;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.Callable;

@RunWith(AndroidJUnit4.class)
public class MediaStorageTest {
    private static final File TEST_JPG = Environment.buildPath(
            Environment.getExternalStorageDirectory(),
            Environment.DIRECTORY_DOWNLOADS, "mediastoragetest_file1.jpg");
    private static final File TEST_PDF = Environment.buildPath(
            Environment.getExternalStorageDirectory(),
            Environment.DIRECTORY_DOWNLOADS, "mediastoragetest_file2.pdf");

    private Context mContext;
    private ContentResolver mContentResolver;
    private int mUserId;

    private static int currentAttempt = 0;
    private static final int MAX_NUMBER_OF_ATTEMPT = 10;

    @Before
    public void setUp() throws Exception {
        mContext = InstrumentationRegistry.getTargetContext();
        mContentResolver = mContext.getContentResolver();
        mUserId = mContext.getUserId();
    }

    @Test
    public void testSandboxed() throws Exception {
        doSandboxed(true);
    }

    @Test
    public void testNotSandboxed() throws Exception {
        doSandboxed(false);
    }

    @Test
    public void testStageFiles() throws Exception {
        final File jpg = stageFile(TEST_JPG);
        assertTrue(jpg.exists());
        final File pdf = stageFile(TEST_PDF);
        assertTrue(pdf.exists());
    }

    @Test
    public void testClearFiles() throws Exception {
        TEST_JPG.delete();
        assertNull(MediaStore.scanFile(mContentResolver, TEST_JPG));
        TEST_PDF.delete();
        assertNull(MediaStore.scanFile(mContentResolver, TEST_PDF));
    }

    private void doSandboxed(boolean sandboxed) throws Exception {
        assertEquals(!sandboxed, Environment.isExternalStorageLegacy());

        // We can always see mounted state
        assertEquals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState());

        // We might have top-level access
        final File probe = new File(Environment.getExternalStorageDirectory(),
                "cts" + System.nanoTime());
        if (!sandboxed) {
            assertTrue(probe.createNewFile());
            assertNotNull(Environment.getExternalStorageDirectory().list());
        }

        // We always have our package directories
        final File probePackage = new File(mContext.getExternalFilesDir(null),
                "cts" + System.nanoTime());
        assertTrue(probePackage.createNewFile());

        assertTrue(TEST_JPG.exists());
        assertTrue(TEST_PDF.exists());

        final Uri jpgUri = MediaStore.scanFile(mContentResolver, TEST_JPG);
        final Uri pdfUri = MediaStore.scanFile(mContentResolver, TEST_PDF);

        final HashSet<Long> seen = new HashSet<>();
        try (Cursor c = mContentResolver.query(
                MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL),
                new String[] { MediaColumns._ID }, null, null)) {
            while (c.moveToNext()) {
                seen.add(c.getLong(0));
            }
        }

        if (sandboxed) {
            // If we're sandboxed, we should only see the image
            assertTrue(seen.contains(ContentUris.parseId(jpgUri)));
            assertFalse(seen.contains(ContentUris.parseId(pdfUri)));
        } else {
            // If we're not sandboxed, we should see both
            assertTrue(seen.contains(ContentUris.parseId(jpgUri)));
            assertTrue(seen.contains(ContentUris.parseId(pdfUri)));
        }
    }

    @Test
    public void testMediaNone() throws Exception {
        doMediaNone(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createAudio);
        doMediaNone(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createVideo);
        doMediaNone(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createImage);

        // But since we don't hold the Music permission, we can't read the
        // indexed metadata
        try (Cursor c = mContentResolver.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
                null, null, null)) {
            assertEquals(0, c.getCount());
        }
        try (Cursor c = mContentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                null, null, null)) {
            assertEquals(0, c.getCount());
        }
        try (Cursor c = mContentResolver.query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,
                null, null, null)) {
            assertEquals(0, c.getCount());
        }
    }

    private void doMediaNone(Uri collection, Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        final Uri blue = create.call();

        clearMediaOwner(blue, mUserId);

        // Since we have no permissions, we should only be able to see media
        // that we've contributed
        final HashSet<Long> seen = new HashSet<>();
        try (Cursor c = mContentResolver.query(collection,
                new String[] { MediaColumns._ID }, null, null)) {
            while (c.moveToNext()) {
                seen.add(c.getLong(0));
            }
        }

        assertTrue(seen.contains(ContentUris.parseId(red)));
        assertFalse(seen.contains(ContentUris.parseId(blue)));

        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "rw")) {
        }
        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(blue, "r")) {
            fail("Expected read access to be blocked");
        } catch (SecurityException | FileNotFoundException expected) {
        }
        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(blue, "w")) {
            fail("Expected write access to be blocked");
        } catch (SecurityException | FileNotFoundException expected) {
        }
    }

    /**
     * Test prefix and non-prefix uri grant for all packages
     */
    @Test
    public void testGrantUriPermission() {
        final int flagGrantRead = Intent.FLAG_GRANT_READ_URI_PERMISSION;
        final int flagGrantWrite = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
        final int flagGrantReadPrefix =
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
        final int flagGrantWritePrefix =
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;

        for (Uri uri : new Uri[] {
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                MediaStore.Downloads.EXTERNAL_CONTENT_URI,
                MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL)
        }) {
            // Non-prefix grant
            checkGrantUriPermission(uri, flagGrantRead, true);
            checkGrantUriPermission(uri, flagGrantWrite, true);

            // Prefix grant
            checkGrantUriPermission(uri, flagGrantReadPrefix, false);
            checkGrantUriPermission(uri, flagGrantWritePrefix, false);
        }
    }

    private void checkGrantUriPermission(Uri uri, int mode, boolean isGrantAllowed) {
        if (isGrantAllowed) {
            mContext.grantUriPermission(mContext.getPackageName(), uri, mode);
        } else {
            try {
                mContext.grantUriPermission(mContext.getPackageName(), uri, mode);
                fail("Expected granting to be blocked for flag 0x" + Integer.toHexString(mode));
            } catch (SecurityException expected) {
            }
        }
    }

    @Test
    public void testMediaRead() throws Exception {
        doMediaRead(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createAudio);
        doMediaRead(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createVideo);
        doMediaRead(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createImage);
    }

    private void doMediaRead(Uri collection, Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        final Uri blue = create.call();

        clearMediaOwner(blue, mUserId);

        // Holding read permission we can see items we don't own
        final HashSet<Long> seen = new HashSet<>();
        try (Cursor c = mContentResolver.query(collection,
                new String[] { MediaColumns._ID }, null, null)) {
            while (c.moveToNext()) {
                seen.add(c.getLong(0));
            }
        }

        assertTrue(seen.contains(ContentUris.parseId(red)));
        assertTrue(seen.contains(ContentUris.parseId(blue)));

        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "rw")) {
        }
        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(blue, "r")) {
        }
        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(blue, "w")) {
            fail("Expected write access to be blocked");
        } catch (SecurityException | FileNotFoundException expected) {
        }
    }

    @Test
    public void testMediaWrite() throws Exception {
        doMediaWrite(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createAudio);
        doMediaWrite(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createVideo);
        doMediaWrite(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStorageTest::createImage);
    }

    private void doMediaWrite(Uri collection, Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        final Uri blue = create.call();

        clearMediaOwner(blue, mUserId);

        // Holding read permission we can see items we don't own
        final HashSet<Long> seen = new HashSet<>();
        try (Cursor c = mContentResolver.query(collection,
                new String[] { MediaColumns._ID }, null, null)) {
            while (c.moveToNext()) {
                seen.add(c.getLong(0));
            }
        }

        assertTrue(seen.contains(ContentUris.parseId(red)));
        assertTrue(seen.contains(ContentUris.parseId(blue)));

        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "rw")) {
        }
        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(blue, "r")) {
        }
        if (Environment.isExternalStorageLegacy()) {
            try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(blue, "w")) {
            }
        } else {
            try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(blue, "w")) {
                fail("Expected write access to be blocked");
            } catch (SecurityException | FileNotFoundException expected) {
            }
        }
    }

    @Test
    public void testMediaEscalation_Open() throws Exception {
        doMediaEscalation_Open(MediaStorageTest::createAudio);
        doMediaEscalation_Open(MediaStorageTest::createVideo);
        doMediaEscalation_Open(MediaStorageTest::createImage);
    }

    private void doMediaEscalation_Open(Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        clearMediaOwner(red, mUserId);

        RecoverableSecurityException exception = null;
        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "w")) {
            fail("Expected write access to be blocked");
        } catch (RecoverableSecurityException expected) {
            exception = expected;
        }

        doEscalation(exception);

        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "w")) {
        }
    }

    @Test
    public void testMediaEscalation_Update() throws Exception {
        doMediaEscalation_Update(MediaStorageTest::createAudio);
        doMediaEscalation_Update(MediaStorageTest::createVideo);
        doMediaEscalation_Update(MediaStorageTest::createImage);
    }

    private void doMediaEscalation_Update(Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        clearMediaOwner(red, mUserId);

        final ContentValues values = new ContentValues();
        values.put(MediaColumns.DISPLAY_NAME, "cts" + System.nanoTime());

        RecoverableSecurityException exception = null;
        try {
            mContentResolver.update(red, values, null, null);
            fail("Expected update access to be blocked");
        } catch (RecoverableSecurityException expected) {
            exception = expected;
        }

        doEscalation(exception);

        assertEquals(1, mContentResolver.update(red, values, null, null));
    }

    @Test
    public void testMediaEscalation_Delete() throws Exception {
        doMediaEscalation_Delete(MediaStorageTest::createAudio);
        doMediaEscalation_Delete(MediaStorageTest::createVideo);
        doMediaEscalation_Delete(MediaStorageTest::createImage);
    }

    private void doMediaEscalation_Delete(Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        clearMediaOwner(red, mUserId);

        RecoverableSecurityException exception = null;
        try {
            mContentResolver.delete(red, null, null);
            fail("Expected update access to be blocked");
        } catch (RecoverableSecurityException expected) {
            exception = expected;
        }

        doEscalation(exception);

        assertEquals(1, mContentResolver.delete(red, null, null));
    }

    @Test
    public void testMediaEscalation_RequestWriteFilePathSupport() throws Exception {
        doMediaEscalation_RequestWrite_withFilePathSupport(
                MediaStorageTest::createAudio);
        doMediaEscalation_RequestWrite_withFilePathSupport(
                MediaStorageTest::createVideo);
        doMediaEscalation_RequestWrite_withFilePathSupport(
                MediaStorageTest::createImage);
        doMediaEscalation_RequestWrite_withFilePathSupport(
                MediaStorageTest::createPlaylist);
        doMediaEscalation_RequestWrite_withFilePathSupport(
                MediaStorageTest::createSubtitle);
    }

    private void doMediaEscalation_RequestWrite_withFilePathSupport(
            Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        assertNotNull(red);
        String path = queryForSingleColumn(red, MediaColumns.DATA);
        File file = new File(path);
        assertTrue(file.exists());
        assertTrue(file.canRead());
        assertTrue(file.canWrite());

        clearMediaOwner(red, mUserId);
        assertFalse(file.canWrite());

        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "w")) {
            fail("Expected write access to be blocked");
        } catch (SecurityException expected) {
        }

        doEscalation(MediaStore.createWriteRequest(mContentResolver, Arrays.asList(red)));

        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "w")) {
        }

        final Instrumentation inst = InstrumentationRegistry.getInstrumentation();
        final UiDevice device = UiDevice.getInstance(inst);
        device.executeShellCommand("setprop sys.filepathsupport.mediauri true");
        assertTrue(file.canRead());
        assertTrue(file.canWrite());
        // TODO(b/173648980): Write to file and read back to verify.
        device.executeShellCommand("setprop sys.filepathsupport.mediauri false");
    }

    @Test
    public void testMediaEscalation_RequestWrite() throws Exception {
        doMediaEscalation_RequestWrite(MediaStorageTest::createAudio);
        doMediaEscalation_RequestWrite(MediaStorageTest::createVideo);
        doMediaEscalation_RequestWrite(MediaStorageTest::createImage);
        doMediaEscalation_RequestWrite(MediaStorageTest::createPlaylist);
        doMediaEscalation_RequestWrite(MediaStorageTest::createSubtitle);
    }

    private void doMediaEscalation_RequestWrite(Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        clearMediaOwner(red, mUserId);

        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "w")) {
            fail("Expected write access to be blocked");
        } catch (SecurityException expected) {
        }

        doEscalation(MediaStore.createWriteRequest(mContentResolver, Arrays.asList(red)));

        try (ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(red, "w")) {
        }
    }

    @Test
    public void testMediaEscalation_RequestTrash() throws Exception {
        doMediaEscalation_RequestTrash(MediaStorageTest::createAudio);
        doMediaEscalation_RequestTrash(MediaStorageTest::createVideo);
        doMediaEscalation_RequestTrash(MediaStorageTest::createImage);
        doMediaEscalation_RequestTrash(MediaStorageTest::createPlaylist);
        doMediaEscalation_RequestTrash(MediaStorageTest::createSubtitle);
    }

    private void doMediaEscalation_RequestTrash(Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        clearMediaOwner(red, mUserId);

        assertEquals("0", queryForSingleColumn(red, MediaColumns.IS_TRASHED));
        doEscalation(MediaStore.createTrashRequest(mContentResolver, Arrays.asList(red), true));
        assertEquals("1", queryForSingleColumn(red, MediaColumns.IS_TRASHED));
        doEscalation(MediaStore.createTrashRequest(mContentResolver, Arrays.asList(red), false));
        assertEquals("0", queryForSingleColumn(red, MediaColumns.IS_TRASHED));
    }

    @Test
    public void testMediaEscalation_RequestFavorite() throws Exception {
        doMediaEscalation_RequestFavorite(MediaStorageTest::createAudio);
        doMediaEscalation_RequestFavorite(MediaStorageTest::createVideo);
        doMediaEscalation_RequestFavorite(MediaStorageTest::createImage);
        doMediaEscalation_RequestFavorite(MediaStorageTest::createPlaylist);
        doMediaEscalation_RequestFavorite(MediaStorageTest::createSubtitle);
    }

    private void doMediaEscalation_RequestFavorite(Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        clearMediaOwner(red, mUserId);

        assertEquals("0", queryForSingleColumn(red, MediaColumns.IS_FAVORITE));
        doEscalation(MediaStore.createFavoriteRequest(mContentResolver, Arrays.asList(red), true));
        assertEquals("1", queryForSingleColumn(red, MediaColumns.IS_FAVORITE));
        doEscalation(MediaStore.createFavoriteRequest(mContentResolver, Arrays.asList(red), false));
        assertEquals("0", queryForSingleColumn(red, MediaColumns.IS_FAVORITE));
    }

    @Test
    public void testMediaEscalation_RequestDelete() throws Exception {
        doMediaEscalation_RequestDelete(MediaStorageTest::createAudio);
        doMediaEscalation_RequestDelete(MediaStorageTest::createVideo);
        doMediaEscalation_RequestDelete(MediaStorageTest::createImage);
        doMediaEscalation_RequestDelete(MediaStorageTest::createPlaylist);
        doMediaEscalation_RequestDelete(MediaStorageTest::createSubtitle);
    }

    private void doMediaEscalation_RequestDelete(Callable<Uri> create) throws Exception {
        final Uri red = create.call();
        clearMediaOwner(red, mUserId);

        try (Cursor c = mContentResolver.query(red, null, null, null)) {
            assertEquals(1, c.getCount());
        }
        doEscalation(MediaStore.createDeleteRequest(mContentResolver, Arrays.asList(red)));
        try (Cursor c = mContentResolver.query(red, null, null, null)) {
            assertEquals(0, c.getCount());
        }
    }

    private void doEscalation(RecoverableSecurityException exception) throws Exception {
        doEscalation(exception.getUserAction().getActionIntent());
    }

    private void doEscalation(PendingIntent pi) throws Exception {
        // Try launching the action to grant ourselves access
        final Instrumentation inst = InstrumentationRegistry.getInstrumentation();
        final Intent intent = new Intent(inst.getContext(), GetResultActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Wake up the device and dismiss the keyguard before the test starts
        final UiDevice device = UiDevice.getInstance(inst);
        device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
        device.executeShellCommand("wm dismiss-keyguard");

        final GetResultActivity activity = (GetResultActivity) inst.startActivitySync(intent);
        device.waitForIdle();
        activity.clearResult();
        activity.startIntentSenderForResult(pi.getIntentSender(), 42, null, 0, 0, 0);

        device.waitForIdle();

        // Some dialogs may have granted access automatically, so we're willing
        // to keep rolling forward if we can't find our grant button
        final UiSelector grant = new UiSelector().textMatches("(?i)Allow");
        if (new UiObject(grant).waitForExists(2_000)) {
            device.findObject(grant).click();
        }

        // Verify that we now have access
        final GetResultActivity.Result res = activity.getResult();
        assertEquals(Activity.RESULT_OK, res.resultCode);
    }

    private static Uri createAudio() throws IOException {
        final Context context = InstrumentationRegistry.getTargetContext();
        final String displayName = "cts" + System.nanoTime();
        final PendingParams params = new PendingParams(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, displayName, "audio/mpeg");
        final Uri pendingUri = MediaStoreUtils.createPending(context, params);
        try (PendingSession session = MediaStoreUtils.openPending(context, pendingUri)) {
            try (InputStream in = context.getResources().getAssets().open("testmp3.mp3");
                    OutputStream out = session.openOutputStream()) {
                FileUtils.copy(in, out);
            }
            return session.publish();
        }
    }

    private static Uri createVideo() throws IOException {
        final Context context = InstrumentationRegistry.getTargetContext();
        final String displayName = "cts" + System.nanoTime();
        final PendingParams params = new PendingParams(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, displayName, "video/mpeg");
        final Uri pendingUri = MediaStoreUtils.createPending(context, params);
        try (PendingSession session = MediaStoreUtils.openPending(context, pendingUri)) {
            try (InputStream in = context.getResources().getAssets().open("testmp3.mp3");
                    OutputStream out = session.openOutputStream()) {
                FileUtils.copy(in, out);
            }
            return session.publish();
        }
    }

    private static Uri createImage() throws IOException {
        final Context context = InstrumentationRegistry.getTargetContext();
        final String displayName = "cts" + System.nanoTime();
        final PendingParams params = new PendingParams(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, displayName, "image/png");
        final Uri pendingUri = MediaStoreUtils.createPending(context, params);
        try (PendingSession session = MediaStoreUtils.openPending(context, pendingUri)) {
            try (OutputStream out = session.openOutputStream()) {
                final Bitmap bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888);
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            }
            return session.publish();
        }
    }

    private static Uri createPlaylist() throws IOException {
        final Context context = InstrumentationRegistry.getTargetContext();
        final String displayName = "cts" + System.nanoTime();
        final PendingParams params = new PendingParams(
                MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, displayName, "audio/mpegurl");
        final Uri pendingUri = MediaStoreUtils.createPending(context, params);
        try (PendingSession session = MediaStoreUtils.openPending(context, pendingUri)) {
            return session.publish();
        }
    }

    private static Uri createSubtitle() throws IOException {
        final Context context = InstrumentationRegistry.getTargetContext();
        final String displayName = "cts" + System.nanoTime();
        final PendingParams params = new PendingParams(
                MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL), displayName,
                "application/x-subrip");
        final Uri pendingUri = MediaStoreUtils.createPending(context, params);
        try (PendingSession session = MediaStoreUtils.openPending(context, pendingUri)) {
            try (InputStream in = context.getResources().getAssets().open("testmp3.mp3");
                 OutputStream out = session.openOutputStream()) {
                 FileUtils.copy(in, out);
            }
            return session.publish();
        }
    }

    private static String queryForSingleColumn(Uri uri, String column) throws Exception {
        final ContentResolver resolver = InstrumentationRegistry.getTargetContext()
                .getContentResolver();
        try (Cursor c = resolver.query(uri, new String[] { column }, null, null)) {
            assertEquals(c.getCount(), 1);
            assertTrue(c.moveToFirst());
            return c.getString(0);
        }
    }

    private static void clearMediaOwner(Uri uri, int userId) throws IOException {
        final String cmd = String.format(
                "content update --uri %s --user %d --bind owner_package_name:n:",
                uri, userId);
        runShellCommand(InstrumentationRegistry.getInstrumentation(), cmd);
    }

    static File stageFile(File file) throws Exception {
        // Sometimes file creation fails due to slow permission update, try more times 
        while(currentAttempt < MAX_NUMBER_OF_ATTEMPT) {
            try {
                file.getParentFile().mkdirs();
                file.createNewFile();
                return file;
            } catch(IOException e) {
                currentAttempt++;
                // wait 500ms
                Thread.sleep(500);
            }
        } 
        return file;
    }
}