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