• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.appenumeration.cts;
18 
19 import static android.Manifest.permission.SET_PREFERRED_APPLICATIONS;
20 import static android.appenumeration.cts.Constants.ACTION_APP_ENUMERATION_PREFERRED_ACTIVITY;
21 import static android.appenumeration.cts.Constants.ACTION_BIND_SERVICE;
22 import static android.appenumeration.cts.Constants.ACTION_CAN_PACKAGE_QUERIES;
23 import static android.appenumeration.cts.Constants.ACTION_CAN_PACKAGE_QUERY;
24 import static android.appenumeration.cts.Constants.ACTION_CHECK_PACKAGE;
25 import static android.appenumeration.cts.Constants.ACTION_CHECK_SIGNATURES;
26 import static android.appenumeration.cts.Constants.ACTION_CHECK_URI_PERMISSION;
27 import static android.appenumeration.cts.Constants.ACTION_CHECK_CONTENT_URI_PERMISSION_FULL;
28 import static android.appenumeration.cts.Constants.ACTION_GET_CONTENT_PROVIDER_MIME_TYPE;
29 import static android.appenumeration.cts.Constants.ACTION_GET_INSTALLED_ACCESSIBILITYSERVICES_PACKAGES;
30 import static android.appenumeration.cts.Constants.ACTION_GET_INSTALLED_APPWIDGET_PROVIDERS;
31 import static android.appenumeration.cts.Constants.ACTION_GET_INSTALLED_PACKAGES;
32 import static android.appenumeration.cts.Constants.ACTION_GET_NAMES_FOR_UIDS;
33 import static android.appenumeration.cts.Constants.ACTION_GET_NAME_FOR_UID;
34 import static android.appenumeration.cts.Constants.ACTION_GET_PACKAGES_FOR_UID;
35 import static android.appenumeration.cts.Constants.ACTION_GET_PACKAGE_INFO;
36 import static android.appenumeration.cts.Constants.ACTION_GET_PREFERRED_ACTIVITIES;
37 import static android.appenumeration.cts.Constants.ACTION_GET_SHAREDLIBRARY_DEPENDENT_PACKAGES;
38 import static android.appenumeration.cts.Constants.ACTION_GRANT_URI_PERMISSION;
39 import static android.appenumeration.cts.Constants.ACTION_HAS_SIGNING_CERTIFICATE;
40 import static android.appenumeration.cts.Constants.ACTION_JUST_FINISH;
41 import static android.appenumeration.cts.Constants.ACTION_MANIFEST_ACTIVITY;
42 import static android.appenumeration.cts.Constants.ACTION_MANIFEST_PROVIDER;
43 import static android.appenumeration.cts.Constants.ACTION_MANIFEST_SERVICE;
44 import static android.appenumeration.cts.Constants.ACTION_MANIFEST_UNEXPORTED_ACTIVITY;
45 import static android.appenumeration.cts.Constants.ACTION_PENDING_INTENT_GET_ACTIVITY;
46 import static android.appenumeration.cts.Constants.ACTION_PENDING_INTENT_GET_CREATOR_PACKAGE;
47 import static android.appenumeration.cts.Constants.ACTION_QUERY_ACTIVITIES;
48 import static android.appenumeration.cts.Constants.ACTION_QUERY_PROVIDERS;
49 import static android.appenumeration.cts.Constants.ACTION_QUERY_RESOLVER;
50 import static android.appenumeration.cts.Constants.ACTION_QUERY_SERVICES;
51 import static android.appenumeration.cts.Constants.ACTION_REVOKE_URI_PERMISSION;
52 import static android.appenumeration.cts.Constants.ACTION_SEND_RESULT;
53 import static android.appenumeration.cts.Constants.ACTION_SET_INSTALLER_PACKAGE_NAME;
54 import static android.appenumeration.cts.Constants.ACTION_START_DIRECTLY;
55 import static android.appenumeration.cts.Constants.ACTION_START_FOR_RESULT;
56 import static android.appenumeration.cts.Constants.ACTION_TAKE_PERSISTABLE_URI_PERMISSION;
57 import static android.appenumeration.cts.Constants.ACTIVITY_CLASS_DUMMY_ACTIVITY;
58 import static android.appenumeration.cts.Constants.ACTIVITY_CLASS_NOT_EXPORTED;
59 import static android.appenumeration.cts.Constants.ACTIVITY_CLASS_PERMISSION_PROTECTED;
60 import static android.appenumeration.cts.Constants.ACTIVITY_CLASS_TEST;
61 import static android.appenumeration.cts.Constants.AUTHORITY_SUFFIX;
62 import static android.appenumeration.cts.Constants.EXTRA_AUTHORITY;
63 import static android.appenumeration.cts.Constants.EXTRA_CERT;
64 import static android.appenumeration.cts.Constants.EXTRA_DATA;
65 import static android.appenumeration.cts.Constants.EXTRA_FLAGS;
66 import static android.appenumeration.cts.Constants.EXTRA_PENDING_INTENT;
67 import static android.appenumeration.cts.Constants.QUERIES_ACTIVITY_ACTION;
68 import static android.appenumeration.cts.Constants.QUERIES_NOTHING;
69 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_APK;
70 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_PERM;
71 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_PROVIDER;
72 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_PROVIDER_APK;
73 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_Q;
74 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_RECEIVES_NON_PERSISTABLE_URI;
75 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_RECEIVES_NON_PERSISTABLE_URI_APK;
76 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_RECEIVES_PERM_URI;
77 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_RECEIVES_PERM_URI_APK;
78 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI;
79 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI_APK;
80 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_RECEIVES_URI;
81 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_RECEIVES_URI_APK;
82 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_SEES_INSTALLER;
83 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_SEES_INSTALLER_APK;
84 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_SHARED_USER;
85 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_USES_LIBRARY;
86 import static android.appenumeration.cts.Constants.QUERIES_NOTHING_USES_OPTIONAL_LIBRARY;
87 import static android.appenumeration.cts.Constants.QUERIES_PACKAGE;
88 import static android.appenumeration.cts.Constants.QUERIES_PACKAGE_PROVIDER;
89 import static android.appenumeration.cts.Constants.QUERIES_PROVIDER_ACTION;
90 import static android.appenumeration.cts.Constants.QUERIES_PROVIDER_AUTH;
91 import static android.appenumeration.cts.Constants.QUERIES_SERVICE_ACTION;
92 import static android.appenumeration.cts.Constants.QUERIES_UNEXPORTED_ACTIVITY_ACTION;
93 import static android.appenumeration.cts.Constants.QUERIES_UNEXPORTED_PROVIDER_ACTION;
94 import static android.appenumeration.cts.Constants.QUERIES_UNEXPORTED_PROVIDER_AUTH;
95 import static android.appenumeration.cts.Constants.QUERIES_UNEXPORTED_SERVICE_ACTION;
96 import static android.appenumeration.cts.Constants.QUERIES_WILDCARD_ACTION;
97 import static android.appenumeration.cts.Constants.QUERIES_WILDCARD_BROWSABLE;
98 import static android.appenumeration.cts.Constants.QUERIES_WILDCARD_BROWSER;
99 import static android.appenumeration.cts.Constants.QUERIES_WILDCARD_CONTACTS;
100 import static android.appenumeration.cts.Constants.QUERIES_WILDCARD_EDITOR;
101 import static android.appenumeration.cts.Constants.QUERIES_WILDCARD_SHARE;
102 import static android.appenumeration.cts.Constants.QUERIES_WILDCARD_WEB;
103 import static android.appenumeration.cts.Constants.SERVICE_CLASS_SELF_VISIBILITY_SERVICE;
104 import static android.appenumeration.cts.Constants.SPLIT_BASE_APK;
105 import static android.appenumeration.cts.Constants.SPLIT_FEATURE_APK;
106 import static android.appenumeration.cts.Constants.SPLIT_PKG;
107 import static android.appenumeration.cts.Constants.TARGET_APPWIDGETPROVIDER;
108 import static android.appenumeration.cts.Constants.TARGET_APPWIDGETPROVIDER_SHARED_USER;
109 import static android.appenumeration.cts.Constants.TARGET_BROWSER;
110 import static android.appenumeration.cts.Constants.TARGET_BROWSER_WILDCARD;
111 import static android.appenumeration.cts.Constants.TARGET_CONTACTS;
112 import static android.appenumeration.cts.Constants.TARGET_EDITOR;
113 import static android.appenumeration.cts.Constants.TARGET_FILTERS;
114 import static android.appenumeration.cts.Constants.TARGET_FILTERS_APK;
115 import static android.appenumeration.cts.Constants.TARGET_FORCEQUERYABLE;
116 import static android.appenumeration.cts.Constants.TARGET_FORCEQUERYABLE_NORMAL;
117 import static android.appenumeration.cts.Constants.TARGET_NO_API;
118 import static android.appenumeration.cts.Constants.TARGET_PREFERRED_ACTIVITY;
119 import static android.appenumeration.cts.Constants.TARGET_PREFIX_WILDCARD_WEB;
120 import static android.appenumeration.cts.Constants.TARGET_SHARE;
121 import static android.appenumeration.cts.Constants.TARGET_SHARED_LIBRARY_PACKAGE;
122 import static android.appenumeration.cts.Constants.TARGET_SHARED_USER;
123 import static android.appenumeration.cts.Constants.TARGET_STUB;
124 import static android.appenumeration.cts.Constants.TARGET_STUB_APK;
125 import static android.appenumeration.cts.Constants.TARGET_SYNCADAPTER;
126 import static android.appenumeration.cts.Constants.TARGET_WEB;
127 import static android.appenumeration.cts.Constants.TEST_NONEXISTENT_PACKAGE_NAME_1;
128 import static android.appenumeration.cts.Constants.TEST_NONEXISTENT_PACKAGE_NAME_2;
129 import static android.appenumeration.cts.Constants.TEST_SHARED_LIB_NAME;
130 import static android.appenumeration.cts.Utils.Result;
131 import static android.appenumeration.cts.Utils.ThrowingBiFunction;
132 import static android.appenumeration.cts.Utils.allowTestApiAccess;
133 import static android.appenumeration.cts.Utils.clearAppDataForUser;
134 import static android.appenumeration.cts.Utils.ensurePackageIsInstalled;
135 import static android.appenumeration.cts.Utils.ensurePackageIsNotInstalled;
136 import static android.appenumeration.cts.Utils.forceStopPackage;
137 import static android.appenumeration.cts.Utils.installPackage;
138 import static android.appenumeration.cts.Utils.resetTestApiAccess;
139 import static android.appenumeration.cts.Utils.suspendPackages;
140 import static android.appenumeration.cts.Utils.uninstallPackage;
141 import static android.content.Intent.EXTRA_PACKAGES;
142 import static android.content.Intent.EXTRA_UID;
143 import static android.content.pm.PackageManager.GET_SIGNING_CERTIFICATES;
144 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
145 import static android.content.pm.PackageManager.SIGNATURE_MATCH;
146 import static android.content.pm.PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
147 import static android.os.Process.INVALID_UID;
148 import static android.os.Process.ROOT_UID;
149 
150 import static org.hamcrest.MatcherAssert.assertThat;
151 import static org.hamcrest.Matchers.allOf;
152 import static org.hamcrest.Matchers.arrayContaining;
153 import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
154 import static org.hamcrest.Matchers.arrayWithSize;
155 import static org.hamcrest.Matchers.containsString;
156 import static org.hamcrest.Matchers.emptyOrNullString;
157 import static org.hamcrest.Matchers.equalTo;
158 import static org.hamcrest.Matchers.greaterThan;
159 import static org.hamcrest.Matchers.greaterThanOrEqualTo;
160 import static org.hamcrest.core.Is.is;
161 import static org.junit.Assert.assertEquals;
162 import static org.junit.Assert.assertFalse;
163 import static org.junit.Assert.assertNotNull;
164 import static org.junit.Assert.assertThrows;
165 import static org.junit.Assert.assertTrue;
166 import static org.junit.Assert.fail;
167 import static org.junit.Assume.assumeFalse;
168 import static org.junit.Assume.assumeTrue;
169 
170 import android.Manifest;
171 import android.app.PendingIntent;
172 import android.appwidget.AppWidgetProviderInfo;
173 import android.content.ActivityNotFoundException;
174 import android.content.ComponentName;
175 import android.content.Intent;
176 import android.content.IntentFilter;
177 import android.content.pm.PackageInfo;
178 import android.content.pm.PackageManager;
179 import android.content.pm.PackageManager.PackageInfoFlags;
180 import android.content.pm.ServiceInfo;
181 import android.content.pm.Signature;
182 import android.content.res.Resources;
183 import android.net.Uri;
184 import android.os.Bundle;
185 import android.platform.test.annotations.RequiresFlagsEnabled;
186 import android.platform.test.flag.junit.CheckFlagsRule;
187 import android.platform.test.flag.junit.DeviceFlagsValueProvider;
188 
189 import androidx.test.filters.LargeTest;
190 
191 import com.android.bedstead.nene.users.UserReference;
192 import com.android.compatibility.common.util.AmUtils;
193 import com.android.compatibility.common.util.SystemUtil;
194 
195 import org.hamcrest.core.IsNull;
196 import org.junit.After;
197 import org.junit.Assert;
198 import org.junit.Before;
199 import org.junit.Rule;
200 import org.junit.Test;
201 import org.junit.runner.RunWith;
202 import org.junit.runners.Parameterized;
203 
204 import java.io.ByteArrayInputStream;
205 import java.io.InputStream;
206 import java.io.PrintWriter;
207 import java.io.StringWriter;
208 import java.security.cert.Certificate;
209 import java.security.cert.CertificateFactory;
210 import java.security.cert.X509Certificate;
211 import java.util.ArrayList;
212 import java.util.Arrays;
213 import java.util.List;
214 
215 @RunWith(Parameterized.class)
216 public class AppEnumerationTests extends AppEnumerationTestsBase {
217 
218     private static final String SKIP_APP_FILTER_CACHE = "0";
219     private static final String USE_APP_FILTER_CACHE = "1";
220 
221     @Rule
222     public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
223 
224     @Parameterized.Parameter
225     public String mUseAppFilterCache;
226 
227     @Parameterized.Parameters
initParameters()228     public static Iterable<Object> initParameters() {
229         return Arrays.asList(SKIP_APP_FILTER_CACHE, USE_APP_FILTER_CACHE);
230     }
231 
232     @Before
onBefore()233     public void onBefore() throws Exception {
234         setSystemProperty("debug.pm.use_app_filter_cache", mUseAppFilterCache);
235     }
236 
237     @After
onAfter()238     public void onAfter() throws Exception {
239         setSystemProperty("debug.pm.use_app_filter_cache", "invalid");
240     }
241 
242     @Test
systemPackagesQueryable_notEnabled()243     public void systemPackagesQueryable_notEnabled() throws Exception {
244         final Resources resources = Resources.getSystem();
245         assertFalse(
246                 "config_forceSystemPackagesQueryable must not be true.",
247                 resources.getBoolean(resources.getIdentifier(
248                         "config_forceSystemPackagesQueryable", "bool", "android")));
249 
250         // now let's assert that the actual set of system apps is limited
251         assertThat("Not all system apps should be visible.",
252                 getInstalledPackages(QUERIES_NOTHING_PERM, MATCH_SYSTEM_ONLY).length,
253                 greaterThan(getInstalledPackages(QUERIES_NOTHING, MATCH_SYSTEM_ONLY).length));
254     }
255 
256     @Test
all_canSeeForceQueryable()257     public void all_canSeeForceQueryable() throws Exception {
258         assertVisible(QUERIES_NOTHING, TARGET_FORCEQUERYABLE);
259         assertVisible(QUERIES_ACTIVITY_ACTION, TARGET_FORCEQUERYABLE);
260         assertVisible(QUERIES_SERVICE_ACTION, TARGET_FORCEQUERYABLE);
261         assertVisible(QUERIES_PROVIDER_AUTH, TARGET_FORCEQUERYABLE);
262         assertVisible(QUERIES_PACKAGE, TARGET_FORCEQUERYABLE);
263     }
264 
265     @Test
all_cannotSeeForceQueryableInstalledNormally()266     public void all_cannotSeeForceQueryableInstalledNormally() throws Exception {
267         assertNotVisible(QUERIES_NOTHING, TARGET_FORCEQUERYABLE_NORMAL);
268         assertNotVisible(QUERIES_ACTIVITY_ACTION, TARGET_FORCEQUERYABLE_NORMAL);
269         assertNotVisible(QUERIES_SERVICE_ACTION, TARGET_FORCEQUERYABLE_NORMAL);
270         assertNotVisible(QUERIES_PROVIDER_AUTH, TARGET_FORCEQUERYABLE_NORMAL);
271         assertNotVisible(QUERIES_PACKAGE, TARGET_FORCEQUERYABLE_NORMAL);
272     }
273 
274     @Test
startExplicitly_canStartNonVisible()275     public void startExplicitly_canStartNonVisible() throws Exception {
276         assertNotVisible(QUERIES_NOTHING, TARGET_FILTERS);
277         startExplicitIntentViaComponent(QUERIES_NOTHING, TARGET_FILTERS);
278         startExplicitIntentViaPackageName(QUERIES_NOTHING, TARGET_FILTERS);
279     }
280 
281     @Test
startExplicitly_cannotStartNonVisibleNonExported()282     public void startExplicitly_cannotStartNonVisibleNonExported() throws Exception {
283         assertNotVisible(QUERIES_NOTHING, TARGET_FILTERS);
284         Assert.assertThrows("Start of non-exported activity should act as if app not installed",
285                 ActivityNotFoundException.class,
286                 () -> startExplicitIntentNotExportedViaComponent(
287                         QUERIES_NOTHING, TARGET_FILTERS));
288     }
289 
290     @Test
startExplicitly_cannotStartVisibleNonExported()291     public void startExplicitly_cannotStartVisibleNonExported() throws Exception {
292         assertVisible(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS);
293         Assert.assertThrows("Start of non-exported activity should fail with SecurityException",
294                 SecurityException.class,
295                 () -> startExplicitIntentNotExportedViaComponent(
296                         QUERIES_ACTIVITY_ACTION, TARGET_FILTERS));
297     }
298 
299     @Test
startExplicitly_canStartVisible()300     public void startExplicitly_canStartVisible() throws Exception {
301         assertVisible(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS);
302         startExplicitIntentViaComponent(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS);
303         startExplicitIntentViaPackageName(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS);
304     }
305 
306     @Test
startExplicitly_activityPermissionProtected_canSeeTarget()307     public void startExplicitly_activityPermissionProtected_canSeeTarget() {
308         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
309         Assert.assertThrows(SecurityException.class,
310                 () -> startExplicitPermissionProtectedIntentViaComponent(
311                         QUERIES_ACTIVITY_ACTION, TARGET_STUB));
312         Assert.assertThrows(SecurityException.class,
313                 () -> startExplicitIntentViaPackageName(QUERIES_ACTIVITY_ACTION, TARGET_STUB));
314     }
315 
316     @Test
startExplicitly_activityPermissionProtected_cannotSeeTarget()317     public void startExplicitly_activityPermissionProtected_cannotSeeTarget() {
318         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
319         Assert.assertThrows(ActivityNotFoundException.class,
320                 () -> startExplicitPermissionProtectedIntentViaComponent(
321                         QUERIES_NOTHING, TARGET_STUB));
322         Assert.assertThrows(ActivityNotFoundException.class,
323                 () -> startExplicitIntentViaPackageName(QUERIES_NOTHING, TARGET_STUB));
324     }
325 
326     @Test
startImplicitly_canStartNonVisible()327     public void startImplicitly_canStartNonVisible() throws Exception {
328         assertNotVisible(QUERIES_NOTHING, TARGET_FILTERS);
329         startImplicitIntent(QUERIES_NOTHING);
330     }
331 
332     @Test
startActivityWithNoPermissionUri_canSeeProvider()333     public void startActivityWithNoPermissionUri_canSeeProvider() throws Exception {
334         uninstallPackage(QUERIES_NOTHING_RECEIVES_URI);
335         installPackage(QUERIES_NOTHING_RECEIVES_URI_APK);
336 
337         assertNotVisible(QUERIES_NOTHING_RECEIVES_URI, QUERIES_NOTHING_PERM);
338 
339         // send with uri but no grant flags; shouldn't be visible
340         startExplicitActivityWithIntent(QUERIES_NOTHING_PERM, QUERIES_NOTHING_RECEIVES_URI,
341                 new Intent(ACTION_JUST_FINISH)
342                         .setData(Uri.parse("content://" + QUERIES_NOTHING_PERM + "/test")));
343         assertNotVisible(QUERIES_NOTHING_RECEIVES_URI, QUERIES_NOTHING_PERM);
344 
345         // send again with uri bug grant flags now set; should be visible
346         startExplicitActivityWithIntent(QUERIES_NOTHING_PERM, QUERIES_NOTHING_RECEIVES_URI,
347                 new Intent(ACTION_JUST_FINISH)
348                         .setData(Uri.parse("content://" + QUERIES_NOTHING_PERM + "/test"))
349                         .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION));
350         assertVisible(QUERIES_NOTHING_RECEIVES_URI, QUERIES_NOTHING_PERM);
351     }
352 
353     @Test
startActivityWithUri_canSeePermissionProtectedProvider()354     public void startActivityWithUri_canSeePermissionProtectedProvider() throws Exception {
355         uninstallPackage(QUERIES_NOTHING_RECEIVES_PERM_URI);
356         installPackage(QUERIES_NOTHING_RECEIVES_PERM_URI_APK);
357 
358         assertNotVisible(QUERIES_NOTHING_RECEIVES_PERM_URI, QUERIES_NOTHING_PERM);
359 
360         // send with uri but no grant flags; shouldn't be visible
361         // Setting a dummy type to mitigate test failure. Bug: b/273465805
362         startExplicitActivityWithIntent(QUERIES_NOTHING_PERM, QUERIES_NOTHING_RECEIVES_PERM_URI,
363                 new Intent(ACTION_JUST_FINISH)
364                         .setDataAndType(
365                                 Uri.parse("content://" + QUERIES_NOTHING_PERM + "2/test"),
366                                 "null"));
367 
368         assertNotVisible(QUERIES_NOTHING_RECEIVES_PERM_URI, QUERIES_NOTHING_PERM);
369 
370         // send again with uri bug grant flags now set; should be visible
371         startExplicitActivityWithIntent(QUERIES_NOTHING_PERM, QUERIES_NOTHING_RECEIVES_PERM_URI,
372                 new Intent(ACTION_JUST_FINISH)
373                         .setDataAndType(
374                                 Uri.parse("content://" + QUERIES_NOTHING_PERM + "2/test"),
375                                 "null")
376                         .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION));
377         assertVisible(QUERIES_NOTHING_RECEIVES_PERM_URI, QUERIES_NOTHING_PERM);
378     }
379 
380     @Test
startActivityWithUriGrant_cannotSeeProviderAfterUpdated()381     public void startActivityWithUriGrant_cannotSeeProviderAfterUpdated() throws Exception {
382         assertNotVisible(QUERIES_NOTHING_RECEIVES_NON_PERSISTABLE_URI, QUERIES_NOTHING_PERM);
383 
384         // send with uri grant flags; should be visible
385         // Setting a dummy type to mitigate test failure. Bug: b/273465805
386         startExplicitActivityWithIntent(QUERIES_NOTHING_PERM,
387                 QUERIES_NOTHING_RECEIVES_NON_PERSISTABLE_URI,
388                 new Intent(ACTION_JUST_FINISH)
389                         .setDataAndType(
390                                 Uri.parse("content://" + QUERIES_NOTHING_PERM + "3/test"),
391                                 "null")
392                         .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION));
393         assertVisible(QUERIES_NOTHING_RECEIVES_NON_PERSISTABLE_URI, QUERIES_NOTHING_PERM);
394 
395         // update the package; shouldn't be visible
396         installPackage(QUERIES_NOTHING_RECEIVES_NON_PERSISTABLE_URI_APK);
397         // Wait until the updating is done
398         AmUtils.waitForBroadcastBarrier();
399         assertNotVisible(QUERIES_NOTHING_RECEIVES_NON_PERSISTABLE_URI, QUERIES_NOTHING_PERM);
400     }
401 
402     @Test
startActivityWithPersistableUriGrant_canSeeProviderAfterUpdated()403     public void startActivityWithPersistableUriGrant_canSeeProviderAfterUpdated() throws Exception {
404         uninstallPackage(QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI);
405         installPackage(QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI_APK);
406 
407         assertNotVisible(QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI, QUERIES_NOTHING_PERM);
408 
409         // send with persistable uri grant flags; should be visible
410         // Setting a dummy type to mitigate test failure. Bug: b/273465805
411         startExplicitActivityWithIntent(QUERIES_NOTHING_PERM,
412                 QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI,
413                 new Intent(ACTION_TAKE_PERSISTABLE_URI_PERMISSION)
414                         .setDataAndType(
415                                 Uri.parse("content://" + QUERIES_NOTHING_PERM + "3/test"),
416                                 "null")
417                         .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
418                                 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
419         assertVisible(QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI, QUERIES_NOTHING_PERM);
420 
421         // update the package; should be still visible
422         installPackage(QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI_APK);
423         // Wait until the updating is done
424         AmUtils.waitForBroadcastBarrier();
425         assertVisible(QUERIES_NOTHING_RECEIVES_PERSISTABLE_URI, QUERIES_NOTHING_PERM);
426     }
427 
startExplicitActivityWithIntent( String sourcePackageName, String targetPackageName, Intent intent)428     private void startExplicitActivityWithIntent(
429             String sourcePackageName, String targetPackageName, Intent intent) throws Exception {
430         sendCommandBlocking(sourcePackageName, targetPackageName,
431                 intent.setClassName(targetPackageName, ACTIVITY_CLASS_TEST),
432                 ACTION_START_DIRECTLY);
433     }
434 
435     @Test
queriesNothing_cannotSeeNonForceQueryable()436     public void queriesNothing_cannotSeeNonForceQueryable() throws Exception {
437         assertNotVisible(QUERIES_NOTHING, TARGET_NO_API);
438         assertNotVisible(QUERIES_NOTHING, TARGET_FILTERS);
439     }
440 
441     @Test
queriesNothingTargetsQ_canSeeAll()442     public void queriesNothingTargetsQ_canSeeAll() throws Exception {
443         assertVisible(QUERIES_NOTHING_Q, TARGET_FORCEQUERYABLE);
444         assertVisible(QUERIES_NOTHING_Q, TARGET_NO_API);
445         assertVisible(QUERIES_NOTHING_Q, TARGET_FILTERS);
446     }
447 
448     @Test
queriesNothingHasPermission_canSeeAll()449     public void queriesNothingHasPermission_canSeeAll() throws Exception {
450         assertVisible(QUERIES_NOTHING_PERM, TARGET_FORCEQUERYABLE);
451         assertVisible(QUERIES_NOTHING_PERM, TARGET_NO_API);
452         assertVisible(QUERIES_NOTHING_PERM, TARGET_FILTERS);
453     }
454 
455     @Test
queriesNothing_cannotSeeFilters()456     public void queriesNothing_cannotSeeFilters() throws Exception {
457         assertNotQueryable(QUERIES_NOTHING, TARGET_FILTERS,
458                 ACTION_MANIFEST_ACTIVITY, this::queryIntentActivities);
459         assertNotQueryable(QUERIES_NOTHING, TARGET_FILTERS,
460                 ACTION_MANIFEST_SERVICE, this::queryIntentServices);
461         assertNotQueryable(QUERIES_NOTHING, TARGET_FILTERS,
462                 ACTION_MANIFEST_PROVIDER, this::queryIntentProviders);
463     }
464 
465     @Test
queriesActivityAction_canSeeFilters()466     public void queriesActivityAction_canSeeFilters() throws Exception {
467         assertQueryable(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS,
468                 ACTION_MANIFEST_ACTIVITY, this::queryIntentActivities);
469         assertQueryable(QUERIES_SERVICE_ACTION, TARGET_FILTERS,
470                 ACTION_MANIFEST_SERVICE, this::queryIntentServices);
471         assertQueryable(QUERIES_PROVIDER_AUTH, TARGET_FILTERS,
472                 ACTION_MANIFEST_PROVIDER, this::queryIntentProviders);
473         assertQueryable(QUERIES_PROVIDER_ACTION, TARGET_FILTERS,
474                 ACTION_MANIFEST_PROVIDER, this::queryIntentProviders);
475     }
476 
477     @Test
queriesNothingHasPermission_canSeeFilters()478     public void queriesNothingHasPermission_canSeeFilters() throws Exception {
479         assertQueryable(QUERIES_NOTHING_PERM, TARGET_FILTERS,
480                 ACTION_MANIFEST_ACTIVITY, this::queryIntentActivities);
481         assertQueryable(QUERIES_NOTHING_PERM, TARGET_FILTERS,
482                 ACTION_MANIFEST_SERVICE, this::queryIntentServices);
483         assertQueryable(QUERIES_NOTHING_PERM, TARGET_FILTERS,
484                 ACTION_MANIFEST_PROVIDER, this::queryIntentProviders);
485     }
486 
487     @Test
queriesSomething_cannotSeeNoApi()488     public void queriesSomething_cannotSeeNoApi() throws Exception {
489         assertNotVisible(QUERIES_ACTIVITY_ACTION, TARGET_NO_API);
490         assertNotVisible(QUERIES_SERVICE_ACTION, TARGET_NO_API);
491         assertNotVisible(QUERIES_PROVIDER_AUTH, TARGET_NO_API);
492         assertNotVisible(QUERIES_PROVIDER_ACTION, TARGET_NO_API);
493     }
494 
495     @Test
queriesActivityAction_canSeeTarget()496     public void queriesActivityAction_canSeeTarget() throws Exception {
497         assertVisible(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS);
498     }
499 
500     @Test
queriesServiceAction_canSeeTarget()501     public void queriesServiceAction_canSeeTarget() throws Exception {
502         assertVisible(QUERIES_SERVICE_ACTION, TARGET_FILTERS);
503     }
504 
505     @Test
queriesWildcardAction_canSeeTargets()506     public void queriesWildcardAction_canSeeTargets() throws Exception {
507         assertVisible(QUERIES_WILDCARD_ACTION, TARGET_FILTERS);
508     }
509 
510     @Test
queriesProviderAuthority_canSeeTarget()511     public void queriesProviderAuthority_canSeeTarget() throws Exception {
512         assertVisible(QUERIES_PROVIDER_AUTH, TARGET_FILTERS);
513     }
514 
515     @Test
queriesProviderAction_canSeeTarget()516     public void queriesProviderAction_canSeeTarget() throws Exception {
517         assertVisible(QUERIES_PROVIDER_ACTION, TARGET_FILTERS);
518     }
519 
520     @Test
queriesActivityAction_cannotSeeUnexportedTarget()521     public void queriesActivityAction_cannotSeeUnexportedTarget() throws Exception {
522         assertNotVisible(QUERIES_UNEXPORTED_ACTIVITY_ACTION, TARGET_FILTERS);
523     }
524 
525     @Test
queriesServiceAction_cannotSeeUnexportedTarget()526     public void queriesServiceAction_cannotSeeUnexportedTarget() throws Exception {
527         assertNotVisible(QUERIES_UNEXPORTED_SERVICE_ACTION, TARGET_FILTERS);
528     }
529 
530     @Test
queriesProviderAuthority_cannotSeeUnexportedTarget()531     public void queriesProviderAuthority_cannotSeeUnexportedTarget() throws Exception {
532         assertNotVisible(QUERIES_UNEXPORTED_PROVIDER_AUTH, TARGET_FILTERS);
533     }
534 
535     @Test
queriesProviderAction_cannotSeeUnexportedTarget()536     public void queriesProviderAction_cannotSeeUnexportedTarget() throws Exception {
537         assertNotVisible(QUERIES_UNEXPORTED_PROVIDER_ACTION, TARGET_FILTERS);
538     }
539 
540     @Test
queriesPackage_canSeeTarget()541     public void queriesPackage_canSeeTarget() throws Exception {
542         assertVisible(QUERIES_PACKAGE, TARGET_NO_API);
543     }
544 
545     @Test
queriesNothing_canSeeInstaller()546     public void queriesNothing_canSeeInstaller() throws Exception {
547         uninstallPackage(QUERIES_NOTHING_SEES_INSTALLER);
548         installPackage(QUERIES_NOTHING_SEES_INSTALLER_APK, TARGET_NO_API);
549         try {
550             assertVisible(QUERIES_NOTHING_SEES_INSTALLER, TARGET_NO_API);
551         } finally {
552             uninstallPackage(QUERIES_NOTHING_SEES_INSTALLER);
553         }
554     }
555 
556     @Test
whenStarted_canSeeCaller()557     public void whenStarted_canSeeCaller() throws Exception {
558         uninstallPackage(QUERIES_NOTHING);
559         installPackage(QUERIES_NOTHING_APK);
560 
561         // let's first make sure that the target cannot see the caller.
562         assertNotVisible(QUERIES_NOTHING, QUERIES_NOTHING_PERM);
563         // now let's start the target and make sure that it can see the caller as part of that call
564         PackageInfo packageInfo = startForResult(QUERIES_NOTHING_PERM, QUERIES_NOTHING);
565         assertThat(packageInfo, IsNull.notNullValue());
566         assertThat(packageInfo.packageName, is(QUERIES_NOTHING_PERM));
567         // and finally let's re-run the last check to make sure that the target can still see the
568         // caller
569         assertVisible(QUERIES_NOTHING, QUERIES_NOTHING_PERM);
570     }
571 
572     @Test
whenStartedViaIntentSender_canSeeCaller()573     public void whenStartedViaIntentSender_canSeeCaller() throws Exception {
574         uninstallPackage(QUERIES_NOTHING);
575         installPackage(QUERIES_NOTHING_APK);
576 
577         // let's first make sure that the target cannot see the caller.
578         assertNotVisible(QUERIES_NOTHING, QUERIES_NOTHING_Q);
579         // now let's start the target via pending intent and make sure that it can see the caller
580         // as part of that call
581         PackageInfo packageInfo = startSenderForResult(QUERIES_NOTHING_Q, QUERIES_NOTHING);
582         assertThat(packageInfo, IsNull.notNullValue());
583         assertThat(packageInfo.packageName, is(QUERIES_NOTHING_Q));
584         // and finally let's re-run the last check to make sure that the target can still see the
585         // caller
586         assertVisible(QUERIES_NOTHING, QUERIES_NOTHING_Q);
587     }
588 
589     @Test
queriesNothing_cannotSeeLibraryPackage()590     public void queriesNothing_cannotSeeLibraryPackage() throws Exception {
591         assertNotVisible(QUERIES_NOTHING, TARGET_SHARED_LIBRARY_PACKAGE);
592     }
593 
594     @Test
queriesNothingUsesLibrary_canSeeLibraryPackage()595     public void queriesNothingUsesLibrary_canSeeLibraryPackage() throws Exception {
596         assertVisible(QUERIES_NOTHING_USES_LIBRARY, TARGET_SHARED_LIBRARY_PACKAGE);
597     }
598 
599     @Test
queriesNothing_cannotSeeOptionalLibraryPackage()600     public void queriesNothing_cannotSeeOptionalLibraryPackage() throws Exception {
601         assertNotVisible(QUERIES_NOTHING, TARGET_SHARED_LIBRARY_PACKAGE);
602     }
603 
604     @Test
queriesNothingUsesOptionalLibrary_canSeeLibraryPackage()605     public void queriesNothingUsesOptionalLibrary_canSeeLibraryPackage() throws Exception {
606         assertVisible(QUERIES_NOTHING_USES_OPTIONAL_LIBRARY, TARGET_SHARED_LIBRARY_PACKAGE);
607     }
608 
609     @Test
queriesNothing_getPackagesForUid_consistentVisibility()610     public void queriesNothing_getPackagesForUid_consistentVisibility()
611             throws Exception {
612         final int targetSharedUid = sPm.getPackageUid(TARGET_SHARED_USER, PackageInfoFlags.of(0));
613         final int targetUid = sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0));
614         Assert.assertNull(getPackagesForUid(QUERIES_NOTHING, targetSharedUid));
615         Assert.assertNull(getPackagesForUid(QUERIES_NOTHING, targetUid));
616     }
617 
618     @Test
queriesNothingHasPermission_getPackagesForUid_consistentVisibility()619     public void queriesNothingHasPermission_getPackagesForUid_consistentVisibility()
620             throws Exception {
621         final int targetSharedUid = sPm.getPackageUid(TARGET_SHARED_USER, PackageInfoFlags.of(0));
622         final int targetUid = sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0));
623         Assert.assertNotNull(getPackagesForUid(QUERIES_NOTHING_PERM, targetSharedUid));
624         Assert.assertNotNull(getPackagesForUid(QUERIES_NOTHING_PERM, targetUid));
625     }
626 
627     @Test
queriesNothing_getNameForUid_consistentVisibility()628     public void queriesNothing_getNameForUid_consistentVisibility()
629             throws Exception {
630         final int targetSharedUid = sPm.getPackageUid(TARGET_SHARED_USER, PackageInfoFlags.of(0));
631         final int targetUid = sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0));
632         Assert.assertNull(getNameForUid(QUERIES_NOTHING, targetSharedUid));
633         Assert.assertNull(getNameForUid(QUERIES_NOTHING, targetUid));
634     }
635 
636     @Test
queriesNothingHasPermission_getNameForUid_consistentVisibility()637     public void queriesNothingHasPermission_getNameForUid_consistentVisibility()
638             throws Exception {
639         final int targetSharedUid = sPm.getPackageUid(TARGET_SHARED_USER, PackageInfoFlags.of(0));
640         final int targetUid = sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0));
641         Assert.assertNotNull(getNameForUid(QUERIES_NOTHING_PERM, targetSharedUid));
642         Assert.assertNotNull(getNameForUid(QUERIES_NOTHING_PERM, targetUid));
643     }
644 
645     @Test
queriesNothing_getNamesForUids_consistentVisibility()646     public void queriesNothing_getNamesForUids_consistentVisibility()
647             throws Exception {
648         try {
649             allowTestApiAccess(QUERIES_NOTHING);
650 
651             final int targetSharedUid =
652                     sPm.getPackageUid(TARGET_SHARED_USER, PackageInfoFlags.of(0));
653             final int targetUid = sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0));
654             Assert.assertNull(getNamesForUids(QUERIES_NOTHING, targetSharedUid)[0]);
655             Assert.assertNull(getNamesForUids(QUERIES_NOTHING, targetUid)[0]);
656         } finally {
657             resetTestApiAccess(QUERIES_NOTHING);
658         }
659     }
660 
661     @Test
queriesNothingHasPermission_getNamesForUids_consistentVisibility()662     public void queriesNothingHasPermission_getNamesForUids_consistentVisibility()
663             throws Exception {
664         try {
665             allowTestApiAccess(QUERIES_NOTHING_PERM);
666 
667             final int targetSharedUid =
668                     sPm.getPackageUid(TARGET_SHARED_USER, PackageInfoFlags.of(0));
669             final int targetUid = sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0));
670             Assert.assertNotNull(getNamesForUids(QUERIES_NOTHING_PERM, targetSharedUid)[0]);
671             Assert.assertNotNull(getNamesForUids(QUERIES_NOTHING_PERM, targetUid)[0]);
672         } finally {
673             resetTestApiAccess(QUERIES_NOTHING_PERM);
674         }
675     }
676 
677     @Test
queriesNothing_checkSignatures_consistentVisibility()678     public void queriesNothing_checkSignatures_consistentVisibility()
679             throws Exception {
680         final int targetSharedUid = sPm.getPackageUid(TARGET_SHARED_USER, PackageInfoFlags.of(0));
681         final int targetUid = sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0));
682         Assert.assertEquals(SIGNATURE_UNKNOWN_PACKAGE,
683                 checkSignatures(QUERIES_NOTHING, targetSharedUid));
684         Assert.assertEquals(SIGNATURE_UNKNOWN_PACKAGE,
685                 checkSignatures(QUERIES_NOTHING, targetUid));
686     }
687 
688     @Test
queriesNothingHasPermission_checkSignatures_consistentVisibility()689     public void queriesNothingHasPermission_checkSignatures_consistentVisibility()
690             throws Exception {
691         final int targetSharedUid = sPm.getPackageUid(TARGET_SHARED_USER, PackageInfoFlags.of(0));
692         final int targetUid = sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0));
693         Assert.assertEquals(SIGNATURE_MATCH,
694                 checkSignatures(QUERIES_NOTHING_PERM, targetSharedUid));
695         Assert.assertEquals(SIGNATURE_MATCH, checkSignatures(QUERIES_NOTHING_PERM, targetUid));
696     }
697 
698     @Test
queriesNothing_hasSigningCertificate_consistentVisibility()699     public void queriesNothing_hasSigningCertificate_consistentVisibility() throws Exception {
700         final PackageInfo targetSharedUidInfo = sPm.getPackageInfo(TARGET_SHARED_USER,
701                 PackageInfoFlags.of(GET_SIGNING_CERTIFICATES));
702         final PackageInfo targetUidInfo = sPm.getPackageInfo(TARGET_FILTERS,
703                 PackageInfoFlags.of(GET_SIGNING_CERTIFICATES));
704         final byte[] targetSharedCert = convertSignaturesToCertificates(
705                 targetSharedUidInfo.signingInfo.getApkContentsSigners()).get(0).getEncoded();
706         final byte[] targetCert = convertSignaturesToCertificates(
707                 targetUidInfo.signingInfo.getApkContentsSigners()).get(0).getEncoded();
708 
709         Assert.assertFalse(
710                 hasSigningCertificate(QUERIES_NOTHING, targetSharedUidInfo.applicationInfo.uid,
711                         targetSharedCert));
712         Assert.assertFalse(
713                 hasSigningCertificate(QUERIES_NOTHING, targetUidInfo.applicationInfo.uid,
714                         targetCert));
715     }
716 
717     @Test
queriesNothingHasPermission_hasSigningCertificate_consistentVisibility()718     public void queriesNothingHasPermission_hasSigningCertificate_consistentVisibility()
719             throws Exception {
720         final PackageInfo targetSharedUidInfo = sPm.getPackageInfo(TARGET_SHARED_USER,
721                 PackageInfoFlags.of(GET_SIGNING_CERTIFICATES));
722         final PackageInfo targetUidInfo = sPm.getPackageInfo(TARGET_FILTERS,
723                 PackageInfoFlags.of(GET_SIGNING_CERTIFICATES));
724         final byte[] targetSharedCert = convertSignaturesToCertificates(
725                 targetSharedUidInfo.signingInfo.getApkContentsSigners()).get(0).getEncoded();
726         final byte[] targetCert = convertSignaturesToCertificates(
727                 targetUidInfo.signingInfo.getApkContentsSigners()).get(0).getEncoded();
728 
729         Assert.assertTrue(
730                 hasSigningCertificate(QUERIES_NOTHING_PERM, targetSharedUidInfo.applicationInfo.uid,
731                         targetSharedCert));
732         Assert.assertTrue(
733                 hasSigningCertificate(QUERIES_NOTHING_PERM, targetUidInfo.applicationInfo.uid,
734                         targetCert));
735     }
736 
737     @Test
sharedUserMember_canSeeOtherMember()738     public void sharedUserMember_canSeeOtherMember() throws Exception {
739         assertVisible(QUERIES_NOTHING_SHARED_USER, TARGET_SHARED_USER);
740     }
741 
742     @Test
queriesPackage_canSeeAllSharedUserMembers()743     public void queriesPackage_canSeeAllSharedUserMembers() throws Exception {
744         // explicitly queries target via manifest
745         assertVisible(QUERIES_PACKAGE, TARGET_SHARED_USER);
746         // implicitly granted visibility to other member of shared user
747         assertVisible(QUERIES_PACKAGE, QUERIES_NOTHING_SHARED_USER);
748     }
749 
750     @Test
queriesWildcardContacts()751     public void queriesWildcardContacts() throws Exception {
752         assertNotVisible(QUERIES_NOTHING, TARGET_CONTACTS);
753         assertVisible(QUERIES_WILDCARD_CONTACTS, TARGET_CONTACTS);
754     }
755 
756     @Test
queriesWildcardWeb()757     public void queriesWildcardWeb() throws Exception {
758         assertNotVisible(QUERIES_NOTHING, TARGET_WEB);
759         assertVisible(QUERIES_WILDCARD_BROWSABLE, TARGET_WEB);
760         assertVisible(QUERIES_WILDCARD_WEB, TARGET_WEB);
761     }
762 
763     @Test
queriesWildcardBrowser()764     public void queriesWildcardBrowser() throws Exception {
765         assertNotVisible(QUERIES_NOTHING, TARGET_BROWSER);
766         assertNotVisible(QUERIES_WILDCARD_BROWSER, TARGET_WEB);
767         assertVisible(QUERIES_WILDCARD_BROWSER, TARGET_BROWSER);
768         assertVisible(QUERIES_WILDCARD_BROWSER, TARGET_BROWSER_WILDCARD);
769     }
770 
771     @Test
queriesWildcardWeb_canSeePrefixWildcardWeb()772     public void queriesWildcardWeb_canSeePrefixWildcardWeb() throws Exception {
773         assertNotVisible(QUERIES_NOTHING, TARGET_PREFIX_WILDCARD_WEB);
774         assertVisible(QUERIES_WILDCARD_BROWSABLE, TARGET_PREFIX_WILDCARD_WEB);
775         assertVisible(QUERIES_WILDCARD_WEB, TARGET_PREFIX_WILDCARD_WEB);
776     }
777 
778     @Test
queriesWildcardBrowser_cannotSeePrefixWildcardWeb()779     public void queriesWildcardBrowser_cannotSeePrefixWildcardWeb() throws Exception {
780         assertNotVisible(QUERIES_NOTHING, TARGET_PREFIX_WILDCARD_WEB);
781         assertNotVisible(QUERIES_WILDCARD_BROWSER, TARGET_PREFIX_WILDCARD_WEB);
782     }
783 
784     @Test
queriesWildcardEditor()785     public void queriesWildcardEditor() throws Exception {
786         assertNotVisible(QUERIES_NOTHING, TARGET_EDITOR);
787         assertVisible(QUERIES_WILDCARD_EDITOR, TARGET_EDITOR);
788     }
789 
790     @Test
queriesWildcardShareSheet()791     public void queriesWildcardShareSheet() throws Exception {
792         assertNotVisible(QUERIES_NOTHING, TARGET_SHARE);
793         assertVisible(QUERIES_WILDCARD_SHARE, TARGET_SHARE);
794     }
795 
796     @Test
queriesNothing_cannotSeeA11yService()797     public void queriesNothing_cannotSeeA11yService() throws Exception {
798         try {
799             allowTestApiAccess(QUERIES_NOTHING);
800 
801             assertNotVisible(QUERIES_NOTHING, TARGET_FILTERS,
802                     this::getInstalledAccessibilityServices);
803         } finally {
804             resetTestApiAccess(QUERIES_NOTHING);
805         }
806     }
807 
808     @Test
queriesNothingHasPermission_canSeeA11yService()809     public void queriesNothingHasPermission_canSeeA11yService() throws Exception {
810         try {
811             allowTestApiAccess(QUERIES_NOTHING_PERM);
812 
813             assertVisible(QUERIES_NOTHING_PERM, TARGET_FILTERS,
814                     this::getInstalledAccessibilityServices);
815         } finally {
816             resetTestApiAccess(QUERIES_NOTHING_PERM);
817         }
818     }
819 
820     @LargeTest
821     @Test
broadcastAdded_notVisibleDoesNotReceive()822     public void broadcastAdded_notVisibleDoesNotReceive() throws Exception {
823         final Result result = sendCommand(QUERIES_NOTHING, TARGET_FILTERS,
824                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
825                 Constants.ACTION_AWAIT_PACKAGE_ADDED, /* waitForReady */ true);
826         installPackage(TARGET_FILTERS_APK);
827         try {
828             result.await();
829             fail();
830         } catch (MissingBroadcastException e) {
831             // hooray
832         }
833     }
834 
835     @Test
broadcastAdded_visibleReceives()836     public void broadcastAdded_visibleReceives() throws Exception {
837         final Result result = sendCommand(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS,
838                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
839                 Constants.ACTION_AWAIT_PACKAGE_ADDED, /* waitForReady */ true);
840         installPackage(TARGET_FILTERS_APK);
841         try {
842             Assert.assertEquals(TARGET_FILTERS,
843                     Uri.parse(result.await().getString(EXTRA_DATA)).getSchemeSpecificPart());
844         } catch (MissingBroadcastException e) {
845             fail(e.getMessage());
846         }
847     }
848 
849     @LargeTest
850     @Test
reinstallTarget_broadcastRemoved_notVisibleDoesNotReceive()851     public void reinstallTarget_broadcastRemoved_notVisibleDoesNotReceive() throws Exception {
852         final Result result = sendCommand(QUERIES_NOTHING, TARGET_FILTERS,
853                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
854                 Constants.ACTION_AWAIT_PACKAGE_REMOVED, /* waitForReady */ true);
855         installPackage(TARGET_FILTERS_APK);
856         try {
857             result.await();
858             fail();
859         } catch (MissingBroadcastException e) {
860             // hooray
861         }
862     }
863 
864     @Test
reinstallTarget_broadcastRemoved_visibleReceives()865     public void reinstallTarget_broadcastRemoved_visibleReceives() throws Exception {
866         final Result result = sendCommand(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS,
867                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
868                 Constants.ACTION_AWAIT_PACKAGE_REMOVED, /* waitForReady */ true);
869         installPackage(TARGET_FILTERS_APK);
870         try {
871             Assert.assertEquals(TARGET_FILTERS,
872                     Uri.parse(result.await().getString(EXTRA_DATA)).getSchemeSpecificPart());
873         } catch (MissingBroadcastException e) {
874             fail(e.getMessage());
875         }
876     }
877 
878     @LargeTest
879     @Test
uninstallTarget_broadcastRemoved_notVisibleDoesNotReceive()880     public void uninstallTarget_broadcastRemoved_notVisibleDoesNotReceive() throws Exception {
881         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
882         final Result result = sendCommand(QUERIES_NOTHING, TARGET_STUB,
883                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
884                 Constants.ACTION_AWAIT_PACKAGE_REMOVED, /* waitForReady */ true);
885         uninstallPackage(TARGET_STUB);
886         try {
887             result.await();
888             fail();
889         } catch (MissingBroadcastException e) {
890             // hooray
891         }
892     }
893 
894     @Test
uninstallTarget_broadcastRemoved_visibleReceives()895     public void uninstallTarget_broadcastRemoved_visibleReceives() throws Exception {
896         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
897         final Result result = sendCommand(QUERIES_NOTHING_PERM, TARGET_STUB,
898                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
899                 Constants.ACTION_AWAIT_PACKAGE_REMOVED, /* waitForReady */ true);
900         uninstallPackage(TARGET_STUB);
901         try {
902             Assert.assertEquals(TARGET_STUB,
903                     Uri.parse(result.await().getString(EXTRA_DATA)).getSchemeSpecificPart());
904         } catch (MissingBroadcastException e) {
905             fail();
906         }
907     }
908 
909     @LargeTest
910     @Test
uninstallTarget_broadcastFullyRemoved_notVisibleDoesNotReceive()911     public void uninstallTarget_broadcastFullyRemoved_notVisibleDoesNotReceive() throws Exception {
912         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
913         final Result result = sendCommand(QUERIES_NOTHING, TARGET_STUB,
914                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
915                 Constants.ACTION_AWAIT_PACKAGE_FULLY_REMOVED, /* waitForReady */ true);
916         uninstallPackage(TARGET_STUB);
917         try {
918             result.await();
919             fail();
920         } catch (MissingBroadcastException e) {
921             // hooray
922         }
923     }
924 
925     @Test
uninstallTarget_broadcastFullyRemoved_visibleReceives()926     public void uninstallTarget_broadcastFullyRemoved_visibleReceives() throws Exception {
927         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
928         final Result result = sendCommand(QUERIES_NOTHING_PERM, TARGET_STUB,
929                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
930                 Constants.ACTION_AWAIT_PACKAGE_FULLY_REMOVED, /* waitForReady */ true);
931         uninstallPackage(TARGET_STUB);
932         try {
933             Assert.assertEquals(TARGET_STUB,
934                     Uri.parse(result.await().getString(EXTRA_DATA)).getSchemeSpecificPart());
935         } catch (MissingBroadcastException e) {
936             fail();
937         }
938     }
939 
940     @LargeTest
941     @Test
clearTargetData_broadcastDataCleared_notVisibleDoesNotReceive()942     public void clearTargetData_broadcastDataCleared_notVisibleDoesNotReceive() throws Exception {
943         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
944         final Result result = sendCommand(QUERIES_NOTHING, TARGET_STUB,
945                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
946                 Constants.ACTION_AWAIT_PACKAGE_DATA_CLEARED, /* waitForReady */ true);
947         clearAppDataForUser(TARGET_STUB, UserReference.of(sContext.getUser()));
948         try {
949             result.await();
950             fail();
951         } catch (MissingBroadcastException e) {
952             // hooray
953         }
954     }
955 
956     @Test
clearTargetData_broadcastDataCleared_visibleReceives()957     public void clearTargetData_broadcastDataCleared_visibleReceives() throws Exception {
958         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
959         final Result result = sendCommand(QUERIES_NOTHING_PERM, TARGET_STUB,
960                 /* targetUid */ INVALID_UID, /* intentExtra */ null,
961                 Constants.ACTION_AWAIT_PACKAGE_DATA_CLEARED, /* waitForReady */ true);
962         clearAppDataForUser(TARGET_STUB, UserReference.of(sContext.getUser()));
963         try {
964             Assert.assertEquals(TARGET_STUB,
965                     Uri.parse(result.await().getString(EXTRA_DATA)).getSchemeSpecificPart());
966         } catch (MissingBroadcastException e) {
967             fail();
968         }
969     }
970 
971     @Test
broadcastRestarted_visibleReceives()972     public void broadcastRestarted_visibleReceives() throws Exception {
973         assertBroadcastRestartedVisible(QUERIES_PACKAGE, TARGET_NO_API, TARGET_NO_API);
974     }
975 
976     @LargeTest
977     @Test
broadcastRestarted_notVisibleDoesNotReceive()978     public void broadcastRestarted_notVisibleDoesNotReceive() throws Exception {
979         assertBroadcastRestartedVisible(QUERIES_NOTHING, /* expectedPackage */ null, TARGET_NO_API);
980     }
981 
982     @Test
broadcastSuspended_visibleReceives()983     public void broadcastSuspended_visibleReceives() throws Exception {
984         assertBroadcastSuspendedVisible(QUERIES_PACKAGE,
985                 Arrays.asList(TARGET_NO_API, TARGET_SYNCADAPTER),
986                 Arrays.asList(TARGET_NO_API, TARGET_SYNCADAPTER));
987     }
988 
989     @LargeTest
990     @Test
broadcastSuspended_notVisibleDoesNotReceive()991     public void broadcastSuspended_notVisibleDoesNotReceive() throws Exception {
992         assertBroadcastSuspendedVisible(QUERIES_NOTHING,
993                 Arrays.asList(),
994                 Arrays.asList(TARGET_NO_API, TARGET_SYNCADAPTER));
995     }
996 
997     @LargeTest
998     @Test
broadcastSuspended_visibleReceivesAndNotVisibleDoesNotReceive()999     public void broadcastSuspended_visibleReceivesAndNotVisibleDoesNotReceive() throws Exception {
1000         assertBroadcastSuspendedVisible(QUERIES_ACTIVITY_ACTION,
1001                 Arrays.asList(TARGET_FILTERS),
1002                 Arrays.asList(TARGET_NO_API, TARGET_FILTERS));
1003     }
1004 
1005     @Test
queriesResolver_grantsVisibilityToProvider()1006     public void queriesResolver_grantsVisibilityToProvider() throws Exception {
1007         uninstallPackage(QUERIES_NOTHING_PROVIDER);
1008         installPackage(QUERIES_NOTHING_PROVIDER_APK);
1009 
1010         assertNotVisible(QUERIES_NOTHING_PROVIDER, QUERIES_NOTHING_PERM);
1011 
1012         String[] result = sendCommandBlocking(
1013                 QUERIES_NOTHING_PERM, QUERIES_NOTHING_PROVIDER, null, ACTION_QUERY_RESOLVER)
1014                 .getStringArray(Intent.EXTRA_RETURN_RESULT);
1015         Arrays.sort(result);
1016         assertThat(QUERIES_NOTHING_PERM + " not visible to " + QUERIES_NOTHING_PROVIDER
1017                         + " during resolver interaction",
1018                 Arrays.binarySearch(result, QUERIES_NOTHING_PERM),
1019                 greaterThanOrEqualTo(0));
1020 
1021         assertVisible(QUERIES_NOTHING_PROVIDER, QUERIES_NOTHING_PERM);
1022     }
1023 
1024     @Test
bindService_consistentVisibility()1025     public void bindService_consistentVisibility() throws Exception {
1026         // Ensure package visibility isn't impacted by optimization or cached result.
1027         // Target service shouldn't be visible to app without query permission even if
1028         // another app with query permission is binding it.
1029         assertServiceVisible(QUERIES_NOTHING_PERM, TARGET_FILTERS);
1030         assertServiceNotVisible(QUERIES_NOTHING, TARGET_FILTERS);
1031     }
1032 
1033     @Test
queriesPackage_canSeeAppWidgetProviderTarget()1034     public void queriesPackage_canSeeAppWidgetProviderTarget() throws Exception {
1035         assumeTrue(sPm.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS));
1036 
1037         assertVisible(QUERIES_PACKAGE, TARGET_APPWIDGETPROVIDER,
1038                 this::getInstalledAppWidgetProviders);
1039     }
1040 
1041     @Test
queriesNothing_cannotSeeAppWidgetProviderTarget()1042     public void queriesNothing_cannotSeeAppWidgetProviderTarget() throws Exception {
1043         assumeTrue(sPm.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS));
1044         assumeFalse("Skipping test: Tv does not support widget yet",
1045                 sPm.hasSystemFeature(PackageManager.FEATURE_LEANBACK));
1046 
1047         assertNotVisible(QUERIES_NOTHING, TARGET_APPWIDGETPROVIDER,
1048                 this::getInstalledAppWidgetProviders);
1049         assertNotVisible(QUERIES_NOTHING, TARGET_APPWIDGETPROVIDER_SHARED_USER,
1050                 this::getInstalledAppWidgetProviders);
1051     }
1052 
1053     @Test
queriesNothingSharedUser_canSeeAppWidgetProviderSharedUserTarget()1054     public void queriesNothingSharedUser_canSeeAppWidgetProviderSharedUserTarget()
1055             throws Exception {
1056         assumeTrue(sPm.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS));
1057 
1058         assertVisible(QUERIES_NOTHING_SHARED_USER, TARGET_APPWIDGETPROVIDER_SHARED_USER,
1059                 this::getInstalledAppWidgetProviders);
1060     }
1061 
1062     @Test
queriesNothing_cannotSeeSharedLibraryDependentPackages()1063     public void queriesNothing_cannotSeeSharedLibraryDependentPackages() throws Exception {
1064         assertNotVisible(QUERIES_NOTHING, TARGET_NO_API, this::getSharedLibraryDependentPackages);
1065         assertNotVisible(QUERIES_NOTHING, TARGET_FILTERS, this::getSharedLibraryDependentPackages);
1066         assertNotVisible(QUERIES_NOTHING, TARGET_SHARED_USER,
1067                 this::getSharedLibraryDependentPackages);
1068 
1069     }
1070 
1071     @Test
queriesPackage_canSeeSharedLibraryDependentPackages()1072     public void queriesPackage_canSeeSharedLibraryDependentPackages() throws Exception {
1073         assertVisible(QUERIES_PACKAGE, TARGET_NO_API, this::getSharedLibraryDependentPackages);
1074         assertVisible(QUERIES_PACKAGE, TARGET_SHARED_USER, this::getSharedLibraryDependentPackages);
1075     }
1076 
1077     @Test
queriesNothingSharedUser_canSeeSharedUserInSharedLibraryDependentPackages()1078     public void queriesNothingSharedUser_canSeeSharedUserInSharedLibraryDependentPackages()
1079             throws Exception {
1080         assertVisible(QUERIES_NOTHING_SHARED_USER, TARGET_SHARED_USER,
1081                 this::getSharedLibraryDependentPackages);
1082     }
1083 
1084     @Test
queriesNothing_cannotSeePreferredActivityTarget()1085     public void queriesNothing_cannotSeePreferredActivityTarget() throws Exception {
1086         addPreferredActivity();
1087         try {
1088             assertNotVisible(QUERIES_NOTHING, TARGET_PREFERRED_ACTIVITY,
1089                     this::getPreferredActivities);
1090         } finally {
1091             clearPreferredActivity();
1092         }
1093     }
1094 
1095     @Test
queriesPackage_canSeePreferredActivityTarget()1096     public void queriesPackage_canSeePreferredActivityTarget() throws Exception {
1097         addPreferredActivity();
1098         try {
1099             assertVisible(QUERIES_PACKAGE, TARGET_PREFERRED_ACTIVITY,
1100                     this::getPreferredActivities);
1101         } finally {
1102             clearPreferredActivity();
1103         }
1104     }
1105 
1106     @Test
queriesNothing_setInstallerPackageName_targetIsNoApi_throwsException()1107     public void queriesNothing_setInstallerPackageName_targetIsNoApi_throwsException() {
1108         final Exception ex = assertThrows(IllegalArgumentException.class,
1109                 () -> setInstallerPackageName(QUERIES_NOTHING, TARGET_NO_API, QUERIES_NOTHING));
1110         assertThat(ex.getMessage(), containsString(TARGET_NO_API));
1111     }
1112 
1113     @Test
queriesNothing_setInstallerPackageName_installerIsNoApi_throwsException()1114     public void queriesNothing_setInstallerPackageName_installerIsNoApi_throwsException() {
1115         final Exception ex = assertThrows(IllegalArgumentException.class,
1116                 () -> setInstallerPackageName(QUERIES_NOTHING, QUERIES_NOTHING, TARGET_NO_API));
1117         assertThat(ex.getMessage(), containsString(TARGET_NO_API));
1118     }
1119 
1120     @Test
queriesPackageHasProvider_checkUriPermission_canSeeNoApi()1121     public void queriesPackageHasProvider_checkUriPermission_canSeeNoApi() throws Exception {
1122         final int permissionResult = checkUriPermission(QUERIES_PACKAGE_PROVIDER, TARGET_NO_API);
1123         assertThat(permissionResult, is(PackageManager.PERMISSION_GRANTED));
1124     }
1125 
1126     @Test
queriesPackageHasProvider_checkUriPermission_cannotSeeFilters()1127     public void queriesPackageHasProvider_checkUriPermission_cannotSeeFilters() throws Exception {
1128         final int permissionResult = checkUriPermission(QUERIES_PACKAGE_PROVIDER, TARGET_FILTERS);
1129         assertThat(permissionResult, is(PackageManager.PERMISSION_DENIED));
1130     }
1131 
1132     @Test
1133     @RequiresFlagsEnabled(android.security.Flags.FLAG_CONTENT_URI_PERMISSION_APIS)
queriesPackageHasProvider_checkContentUriPermissionFull_canSeeNoApi()1134     public void queriesPackageHasProvider_checkContentUriPermissionFull_canSeeNoApi()
1135             throws Exception {
1136         final int permissionResult = checkContentUriPermissionFull(QUERIES_PACKAGE_PROVIDER,
1137                 TARGET_NO_API);
1138         assertThat(permissionResult, is(PackageManager.PERMISSION_GRANTED));
1139     }
1140 
1141     @Test
1142     @RequiresFlagsEnabled(android.security.Flags.FLAG_CONTENT_URI_PERMISSION_APIS)
queriesPackageHasProvider_checkContentUriPermissionFull_cannotSeeFilters()1143     public void queriesPackageHasProvider_checkContentUriPermissionFull_cannotSeeFilters()
1144             throws Exception {
1145         final int permissionResult = checkContentUriPermissionFull(QUERIES_PACKAGE_PROVIDER,
1146                 TARGET_FILTERS);
1147         assertThat(permissionResult, is(PackageManager.PERMISSION_DENIED));
1148     }
1149 
1150     @Test
queriesPackageHasProvider_grantUriPermission_canSeeNoApi()1151     public void queriesPackageHasProvider_grantUriPermission_canSeeNoApi() throws Exception {
1152         try {
1153             grantUriPermission(QUERIES_PACKAGE_PROVIDER, TARGET_NO_API);
1154             assertThat(sContext.checkUriPermission(
1155                             Uri.parse("content://" + QUERIES_PACKAGE_PROVIDER),
1156                             0 /* pid */,
1157                             sPm.getPackageUid(TARGET_NO_API, PackageInfoFlags.of(0)),
1158                             Intent.FLAG_GRANT_READ_URI_PERMISSION),
1159                     is(PackageManager.PERMISSION_GRANTED));
1160         } finally {
1161             revokeUriPermission(QUERIES_PACKAGE_PROVIDER);
1162         }
1163     }
1164 
1165     @Test
queriesPackageHasProvider_grantUriPermission_cannotSeeFilters()1166     public void queriesPackageHasProvider_grantUriPermission_cannotSeeFilters() throws Exception {
1167         try {
1168             grantUriPermission(QUERIES_PACKAGE_PROVIDER, TARGET_FILTERS);
1169             assertThat(sContext.checkUriPermission(
1170                                     Uri.parse("content://" + QUERIES_PACKAGE_PROVIDER),
1171                                     0 /* pid */,
1172                                     sPm.getPackageUid(TARGET_FILTERS, PackageInfoFlags.of(0)),
1173                                     Intent.FLAG_GRANT_READ_URI_PERMISSION),
1174                     is(PackageManager.PERMISSION_DENIED));
1175         } finally {
1176             revokeUriPermission(QUERIES_PACKAGE_PROVIDER);
1177         }
1178     }
1179 
1180     @Test
queriesPackage_getType_canGetMimeType()1181     public void queriesPackage_getType_canGetMimeType() throws Exception {
1182         assertThat(getContentProviderMimeType(QUERIES_PACKAGE, TARGET_SYNCADAPTER),
1183                 is("got/theMIME"));
1184     }
1185 
1186     @Test
queriesNothing_getType_cannotGetMimeType()1187     public void queriesNothing_getType_cannotGetMimeType() throws Exception {
1188         assertThat(getContentProviderMimeType(QUERIES_NOTHING, TARGET_SYNCADAPTER),
1189                 IsNull.nullValue());
1190     }
1191 
1192     @Test
setAutoRevokeWhitelisted_targetIsNotExisting_setFailed()1193     public void setAutoRevokeWhitelisted_targetIsNotExisting_setFailed() throws Exception {
1194         final boolean result = SystemUtil.callWithShellPermissionIdentity(
1195                 () -> sPm.setAutoRevokeWhitelisted(TEST_NONEXISTENT_PACKAGE_NAME_1,
1196                         false /* whitelisted */),
1197                 Manifest.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS);
1198         assertThat(result, is(false));
1199     }
1200 
1201     @Test
setAutoRevokeWhitelisted_cannotSeeTarget_setFailed()1202     public void setAutoRevokeWhitelisted_cannotSeeTarget_setFailed() throws Exception {
1203         final boolean result = SystemUtil.callWithShellPermissionIdentity(
1204                 () -> sPm.setAutoRevokeWhitelisted(QUERIES_PACKAGE, false /* whitelisted */),
1205                 Manifest.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS);
1206         assertThat(result, is(false));
1207     }
1208 
1209     @Test
setAutoRevokeWhitelisted_canSeeTarget_setSuccessful()1210     public void setAutoRevokeWhitelisted_canSeeTarget_setSuccessful() throws Exception {
1211         final boolean result = SystemUtil.callWithShellPermissionIdentity(
1212                 () -> sPm.setAutoRevokeWhitelisted(QUERIES_NOTHING, false /* whitelisted */),
1213                 Manifest.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS);
1214         assertThat(result, is(true));
1215     }
1216 
1217     @Test
setAutoRevokeWhitelisted_withoutPermission_throwsException()1218     public void setAutoRevokeWhitelisted_withoutPermission_throwsException() throws Exception {
1219         assertThrows(SecurityException.class,
1220                 () -> sPm.setAutoRevokeWhitelisted(QUERIES_NOTHING, false /* whitelisted */));
1221     }
1222 
1223     @Test
canPackageQuery_queriesActivityAction_canSeeFilters()1224     public void canPackageQuery_queriesActivityAction_canSeeFilters() throws Exception {
1225         assertThat(sPm.canPackageQuery(QUERIES_ACTIVITY_ACTION, TARGET_FILTERS),
1226                 is(true));
1227     }
1228 
1229     @Test
canPackageQuery_queriesNothing_cannotSeeFilters()1230     public void canPackageQuery_queriesNothing_cannotSeeFilters() throws Exception {
1231         assertThat(sPm.canPackageQuery(QUERIES_NOTHING, TARGET_FILTERS),
1232                 is(false));
1233     }
1234 
1235     @Test
canPackageQuery_withNonexistentPackages()1236     public void canPackageQuery_withNonexistentPackages() {
1237         assertThrows(PackageManager.NameNotFoundException.class,
1238                 () -> sPm.canPackageQuery(
1239                         TEST_NONEXISTENT_PACKAGE_NAME_1, TEST_NONEXISTENT_PACKAGE_NAME_2));
1240         assertThrows(PackageManager.NameNotFoundException.class,
1241                 () -> sPm.canPackageQuery(
1242                         QUERIES_NOTHING_PERM, TEST_NONEXISTENT_PACKAGE_NAME_2));
1243         assertThrows(PackageManager.NameNotFoundException.class,
1244                 () -> sPm.canPackageQuery(
1245                         TEST_NONEXISTENT_PACKAGE_NAME_1, TARGET_FILTERS));
1246     }
1247 
1248     @Test
canPackageQuery_callerHasNoPackageVisibility()1249     public void canPackageQuery_callerHasNoPackageVisibility() {
1250         assertThrows(PackageManager.NameNotFoundException.class,
1251                 () -> canPackageQuery(
1252                         QUERIES_NOTHING, QUERIES_ACTIVITY_ACTION, TARGET_FILTERS));
1253         assertThrows(PackageManager.NameNotFoundException.class,
1254                 () -> canPackageQuery(
1255                         QUERIES_NOTHING_SHARED_USER, QUERIES_PACKAGE, TARGET_SHARED_USER));
1256     }
1257 
1258     @Test
canPackageQuery_cannotDetectPackageExistence()1259     public void canPackageQuery_cannotDetectPackageExistence() {
1260         ensurePackageIsNotInstalled(TARGET_STUB);
1261         final Exception ex1 = assertThrows(PackageManager.NameNotFoundException.class,
1262                 () -> canPackageQuery(QUERIES_NOTHING, TARGET_STUB, ""));
1263         final StringWriter stackTrace1 = new StringWriter();
1264         ex1.printStackTrace(new PrintWriter(stackTrace1));
1265 
1266         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
1267 
1268         final Exception ex2 = assertThrows(PackageManager.NameNotFoundException.class,
1269                 () -> canPackageQuery(QUERIES_NOTHING, TARGET_STUB, ""));
1270         final StringWriter stackTrace2 = new StringWriter();
1271         ex1.printStackTrace(new PrintWriter(stackTrace2));
1272 
1273         assertThat(ex1.getMessage(), is(ex2.getMessage()));
1274         assertThat(stackTrace1.toString(), is(stackTrace2.toString()));
1275     }
1276 
1277     @Test
canPackageQueries_queriesPackage_canSeeDeclaredPackages_cannotSeeOthers()1278     public void canPackageQueries_queriesPackage_canSeeDeclaredPackages_cannotSeeOthers()
1279             throws Exception {
1280         assertThat(canPackageQueries(QUERIES_NOTHING_PERM, QUERIES_PACKAGE,
1281                         new String[]{
1282                                 TARGET_NO_API,
1283                                 TARGET_BROWSER,
1284                                 TARGET_SHARED_USER,
1285                                 TARGET_WEB,
1286                                 TARGET_SYNCADAPTER}),
1287                 allOf(arrayWithSize(5), arrayContaining(true, false, true, false, true)));
1288     }
1289 
1290     @Test
canPackageQueries_callerHasNoPackageVisibility()1291     public void canPackageQueries_callerHasNoPackageVisibility() {
1292         assertThrows(PackageManager.NameNotFoundException.class,
1293                 () -> canPackageQueries(QUERIES_PACKAGE, TARGET_NO_API,
1294                         new String[]{TARGET_SHARED_USER, TARGET_WEB}));
1295     }
1296 
1297     @Test
checkPackage_queriesNothing_validateFailed()1298     public void checkPackage_queriesNothing_validateFailed() {
1299         // Using ROOT_UID here to pass the check in #verifyAndGetBypass, this is intended by design.
1300         assertThrows(SecurityException.class,
1301                 () -> checkPackage(QUERIES_NOTHING, TARGET_FILTERS, ROOT_UID));
1302     }
1303 
1304     @Test
checkPackage_queriesNothing_targetIsNotExisting_validateFailed()1305     public void checkPackage_queriesNothing_targetIsNotExisting_validateFailed() {
1306         // Using ROOT_UID here to pass the check in #verifyAndGetBypass, this is intended by design.
1307         assertThrows(SecurityException.class,
1308                 () -> checkPackage(QUERIES_NOTHING, TEST_NONEXISTENT_PACKAGE_NAME_1, ROOT_UID));
1309     }
1310 
1311     @Test
checkPackage_queriesNothingHasPerm_validateSuccessful()1312     public void checkPackage_queriesNothingHasPerm_validateSuccessful() throws Exception {
1313         // Using ROOT_UID here to pass the check in #verifyAndGetBypass, this is intended by design.
1314         assertThat(checkPackage(QUERIES_NOTHING_PERM, TARGET_FILTERS, ROOT_UID), is(true));
1315     }
1316 
1317     @Test
checkPackage_queriesNothingHasPerm_targetIsNotExisting_validateFailed()1318     public void checkPackage_queriesNothingHasPerm_targetIsNotExisting_validateFailed()
1319             throws Exception {
1320         // Using ROOT_UID here to pass the check in #verifyAndGetBypass, this is intended by design.
1321         assertThrows(SecurityException.class,
1322                 () -> checkPackage(QUERIES_NOTHING_PERM, TEST_NONEXISTENT_PACKAGE_NAME_1,
1323                         ROOT_UID));
1324     }
1325 
1326     @Test
pendingIntent_getCreatorPackage_queriesPackage_canSeeNoApi()1327     public void pendingIntent_getCreatorPackage_queriesPackage_canSeeNoApi()
1328             throws Exception {
1329         final PendingIntent pendingIntent = getPendingIntentActivity(TARGET_NO_API);
1330         assertThat(getPendingIntentCreatorPackage(QUERIES_PACKAGE, pendingIntent),
1331                 is(TARGET_NO_API));
1332     }
1333 
1334     @Test
pendingIntent_getCreatorPackage_queriesNothing_cannotSeeNoApi()1335     public void pendingIntent_getCreatorPackage_queriesNothing_cannotSeeNoApi()
1336             throws Exception {
1337         final PendingIntent pendingIntent = getPendingIntentActivity(TARGET_NO_API);
1338         assertThat(getPendingIntentCreatorPackage(QUERIES_NOTHING, pendingIntent),
1339                 is(emptyOrNullString()));
1340     }
1341 
1342     @Test
makeUidVisible_throwsException()1343     public void makeUidVisible_throwsException() throws Exception {
1344         final int recipientUid = sPm.getPackageUid(
1345                 QUERIES_NOTHING, PackageManager.PackageInfoFlags.of(0));
1346         final int visibleUid = sPm.getPackageUid(
1347                 TARGET_NO_API, PackageManager.PackageInfoFlags.of(0));
1348         assertThrows(SecurityException.class,
1349                 () -> sPm.makeUidVisible(recipientUid, visibleUid));
1350     }
1351 
1352     @Test
makeUidVisible_queriesNothing_canSeeStub()1353     public void makeUidVisible_queriesNothing_canSeeStub() throws Exception {
1354         ensurePackageIsInstalled(TARGET_STUB, TARGET_STUB_APK);
1355         try {
1356             assertNotVisible(QUERIES_NOTHING, TARGET_STUB);
1357 
1358             final int recipientUid = sPm.getPackageUid(
1359                     QUERIES_NOTHING, PackageManager.PackageInfoFlags.of(0));
1360             final int visibleUid = sPm.getPackageUid(
1361                     TARGET_STUB, PackageManager.PackageInfoFlags.of(0));
1362             SystemUtil.runWithShellPermissionIdentity(
1363                     () -> sPm.makeUidVisible(recipientUid, visibleUid),
1364                             Manifest.permission.MAKE_UID_VISIBLE);
1365 
1366             assertVisible(QUERIES_NOTHING, TARGET_STUB);
1367         } finally {
1368             ensurePackageIsNotInstalled(TARGET_STUB);
1369         }
1370     }
1371 
1372     @Test
testSelfVisibility()1373     public void testSelfVisibility() throws Exception {
1374         final ServiceInfo serviceInfo = sPm.getServiceInfo(
1375                 new ComponentName(sContext, SERVICE_CLASS_SELF_VISIBILITY_SERVICE),
1376                 PackageManager.GET_META_DATA);
1377         assertNotNull(serviceInfo);
1378     }
1379 
1380     @Test
grantImplicitAccessByUriGrant_canSeeProviderAfterUpdatedWithDontKill()1381     public void grantImplicitAccessByUriGrant_canSeeProviderAfterUpdatedWithDontKill()
1382             throws Exception {
1383         try {
1384             new InstallMultiple().addApk(SPLIT_BASE_APK).run();
1385             assertThat(sPm.canPackageQuery(SPLIT_PKG, QUERIES_PACKAGE_PROVIDER),
1386                     is(false));
1387             grantUriPermission(QUERIES_PACKAGE_PROVIDER, SPLIT_PKG);
1388             assertThat(sPm.canPackageQuery(SPLIT_PKG, QUERIES_PACKAGE_PROVIDER),
1389                     is(true));
1390 
1391             new InstallMultiple().addApk(SPLIT_FEATURE_APK)
1392                     .inheritFrom(SPLIT_PKG).dontKill().run();
1393 
1394             assertThat(sPm.canPackageQuery(SPLIT_PKG, QUERIES_PACKAGE_PROVIDER),
1395                     is(true));
1396         } finally {
1397             revokeUriPermission(QUERIES_PACKAGE_PROVIDER);
1398             uninstallPackage(SPLIT_PKG);
1399         }
1400     }
1401 
assertVisible(String sourcePackageName, String targetPackageName)1402     private void assertVisible(String sourcePackageName, String targetPackageName)
1403             throws Exception {
1404         Assert.assertNotNull(sourcePackageName + " should be able to see " + targetPackageName,
1405                 getPackageInfo(sourcePackageName, targetPackageName));
1406     }
1407 
assertNotVisible(String sourcePackageName, String targetPackageName)1408     private void assertNotVisible(String sourcePackageName, String targetPackageName)
1409             throws Exception {
1410         try {
1411             getPackageInfo(sourcePackageName, targetPackageName);
1412             fail(sourcePackageName + " should not be able to see " + targetPackageName);
1413         } catch (PackageManager.NameNotFoundException ignored) {
1414         }
1415     }
1416 
assertServiceVisible(String sourcePackageName, String targetPackageName)1417     private void assertServiceVisible(String sourcePackageName, String targetPackageName)
1418             throws Exception {
1419         assertTrue(bindService(sourcePackageName, targetPackageName));
1420     }
1421 
assertServiceNotVisible(String sourcePackageName, String targetPackageName)1422     private void assertServiceNotVisible(String sourcePackageName, String targetPackageName)
1423             throws Exception {
1424         assertFalse(bindService(sourcePackageName, targetPackageName));
1425     }
1426 
assertNotQueryable(String sourcePackageName, String targetPackageName, String intentAction, ThrowingBiFunction<String, Intent, String[]> commandMethod)1427     private void assertNotQueryable(String sourcePackageName, String targetPackageName,
1428             String intentAction, ThrowingBiFunction<String, Intent, String[]> commandMethod)
1429             throws Exception {
1430         Intent intent = new Intent(intentAction);
1431         String[] queryablePackageNames = commandMethod.apply(sourcePackageName, intent);
1432         for (String packageName : queryablePackageNames) {
1433             if (packageName.contentEquals(targetPackageName)) {
1434                 fail(sourcePackageName + " should not be able to query " + targetPackageName +
1435                         " via " + intentAction);
1436             }
1437         }
1438     }
1439 
assertQueryable(String sourcePackageName, String targetPackageName, String intentAction, ThrowingBiFunction<String, Intent, String[]> commandMethod)1440     private void assertQueryable(String sourcePackageName, String targetPackageName,
1441             String intentAction, ThrowingBiFunction<String, Intent, String[]> commandMethod)
1442             throws Exception {
1443         Intent intent = new Intent(intentAction);
1444         String[] queryablePackageNames = commandMethod.apply(sourcePackageName, intent);
1445         for (String packageName : queryablePackageNames) {
1446             if (packageName.contentEquals(targetPackageName)) {
1447                 return;
1448             }
1449         }
1450         fail(sourcePackageName + " should be able to query " + targetPackageName + " via "
1451                 + intentAction);
1452     }
1453 
assertBroadcastRestartedVisible(String sourcePackageName, String expectedPackage, String packageToRestart)1454     private void assertBroadcastRestartedVisible(String sourcePackageName,
1455             String expectedPackage, String packageToRestart) throws Exception {
1456         final Bundle extras = new Bundle();
1457         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageToRestart);
1458         final Result result = sendCommand(sourcePackageName, /* targetPackageName */ null,
1459                 /* targetUid */ INVALID_UID, extras, Constants.ACTION_AWAIT_PACKAGE_RESTARTED,
1460                 /* waitForReady */ true);
1461         forceStopPackage(packageToRestart);
1462         final String restartedPackages = result.await().getString(Intent.EXTRA_PACKAGE_NAME,
1463                 null /* defaultValue */);
1464         assertThat(restartedPackages, expectedPackage == null ? IsNull.nullValue()
1465                 : equalTo(expectedPackage));
1466     }
1467 
assertBroadcastSuspendedVisible(String sourcePackageName, List<String> expectedVisiblePackages, List<String> packagesToSuspend)1468     private void assertBroadcastSuspendedVisible(String sourcePackageName,
1469             List<String> expectedVisiblePackages, List<String> packagesToSuspend)
1470             throws Exception {
1471         final Bundle extras = new Bundle();
1472         extras.putStringArray(EXTRA_PACKAGES, packagesToSuspend.toArray(new String[] {}));
1473         final Result result = sendCommand(sourcePackageName, /* targetPackageName */ null,
1474                 /* targetUid */ INVALID_UID, extras, Constants.ACTION_AWAIT_PACKAGES_SUSPENDED,
1475                 /* waitForReady */ true);
1476         try {
1477             suspendPackages(true /* suspend */, packagesToSuspend);
1478             final String[] suspendedPackages = result.await().getStringArray(EXTRA_PACKAGES);
1479             assertThat(suspendedPackages, arrayContainingInAnyOrder(
1480                     expectedVisiblePackages.toArray()));
1481         } finally {
1482             suspendPackages(false /* suspend */, packagesToSuspend);
1483         }
1484     }
1485 
getInstalledAccessibilityServices(String sourcePackageName)1486     private String[] getInstalledAccessibilityServices (String sourcePackageName)
1487             throws Exception {
1488         final Bundle response = sendCommandBlocking(sourcePackageName, null /*targetPackageName*/,
1489                 null /*queryIntent*/, ACTION_GET_INSTALLED_ACCESSIBILITYSERVICES_PACKAGES);
1490         return response.getStringArray(Intent.EXTRA_RETURN_RESULT);
1491     }
1492 
getPackageInfo(String sourcePackageName, String targetPackageName)1493     private PackageInfo getPackageInfo(String sourcePackageName, String targetPackageName)
1494             throws Exception {
1495         Bundle response = sendCommandBlocking(sourcePackageName, targetPackageName,
1496                 null /*queryIntent*/, ACTION_GET_PACKAGE_INFO);
1497         return response.getParcelable(Intent.EXTRA_RETURN_RESULT, PackageInfo.class);
1498     }
1499 
getPackagesForUid(String sourcePackageName, int targetUid)1500     private String[] getPackagesForUid(String sourcePackageName, int targetUid)
1501             throws Exception {
1502         final Bundle response = sendCommandBlocking(sourcePackageName, targetUid,
1503                 /* intentExtra */ null, ACTION_GET_PACKAGES_FOR_UID);
1504         return response.getStringArray(Intent.EXTRA_RETURN_RESULT);
1505     }
1506 
getNameForUid(String sourcePackageName, int targetUid)1507     private String getNameForUid(String sourcePackageName, int targetUid) throws Exception {
1508         final Bundle response = sendCommandBlocking(sourcePackageName, targetUid,
1509                 /* intentExtra */ null, ACTION_GET_NAME_FOR_UID);
1510         return response.getString(Intent.EXTRA_RETURN_RESULT);
1511     }
1512 
getNamesForUids(String sourcePackageName, int targetUid)1513     private String[] getNamesForUids(String sourcePackageName, int targetUid) throws Exception {
1514         final Bundle response = sendCommandBlocking(sourcePackageName, targetUid,
1515                 /* intentExtra */ null, ACTION_GET_NAMES_FOR_UIDS);
1516         return response.getStringArray(Intent.EXTRA_RETURN_RESULT);
1517     }
1518 
checkSignatures(String sourcePackageName, int targetUid)1519     private int checkSignatures(String sourcePackageName, int targetUid) throws Exception {
1520         final Bundle response = sendCommandBlocking(sourcePackageName, targetUid,
1521                 /* intentExtra */ null, ACTION_CHECK_SIGNATURES);
1522         return response.getInt(Intent.EXTRA_RETURN_RESULT);
1523     }
1524 
hasSigningCertificate(String sourcePackageName, int targetUid, byte[] cert)1525     private boolean hasSigningCertificate(String sourcePackageName, int targetUid, byte[] cert)
1526             throws Exception {
1527         final Bundle extra = new Bundle();
1528         extra.putByteArray(EXTRA_CERT, cert);
1529         final Bundle response = sendCommandBlocking(sourcePackageName, targetUid, extra,
1530                 ACTION_HAS_SIGNING_CERTIFICATE);
1531         return response.getBoolean(Intent.EXTRA_RETURN_RESULT);
1532     }
1533 
convertSignaturesToCertificates(Signature[] signatures)1534     private List<Certificate> convertSignaturesToCertificates(Signature[] signatures)
1535             throws Exception {
1536         final CertificateFactory cf = CertificateFactory.getInstance("X.509");
1537         ArrayList<Certificate> certs = new ArrayList<>(signatures.length);
1538         for (Signature signature : signatures) {
1539             final InputStream is = new ByteArrayInputStream(signature.toByteArray());
1540             final X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
1541             certs.add(cert);
1542         }
1543         return certs;
1544     }
1545 
checkPackage(String sourcePackageName, String targetPackageName, int targetUid)1546     private boolean checkPackage(String sourcePackageName, String targetPackageName, int targetUid)
1547             throws Exception {
1548         final Bundle extra = new Bundle();
1549         extra.putInt(EXTRA_UID, targetUid);
1550         final Bundle response = sendCommandBlocking(sourcePackageName, targetPackageName, extra,
1551                 ACTION_CHECK_PACKAGE);
1552         return response.getBoolean(Intent.EXTRA_RETURN_RESULT);
1553     }
1554 
startForResult(String sourcePackageName, String targetPackageName)1555     private PackageInfo startForResult(String sourcePackageName, String targetPackageName)
1556             throws Exception {
1557         Bundle response = sendCommandBlocking(sourcePackageName, targetPackageName,
1558                 null /*queryIntent*/, ACTION_START_FOR_RESULT);
1559         return response.getParcelable(Intent.EXTRA_RETURN_RESULT, PackageInfo.class);
1560     }
1561 
startSenderForResult(String sourcePackageName, String targetPackageName)1562     private PackageInfo startSenderForResult(String sourcePackageName, String targetPackageName)
1563             throws Exception {
1564         PendingIntent pendingIntent = PendingIntent.getActivity(sContext, 100 /* requestCode */,
1565                 new Intent(ACTION_SEND_RESULT).setComponent(
1566                         new ComponentName(targetPackageName, ACTIVITY_CLASS_TEST)),
1567                 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
1568 
1569         Bundle response = sendCommandBlocking(sourcePackageName, targetPackageName,
1570                 pendingIntent /*queryIntent*/, Constants.ACTION_START_SENDER_FOR_RESULT);
1571         return response.getParcelable(Intent.EXTRA_RETURN_RESULT, PackageInfo.class);
1572     }
1573 
queryIntentActivities(String sourcePackageName, Intent queryIntent)1574     private String[] queryIntentActivities(String sourcePackageName, Intent queryIntent)
1575             throws Exception {
1576         Bundle response =
1577                 sendCommandBlocking(sourcePackageName, null, queryIntent, ACTION_QUERY_ACTIVITIES);
1578         return response.getStringArray(Intent.EXTRA_RETURN_RESULT);
1579     }
1580 
queryIntentServices(String sourcePackageName, Intent queryIntent)1581     private String[] queryIntentServices(String sourcePackageName, Intent queryIntent)
1582             throws Exception {
1583         Bundle response = sendCommandBlocking(sourcePackageName, null, queryIntent,
1584                 ACTION_QUERY_SERVICES);
1585         return response.getStringArray(Intent.EXTRA_RETURN_RESULT);
1586     }
1587 
queryIntentProviders(String sourcePackageName, Intent queryIntent)1588     private String[] queryIntentProviders(String sourcePackageName, Intent queryIntent)
1589             throws Exception {
1590         Bundle response = sendCommandBlocking(sourcePackageName, null, queryIntent,
1591                 ACTION_QUERY_PROVIDERS);
1592         return response.getStringArray(Intent.EXTRA_RETURN_RESULT);
1593     }
1594 
getInstalledPackages(String sourcePackageNames, int flags)1595     private String[] getInstalledPackages(String sourcePackageNames, int flags) throws Exception {
1596         Bundle response = sendCommandBlocking(sourcePackageNames, null,
1597                 new Intent().putExtra(EXTRA_FLAGS, flags), ACTION_GET_INSTALLED_PACKAGES);
1598         return response.getStringArray(Intent.EXTRA_RETURN_RESULT);
1599     }
1600 
startExplicitIntentViaComponent(String sourcePackage, String targetPackage)1601     private void startExplicitIntentViaComponent(String sourcePackage, String targetPackage)
1602             throws Exception {
1603         sendCommandBlocking(sourcePackage, targetPackage,
1604                 new Intent(ACTION_MANIFEST_ACTIVITY)
1605                         .setClassName(targetPackage, ACTIVITY_CLASS_DUMMY_ACTIVITY),
1606                 ACTION_START_DIRECTLY);
1607     }
startExplicitIntentNotExportedViaComponent( String sourcePackage, String targetPackage)1608     private void startExplicitIntentNotExportedViaComponent(
1609             String sourcePackage, String targetPackage) throws Exception {
1610         sendCommandBlocking(sourcePackage, targetPackage,
1611                 new Intent(ACTION_MANIFEST_UNEXPORTED_ACTIVITY)
1612                         .setClassName(targetPackage, ACTIVITY_CLASS_NOT_EXPORTED),
1613                 ACTION_START_DIRECTLY);
1614     }
startExplicitIntentViaPackageName(String sourcePackage, String targetPackage)1615     private void startExplicitIntentViaPackageName(String sourcePackage, String targetPackage)
1616             throws Exception {
1617         sendCommandBlocking(sourcePackage, targetPackage,
1618                 new Intent(ACTION_MANIFEST_ACTIVITY).setPackage(targetPackage),
1619                 ACTION_START_DIRECTLY);
1620     }
1621 
startExplicitPermissionProtectedIntentViaComponent( String sourcePackage, String targetPackage)1622     private void startExplicitPermissionProtectedIntentViaComponent(
1623             String sourcePackage, String targetPackage) throws Exception {
1624         sendCommandBlocking(sourcePackage, targetPackage,
1625                 new Intent(ACTION_MANIFEST_ACTIVITY)
1626                         .setClassName(targetPackage, ACTIVITY_CLASS_PERMISSION_PROTECTED),
1627                 ACTION_START_DIRECTLY);
1628     }
1629 
startImplicitIntent(String sourcePackage)1630     private void startImplicitIntent(String sourcePackage) throws Exception {
1631         sendCommandBlocking(sourcePackage, TARGET_FILTERS, new Intent(ACTION_MANIFEST_ACTIVITY),
1632                 ACTION_START_DIRECTLY);
1633     }
1634 
bindService(String sourcePackageName, String targetPackageName)1635     private boolean bindService(String sourcePackageName, String targetPackageName)
1636             throws Exception {
1637         final Bundle response = sendCommandBlocking(sourcePackageName, targetPackageName,
1638                 /* intentExtra */ null, ACTION_BIND_SERVICE);
1639         return response.getBoolean(Intent.EXTRA_RETURN_RESULT);
1640     }
1641 
getInstalledAppWidgetProviders(String sourcePackageName)1642     private String[] getInstalledAppWidgetProviders(String sourcePackageName) throws Exception {
1643         final Bundle response = sendCommandBlocking(sourcePackageName, /* targetPackageName */ null,
1644                 /* intentExtra */ null, ACTION_GET_INSTALLED_APPWIDGET_PROVIDERS);
1645         final List<AppWidgetProviderInfo> infos = response.getParcelableArrayList(
1646                 Intent.EXTRA_RETURN_RESULT, AppWidgetProviderInfo.class);
1647         return infos.stream()
1648                 .map(info -> info.provider.getPackageName())
1649                 .distinct()
1650                 .toArray(String[]::new);
1651     }
1652 
getSharedLibraryDependentPackages(String sourcePackageName)1653     private String[] getSharedLibraryDependentPackages(String sourcePackageName) throws Exception {
1654         final Bundle extraData = new Bundle();
1655         final Bundle response = sendCommandBlocking(sourcePackageName, TEST_SHARED_LIB_NAME,
1656                 extraData, ACTION_GET_SHAREDLIBRARY_DEPENDENT_PACKAGES);
1657         return response.getStringArray(Intent.EXTRA_PACKAGES);
1658     }
1659 
getPreferredActivities(String sourcePackageName)1660     private String[] getPreferredActivities(String sourcePackageName) throws Exception {
1661         final Bundle extraData = new Bundle();
1662         final Bundle response = sendCommandBlocking(sourcePackageName, null /* targetPackageName */,
1663                 extraData, ACTION_GET_PREFERRED_ACTIVITIES);
1664         return response.getStringArray(Intent.EXTRA_PACKAGES);
1665     }
1666 
setInstallerPackageName(String sourcePackageName, String targetPackageName, String installerPackageName)1667     private void setInstallerPackageName(String sourcePackageName, String targetPackageName,
1668             String installerPackageName) throws Exception {
1669         final Bundle extraData = new Bundle();
1670         extraData.putString(Intent.EXTRA_INSTALLER_PACKAGE_NAME, installerPackageName);
1671         sendCommandBlocking(sourcePackageName, targetPackageName,
1672                 extraData, ACTION_SET_INSTALLER_PACKAGE_NAME);
1673     }
1674 
checkUriPermission(String sourcePackageName, String targetPackageName)1675     private int checkUriPermission(String sourcePackageName, String targetPackageName)
1676             throws Exception {
1677         return internalCheckUriPermissionOrContentUriPermissionFull(sourcePackageName,
1678                 targetPackageName, ACTION_CHECK_URI_PERMISSION);
1679     }
1680 
checkContentUriPermissionFull(String sourcePackageName, String targetPackageName)1681     private int checkContentUriPermissionFull(String sourcePackageName, String targetPackageName)
1682             throws Exception {
1683         return internalCheckUriPermissionOrContentUriPermissionFull(sourcePackageName,
1684                 targetPackageName, ACTION_CHECK_CONTENT_URI_PERMISSION_FULL);
1685     }
1686 
internalCheckUriPermissionOrContentUriPermissionFull(String sourcePackageName, String targetPackageName, String action)1687     private int internalCheckUriPermissionOrContentUriPermissionFull(String sourcePackageName,
1688             String targetPackageName, String action) throws Exception {
1689         final int targetUid = sPm.getPackageUid(targetPackageName, PackageInfoFlags.of(0));
1690         final Bundle extraData = new Bundle();
1691         extraData.putString(EXTRA_AUTHORITY, sourcePackageName);
1692         final Result result = sendCommand(sourcePackageName, targetPackageName, targetUid,
1693                 extraData, action, /* waitForReady */ false);
1694         final Bundle response = result.await();
1695         return response.getInt(Intent.EXTRA_RETURN_RESULT);
1696     }
1697 
grantUriPermission(String providerPackageName, String targetPackageName)1698     private void grantUriPermission(String providerPackageName, String targetPackageName)
1699             throws Exception {
1700         final Bundle extraData = new Bundle();
1701         extraData.putString(EXTRA_AUTHORITY, providerPackageName);
1702         sendCommandBlocking(providerPackageName, targetPackageName, extraData,
1703                 ACTION_GRANT_URI_PERMISSION);
1704     }
1705 
revokeUriPermission(String providerPackageName)1706     private void revokeUriPermission(String providerPackageName) throws Exception {
1707         final Bundle extraData = new Bundle();
1708         extraData.putString(EXTRA_AUTHORITY, providerPackageName);
1709         sendCommandBlocking(providerPackageName, null /* targetPackageName */, extraData,
1710                 ACTION_REVOKE_URI_PERMISSION);
1711     }
1712 
getContentProviderMimeType(String sourcePackageName, String targetPackageName)1713     private String getContentProviderMimeType(String sourcePackageName, String targetPackageName)
1714             throws Exception {
1715         final Bundle extraData = new Bundle();
1716         extraData.putString(EXTRA_AUTHORITY, targetPackageName + AUTHORITY_SUFFIX);
1717         final Bundle response = sendCommandBlocking(sourcePackageName, /* targetPackageName */ null,
1718                 extraData, ACTION_GET_CONTENT_PROVIDER_MIME_TYPE);
1719         return response.getString(Intent.EXTRA_RETURN_RESULT);
1720     }
1721 
canPackageQuery(String callerPackageName, String sourcePackageName, String targetPackageName)1722     private boolean canPackageQuery(String callerPackageName, String sourcePackageName,
1723             String targetPackageName) throws Exception {
1724         final Bundle extraData = new Bundle();
1725         extraData.putString(Intent.EXTRA_PACKAGE_NAME, targetPackageName);
1726         final Bundle response = sendCommandBlocking(callerPackageName, sourcePackageName,
1727                 extraData, ACTION_CAN_PACKAGE_QUERY);
1728         return response.getBoolean(Intent.EXTRA_RETURN_RESULT);
1729     }
1730 
canPackageQueries(String callerPackageName, String sourcePackageName, String[] targetPackageNames)1731     private Boolean[] canPackageQueries(String callerPackageName, String sourcePackageName,
1732             String[] targetPackageNames) throws Exception {
1733         final Bundle extraData = new Bundle();
1734         extraData.putStringArray(EXTRA_PACKAGES, targetPackageNames);
1735         final Bundle response = sendCommandBlocking(callerPackageName, sourcePackageName,
1736                 extraData, ACTION_CAN_PACKAGE_QUERIES);
1737         return toBooleanArray(response.getBooleanArray(Intent.EXTRA_RETURN_RESULT));
1738     }
1739 
getPendingIntentActivity(String sourcePackageName)1740     private PendingIntent getPendingIntentActivity(String sourcePackageName) throws Exception  {
1741         final Bundle bundle = sendCommandBlocking(sourcePackageName, null /* targetPackageName */,
1742                 null /* intentExtra */, ACTION_PENDING_INTENT_GET_ACTIVITY);
1743         return bundle.getParcelable(EXTRA_PENDING_INTENT, PendingIntent.class);
1744     }
1745 
getPendingIntentCreatorPackage(String sourcePackageName, PendingIntent pendingIntent)1746     private String getPendingIntentCreatorPackage(String sourcePackageName,
1747             PendingIntent pendingIntent) throws Exception  {
1748         final Bundle bundle = sendCommandBlocking(sourcePackageName, null /* targetPackageName */,
1749                 pendingIntent, ACTION_PENDING_INTENT_GET_CREATOR_PACKAGE);
1750         return bundle.getString(Intent.EXTRA_PACKAGE_NAME);
1751     }
1752 
addPreferredActivity()1753     private void addPreferredActivity() {
1754         final IntentFilter filter = new IntentFilter(
1755                 ACTION_APP_ENUMERATION_PREFERRED_ACTIVITY);
1756         final ComponentName[] candidates = {new ComponentName(TARGET_PREFERRED_ACTIVITY,
1757                 ACTIVITY_CLASS_DUMMY_ACTIVITY)};
1758         SystemUtil.runWithShellPermissionIdentity(() -> {
1759             sPm.addPreferredActivity(filter, IntentFilter.MATCH_ADJUSTMENT_NORMAL,
1760                     candidates, candidates[0]);
1761         }, SET_PREFERRED_APPLICATIONS);
1762     }
1763 
clearPreferredActivity()1764     private void clearPreferredActivity() {
1765         SystemUtil.runWithShellPermissionIdentity(() -> {
1766             sPm.clearPackagePreferredActivities(TARGET_PREFERRED_ACTIVITY);
1767         }, SET_PREFERRED_APPLICATIONS);
1768     }
1769 
setSystemProperty(String name, String value)1770     private void setSystemProperty(String name, String value) throws Exception {
1771         assertEquals("", SystemUtil.runShellCommand("setprop " + name + " " + value));
1772     }
1773 
toBooleanArray(boolean[] from)1774     private static Boolean[] toBooleanArray(boolean[] from) {
1775         final Boolean[] copies = new Boolean[from.length];
1776         for (int i = 0; i < from.length; i++) {
1777             copies[i] = from[i];
1778         }
1779         return copies;
1780     }
1781 }
1782