ifAbsent) {
+ final Integer granted = mMockedPermissions.get(permission + "," + pid + "," + uid);
+ if (null != granted) {
+ return granted;
+ }
+ final Integer allGranted = mMockedPermissions.get(permission);
+ if (null != allGranted) {
+ return allGranted;
+ }
+ return ifAbsent.get();
}
@Override
public int checkPermission(String permission, int pid, int uid) {
- return checkMockedPermission(
- permission, () -> super.checkPermission(permission, pid, uid));
+ return checkMockedPermission(permission, pid, uid,
+ () -> super.checkPermission(permission, pid, uid));
}
@Override
public int checkCallingOrSelfPermission(String permission) {
- return checkMockedPermission(
- permission, () -> super.checkCallingOrSelfPermission(permission));
+ return checkMockedPermission(permission, Process.myPid(), Process.myUid(),
+ () -> super.checkCallingOrSelfPermission(permission));
}
@Override
public void enforceCallingOrSelfPermission(String permission, String message) {
- final Integer granted = mMockedPermissions.get(permission);
- if (granted == null) {
- super.enforceCallingOrSelfPermission(permission, message);
- return;
- }
+ final Integer granted = checkMockedPermission(permission,
+ Process.myPid(), Process.myUid(),
+ () -> {
+ super.enforceCallingOrSelfPermission(permission, message);
+ // enforce will crash if the permission is not granted
+ return PERMISSION_GRANTED;
+ });
if (!granted.equals(PERMISSION_GRANTED)) {
throw new SecurityException("[Test] permission denied: " + permission);
@@ -673,6 +687,8 @@ public class ConnectivityServiceTest {
/**
* Mock checks for the specified permission, and have them behave as per {@code granted}.
*
+ * This will apply across the board no matter what the checked UID and PID are.
+ *
* Passing null reverts to default behavior, which does a real permission check on the
* test package.
* @param granted One of {@link PackageManager#PERMISSION_GRANTED} or
@@ -682,6 +698,21 @@ public class ConnectivityServiceTest {
mMockedPermissions.put(permission, granted);
}
+ /**
+ * Mock checks for the specified permission, and have them behave as per {@code granted}.
+ *
+ * This will only apply to the passed UID and PID.
+ *
+ *
Passing null reverts to default behavior, which does a real permission check on the
+ * test package.
+ * @param granted One of {@link PackageManager#PERMISSION_GRANTED} or
+ * {@link PackageManager#PERMISSION_DENIED}.
+ */
+ public void setPermission(String permission, int pid, int uid, Integer granted) {
+ final String key = permission + "," + pid + "," + uid;
+ mMockedPermissions.put(key, granted);
+ }
+
@Override
public Intent registerReceiverForAllUsers(@Nullable BroadcastReceiver receiver,
@NonNull IntentFilter filter, @Nullable String broadcastPermission,
@@ -1569,15 +1600,21 @@ public class ConnectivityServiceTest {
}
private void withPermission(String permission, ExceptionalRunnable r) throws Exception {
- if (mServiceContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
- r.run();
- return;
- }
try {
mServiceContext.setPermission(permission, PERMISSION_GRANTED);
r.run();
} finally {
- mServiceContext.setPermission(permission, PERMISSION_DENIED);
+ mServiceContext.setPermission(permission, null);
+ }
+ }
+
+ private void withPermission(String permission, int pid, int uid, ExceptionalRunnable r)
+ throws Exception {
+ try {
+ mServiceContext.setPermission(permission, pid, uid, PERMISSION_GRANTED);
+ r.run();
+ } finally {
+ mServiceContext.setPermission(permission, pid, uid, null);
}
}
@@ -9509,6 +9546,19 @@ public class ConnectivityServiceTest {
assertContainsExactly(uidCaptor.getValue(), APP1_UID, APP2_UID);
}
+ @Test
+ public void testStartVpnProfileFromDiffPackage() throws Exception {
+ final String notMyVpnPkg = "com.not.my.vpn";
+ assertThrows(
+ SecurityException.class, () -> mVpnManagerService.startVpnProfile(notMyVpnPkg));
+ }
+
+ @Test
+ public void testStopVpnProfileFromDiffPackage() throws Exception {
+ final String notMyVpnPkg = "com.not.my.vpn";
+ assertThrows(SecurityException.class, () -> mVpnManagerService.stopVpnProfile(notMyVpnPkg));
+ }
+
@Test
public void testUidUpdateChangesInterfaceFilteringRule() throws Exception {
LinkProperties lp = new LinkProperties();
@@ -13368,17 +13418,45 @@ public class ConnectivityServiceTest {
@Test
public void testProfileNetworkPrefCountsRequestsCorrectlyOnSet() throws Exception {
final UserHandle testHandle = setupEnterpriseNetwork();
- testRequestCountLimits(() -> {
- // Set initially to test the limit prior to having existing requests.
- final TestOnCompleteListener listener = new TestOnCompleteListener();
- mCm.setProfileNetworkPreference(testHandle, PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
- Runnable::run, listener);
+ final TestOnCompleteListener listener = new TestOnCompleteListener();
+ // Leave one request available so the profile preference can be set.
+ testRequestCountLimits(1 /* countToLeaveAvailable */, () -> {
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ Process.myPid(), Process.myUid(), () -> {
+ // Set initially to test the limit prior to having existing requests.
+ mCm.setProfileNetworkPreference(testHandle,
+ PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
+ Runnable::run, listener);
+ });
listener.expectOnComplete();
- // re-set so as to test the limit as part of replacing existing requests.
- mCm.setProfileNetworkPreference(testHandle, PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
- Runnable::run, listener);
+ // Simulate filing requests as some app on the work profile
+ final int otherAppUid = UserHandle.getUid(TEST_WORK_PROFILE_USER_ID,
+ UserHandle.getAppId(Process.myUid() + 1));
+ final int remainingCount = ConnectivityService.MAX_NETWORK_REQUESTS_PER_UID
+ - mService.mNetworkRequestCounter.mUidToNetworkRequestCount.get(otherAppUid)
+ - 1;
+ final NetworkCallback[] callbacks = new NetworkCallback[remainingCount];
+ doAsUid(otherAppUid, () -> {
+ for (int i = 0; i < remainingCount; ++i) {
+ callbacks[i] = new TestableNetworkCallback();
+ mCm.registerDefaultNetworkCallback(callbacks[i]);
+ }
+ });
+
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ Process.myPid(), Process.myUid(), () -> {
+ // re-set so as to test the limit as part of replacing existing requests.
+ mCm.setProfileNetworkPreference(testHandle,
+ PROFILE_NETWORK_PREFERENCE_ENTERPRISE, Runnable::run, listener);
+ });
listener.expectOnComplete();
+
+ doAsUid(otherAppUid, () -> {
+ for (final NetworkCallback callback : callbacks) {
+ mCm.unregisterNetworkCallback(callback);
+ }
+ });
});
}
@@ -13390,39 +13468,45 @@ public class ConnectivityServiceTest {
mockHasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE, true);
@OemNetworkPreferences.OemNetworkPreference final int networkPref =
OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY;
- testRequestCountLimits(() -> {
- // Set initially to test the limit prior to having existing requests.
- final TestOemListenerCallback listener = new TestOemListenerCallback();
- mService.setOemNetworkPreference(
- createDefaultOemNetworkPreferences(networkPref), listener);
- listener.expectOnComplete();
+ // Leave one request available so the OEM preference can be set.
+ testRequestCountLimits(1 /* countToLeaveAvailable */, () ->
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, () -> {
+ // Set initially to test the limit prior to having existing requests.
+ final TestOemListenerCallback listener = new TestOemListenerCallback();
+ mService.setOemNetworkPreference(
+ createDefaultOemNetworkPreferences(networkPref), listener);
+ listener.expectOnComplete();
- // re-set so as to test the limit as part of replacing existing requests.
- mService.setOemNetworkPreference(
- createDefaultOemNetworkPreferences(networkPref), listener);
- listener.expectOnComplete();
- });
+ // re-set so as to test the limit as part of replacing existing requests.
+ mService.setOemNetworkPreference(
+ createDefaultOemNetworkPreferences(networkPref), listener);
+ listener.expectOnComplete();
+ }));
}
- private void testRequestCountLimits(@NonNull final Runnable r) throws Exception {
+ private void testRequestCountLimits(final int countToLeaveAvailable,
+ @NonNull final ExceptionalRunnable r) throws Exception {
final ArraySet callbacks = new ArraySet<>();
try {
final int requestCount = mService.mSystemNetworkRequestCounter
.mUidToNetworkRequestCount.get(Process.myUid());
- // The limit is hit when total requests <= limit.
- final int maxCount =
- ConnectivityService.MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - requestCount;
+ // The limit is hit when total requests = limit - 1, and exceeded with a crash when
+ // total requests >= limit.
+ final int countToFile =
+ MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - requestCount - countToLeaveAvailable;
// Need permission so registerDefaultNetworkCallback uses mSystemNetworkRequestCounter
withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, () -> {
- for (int i = 1; i < maxCount - 1; i++) {
+ for (int i = 1; i < countToFile; i++) {
final TestNetworkCallback cb = new TestNetworkCallback();
mCm.registerDefaultNetworkCallback(cb);
callbacks.add(cb);
}
-
- // Code to run to check if it triggers a max request count limit error.
- r.run();
+ assertEquals(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1 - countToLeaveAvailable,
+ mService.mSystemNetworkRequestCounter
+ .mUidToNetworkRequestCount.get(Process.myUid()));
});
+ // Code to run to check if it triggers a max request count limit error.
+ r.run();
} finally {
for (final TestNetworkCallback cb : callbacks) {
mCm.unregisterNetworkCallback(cb);
@@ -13667,15 +13751,18 @@ public class ConnectivityServiceTest {
public void testMobileDataPreferredUidsChangedCountsRequestsCorrectlyOnSet() throws Exception {
ConnectivitySettingsManager.setMobileDataPreferredUids(mServiceContext,
Set.of(PRIMARY_USER_HANDLE.getUid(TEST_PACKAGE_UID)));
- testRequestCountLimits(() -> {
- // Set initially to test the limit prior to having existing requests.
- mService.updateMobileDataPreferredUids();
- waitForIdle();
+ // Leave one request available so MDO preference set up above can be set.
+ testRequestCountLimits(1 /* countToLeaveAvailable */, () ->
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ Process.myPid(), Process.myUid(), () -> {
+ // Set initially to test the limit prior to having existing requests.
+ mService.updateMobileDataPreferredUids();
+ waitForIdle();
- // re-set so as to test the limit as part of replacing existing requests.
- mService.updateMobileDataPreferredUids();
- waitForIdle();
- });
+ // re-set so as to test the limit as part of replacing existing requests
+ mService.updateMobileDataPreferredUids();
+ waitForIdle();
+ }));
}
@Test
diff --git a/tests/unit/java/com/android/server/connectivity/DnsManagerTest.java b/tests/unit/java/com/android/server/connectivity/DnsManagerTest.java
index 9ef558fcea..24aecdb90a 100644
--- a/tests/unit/java/com/android/server/connectivity/DnsManagerTest.java
+++ b/tests/unit/java/com/android/server/connectivity/DnsManagerTest.java
@@ -43,6 +43,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.content.Context;
import android.net.ConnectivitySettingsManager;
import android.net.IDnsResolver;
@@ -106,8 +107,14 @@ public class DnsManagerTest {
@Mock IDnsResolver mMockDnsResolver;
private void assertResolverOptionsEquals(
- @NonNull ResolverOptionsParcel actual,
- @NonNull ResolverOptionsParcel expected) {
+ @Nullable ResolverOptionsParcel actual,
+ @Nullable ResolverOptionsParcel expected) {
+ if (actual == null) {
+ assertNull(expected);
+ return;
+ } else {
+ assertNotNull(expected);
+ }
assertEquals(actual.hosts, expected.hosts);
assertEquals(actual.tcMode, expected.tcMode);
assertEquals(actual.enforceDnsUid, expected.enforceDnsUid);
@@ -365,7 +372,7 @@ public class DnsManagerTest {
expectedParams.tlsName = "";
expectedParams.tlsServers = new String[]{"3.3.3.3", "4.4.4.4"};
expectedParams.transportTypes = TEST_TRANSPORT_TYPES;
- expectedParams.resolverOptions = new ResolverOptionsParcel();
+ expectedParams.resolverOptions = null;
assertResolverParamsEquals(actualParams, expectedParams);
}
diff --git a/tests/unit/java/com/android/server/connectivity/NetworkNotificationManagerTest.java b/tests/unit/java/com/android/server/connectivity/NetworkNotificationManagerTest.java
index c1059b33a8..2cf5d8eaef 100644
--- a/tests/unit/java/com/android/server/connectivity/NetworkNotificationManagerTest.java
+++ b/tests/unit/java/com/android/server/connectivity/NetworkNotificationManagerTest.java
@@ -27,6 +27,7 @@ import static com.android.server.connectivity.NetworkNotificationManager.Notific
import static com.android.server.connectivity.NetworkNotificationManager.NotificationType.SIGN_IN;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.clearInvocations;
@@ -39,9 +40,14 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import android.app.Activity;
+import android.app.Instrumentation;
+import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
+import android.app.PendingIntent;
import android.content.Context;
+import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
@@ -49,11 +55,19 @@ import android.net.ConnectivityResources;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
+import android.os.Bundle;
import android.os.UserHandle;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
+import android.widget.TextView;
+import androidx.annotation.Nullable;
+import androidx.annotation.StringRes;
import androidx.test.filters.SmallTest;
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.uiautomator.UiDevice;
+import androidx.test.uiautomator.UiObject;
+import androidx.test.uiautomator.UiSelector;
import com.android.connectivity.resources.R;
import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
@@ -84,6 +98,7 @@ public class NetworkNotificationManagerTest {
private static final String TEST_EXTRA_INFO = "extra";
private static final int TEST_NOTIF_ID = 101;
private static final String TEST_NOTIF_TAG = NetworkNotificationManager.tagFor(TEST_NOTIF_ID);
+ private static final long TEST_TIMEOUT_MS = 10_000L;
static final NetworkCapabilities CELL_CAPABILITIES = new NetworkCapabilities();
static final NetworkCapabilities WIFI_CAPABILITIES = new NetworkCapabilities();
static final NetworkCapabilities VPN_CAPABILITIES = new NetworkCapabilities();
@@ -102,6 +117,25 @@ public class NetworkNotificationManagerTest {
VPN_CAPABILITIES.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
}
+ /**
+ * Test activity that shows the action it was started with on screen, and dismisses when the
+ * text is tapped.
+ */
+ public static class TestDialogActivity extends Activity {
+ @Override
+ protected void onCreate(@Nullable Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setTurnScreenOn(true);
+ getSystemService(KeyguardManager.class).requestDismissKeyguard(
+ this, null /* callback */);
+
+ final TextView txt = new TextView(this);
+ txt.setText(getIntent().getAction());
+ txt.setOnClickListener(e -> finish());
+ setContentView(txt);
+ }
+ }
+
@Mock Context mCtx;
@Mock Resources mResources;
@Mock DisplayMetrics mDisplayMetrics;
@@ -345,4 +379,82 @@ public class NetworkNotificationManagerTest {
mManager.clearNotification(id, PARTIAL_CONNECTIVITY);
verify(mNotificationManager, never()).cancel(eq(tag), eq(PARTIAL_CONNECTIVITY.eventId));
}
+
+ @Test
+ public void testNotifyNoInternetAsDialogWhenHighPriority() throws Exception {
+ doReturn(true).when(mResources).getBoolean(
+ R.bool.config_notifyNoInternetAsDialogWhenHighPriority);
+
+ mManager.showNotification(TEST_NOTIF_ID, NETWORK_SWITCH, mWifiNai, mCellNai, null, false);
+ // Non-"no internet" notifications are not affected
+ verify(mNotificationManager).notify(eq(TEST_NOTIF_TAG), eq(NETWORK_SWITCH.eventId), any());
+
+ final Instrumentation instr = InstrumentationRegistry.getInstrumentation();
+ final Context ctx = instr.getContext();
+ final String testAction = "com.android.connectivity.coverage.TEST_DIALOG";
+ final Intent intent = new Intent(testAction)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ .setClassName(ctx.getPackageName(), TestDialogActivity.class.getName());
+ final PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0 /* requestCode */,
+ intent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
+
+ mManager.showNotification(TEST_NOTIF_ID, NO_INTERNET, mWifiNai, null /* switchToNai */,
+ pendingIntent, true /* highPriority */);
+
+ // Previous notifications are still dismissed
+ verify(mNotificationManager).cancel(TEST_NOTIF_TAG, NETWORK_SWITCH.eventId);
+
+ // Verify that the activity is shown (the activity shows the action on screen)
+ final UiObject actionText = UiDevice.getInstance(instr).findObject(
+ new UiSelector().text(testAction));
+ assertTrue("Activity not shown", actionText.waitForExists(TEST_TIMEOUT_MS));
+
+ // Tapping the text should dismiss the dialog
+ actionText.click();
+ assertTrue("Activity not dismissed", actionText.waitUntilGone(TEST_TIMEOUT_MS));
+
+ // Verify no NO_INTERNET notification was posted
+ verify(mNotificationManager, never()).notify(any(), eq(NO_INTERNET.eventId), any());
+ }
+
+ private void doNotificationTextTest(NotificationType type, @StringRes int expectedTitleRes,
+ String expectedTitleArg, @StringRes int expectedContentRes) {
+ final String expectedTitle = "title " + expectedTitleArg;
+ final String expectedContent = "expected content";
+ doReturn(expectedTitle).when(mResources).getString(expectedTitleRes, expectedTitleArg);
+ doReturn(expectedContent).when(mResources).getString(expectedContentRes);
+
+ mManager.showNotification(TEST_NOTIF_ID, type, mWifiNai, mCellNai, null, false);
+ final ArgumentCaptor notifCap = ArgumentCaptor.forClass(Notification.class);
+
+ verify(mNotificationManager).notify(eq(TEST_NOTIF_TAG), eq(type.eventId),
+ notifCap.capture());
+ final Notification notif = notifCap.getValue();
+
+ assertEquals(expectedTitle, notif.extras.getString(Notification.EXTRA_TITLE));
+ assertEquals(expectedContent, notif.extras.getString(Notification.EXTRA_TEXT));
+ }
+
+ @Test
+ public void testNotificationText_NoInternet() {
+ doNotificationTextTest(NO_INTERNET,
+ R.string.wifi_no_internet, TEST_EXTRA_INFO,
+ R.string.wifi_no_internet_detailed);
+ }
+
+ @Test
+ public void testNotificationText_Partial() {
+ doNotificationTextTest(PARTIAL_CONNECTIVITY,
+ R.string.network_partial_connectivity, TEST_EXTRA_INFO,
+ R.string.network_partial_connectivity_detailed);
+ }
+
+ @Test
+ public void testNotificationText_PartialAsNoInternet() {
+ doReturn(true).when(mResources).getBoolean(
+ R.bool.config_partialConnectivityNotifiedAsNoInternet);
+ doNotificationTextTest(PARTIAL_CONNECTIVITY,
+ R.string.wifi_no_internet, TEST_EXTRA_INFO,
+ R.string.wifi_no_internet_detailed);
+ }
}