WifiConfigManagerTest.java revision f9c69201a95062e33cf62d7bacd465e799788a8f
1/* 2 * Copyright (C) 2016 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 17package com.android.server.wifi; 18 19import static org.junit.Assert.*; 20import static org.mockito.Mockito.*; 21 22import android.app.admin.DeviceAdminInfo; 23import android.app.admin.DevicePolicyManagerInternal; 24import android.app.test.MockAnswerUtil.AnswerWithArguments; 25import android.content.Context; 26import android.content.Intent; 27import android.content.pm.ApplicationInfo; 28import android.content.pm.PackageManager; 29import android.content.pm.UserInfo; 30import android.net.IpConfiguration; 31import android.net.wifi.ScanResult; 32import android.net.wifi.WifiConfiguration; 33import android.net.wifi.WifiConfiguration.NetworkSelectionStatus; 34import android.net.wifi.WifiEnterpriseConfig; 35import android.net.wifi.WifiManager; 36import android.net.wifi.WifiScanner; 37import android.net.wifi.WifiSsid; 38import android.os.UserHandle; 39import android.os.UserManager; 40import android.telephony.TelephonyManager; 41import android.test.suitebuilder.annotation.SmallTest; 42import android.text.TextUtils; 43import android.util.Pair; 44 45import com.android.internal.R; 46import com.android.server.wifi.WifiConfigStoreLegacy.WifiConfigStoreDataLegacy; 47import com.android.server.wifi.util.WifiPermissionsWrapper; 48 49import org.junit.After; 50import org.junit.Before; 51import org.junit.Test; 52import org.mockito.ArgumentCaptor; 53import org.mockito.InOrder; 54import org.mockito.Mock; 55import org.mockito.MockitoAnnotations; 56 57import java.io.FileDescriptor; 58import java.io.PrintWriter; 59import java.io.StringWriter; 60import java.util.ArrayList; 61import java.util.Arrays; 62import java.util.HashSet; 63import java.util.List; 64import java.util.Random; 65import java.util.Set; 66 67/** 68 * Unit tests for {@link com.android.server.wifi.WifiConfigManager}. 69 */ 70@SmallTest 71public class WifiConfigManagerTest { 72 73 private static final String TEST_BSSID = "0a:08:5c:67:89:00"; 74 private static final long TEST_WALLCLOCK_CREATION_TIME_MILLIS = 9845637; 75 private static final long TEST_WALLCLOCK_UPDATE_TIME_MILLIS = 75455637; 76 private static final long TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS = 29457631; 77 private static final int TEST_CREATOR_UID = WifiConfigurationTestUtil.TEST_UID; 78 private static final int TEST_NO_PERM_UID = 7; 79 private static final int TEST_UPDATE_UID = 4; 80 private static final int TEST_SYSUI_UID = 56; 81 private static final int TEST_DEFAULT_USER = UserHandle.USER_SYSTEM; 82 private static final int TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN = 5; 83 private static final Integer[] TEST_FREQ_LIST = {2400, 2450, 5150, 5175, 5650}; 84 private static final String TEST_CREATOR_NAME = "com.wificonfigmanager.creator"; 85 private static final String TEST_UPDATE_NAME = "com.wificonfigmanager.update"; 86 private static final String TEST_NO_PERM_NAME = "com.wificonfigmanager.noperm"; 87 private static final String TEST_DEFAULT_GW_MAC_ADDRESS = "0f:67:ad:ef:09:34"; 88 private static final String TEST_STATIC_PROXY_HOST_1 = "192.168.48.1"; 89 private static final int TEST_STATIC_PROXY_PORT_1 = 8000; 90 private static final String TEST_STATIC_PROXY_EXCLUSION_LIST_1 = ""; 91 private static final String TEST_PAC_PROXY_LOCATION_1 = "http://bleh"; 92 private static final String TEST_STATIC_PROXY_HOST_2 = "192.168.1.1"; 93 private static final int TEST_STATIC_PROXY_PORT_2 = 3000; 94 private static final String TEST_STATIC_PROXY_EXCLUSION_LIST_2 = ""; 95 private static final String TEST_PAC_PROXY_LOCATION_2 = "http://blah"; 96 97 @Mock private Context mContext; 98 @Mock private FrameworkFacade mFrameworkFacade; 99 @Mock private Clock mClock; 100 @Mock private UserManager mUserManager; 101 @Mock private TelephonyManager mTelephonyManager; 102 @Mock private WifiKeyStore mWifiKeyStore; 103 @Mock private WifiConfigStore mWifiConfigStore; 104 @Mock private WifiConfigStoreLegacy mWifiConfigStoreLegacy; 105 @Mock private PackageManager mPackageManager; 106 @Mock private DevicePolicyManagerInternal mDevicePolicyManagerInternal; 107 @Mock private WifiPermissionsWrapper mWifiPermissionsWrapper; 108 @Mock private NetworkListStoreData mNetworkListStoreData; 109 @Mock private DeletedEphemeralSsidsStoreData mDeletedEphemeralSsidsStoreData; 110 111 private MockResources mResources; 112 private InOrder mContextConfigStoreMockOrder; 113 private InOrder mNetworkListStoreDataMockOrder; 114 private WifiConfigManager mWifiConfigManager; 115 116 /** 117 * Setup the mocks and an instance of WifiConfigManager before each test. 118 */ 119 @Before 120 public void setUp() throws Exception { 121 MockitoAnnotations.initMocks(this); 122 123 // Set up the inorder for verifications. This is needed to verify that the broadcasts, 124 // store writes for network updates followed by network additions are in the expected order. 125 mContextConfigStoreMockOrder = inOrder(mContext, mWifiConfigStore); 126 mNetworkListStoreDataMockOrder = inOrder(mNetworkListStoreData); 127 128 // Set up the package name stuff & permission override. 129 when(mContext.getPackageManager()).thenReturn(mPackageManager); 130 mResources = new MockResources(); 131 mResources.setBoolean( 132 R.bool.config_wifi_only_link_same_credential_configurations, true); 133 mResources.setInteger( 134 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels, 135 TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN); 136 when(mContext.getResources()).thenReturn(mResources); 137 138 // Setup UserManager profiles for the default user. 139 setupUserProfiles(TEST_DEFAULT_USER); 140 141 doAnswer(new AnswerWithArguments() { 142 public String answer(int uid) throws Exception { 143 if (uid == TEST_CREATOR_UID) { 144 return TEST_CREATOR_NAME; 145 } else if (uid == TEST_UPDATE_UID) { 146 return TEST_UPDATE_NAME; 147 } else if (uid == TEST_SYSUI_UID) { 148 return WifiConfigManager.SYSUI_PACKAGE_NAME; 149 } else if (uid == TEST_NO_PERM_UID) { 150 return TEST_NO_PERM_NAME; 151 } 152 fail("Unexpected UID: " + uid); 153 return ""; 154 } 155 }).when(mPackageManager).getNameForUid(anyInt()); 156 doAnswer(new AnswerWithArguments() { 157 public int answer(String packageName, int flags, int userId) throws Exception { 158 if (packageName.equals(WifiConfigManager.SYSUI_PACKAGE_NAME)) { 159 return TEST_SYSUI_UID; 160 } else { 161 return 0; 162 } 163 } 164 }).when(mPackageManager).getPackageUidAsUser(anyString(), anyInt(), anyInt()); 165 166 // Both the UID's in the test have the configuration override permission granted by 167 // default. This maybe modified for particular tests if needed. 168 doAnswer(new AnswerWithArguments() { 169 public int answer(String permName, int uid) throws Exception { 170 if (uid == TEST_CREATOR_UID || uid == TEST_UPDATE_UID || uid == TEST_SYSUI_UID) { 171 return PackageManager.PERMISSION_GRANTED; 172 } 173 return PackageManager.PERMISSION_DENIED; 174 } 175 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 176 177 when(mWifiKeyStore 178 .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class))) 179 .thenReturn(true); 180 181 when(mWifiConfigStore.areStoresPresent()).thenReturn(true); 182 183 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), anyInt())) 184 .thenReturn(false); 185 when(mWifiPermissionsWrapper.getDevicePolicyManagerInternal()) 186 .thenReturn(mDevicePolicyManagerInternal); 187 createWifiConfigManager(); 188 } 189 190 /** 191 * Called after each test 192 */ 193 @After 194 public void cleanup() { 195 validateMockitoUsage(); 196 } 197 198 /** 199 * Verifies that network retrieval via 200 * {@link WifiConfigManager#getConfiguredNetworks()} and 201 * {@link WifiConfigManager#getConfiguredNetworksWithPasswords()} works even if we have not 202 * yet loaded data from store. 203 */ 204 @Test 205 public void testGetConfiguredNetworksBeforeLoadFromStore() { 206 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 207 assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty()); 208 } 209 210 /** 211 * Verifies the addition of a single network using 212 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 213 */ 214 @Test 215 public void testAddSingleOpenNetwork() { 216 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 217 List<WifiConfiguration> networks = new ArrayList<>(); 218 networks.add(openNetwork); 219 220 verifyAddNetworkToWifiConfigManager(openNetwork); 221 222 List<WifiConfiguration> retrievedNetworks = 223 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 224 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 225 networks, retrievedNetworks); 226 // Ensure that the newly added network is disabled. 227 assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetworks.get(0).status); 228 } 229 230 /** 231 * Verifies the modification of a single network using 232 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 233 */ 234 @Test 235 public void testUpdateSingleOpenNetwork() { 236 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 237 List<WifiConfiguration> networks = new ArrayList<>(); 238 networks.add(openNetwork); 239 240 verifyAddNetworkToWifiConfigManager(openNetwork); 241 242 // Now change BSSID for the network. 243 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 244 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork); 245 246 // Now verify that the modification has been effective. 247 List<WifiConfiguration> retrievedNetworks = 248 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 249 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 250 networks, retrievedNetworks); 251 } 252 253 /** 254 * Verifies the addition of a single ephemeral network using 255 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that 256 * the {@link WifiConfigManager#getSavedNetworks()} does not return this network. 257 */ 258 @Test 259 public void testAddSingleEphemeralNetwork() throws Exception { 260 WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 261 ephemeralNetwork.ephemeral = true; 262 List<WifiConfiguration> networks = new ArrayList<>(); 263 networks.add(ephemeralNetwork); 264 265 verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork); 266 267 List<WifiConfiguration> retrievedNetworks = 268 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 269 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 270 networks, retrievedNetworks); 271 272 // Ensure that this is not returned in the saved network list. 273 assertTrue(mWifiConfigManager.getSavedNetworks().isEmpty()); 274 } 275 276 /** 277 * Verifies the addition of 2 networks (1 normal and 1 ephemeral) using 278 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that 279 * the ephemeral network configuration is not persisted in config store. 280 */ 281 @Test 282 public void testAddMultipleNetworksAndEnsureEphemeralNetworkNotPersisted() { 283 WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 284 ephemeralNetwork.ephemeral = true; 285 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 286 287 assertTrue(addNetworkToWifiConfigManager(ephemeralNetwork).isSuccess()); 288 assertTrue(addNetworkToWifiConfigManager(openNetwork).isSuccess()); 289 290 // The open network addition should trigger a store write. 291 Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData = 292 captureWriteNetworksListStoreData(); 293 List<WifiConfiguration> networkList = new ArrayList<>(); 294 networkList.addAll(networkListStoreData.first); 295 networkList.addAll(networkListStoreData.second); 296 assertFalse(isNetworkInConfigStoreData(ephemeralNetwork, networkList)); 297 assertTrue(isNetworkInConfigStoreData(openNetwork, networkList)); 298 } 299 300 /** 301 * Verifies that the modification of a single open network using 302 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with a UID which 303 * has no permission to modify the network fails. 304 */ 305 @Test 306 public void testUpdateSingleOpenNetworkFailedDueToPermissionDenied() throws Exception { 307 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 308 List<WifiConfiguration> networks = new ArrayList<>(); 309 networks.add(openNetwork); 310 311 verifyAddNetworkToWifiConfigManager(openNetwork); 312 313 // Now change BSSID of the network. 314 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 315 316 // Deny permission for |UPDATE_UID|. 317 doAnswer(new AnswerWithArguments() { 318 public int answer(String permName, int uid) throws Exception { 319 if (uid == TEST_CREATOR_UID) { 320 return PackageManager.PERMISSION_GRANTED; 321 } 322 return PackageManager.PERMISSION_DENIED; 323 } 324 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 325 326 // Update the same configuration and ensure that the operation failed. 327 NetworkUpdateResult result = updateNetworkToWifiConfigManager(openNetwork); 328 assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID); 329 } 330 331 /** 332 * Verifies that the modification of a single open network using 333 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with the creator UID 334 * should always succeed. 335 */ 336 @Test 337 public void testUpdateSingleOpenNetworkSuccessWithCreatorUID() throws Exception { 338 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 339 List<WifiConfiguration> networks = new ArrayList<>(); 340 networks.add(openNetwork); 341 342 verifyAddNetworkToWifiConfigManager(openNetwork); 343 344 // Now change BSSID of the network. 345 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 346 347 // Deny permission for all UIDs. 348 doAnswer(new AnswerWithArguments() { 349 public int answer(String permName, int uid) throws Exception { 350 return PackageManager.PERMISSION_DENIED; 351 } 352 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 353 354 // Update the same configuration using the creator UID. 355 NetworkUpdateResult result = 356 mWifiConfigManager.addOrUpdateNetwork(openNetwork, TEST_CREATOR_UID); 357 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 358 359 // Now verify that the modification has been effective. 360 List<WifiConfiguration> retrievedNetworks = 361 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 362 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 363 networks, retrievedNetworks); 364 } 365 366 /** 367 * Verifies the addition of a single PSK network using 368 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that 369 * {@link WifiConfigManager#getSavedNetworks()} masks the password. 370 */ 371 @Test 372 public void testAddSinglePskNetwork() { 373 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 374 List<WifiConfiguration> networks = new ArrayList<>(); 375 networks.add(pskNetwork); 376 377 verifyAddNetworkToWifiConfigManager(pskNetwork); 378 379 List<WifiConfiguration> retrievedNetworks = 380 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 381 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 382 networks, retrievedNetworks); 383 384 List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks(); 385 assertEquals(retrievedSavedNetworks.size(), 1); 386 assertEquals(retrievedSavedNetworks.get(0).configKey(), pskNetwork.configKey()); 387 assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0)); 388 } 389 390 /** 391 * Verifies the addition of a single WEP network using 392 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that 393 * {@link WifiConfigManager#getSavedNetworks()} masks the password. 394 */ 395 @Test 396 public void testAddSingleWepNetwork() { 397 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 398 List<WifiConfiguration> networks = new ArrayList<>(); 399 networks.add(wepNetwork); 400 401 verifyAddNetworkToWifiConfigManager(wepNetwork); 402 403 List<WifiConfiguration> retrievedNetworks = 404 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 405 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 406 networks, retrievedNetworks); 407 408 List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks(); 409 assertEquals(retrievedSavedNetworks.size(), 1); 410 assertEquals(retrievedSavedNetworks.get(0).configKey(), wepNetwork.configKey()); 411 assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0)); 412 } 413 414 /** 415 * Verifies the modification of an IpConfiguration using 416 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 417 */ 418 @Test 419 public void testUpdateIpConfiguration() { 420 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 421 List<WifiConfiguration> networks = new ArrayList<>(); 422 networks.add(openNetwork); 423 424 verifyAddNetworkToWifiConfigManager(openNetwork); 425 426 // Now change BSSID of the network. 427 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 428 429 // Update the same configuration and ensure that the IP configuration change flags 430 // are not set. 431 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork); 432 433 // Configure mock DevicePolicyManager to give Profile Owner permission so that we can modify 434 // proxy settings on a configuration 435 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), 436 eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER))).thenReturn(true); 437 438 // Change the IpConfiguration now and ensure that the IP configuration flags are set now. 439 assertAndSetNetworkIpConfiguration( 440 openNetwork, 441 WifiConfigurationTestUtil.createStaticIpConfigurationWithStaticProxy()); 442 verifyUpdateNetworkToWifiConfigManagerWithIpChange(openNetwork); 443 444 // Now verify that all the modifications have been effective. 445 List<WifiConfiguration> retrievedNetworks = 446 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 447 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 448 networks, retrievedNetworks); 449 } 450 451 /** 452 * Verifies the removal of a single network using 453 * {@link WifiConfigManager#removeNetwork(int)} 454 */ 455 @Test 456 public void testRemoveSingleOpenNetwork() { 457 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 458 459 verifyAddNetworkToWifiConfigManager(openNetwork); 460 // Ensure that configured network list is not empty. 461 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 462 463 verifyRemoveNetworkFromWifiConfigManager(openNetwork); 464 // Ensure that configured network list is empty now. 465 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 466 } 467 468 /** 469 * Verifies the removal of an ephemeral network using 470 * {@link WifiConfigManager#removeNetwork(int)} 471 */ 472 @Test 473 public void testRemoveSingleEphemeralNetwork() throws Exception { 474 WifiConfiguration ephemeralNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 475 ephemeralNetwork.ephemeral = true; 476 477 verifyAddEphemeralNetworkToWifiConfigManager(ephemeralNetwork); 478 // Ensure that configured network list is not empty. 479 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 480 481 verifyRemoveEphemeralNetworkFromWifiConfigManager(ephemeralNetwork); 482 // Ensure that configured network list is empty now. 483 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 484 } 485 486 /** 487 * Verifies the removal of a Passpoint network using 488 * {@link WifiConfigManager#removeNetwork(int)} 489 */ 490 @Test 491 public void testRemoveSinglePasspointNetwork() throws Exception { 492 WifiConfiguration passpointNetwork = WifiConfigurationTestUtil.createPasspointNetwork(); 493 494 verifyAddPasspointNetworkToWifiConfigManager(passpointNetwork); 495 // Ensure that configured network list is not empty. 496 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 497 498 verifyRemovePasspointNetworkFromWifiConfigManager(passpointNetwork); 499 // Ensure that configured network list is empty now. 500 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 501 } 502 503 /** 504 * Verifies the addition & update of multiple networks using 505 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and the 506 * removal of networks using 507 * {@link WifiConfigManager#removeNetwork(int)} 508 */ 509 @Test 510 public void testAddUpdateRemoveMultipleNetworks() { 511 List<WifiConfiguration> networks = new ArrayList<>(); 512 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 513 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 514 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 515 networks.add(openNetwork); 516 networks.add(pskNetwork); 517 networks.add(wepNetwork); 518 519 verifyAddNetworkToWifiConfigManager(openNetwork); 520 verifyAddNetworkToWifiConfigManager(pskNetwork); 521 verifyAddNetworkToWifiConfigManager(wepNetwork); 522 523 // Now verify that all the additions has been effective. 524 List<WifiConfiguration> retrievedNetworks = 525 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 526 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 527 networks, retrievedNetworks); 528 529 // Modify all the 3 configurations and update it to WifiConfigManager. 530 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 531 assertAndSetNetworkBSSID(pskNetwork, TEST_BSSID); 532 assertAndSetNetworkIpConfiguration( 533 wepNetwork, 534 WifiConfigurationTestUtil.createStaticIpConfigurationWithPacProxy()); 535 536 // Configure mock DevicePolicyManager to give Profile Owner permission so that we can modify 537 // proxy settings on a configuration 538 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), 539 eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER))).thenReturn(true); 540 541 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork); 542 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork); 543 verifyUpdateNetworkToWifiConfigManagerWithIpChange(wepNetwork); 544 // Now verify that all the modifications has been effective. 545 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 546 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 547 networks, retrievedNetworks); 548 549 // Now remove all 3 networks. 550 verifyRemoveNetworkFromWifiConfigManager(openNetwork); 551 verifyRemoveNetworkFromWifiConfigManager(pskNetwork); 552 verifyRemoveNetworkFromWifiConfigManager(wepNetwork); 553 554 // Ensure that configured network list is empty now. 555 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 556 } 557 558 /** 559 * Verifies the update of network status using 560 * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)}. 561 */ 562 @Test 563 public void testNetworkSelectionStatus() { 564 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 565 566 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 567 568 // First set it to enabled. 569 verifyUpdateNetworkSelectionStatus( 570 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 571 572 // Now set it to temporarily disabled. The threshold for association rejection is 5, so 573 // disable it 5 times to actually mark it temporarily disabled. 574 int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION; 575 int assocRejectThreshold = 576 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason]; 577 for (int i = 1; i <= assocRejectThreshold; i++) { 578 verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i); 579 } 580 581 // Now set it to permanently disabled. 582 verifyUpdateNetworkSelectionStatus( 583 result.getNetworkId(), NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER, 0); 584 585 // Now set it back to enabled. 586 verifyUpdateNetworkSelectionStatus( 587 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 588 } 589 590 /** 591 * Verifies the update of network status using 592 * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and ensures that 593 * enabling a network clears out all the temporary disable counters. 594 */ 595 @Test 596 public void testNetworkSelectionStatusEnableClearsDisableCounters() { 597 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 598 599 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 600 601 // First set it to enabled. 602 verifyUpdateNetworkSelectionStatus( 603 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 604 605 // Now set it to temporarily disabled 2 times for 2 different reasons. 606 verifyUpdateNetworkSelectionStatus( 607 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1); 608 verifyUpdateNetworkSelectionStatus( 609 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 2); 610 verifyUpdateNetworkSelectionStatus( 611 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1); 612 verifyUpdateNetworkSelectionStatus( 613 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 2); 614 615 // Now set it back to enabled. 616 verifyUpdateNetworkSelectionStatus( 617 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 618 619 // Ensure that the counters have all been reset now. 620 verifyUpdateNetworkSelectionStatus( 621 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1); 622 verifyUpdateNetworkSelectionStatus( 623 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1); 624 } 625 626 /** 627 * Verifies the enabling of temporarily disabled network using 628 * {@link WifiConfigManager#tryEnableNetwork(int)}. 629 */ 630 @Test 631 public void testTryEnableNetwork() { 632 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 633 634 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 635 636 // First set it to enabled. 637 verifyUpdateNetworkSelectionStatus( 638 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 639 640 // Now set it to temporarily disabled. The threshold for association rejection is 5, so 641 // disable it 5 times to actually mark it temporarily disabled. 642 int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION; 643 int assocRejectThreshold = 644 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason]; 645 for (int i = 1; i <= assocRejectThreshold; i++) { 646 verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i); 647 } 648 649 // Now let's try enabling this network without changing the time, this should fail and the 650 // status remains temporarily disabled. 651 assertFalse(mWifiConfigManager.tryEnableNetwork(result.getNetworkId())); 652 NetworkSelectionStatus retrievedStatus = 653 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()) 654 .getNetworkSelectionStatus(); 655 assertTrue(retrievedStatus.isNetworkTemporaryDisabled()); 656 657 // Now advance time by the timeout for association rejection and ensure that the network 658 // is now enabled. 659 int assocRejectTimeout = 660 WifiConfigManager.NETWORK_SELECTION_DISABLE_TIMEOUT_MS[assocRejectReason]; 661 when(mClock.getElapsedSinceBootMillis()) 662 .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS + assocRejectTimeout); 663 664 assertTrue(mWifiConfigManager.tryEnableNetwork(result.getNetworkId())); 665 retrievedStatus = 666 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()) 667 .getNetworkSelectionStatus(); 668 assertTrue(retrievedStatus.isNetworkEnabled()); 669 } 670 671 /** 672 * Verifies the enabling of network using 673 * {@link WifiConfigManager#enableNetwork(int, boolean, int)} and 674 * {@link WifiConfigManager#disableNetwork(int, int)}. 675 */ 676 @Test 677 public void testEnableDisableNetwork() { 678 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 679 680 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 681 682 assertTrue(mWifiConfigManager.enableNetwork( 683 result.getNetworkId(), false, TEST_CREATOR_UID)); 684 WifiConfiguration retrievedNetwork = 685 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 686 NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 687 assertTrue(retrievedStatus.isNetworkEnabled()); 688 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED); 689 690 // Now set it disabled. 691 assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 692 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 693 retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 694 assertTrue(retrievedStatus.isNetworkPermanentlyDisabled()); 695 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED); 696 } 697 698 /** 699 * Verifies the enabling of network using 700 * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with a UID which 701 * has no permission to modify the network fails.. 702 */ 703 @Test 704 public void testEnableDisableNetworkFailedDueToPermissionDenied() throws Exception { 705 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 706 707 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 708 709 assertTrue(mWifiConfigManager.enableNetwork( 710 result.getNetworkId(), false, TEST_CREATOR_UID)); 711 WifiConfiguration retrievedNetwork = 712 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 713 NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 714 assertTrue(retrievedStatus.isNetworkEnabled()); 715 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED); 716 717 // Deny permission for |UPDATE_UID|. 718 doAnswer(new AnswerWithArguments() { 719 public int answer(String permName, int uid) throws Exception { 720 if (uid == TEST_CREATOR_UID) { 721 return PackageManager.PERMISSION_GRANTED; 722 } 723 return PackageManager.PERMISSION_DENIED; 724 } 725 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 726 727 // Now try to set it disabled with |TEST_UPDATE_UID|, it should fail and the network 728 // should remain enabled. 729 assertFalse(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_UPDATE_UID)); 730 retrievedStatus = 731 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()) 732 .getNetworkSelectionStatus(); 733 assertTrue(retrievedStatus.isNetworkEnabled()); 734 assertEquals(WifiConfiguration.Status.ENABLED, retrievedNetwork.status); 735 } 736 737 /** 738 * Verifies the updation of network's connectUid using 739 * {@link WifiConfigManager#checkAndUpdateLastConnectUid(int, int)}. 740 */ 741 @Test 742 public void testUpdateLastConnectUid() throws Exception { 743 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 744 745 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 746 747 assertTrue( 748 mWifiConfigManager.checkAndUpdateLastConnectUid( 749 result.getNetworkId(), TEST_CREATOR_UID)); 750 WifiConfiguration retrievedNetwork = 751 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 752 assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid); 753 754 // Deny permission for |UPDATE_UID|. 755 doAnswer(new AnswerWithArguments() { 756 public int answer(String permName, int uid) throws Exception { 757 if (uid == TEST_CREATOR_UID) { 758 return PackageManager.PERMISSION_GRANTED; 759 } 760 return PackageManager.PERMISSION_DENIED; 761 } 762 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 763 764 // Now try to update the last connect UID with |TEST_UPDATE_UID|, it should fail and 765 // the lastConnectUid should remain the same. 766 assertFalse( 767 mWifiConfigManager.checkAndUpdateLastConnectUid( 768 result.getNetworkId(), TEST_UPDATE_UID)); 769 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 770 assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid); 771 } 772 773 /** 774 * Verifies that any configuration update attempt with an null config is gracefully 775 * handled. 776 * This invokes {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}. 777 */ 778 @Test 779 public void testAddOrUpdateNetworkWithNullConfig() { 780 NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork(null, TEST_CREATOR_UID); 781 assertFalse(result.isSuccess()); 782 } 783 784 /** 785 * Verifies that attempting to remove a network without any configs stored will return false. 786 * This tests the case where we have not loaded any configs, potentially due to a pending store 787 * read. 788 * This invokes {@link WifiConfigManager#removeNetwork(int)}. 789 */ 790 @Test 791 public void testRemoveNetworkWithEmptyConfigStore() { 792 int networkId = new Random().nextInt(); 793 assertFalse(mWifiConfigManager.removeNetwork(networkId, TEST_CREATOR_UID)); 794 } 795 796 /** 797 * Verifies that any configuration removal attempt with an invalid networkID is gracefully 798 * handled. 799 * This invokes {@link WifiConfigManager#removeNetwork(int)}. 800 */ 801 @Test 802 public void testRemoveNetworkWithInvalidNetworkId() { 803 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 804 805 verifyAddNetworkToWifiConfigManager(openNetwork); 806 807 // Change the networkID to an invalid one. 808 openNetwork.networkId++; 809 assertFalse(mWifiConfigManager.removeNetwork(openNetwork.networkId, TEST_CREATOR_UID)); 810 } 811 812 /** 813 * Verifies that any configuration update attempt with an invalid networkID is gracefully 814 * handled. 815 * This invokes {@link WifiConfigManager#enableNetwork(int, boolean, int)}, 816 * {@link WifiConfigManager#disableNetwork(int, int)}, 817 * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and 818 * {@link WifiConfigManager#checkAndUpdateLastConnectUid(int, int)}. 819 */ 820 @Test 821 public void testChangeConfigurationWithInvalidNetworkId() { 822 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 823 824 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 825 826 assertFalse(mWifiConfigManager.enableNetwork( 827 result.getNetworkId() + 1, false, TEST_CREATOR_UID)); 828 assertFalse(mWifiConfigManager.disableNetwork(result.getNetworkId() + 1, TEST_CREATOR_UID)); 829 assertFalse(mWifiConfigManager.updateNetworkSelectionStatus( 830 result.getNetworkId() + 1, NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER)); 831 assertFalse(mWifiConfigManager.checkAndUpdateLastConnectUid( 832 result.getNetworkId() + 1, TEST_CREATOR_UID)); 833 } 834 835 /** 836 * Verifies multiple modification of a single network using 837 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}. 838 * This test is basically checking if the apps can reset some of the fields of the config after 839 * addition. The fields being reset in this test are the |preSharedKey| and |wepKeys|. 840 * 1. Create an open network initially. 841 * 2. Modify the added network config to a WEP network config with all the 4 keys set. 842 * 3. Modify the added network config to a WEP network config with only 1 key set. 843 * 4. Modify the added network config to a PSK network config. 844 */ 845 @Test 846 public void testMultipleUpdatesSingleNetwork() { 847 WifiConfiguration network = WifiConfigurationTestUtil.createOpenNetwork(); 848 verifyAddNetworkToWifiConfigManager(network); 849 850 // Now add |wepKeys| to the network. We don't need to update the |allowedKeyManagement| 851 // fields for open to WEP conversion. 852 String[] wepKeys = 853 Arrays.copyOf(WifiConfigurationTestUtil.TEST_WEP_KEYS, 854 WifiConfigurationTestUtil.TEST_WEP_KEYS.length); 855 int wepTxKeyIdx = WifiConfigurationTestUtil.TEST_WEP_TX_KEY_INDEX; 856 assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx); 857 858 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 859 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 860 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 861 862 // Now empty out 3 of the |wepKeys[]| and ensure that those keys have been reset correctly. 863 for (int i = 1; i < network.wepKeys.length; i++) { 864 wepKeys[i] = ""; 865 } 866 wepTxKeyIdx = 0; 867 assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx); 868 869 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 870 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 871 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 872 873 // Now change the config to a PSK network config by resetting the remaining |wepKey[0]| 874 // field and setting the |preSharedKey| and |allowedKeyManagement| fields. 875 wepKeys[0] = ""; 876 wepTxKeyIdx = -1; 877 assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx); 878 network.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 879 assertAndSetNetworkPreSharedKey(network, WifiConfigurationTestUtil.TEST_PSK); 880 881 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 882 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 883 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 884 } 885 886 /** 887 * Verifies the modification of a WifiEnteriseConfig using 888 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}. 889 */ 890 @Test 891 public void testUpdateWifiEnterpriseConfig() { 892 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 893 verifyAddNetworkToWifiConfigManager(network); 894 895 // Set the |password| field in WifiEnterpriseConfig and modify the config to PEAP/GTC. 896 network.enterpriseConfig = 897 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 898 assertAndSetNetworkEnterprisePassword(network, "test"); 899 900 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 901 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 902 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 903 904 // Reset the |password| field in WifiEnterpriseConfig and modify the config to TLS/None. 905 network.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS); 906 network.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE); 907 assertAndSetNetworkEnterprisePassword(network, ""); 908 909 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 910 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 911 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 912 } 913 914 /** 915 * Verifies the modification of a single network using 916 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} by passing in nulls 917 * in all the publicly exposed fields. 918 */ 919 @Test 920 public void testUpdateSingleNetworkWithNullValues() { 921 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 922 verifyAddNetworkToWifiConfigManager(network); 923 924 // Save a copy of the original network for comparison. 925 WifiConfiguration originalNetwork = new WifiConfiguration(network); 926 927 // Now set all the public fields to null and try updating the network. 928 network.allowedAuthAlgorithms.clear(); 929 network.allowedProtocols.clear(); 930 network.allowedKeyManagement.clear(); 931 network.allowedPairwiseCiphers.clear(); 932 network.allowedGroupCiphers.clear(); 933 network.setIpConfiguration(null); 934 network.enterpriseConfig = null; 935 936 // Update the network. 937 NetworkUpdateResult result = updateNetworkToWifiConfigManager(network); 938 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 939 assertFalse(result.isNewNetwork()); 940 941 // Verify no changes to the original network configuration. 942 verifyNetworkUpdateBroadcast(originalNetwork); 943 verifyNetworkInConfigStoreData(originalNetwork); 944 assertFalse(result.hasIpChanged()); 945 assertFalse(result.hasProxyChanged()); 946 947 // Copy over the updated debug params to the original network config before comparison. 948 originalNetwork.lastUpdateUid = network.lastUpdateUid; 949 originalNetwork.lastUpdateName = network.lastUpdateName; 950 originalNetwork.updateTime = network.updateTime; 951 952 // Now verify that there was no change to the network configurations. 953 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 954 originalNetwork, 955 mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId)); 956 } 957 958 /** 959 * Verifies that the modification of a single network using 960 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} does not modify 961 * existing configuration if there is a failure. 962 */ 963 @Test 964 public void testUpdateSingleNetworkFailureDoesNotModifyOriginal() { 965 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 966 network.enterpriseConfig = 967 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 968 verifyAddNetworkToWifiConfigManager(network); 969 970 // Save a copy of the original network for comparison. 971 WifiConfiguration originalNetwork = new WifiConfiguration(network); 972 973 // Now modify the network's EAP method. 974 network.enterpriseConfig = 975 WifiConfigurationTestUtil.createTLSWifiEnterpriseConfigWithNonePhase2(); 976 977 // Fail this update because of cert installation failure. 978 when(mWifiKeyStore 979 .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class))) 980 .thenReturn(false); 981 NetworkUpdateResult result = 982 mWifiConfigManager.addOrUpdateNetwork(network, TEST_UPDATE_UID); 983 assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID); 984 985 // Now verify that there was no change to the network configurations. 986 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 987 originalNetwork, 988 mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId)); 989 } 990 991 /** 992 * Verifies the matching of networks with different encryption types with the 993 * corresponding scan detail using 994 * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)}. 995 * The test also verifies that the provided scan detail was cached, 996 */ 997 @Test 998 public void testMatchScanDetailToNetworksAndCache() { 999 // Create networks of different types and ensure that they're all matched using 1000 // the corresponding ScanDetail correctly. 1001 verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 1002 WifiConfigurationTestUtil.createOpenNetwork()); 1003 verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 1004 WifiConfigurationTestUtil.createWepNetwork()); 1005 verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 1006 WifiConfigurationTestUtil.createPskNetwork()); 1007 verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 1008 WifiConfigurationTestUtil.createEapNetwork()); 1009 } 1010 1011 /** 1012 * Verifies that scan details with wrong SSID/authentication types are not matched using 1013 * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)} 1014 * to the added networks. 1015 */ 1016 @Test 1017 public void testNoMatchScanDetailToNetwork() { 1018 // First create networks of different types. 1019 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 1020 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 1021 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1022 WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); 1023 1024 // Now add them to WifiConfigManager. 1025 verifyAddNetworkToWifiConfigManager(openNetwork); 1026 verifyAddNetworkToWifiConfigManager(wepNetwork); 1027 verifyAddNetworkToWifiConfigManager(pskNetwork); 1028 verifyAddNetworkToWifiConfigManager(eapNetwork); 1029 1030 // Now create dummy scan detail corresponding to the networks. 1031 ScanDetail openNetworkScanDetail = createScanDetailForNetwork(openNetwork); 1032 ScanDetail wepNetworkScanDetail = createScanDetailForNetwork(wepNetwork); 1033 ScanDetail pskNetworkScanDetail = createScanDetailForNetwork(pskNetwork); 1034 ScanDetail eapNetworkScanDetail = createScanDetailForNetwork(eapNetwork); 1035 1036 // Now mix and match parameters from different scan details. 1037 openNetworkScanDetail.getScanResult().SSID = 1038 wepNetworkScanDetail.getScanResult().SSID; 1039 wepNetworkScanDetail.getScanResult().capabilities = 1040 pskNetworkScanDetail.getScanResult().capabilities; 1041 pskNetworkScanDetail.getScanResult().capabilities = 1042 eapNetworkScanDetail.getScanResult().capabilities; 1043 eapNetworkScanDetail.getScanResult().capabilities = 1044 openNetworkScanDetail.getScanResult().capabilities; 1045 1046 // Try to lookup a saved network using the modified scan details. All of these should fail. 1047 assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(openNetworkScanDetail)); 1048 assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(wepNetworkScanDetail)); 1049 assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(pskNetworkScanDetail)); 1050 assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(eapNetworkScanDetail)); 1051 1052 // All the cache's should be empty as well. 1053 assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId)); 1054 assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(wepNetwork.networkId)); 1055 assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(pskNetwork.networkId)); 1056 assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(eapNetwork.networkId)); 1057 } 1058 1059 /** 1060 * Verifies that ScanDetail added for a network is cached correctly. 1061 */ 1062 @Test 1063 public void testUpdateScanDetailForNetwork() { 1064 // First add the provided network. 1065 WifiConfiguration testNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 1066 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(testNetwork); 1067 1068 // Now create a dummy scan detail corresponding to the network. 1069 ScanDetail scanDetail = createScanDetailForNetwork(testNetwork); 1070 ScanResult scanResult = scanDetail.getScanResult(); 1071 1072 mWifiConfigManager.updateScanDetailForNetwork(result.getNetworkId(), scanDetail); 1073 1074 // Now retrieve the scan detail cache and ensure that the new scan detail is in cache. 1075 ScanDetailCache retrievedScanDetailCache = 1076 mWifiConfigManager.getScanDetailCacheForNetwork(result.getNetworkId()); 1077 assertEquals(1, retrievedScanDetailCache.size()); 1078 ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID); 1079 1080 ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult); 1081 } 1082 1083 /** 1084 * Verifies that scan detail cache is trimmed down when the size of the cache for a network 1085 * exceeds {@link WifiConfigManager#SCAN_CACHE_ENTRIES_MAX_SIZE}. 1086 */ 1087 @Test 1088 public void testScanDetailCacheTrimForNetwork() { 1089 // Add a single network. 1090 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 1091 verifyAddNetworkToWifiConfigManager(openNetwork); 1092 1093 ScanDetailCache scanDetailCache; 1094 String testBssidPrefix = "00:a5:b8:c9:45:"; 1095 1096 // Modify |BSSID| field in the scan result and add copies of scan detail 1097 // |SCAN_CACHE_ENTRIES_MAX_SIZE| times. 1098 int scanDetailNum = 1; 1099 for (; scanDetailNum <= WifiConfigManager.SCAN_CACHE_ENTRIES_MAX_SIZE; scanDetailNum++) { 1100 // Create dummy scan detail caches with different BSSID for the network. 1101 ScanDetail scanDetail = 1102 createScanDetailForNetwork( 1103 openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum)); 1104 assertNotNull( 1105 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail)); 1106 1107 // The size of scan detail cache should keep growing until it hits 1108 // |SCAN_CACHE_ENTRIES_MAX_SIZE|. 1109 scanDetailCache = 1110 mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId); 1111 assertEquals(scanDetailNum, scanDetailCache.size()); 1112 } 1113 1114 // Now add the |SCAN_CACHE_ENTRIES_MAX_SIZE + 1| entry. This should trigger the trim. 1115 ScanDetail scanDetail = 1116 createScanDetailForNetwork( 1117 openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum)); 1118 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail)); 1119 1120 // Retrieve the scan detail cache and ensure that the size was trimmed down to 1121 // |SCAN_CACHE_ENTRIES_TRIM_SIZE + 1|. The "+1" is to account for the new entry that 1122 // was added after the trim. 1123 scanDetailCache = mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId); 1124 assertEquals(WifiConfigManager.SCAN_CACHE_ENTRIES_TRIM_SIZE + 1, scanDetailCache.size()); 1125 } 1126 1127 /** 1128 * Verifies that hasEverConnected is false for a newly added network. 1129 */ 1130 @Test 1131 public void testAddNetworkHasEverConnectedFalse() { 1132 verifyAddNetworkHasEverConnectedFalse(WifiConfigurationTestUtil.createOpenNetwork()); 1133 } 1134 1135 /** 1136 * Verifies that hasEverConnected is false for a newly added network even when new config has 1137 * mistakenly set HasEverConnected to true. 1138 */ 1139 @Test 1140 public void testAddNetworkOverridesHasEverConnectedWhenTrueInNewConfig() { 1141 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 1142 openNetwork.getNetworkSelectionStatus().setHasEverConnected(true); 1143 verifyAddNetworkHasEverConnectedFalse(openNetwork); 1144 } 1145 1146 /** 1147 * Verify that the |HasEverConnected| is set when 1148 * {@link WifiConfigManager#updateNetworkAfterConnect(int)} is invoked. 1149 */ 1150 @Test 1151 public void testUpdateConfigAfterConnectHasEverConnectedTrue() { 1152 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 1153 verifyAddNetworkHasEverConnectedFalse(openNetwork); 1154 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(openNetwork.networkId); 1155 } 1156 1157 /** 1158 * Verifies that hasEverConnected is cleared when a network config |preSharedKey| is updated. 1159 */ 1160 @Test 1161 public void testUpdatePreSharedKeyClearsHasEverConnected() { 1162 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1163 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1164 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1165 1166 // Now update the same network with a different psk. 1167 assertFalse(pskNetwork.preSharedKey.equals("newpassword")); 1168 pskNetwork.preSharedKey = "newpassword"; 1169 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1170 } 1171 1172 /** 1173 * Verifies that hasEverConnected is cleared when a network config |wepKeys| is updated. 1174 */ 1175 @Test 1176 public void testUpdateWepKeysClearsHasEverConnected() { 1177 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 1178 verifyAddNetworkHasEverConnectedFalse(wepNetwork); 1179 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId); 1180 1181 // Now update the same network with a different wep. 1182 assertFalse(wepNetwork.wepKeys[0].equals("newpassword")); 1183 wepNetwork.wepKeys[0] = "newpassword"; 1184 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork); 1185 } 1186 1187 /** 1188 * Verifies that hasEverConnected is cleared when a network config |wepTxKeyIndex| is updated. 1189 */ 1190 @Test 1191 public void testUpdateWepTxKeyClearsHasEverConnected() { 1192 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 1193 verifyAddNetworkHasEverConnectedFalse(wepNetwork); 1194 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId); 1195 1196 // Now update the same network with a different wep. 1197 assertFalse(wepNetwork.wepTxKeyIndex == 3); 1198 wepNetwork.wepTxKeyIndex = 3; 1199 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork); 1200 } 1201 1202 /** 1203 * Verifies that hasEverConnected is cleared when a network config |allowedKeyManagement| is 1204 * updated. 1205 */ 1206 @Test 1207 public void testUpdateAllowedKeyManagementClearsHasEverConnected() { 1208 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1209 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1210 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1211 1212 assertFalse(pskNetwork.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)); 1213 pskNetwork.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X); 1214 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1215 } 1216 1217 /** 1218 * Verifies that hasEverConnected is cleared when a network config |allowedProtocol| is 1219 * updated. 1220 */ 1221 @Test 1222 public void testUpdateProtocolsClearsHasEverConnected() { 1223 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1224 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1225 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1226 1227 assertFalse(pskNetwork.allowedProtocols.get(WifiConfiguration.Protocol.OSEN)); 1228 pskNetwork.allowedProtocols.set(WifiConfiguration.Protocol.OSEN); 1229 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1230 } 1231 1232 /** 1233 * Verifies that hasEverConnected is cleared when a network config |allowedAuthAlgorithms| is 1234 * updated. 1235 */ 1236 @Test 1237 public void testUpdateAllowedAuthAlgorithmsClearsHasEverConnected() { 1238 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1239 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1240 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1241 1242 assertFalse(pskNetwork.allowedAuthAlgorithms.get(WifiConfiguration.AuthAlgorithm.LEAP)); 1243 pskNetwork.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP); 1244 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1245 } 1246 1247 /** 1248 * Verifies that hasEverConnected is cleared when a network config |allowedPairwiseCiphers| is 1249 * updated. 1250 */ 1251 @Test 1252 public void testUpdateAllowedPairwiseCiphersClearsHasEverConnected() { 1253 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1254 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1255 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1256 1257 assertFalse(pskNetwork.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.NONE)); 1258 pskNetwork.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE); 1259 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1260 } 1261 1262 /** 1263 * Verifies that hasEverConnected is cleared when a network config |allowedGroup| is 1264 * updated. 1265 */ 1266 @Test 1267 public void testUpdateAllowedGroupCiphersClearsHasEverConnected() { 1268 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1269 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1270 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1271 1272 assertTrue(pskNetwork.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.WEP104)); 1273 pskNetwork.allowedGroupCiphers.clear(WifiConfiguration.GroupCipher.WEP104); 1274 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1275 } 1276 1277 /** 1278 * Verifies that hasEverConnected is cleared when a network config |hiddenSSID| is 1279 * updated. 1280 */ 1281 @Test 1282 public void testUpdateHiddenSSIDClearsHasEverConnected() { 1283 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1284 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1285 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1286 1287 assertFalse(pskNetwork.hiddenSSID); 1288 pskNetwork.hiddenSSID = true; 1289 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1290 } 1291 1292 /** 1293 * Verifies that hasEverConnected is not cleared when a network config |requirePMF| is 1294 * updated. 1295 */ 1296 @Test 1297 public void testUpdateRequirePMFDoesNotClearHasEverConnected() { 1298 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1299 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1300 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1301 1302 assertFalse(pskNetwork.requirePMF); 1303 pskNetwork.requirePMF = true; 1304 1305 NetworkUpdateResult result = 1306 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork); 1307 WifiConfiguration retrievedNetwork = 1308 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 1309 assertTrue("Updating network non-credentials config should not clear hasEverConnected.", 1310 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 1311 } 1312 1313 /** 1314 * Verifies that hasEverConnected is cleared when a network config |enterpriseConfig| is 1315 * updated. 1316 */ 1317 @Test 1318 public void testUpdateEnterpriseConfigClearsHasEverConnected() { 1319 WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); 1320 eapNetwork.enterpriseConfig = 1321 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 1322 verifyAddNetworkHasEverConnectedFalse(eapNetwork); 1323 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(eapNetwork.networkId); 1324 1325 assertFalse(eapNetwork.enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS); 1326 eapNetwork.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS); 1327 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(eapNetwork); 1328 } 1329 1330 /** 1331 * Verifies the ordering of network list generated using 1332 * {@link WifiConfigManager#retrievePnoNetworkList()}. 1333 */ 1334 @Test 1335 public void testRetrievePnoList() { 1336 // Create and add 3 networks. 1337 WifiConfiguration network1 = WifiConfigurationTestUtil.createEapNetwork(); 1338 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1339 WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 1340 verifyAddNetworkToWifiConfigManager(network1); 1341 verifyAddNetworkToWifiConfigManager(network2); 1342 verifyAddNetworkToWifiConfigManager(network3); 1343 1344 // Enable all of them. 1345 assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID)); 1346 assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID)); 1347 assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID)); 1348 1349 // Now set scan results in 2 of them to set the corresponding 1350 // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field. 1351 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 1352 network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54)); 1353 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 1354 network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54)); 1355 1356 // Now increment |network3|'s association count. This should ensure that this network 1357 // is preferred over |network1|. 1358 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId)); 1359 1360 // Retrieve the Pno network list & verify the order of the networks returned. 1361 List<WifiScanner.PnoSettings.PnoNetwork> pnoNetworks = 1362 mWifiConfigManager.retrievePnoNetworkList(); 1363 assertEquals(3, pnoNetworks.size()); 1364 assertEquals(network3.SSID, pnoNetworks.get(0).ssid); 1365 assertEquals(network1.SSID, pnoNetworks.get(1).ssid); 1366 assertEquals(network2.SSID, pnoNetworks.get(2).ssid); 1367 1368 // Now permanently disable |network3|. This should remove network 3 from the list. 1369 assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID)); 1370 1371 // Retrieve the Pno network list again & verify the order of the networks returned. 1372 pnoNetworks = mWifiConfigManager.retrievePnoNetworkList(); 1373 assertEquals(2, pnoNetworks.size()); 1374 assertEquals(network1.SSID, pnoNetworks.get(0).ssid); 1375 assertEquals(network2.SSID, pnoNetworks.get(1).ssid); 1376 } 1377 1378 /** 1379 * Verifies the linking of networks when they have the same default GW Mac address in 1380 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1381 */ 1382 @Test 1383 public void testNetworkLinkUsingGwMacAddress() { 1384 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1385 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1386 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 1387 verifyAddNetworkToWifiConfigManager(network1); 1388 verifyAddNetworkToWifiConfigManager(network2); 1389 verifyAddNetworkToWifiConfigManager(network3); 1390 1391 // Set the same default GW mac address for all of the networks. 1392 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1393 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1394 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1395 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1396 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1397 network3.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1398 1399 // Now create dummy scan detail corresponding to the networks. 1400 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1); 1401 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2); 1402 ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3); 1403 1404 // Now save all these scan details corresponding to each of this network and expect 1405 // all of these networks to be linked with each other. 1406 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1)); 1407 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1408 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail3)); 1409 1410 List<WifiConfiguration> retrievedNetworks = 1411 mWifiConfigManager.getConfiguredNetworks(); 1412 for (WifiConfiguration network : retrievedNetworks) { 1413 assertEquals(2, network.linkedConfigurations.size()); 1414 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1415 if (otherNetwork == network) { 1416 continue; 1417 } 1418 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1419 } 1420 } 1421 } 1422 1423 /** 1424 * Verifies the linking of networks when they have scan results with same first 16 ASCII of 1425 * bssid in 1426 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1427 */ 1428 @Test 1429 public void testNetworkLinkUsingBSSIDMatch() { 1430 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1431 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1432 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 1433 verifyAddNetworkToWifiConfigManager(network1); 1434 verifyAddNetworkToWifiConfigManager(network2); 1435 verifyAddNetworkToWifiConfigManager(network3); 1436 1437 // Create scan results with bssid which is different in only the last char. 1438 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67"); 1439 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68"); 1440 ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3, "af:89:56:34:56:69"); 1441 1442 // Now save all these scan details corresponding to each of this network and expect 1443 // all of these networks to be linked with each other. 1444 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1)); 1445 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1446 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail3)); 1447 1448 List<WifiConfiguration> retrievedNetworks = 1449 mWifiConfigManager.getConfiguredNetworks(); 1450 for (WifiConfiguration network : retrievedNetworks) { 1451 assertEquals(2, network.linkedConfigurations.size()); 1452 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1453 if (otherNetwork == network) { 1454 continue; 1455 } 1456 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1457 } 1458 } 1459 } 1460 1461 /** 1462 * Verifies the linking of networks does not happen for non WPA networks when they have scan 1463 * results with same first 16 ASCII of bssid in 1464 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1465 */ 1466 @Test 1467 public void testNoNetworkLinkUsingBSSIDMatchForNonWpaNetworks() { 1468 WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork(); 1469 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1470 verifyAddNetworkToWifiConfigManager(network1); 1471 verifyAddNetworkToWifiConfigManager(network2); 1472 1473 // Create scan results with bssid which is different in only the last char. 1474 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67"); 1475 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68"); 1476 1477 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1)); 1478 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1479 1480 List<WifiConfiguration> retrievedNetworks = 1481 mWifiConfigManager.getConfiguredNetworks(); 1482 for (WifiConfiguration network : retrievedNetworks) { 1483 assertNull(network.linkedConfigurations); 1484 } 1485 } 1486 1487 /** 1488 * Verifies the linking of networks does not happen for networks with more than 1489 * {@link WifiConfigManager#LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES} scan 1490 * results with same first 16 ASCII of bssid in 1491 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1492 */ 1493 @Test 1494 public void testNoNetworkLinkUsingBSSIDMatchForNetworksWithHighScanDetailCacheSize() { 1495 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1496 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1497 verifyAddNetworkToWifiConfigManager(network1); 1498 verifyAddNetworkToWifiConfigManager(network2); 1499 1500 // Create 7 scan results with bssid which is different in only the last char. 1501 String test_bssid_base = "af:89:56:34:56:6"; 1502 int scan_result_num = 0; 1503 for (; scan_result_num < WifiConfigManager.LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES + 1; 1504 scan_result_num++) { 1505 ScanDetail networkScanDetail = 1506 createScanDetailForNetwork( 1507 network1, test_bssid_base + Integer.toString(scan_result_num)); 1508 assertNotNull( 1509 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1510 } 1511 1512 // Now add 1 scan result to the other network with bssid which is different in only the 1513 // last char. 1514 ScanDetail networkScanDetail2 = 1515 createScanDetailForNetwork( 1516 network2, test_bssid_base + Integer.toString(scan_result_num++)); 1517 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1518 1519 List<WifiConfiguration> retrievedNetworks = 1520 mWifiConfigManager.getConfiguredNetworks(); 1521 for (WifiConfiguration network : retrievedNetworks) { 1522 assertNull(network.linkedConfigurations); 1523 } 1524 } 1525 1526 /** 1527 * Verifies the linking of networks when they have scan results with same first 16 ASCII of 1528 * bssid in {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)} 1529 * and then subsequently delinked when the networks have default gateway set which do not match. 1530 */ 1531 @Test 1532 public void testNetworkLinkUsingBSSIDMatchAndThenUnlinkDueToGwMacAddress() { 1533 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1534 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1535 verifyAddNetworkToWifiConfigManager(network1); 1536 verifyAddNetworkToWifiConfigManager(network2); 1537 1538 // Create scan results with bssid which is different in only the last char. 1539 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67"); 1540 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68"); 1541 1542 // Now save all these scan details corresponding to each of this network and expect 1543 // all of these networks to be linked with each other. 1544 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1)); 1545 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1546 1547 List<WifiConfiguration> retrievedNetworks = 1548 mWifiConfigManager.getConfiguredNetworks(); 1549 for (WifiConfiguration network : retrievedNetworks) { 1550 assertEquals(1, network.linkedConfigurations.size()); 1551 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1552 if (otherNetwork == network) { 1553 continue; 1554 } 1555 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1556 } 1557 } 1558 1559 // Now Set different GW mac address for both the networks and ensure they're unlinked. 1560 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1561 network1.networkId, "de:ad:fe:45:23:34")); 1562 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1563 network2.networkId, "ad:de:fe:45:23:34")); 1564 1565 // Add some dummy scan results again to re-evaluate the linking of networks. 1566 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache( 1567 createScanDetailForNetwork(network1, "af:89:56:34:45:67"))); 1568 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache( 1569 createScanDetailForNetwork(network1, "af:89:56:34:45:68"))); 1570 1571 retrievedNetworks = mWifiConfigManager.getConfiguredNetworks(); 1572 for (WifiConfiguration network : retrievedNetworks) { 1573 assertNull(network.linkedConfigurations); 1574 } 1575 } 1576 1577 /** 1578 * Verifies the creation of channel list using 1579 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)}. 1580 */ 1581 @Test 1582 public void testFetchChannelSetForNetwork() { 1583 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1584 verifyAddNetworkToWifiConfigManager(network); 1585 1586 // Create 5 scan results with different bssid's & frequencies. 1587 String test_bssid_base = "af:89:56:34:56:6"; 1588 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1589 ScanDetail networkScanDetail = 1590 createScanDetailForNetwork( 1591 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1592 assertNotNull( 1593 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1594 1595 } 1596 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1597 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network.networkId, 1, 1598 TEST_FREQ_LIST[4])); 1599 } 1600 1601 /** 1602 * Verifies the creation of channel list using 1603 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1604 * ensures that the frequenecy of the currently connected network is in the returned 1605 * channel set. 1606 */ 1607 @Test 1608 public void testFetchChannelSetForNetworkIncludeCurrentNetwork() { 1609 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1610 verifyAddNetworkToWifiConfigManager(network); 1611 1612 // Create 5 scan results with different bssid's & frequencies. 1613 String test_bssid_base = "af:89:56:34:56:6"; 1614 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1615 ScanDetail networkScanDetail = 1616 createScanDetailForNetwork( 1617 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1618 assertNotNull( 1619 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1620 1621 } 1622 1623 // Currently connected network frequency 2427 is not in the TEST_FREQ_LIST 1624 Set<Integer> freqs = mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1625 network.networkId, 1, 2427); 1626 1627 assertEquals(true, freqs.contains(2427)); 1628 } 1629 1630 /** 1631 * Verifies the creation of channel list using 1632 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1633 * ensures that scan results which have a timestamp beyond the provided age are not used 1634 * in the channel list. 1635 */ 1636 @Test 1637 public void testFetchChannelSetForNetworkIgnoresStaleScanResults() { 1638 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1639 verifyAddNetworkToWifiConfigManager(network); 1640 1641 long wallClockBase = 0; 1642 // Create 5 scan results with different bssid's & frequencies. 1643 String test_bssid_base = "af:89:56:34:56:6"; 1644 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1645 // Increment the seen value in the scan results for each of them. 1646 when(mClock.getWallClockMillis()).thenReturn(wallClockBase + i); 1647 ScanDetail networkScanDetail = 1648 createScanDetailForNetwork( 1649 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1650 assertNotNull( 1651 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1652 1653 } 1654 int ageInMillis = 4; 1655 // Now fetch only scan results which are 4 millis stale. This should ignore the first 1656 // scan result. 1657 assertEquals( 1658 new HashSet<>(Arrays.asList( 1659 Arrays.copyOfRange( 1660 TEST_FREQ_LIST, 1661 TEST_FREQ_LIST.length - ageInMillis, TEST_FREQ_LIST.length))), 1662 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1663 network.networkId, ageInMillis, TEST_FREQ_LIST[4])); 1664 } 1665 1666 /** 1667 * Verifies the creation of channel list using 1668 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1669 * ensures that the list size does not exceed the max configured for the device. 1670 */ 1671 @Test 1672 public void testFetchChannelSetForNetworkIsLimitedToConfiguredSize() { 1673 // Need to recreate the WifiConfigManager instance for this test to modify the config 1674 // value which is read only in the constructor. 1675 int maxListSize = 3; 1676 mResources.setInteger( 1677 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels, 1678 maxListSize); 1679 createWifiConfigManager(); 1680 1681 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1682 verifyAddNetworkToWifiConfigManager(network); 1683 1684 // Create 5 scan results with different bssid's & frequencies. 1685 String test_bssid_base = "af:89:56:34:56:6"; 1686 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1687 ScanDetail networkScanDetail = 1688 createScanDetailForNetwork( 1689 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1690 assertNotNull( 1691 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1692 1693 } 1694 // Ensure that the fetched list size is limited. 1695 assertEquals(maxListSize, 1696 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1697 network.networkId, 1, TEST_FREQ_LIST[4]).size()); 1698 } 1699 1700 /** 1701 * Verifies the creation of channel list using 1702 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1703 * ensures that scan results from linked networks are used in the channel list. 1704 */ 1705 @Test 1706 public void testFetchChannelSetForNetworkIncludesLinkedNetworks() { 1707 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1708 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1709 verifyAddNetworkToWifiConfigManager(network1); 1710 verifyAddNetworkToWifiConfigManager(network2); 1711 1712 String test_bssid_base = "af:89:56:34:56:6"; 1713 int TEST_FREQ_LISTIdx = 0; 1714 // Create 3 scan results with different bssid's & frequencies for network 1. 1715 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) { 1716 ScanDetail networkScanDetail = 1717 createScanDetailForNetwork( 1718 network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1719 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1720 assertNotNull( 1721 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1722 1723 } 1724 // Create 3 scan results with different bssid's & frequencies for network 2. 1725 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) { 1726 ScanDetail networkScanDetail = 1727 createScanDetailForNetwork( 1728 network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1729 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1730 assertNotNull( 1731 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1732 } 1733 1734 // Link the 2 configurations together using the GwMacAddress. 1735 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1736 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1737 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1738 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1739 1740 // The channel list fetched should include scan results from both the linked networks. 1741 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1742 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network1.networkId, 1, 1743 TEST_FREQ_LIST[0])); 1744 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1745 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network2.networkId, 1, 1746 TEST_FREQ_LIST[0])); 1747 } 1748 1749 /** 1750 * Verifies the creation of channel list using 1751 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long, int)} and 1752 * ensures that scan results from linked networks are used in the channel list and that the 1753 * list size does not exceed the max configured for the device. 1754 */ 1755 @Test 1756 public void testFetchChannelSetForNetworkIncludesLinkedNetworksIsLimitedToConfiguredSize() { 1757 // Need to recreate the WifiConfigManager instance for this test to modify the config 1758 // value which is read only in the constructor. 1759 int maxListSize = 3; 1760 mResources.setInteger( 1761 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels, 1762 maxListSize); 1763 1764 createWifiConfigManager(); 1765 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1766 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1767 verifyAddNetworkToWifiConfigManager(network1); 1768 verifyAddNetworkToWifiConfigManager(network2); 1769 1770 String test_bssid_base = "af:89:56:34:56:6"; 1771 int TEST_FREQ_LISTIdx = 0; 1772 // Create 3 scan results with different bssid's & frequencies for network 1. 1773 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) { 1774 ScanDetail networkScanDetail = 1775 createScanDetailForNetwork( 1776 network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1777 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1778 assertNotNull( 1779 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1780 1781 } 1782 // Create 3 scan results with different bssid's & frequencies for network 2. 1783 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) { 1784 ScanDetail networkScanDetail = 1785 createScanDetailForNetwork( 1786 network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1787 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1788 assertNotNull( 1789 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1790 } 1791 1792 // Link the 2 configurations together using the GwMacAddress. 1793 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1794 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1795 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1796 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1797 1798 // Ensure that the fetched list size is limited. 1799 assertEquals(maxListSize, 1800 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1801 network1.networkId, 1, TEST_FREQ_LIST[0]).size()); 1802 assertEquals(maxListSize, 1803 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1804 network2.networkId, 1, TEST_FREQ_LIST[0]).size()); 1805 } 1806 1807 /** 1808 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 1809 * and ensures that any shared private networks networkId is not changed. 1810 * Test scenario: 1811 * 1. Load the shared networks from shared store and user 1 store. 1812 * 2. Switch to user 2 and ensure that the shared network's Id is not changed. 1813 */ 1814 @Test 1815 public void testHandleUserSwitchDoesNotChangeSharedNetworksId() throws Exception { 1816 int user1 = TEST_DEFAULT_USER; 1817 int user2 = TEST_DEFAULT_USER + 1; 1818 setupUserProfiles(user2); 1819 1820 int appId = 674; 1821 1822 // Create 3 networks. 1 for user1, 1 for user2 and 1 shared. 1823 final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork(); 1824 user1Network.shared = false; 1825 user1Network.creatorUid = UserHandle.getUid(user1, appId); 1826 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 1827 user2Network.shared = false; 1828 user2Network.creatorUid = UserHandle.getUid(user2, appId); 1829 final WifiConfiguration sharedNetwork1 = WifiConfigurationTestUtil.createPskNetwork(); 1830 final WifiConfiguration sharedNetwork2 = WifiConfigurationTestUtil.createPskNetwork(); 1831 1832 // Set up the store data that is loaded initially. 1833 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 1834 { 1835 add(sharedNetwork1); 1836 add(sharedNetwork2); 1837 } 1838 }; 1839 List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() { 1840 { 1841 add(user1Network); 1842 } 1843 }; 1844 setupStoreDataForRead(sharedNetworks, user1Networks, new HashSet<String>()); 1845 assertTrue(mWifiConfigManager.loadFromStore()); 1846 verify(mWifiConfigStore).read(); 1847 1848 // Fetch the network ID's assigned to the shared networks initially. 1849 int sharedNetwork1Id = WifiConfiguration.INVALID_NETWORK_ID; 1850 int sharedNetwork2Id = WifiConfiguration.INVALID_NETWORK_ID; 1851 List<WifiConfiguration> retrievedNetworks = 1852 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 1853 for (WifiConfiguration network : retrievedNetworks) { 1854 if (network.configKey().equals(sharedNetwork1.configKey())) { 1855 sharedNetwork1Id = network.networkId; 1856 } else if (network.configKey().equals(sharedNetwork2.configKey())) { 1857 sharedNetwork2Id = network.networkId; 1858 } 1859 } 1860 assertTrue(sharedNetwork1Id != WifiConfiguration.INVALID_NETWORK_ID); 1861 assertTrue(sharedNetwork2Id != WifiConfiguration.INVALID_NETWORK_ID); 1862 1863 // Set up the user 2 store data that is loaded at user switch. 1864 List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() { 1865 { 1866 add(user2Network); 1867 } 1868 }; 1869 setupStoreDataForUserRead(user2Networks, new HashSet<String>()); 1870 // Now switch the user to user 2 and ensure that shared network's IDs have not changed. 1871 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 1872 mWifiConfigManager.handleUserSwitch(user2); 1873 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 1874 1875 // Again fetch the network ID's assigned to the shared networks and ensure they have not 1876 // changed. 1877 int updatedSharedNetwork1Id = WifiConfiguration.INVALID_NETWORK_ID; 1878 int updatedSharedNetwork2Id = WifiConfiguration.INVALID_NETWORK_ID; 1879 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 1880 for (WifiConfiguration network : retrievedNetworks) { 1881 if (network.configKey().equals(sharedNetwork1.configKey())) { 1882 updatedSharedNetwork1Id = network.networkId; 1883 } else if (network.configKey().equals(sharedNetwork2.configKey())) { 1884 updatedSharedNetwork2Id = network.networkId; 1885 } 1886 } 1887 assertEquals(sharedNetwork1Id, updatedSharedNetwork1Id); 1888 assertEquals(sharedNetwork2Id, updatedSharedNetwork2Id); 1889 } 1890 1891 /** 1892 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 1893 * and ensures that any old user private networks are not visible anymore. 1894 * Test scenario: 1895 * 1. Load the shared networks from shared store and user 1 store. 1896 * 2. Switch to user 2 and ensure that the user 1's private network has been removed. 1897 */ 1898 @Test 1899 public void testHandleUserSwitchRemovesOldUserPrivateNetworks() throws Exception { 1900 int user1 = TEST_DEFAULT_USER; 1901 int user2 = TEST_DEFAULT_USER + 1; 1902 setupUserProfiles(user2); 1903 1904 int appId = 674; 1905 1906 // Create 3 networks. 1 for user1, 1 for user2 and 1 shared. 1907 final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork(); 1908 user1Network.shared = false; 1909 user1Network.creatorUid = UserHandle.getUid(user1, appId); 1910 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 1911 user2Network.shared = false; 1912 user2Network.creatorUid = UserHandle.getUid(user2, appId); 1913 final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1914 1915 // Set up the store data that is loaded initially. 1916 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 1917 { 1918 add(sharedNetwork); 1919 } 1920 }; 1921 List<WifiConfiguration> user1Networks = new ArrayList<WifiConfiguration>() { 1922 { 1923 add(user1Network); 1924 } 1925 }; 1926 setupStoreDataForRead(sharedNetworks, user1Networks, new HashSet<String>()); 1927 assertTrue(mWifiConfigManager.loadFromStore()); 1928 verify(mWifiConfigStore).read(); 1929 1930 // Fetch the network ID assigned to the user 1 network initially. 1931 int user1NetworkId = WifiConfiguration.INVALID_NETWORK_ID; 1932 List<WifiConfiguration> retrievedNetworks = 1933 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 1934 for (WifiConfiguration network : retrievedNetworks) { 1935 if (network.configKey().equals(user1Network.configKey())) { 1936 user1NetworkId = network.networkId; 1937 } 1938 } 1939 1940 // Set up the user 2 store data that is loaded at user switch. 1941 List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() { 1942 { 1943 add(user2Network); 1944 } 1945 }; 1946 setupStoreDataForUserRead(user2Networks, new HashSet<String>()); 1947 // Now switch the user to user 2 and ensure that user 1's private network has been removed. 1948 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 1949 Set<Integer> removedNetworks = mWifiConfigManager.handleUserSwitch(user2); 1950 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 1951 assertTrue((removedNetworks.size() == 1) && (removedNetworks.contains(user1NetworkId))); 1952 1953 // Set the expected networks to be |sharedNetwork| and |user2Network|. 1954 List<WifiConfiguration> expectedNetworks = new ArrayList<WifiConfiguration>() { 1955 { 1956 add(sharedNetwork); 1957 add(user2Network); 1958 } 1959 }; 1960 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 1961 expectedNetworks, mWifiConfigManager.getConfiguredNetworksWithPasswords()); 1962 1963 // Send another user switch indication with the same user 2. This should be ignored and 1964 // hence should not remove any new networks. 1965 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 1966 removedNetworks = mWifiConfigManager.handleUserSwitch(user2); 1967 assertTrue(removedNetworks.isEmpty()); 1968 } 1969 1970 /** 1971 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 1972 * and ensures that user switch from a user with no private networks is handled. 1973 * Test scenario: 1974 * 1. Load the shared networks from shared store and emptu user 1 store. 1975 * 2. Switch to user 2 and ensure that no private networks were removed. 1976 */ 1977 @Test 1978 public void testHandleUserSwitchWithNoOldUserPrivateNetworks() throws Exception { 1979 int user1 = TEST_DEFAULT_USER; 1980 int user2 = TEST_DEFAULT_USER + 1; 1981 setupUserProfiles(user2); 1982 1983 int appId = 674; 1984 1985 // Create 2 networks. 1 for user2 and 1 shared. 1986 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 1987 user2Network.shared = false; 1988 user2Network.creatorUid = UserHandle.getUid(user2, appId); 1989 final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1990 1991 // Set up the store data that is loaded initially. 1992 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 1993 { 1994 add(sharedNetwork); 1995 } 1996 }; 1997 setupStoreDataForRead(sharedNetworks, new ArrayList<WifiConfiguration>(), 1998 new HashSet<String>()); 1999 assertTrue(mWifiConfigManager.loadFromStore()); 2000 verify(mWifiConfigStore).read(); 2001 2002 // Set up the user 2 store data that is loaded at user switch. 2003 List<WifiConfiguration> user2Networks = new ArrayList<WifiConfiguration>() { 2004 { 2005 add(user2Network); 2006 } 2007 }; 2008 setupStoreDataForUserRead(user2Networks, new HashSet<String>()); 2009 // Now switch the user to user 2 and ensure that no private network has been removed. 2010 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2011 Set<Integer> removedNetworks = mWifiConfigManager.handleUserSwitch(user2); 2012 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2013 assertTrue(removedNetworks.isEmpty()); 2014 } 2015 2016 /** 2017 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2018 * and ensures that any non current user private networks are moved to shared store file. 2019 * This test simulates the following test case: 2020 * 1. Loads the shared networks from shared store at bootup. 2021 * 2. Load the private networks from user store on user 1 unlock. 2022 * 3. Switch to user 2 and ensure that the user 2's private network has been moved to user 2's 2023 * private store file. 2024 */ 2025 @Test 2026 public void testHandleUserSwitchPushesOtherPrivateNetworksToSharedStore() throws Exception { 2027 int user1 = TEST_DEFAULT_USER; 2028 int user2 = TEST_DEFAULT_USER + 1; 2029 setupUserProfiles(user2); 2030 2031 int appId = 674; 2032 2033 // Create 3 networks. 1 for user1, 1 for user2 and 1 shared. 2034 final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork(); 2035 user1Network.shared = false; 2036 user1Network.creatorUid = UserHandle.getUid(user1, appId); 2037 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2038 user2Network.shared = false; 2039 user2Network.creatorUid = UserHandle.getUid(user2, appId); 2040 final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork(); 2041 2042 // Set up the shared store data that is loaded at bootup. User 2's private network 2043 // is still in shared store because they have not yet logged-in after upgrade. 2044 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 2045 { 2046 add(sharedNetwork); 2047 add(user2Network); 2048 } 2049 }; 2050 setupStoreDataForRead(sharedNetworks, new ArrayList<WifiConfiguration>(), 2051 new HashSet<String>()); 2052 assertTrue(mWifiConfigManager.loadFromStore()); 2053 verify(mWifiConfigStore).read(); 2054 2055 // Set up the user store data that is loaded at user unlock. 2056 List<WifiConfiguration> userNetworks = new ArrayList<WifiConfiguration>() { 2057 { 2058 add(user1Network); 2059 } 2060 }; 2061 setupStoreDataForUserRead(userNetworks, new HashSet<String>()); 2062 mWifiConfigManager.handleUserUnlock(user1); 2063 verify(mWifiConfigStore).switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2064 // Capture the written data for the user 1 and ensure that it corresponds to what was 2065 // setup. 2066 Pair<List<WifiConfiguration>, List<WifiConfiguration>> writtenNetworkList = 2067 captureWriteNetworksListStoreData(); 2068 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2069 sharedNetworks, writtenNetworkList.first); 2070 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2071 userNetworks, writtenNetworkList.second); 2072 2073 // Now switch the user to user2 and ensure that user 2's private network has been moved to 2074 // the user store. 2075 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2076 mWifiConfigManager.handleUserSwitch(user2); 2077 // Set the expected network list before comparing. user1Network should be in shared data. 2078 // Note: In the real world, user1Network will no longer be visible now because it should 2079 // already be in user1's private store file. But, we're purposefully exposing it 2080 // via |loadStoreData| to test if other user's private networks are pushed to shared store. 2081 List<WifiConfiguration> expectedSharedNetworks = new ArrayList<WifiConfiguration>() { 2082 { 2083 add(sharedNetwork); 2084 add(user1Network); 2085 } 2086 }; 2087 List<WifiConfiguration> expectedUserNetworks = new ArrayList<WifiConfiguration>() { 2088 { 2089 add(user2Network); 2090 } 2091 }; 2092 // Capture the first written data triggered for saving the old user's network 2093 // configurations. 2094 writtenNetworkList = captureWriteNetworksListStoreData(); 2095 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2096 sharedNetworks, writtenNetworkList.first); 2097 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2098 userNetworks, writtenNetworkList.second); 2099 2100 // Now capture the next written data triggered after the switch and ensure that user 2's 2101 // network is now in user store data. 2102 writtenNetworkList = captureWriteNetworksListStoreData(); 2103 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2104 expectedSharedNetworks, writtenNetworkList.first); 2105 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2106 expectedUserNetworks, writtenNetworkList.second); 2107 } 2108 2109 /** 2110 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2111 * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is 2112 * read immediately if the user is unlocked during the switch. 2113 */ 2114 @Test 2115 public void testHandleUserSwitchWhenUnlocked() throws Exception { 2116 int user1 = TEST_DEFAULT_USER; 2117 int user2 = TEST_DEFAULT_USER + 1; 2118 setupUserProfiles(user2); 2119 2120 // Set up the internal data first. 2121 assertTrue(mWifiConfigManager.loadFromStore()); 2122 2123 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2124 // user2 is unlocked and switched to foreground. 2125 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2126 mWifiConfigManager.handleUserSwitch(user2); 2127 // Ensure that the read was invoked. 2128 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2129 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2130 } 2131 2132 /** 2133 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 2134 * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is not 2135 * read until the user is unlocked. 2136 */ 2137 public void testHandleUserSwitchWhenLocked() throws Exception { 2138 int user1 = TEST_DEFAULT_USER; 2139 int user2 = TEST_DEFAULT_USER + 1; 2140 setupUserProfiles(user2); 2141 2142 // Set up the internal data first. 2143 assertTrue(mWifiConfigManager.loadFromStore()); 2144 2145 // user2 is locked and switched to foreground. 2146 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2147 mWifiConfigManager.handleUserSwitch(user2); 2148 2149 // Ensure that the read was not invoked. 2150 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2151 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2152 2153 // Now try unlocking some other user (user1), this should be ignored. 2154 mWifiConfigManager.handleUserUnlock(user1); 2155 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2156 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2157 2158 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2159 // Unlock the user2 and ensure that we read the data now. 2160 mWifiConfigManager.handleUserUnlock(user2); 2161 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2162 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2163 } 2164 2165 /** 2166 * Verifies that the foreground user stop using {@link WifiConfigManager#handleUserStop(int)} 2167 * and ensures that the store is written only when the foreground user is stopped. 2168 */ 2169 @Test 2170 public void testHandleUserStop() throws Exception { 2171 int user1 = TEST_DEFAULT_USER; 2172 int user2 = TEST_DEFAULT_USER + 1; 2173 setupUserProfiles(user2); 2174 2175 // Try stopping background user2 first, this should not do anything. 2176 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2177 mWifiConfigManager.handleUserStop(user2); 2178 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2179 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2180 2181 // Now try stopping the foreground user1, this should trigger a write to store. 2182 mWifiConfigManager.handleUserStop(user1); 2183 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2184 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2185 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 2186 } 2187 2188 /** 2189 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2190 * results in a store read after bootup. 2191 */ 2192 @Test 2193 public void testHandleUserUnlockAfterBootup() throws Exception { 2194 int user1 = TEST_DEFAULT_USER; 2195 2196 // Set up the internal data first. 2197 assertTrue(mWifiConfigManager.loadFromStore()); 2198 mContextConfigStoreMockOrder.verify(mWifiConfigStore).read(); 2199 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2200 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2201 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2202 2203 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2204 // Unlock the user1 (default user) for the first time and ensure that we read the data. 2205 mWifiConfigManager.handleUserUnlock(user1); 2206 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 2207 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2208 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2209 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 2210 } 2211 2212 /** 2213 * Verifies that the store read after bootup received after 2214 * foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2215 * results in a user store read. 2216 */ 2217 @Test 2218 public void testHandleBootupAfterUserUnlock() throws Exception { 2219 int user1 = TEST_DEFAULT_USER; 2220 2221 // Unlock the user1 (default user) for the first time and ensure that we don't read the 2222 // data. 2223 mWifiConfigManager.handleUserUnlock(user1); 2224 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 2225 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2226 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2227 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2228 2229 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2230 // Read from store now. 2231 assertTrue(mWifiConfigManager.loadFromStore()); 2232 mContextConfigStoreMockOrder.verify(mWifiConfigStore).read(); 2233 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2234 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2235 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 2236 } 2237 2238 /** 2239 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} does 2240 * not always result in a store read unless the user had switched or just booted up. 2241 */ 2242 @Test 2243 public void testHandleUserUnlockWithoutSwitchOrBootup() throws Exception { 2244 int user1 = TEST_DEFAULT_USER; 2245 int user2 = TEST_DEFAULT_USER + 1; 2246 setupUserProfiles(user2); 2247 2248 // Set up the internal data first. 2249 assertTrue(mWifiConfigManager.loadFromStore()); 2250 2251 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2252 // user2 is unlocked and switched to foreground. 2253 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2254 mWifiConfigManager.handleUserSwitch(user2); 2255 // Ensure that the read was invoked. 2256 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2257 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2258 2259 // Unlock the user2 again and ensure that we don't read the data now. 2260 mWifiConfigManager.handleUserUnlock(user2); 2261 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2262 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2263 } 2264 2265 /** 2266 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserSwitch(int)} 2267 * is ignored if the legacy store migration is not complete. 2268 */ 2269 @Test 2270 public void testHandleUserSwitchAfterBootupBeforeLegacyStoreMigration() throws Exception { 2271 int user2 = TEST_DEFAULT_USER + 1; 2272 2273 // Switch to user2 for the first time and ensure that we don't read or 2274 // write the store files. 2275 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2276 mWifiConfigManager.handleUserSwitch(user2); 2277 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2278 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2279 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2280 } 2281 2282 /** 2283 * Verifies the foreground user unlock via {@link WifiConfigManager#handleUserUnlock(int)} 2284 * is ignored if the legacy store migration is not complete. 2285 */ 2286 @Test 2287 public void testHandleUserUnlockAfterBootupBeforeLegacyStoreMigration() throws Exception { 2288 int user1 = TEST_DEFAULT_USER; 2289 2290 // Unlock the user1 (default user) for the first time and ensure that we don't read or 2291 // write the store files. 2292 mWifiConfigManager.handleUserUnlock(user1); 2293 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()) 2294 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2295 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 2296 } 2297 2298 /** 2299 * Verifies the private network addition using 2300 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 2301 * by a non foreground user is rejected. 2302 */ 2303 @Test 2304 public void testAddNetworkUsingBackgroundUserUId() throws Exception { 2305 int user2 = TEST_DEFAULT_USER + 1; 2306 setupUserProfiles(user2); 2307 2308 int creatorUid = UserHandle.getUid(user2, 674); 2309 2310 // Create a network for user2 try adding it. This should be rejected. 2311 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2312 NetworkUpdateResult result = 2313 mWifiConfigManager.addOrUpdateNetwork(user2Network, creatorUid); 2314 assertFalse(result.isSuccess()); 2315 } 2316 2317 /** 2318 * Verifies the private network addition using 2319 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 2320 * by SysUI is always accepted. 2321 */ 2322 @Test 2323 public void testAddNetworkUsingSysUiUid() throws Exception { 2324 // Set up the user profiles stuff. Needed for |WifiConfigurationUtil.isVisibleToAnyProfile| 2325 int user2 = TEST_DEFAULT_USER + 1; 2326 setupUserProfiles(user2); 2327 2328 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 2329 mWifiConfigManager.handleUserSwitch(user2); 2330 2331 // Create a network for user2 try adding it. This should be rejected. 2332 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 2333 NetworkUpdateResult result = 2334 mWifiConfigManager.addOrUpdateNetwork(user2Network, TEST_SYSUI_UID); 2335 assertTrue(result.isSuccess()); 2336 } 2337 2338 /** 2339 * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()} 2340 * attempts to migrate data from legacy stores when the legacy store files are present. 2341 */ 2342 @Test 2343 public void testMigrationFromLegacyStore() throws Exception { 2344 // Create the store data to be returned from legacy stores. 2345 List<WifiConfiguration> networks = new ArrayList<>(); 2346 networks.add(WifiConfigurationTestUtil.createPskNetwork()); 2347 networks.add(WifiConfigurationTestUtil.createEapNetwork()); 2348 networks.add(WifiConfigurationTestUtil.createWepNetwork()); 2349 String deletedEphemeralSSID = "EphemeralSSID"; 2350 Set<String> deletedEphermalSSIDs = new HashSet<>(Arrays.asList(deletedEphemeralSSID)); 2351 WifiConfigStoreDataLegacy storeData = 2352 new WifiConfigStoreDataLegacy(networks, deletedEphermalSSIDs); 2353 2354 when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(true); 2355 when(mWifiConfigStoreLegacy.read()).thenReturn(storeData); 2356 2357 // Now trigger the migration from legacy store. This should populate the in memory list with 2358 // all the networks above from the legacy store. 2359 assertTrue(mWifiConfigManager.migrateFromLegacyStore()); 2360 2361 verify(mWifiConfigStoreLegacy).read(); 2362 verify(mWifiConfigStoreLegacy).removeStores(); 2363 2364 List<WifiConfiguration> retrievedNetworks = 2365 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2366 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2367 networks, retrievedNetworks); 2368 assertTrue(mWifiConfigManager.wasEphemeralNetworkDeleted(deletedEphemeralSSID)); 2369 } 2370 2371 /** 2372 * Verifies the loading of networks using {@link WifiConfigManager#migrateFromLegacyStore()} ()} 2373 * does not attempt to migrate data from legacy stores when the legacy store files are absent 2374 * (i.e migration was already done once). 2375 */ 2376 @Test 2377 public void testNoDuplicateMigrationFromLegacyStore() throws Exception { 2378 when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false); 2379 2380 // Now trigger a migration from legacy store. 2381 assertTrue(mWifiConfigManager.migrateFromLegacyStore()); 2382 2383 verify(mWifiConfigStoreLegacy, never()).read(); 2384 verify(mWifiConfigStoreLegacy, never()).removeStores(); 2385 } 2386 2387 /** 2388 * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} does 2389 * not attempt to read from any of the stores (new or legacy) when the store files are 2390 * not present. 2391 */ 2392 @Test 2393 public void testFreshInstallDoesNotLoadFromStore() throws Exception { 2394 when(mWifiConfigStore.areStoresPresent()).thenReturn(false); 2395 when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false); 2396 2397 assertTrue(mWifiConfigManager.loadFromStore()); 2398 2399 verify(mWifiConfigStore, never()).read(); 2400 verify(mWifiConfigStoreLegacy, never()).read(); 2401 2402 assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty()); 2403 } 2404 2405 /** 2406 * Verifies the user switch using {@link WifiConfigManager#handleUserSwitch(int)} is handled 2407 * when the store files (new or legacy) are not present. 2408 */ 2409 @Test 2410 public void testHandleUserSwitchAfterFreshInstall() throws Exception { 2411 int user2 = TEST_DEFAULT_USER + 1; 2412 when(mWifiConfigStore.areStoresPresent()).thenReturn(false); 2413 when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false); 2414 2415 assertTrue(mWifiConfigManager.loadFromStore()); 2416 verify(mWifiConfigStore, never()).read(); 2417 verify(mWifiConfigStoreLegacy, never()).read(); 2418 2419 setupStoreDataForUserRead(new ArrayList<WifiConfiguration>(), new HashSet<String>()); 2420 // Now switch the user to user 2. 2421 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 2422 mWifiConfigManager.handleUserSwitch(user2); 2423 // Ensure that the read was invoked. 2424 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2425 .switchUserStoreAndRead(any(WifiConfigStore.StoreFile.class)); 2426 } 2427 2428 /** 2429 * Verifies that the last user selected network parameter is set when 2430 * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with disableOthers flag is set 2431 * to true and cleared when either {@link WifiConfigManager#disableNetwork(int, int)} or 2432 * {@link WifiConfigManager#removeNetwork(int, int)} is invoked using the same network ID. 2433 */ 2434 @Test 2435 public void testLastSelectedNetwork() throws Exception { 2436 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 2437 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 2438 2439 when(mClock.getElapsedSinceBootMillis()).thenReturn(67L); 2440 assertTrue(mWifiConfigManager.enableNetwork( 2441 result.getNetworkId(), true, TEST_CREATOR_UID)); 2442 assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork()); 2443 assertEquals(67, mWifiConfigManager.getLastSelectedTimeStamp()); 2444 2445 // Now disable the network and ensure that the last selected flag is cleared. 2446 assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 2447 assertEquals( 2448 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork()); 2449 2450 // Enable it again and remove the network to ensure that the last selected flag was cleared. 2451 assertTrue(mWifiConfigManager.enableNetwork( 2452 result.getNetworkId(), true, TEST_CREATOR_UID)); 2453 assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork()); 2454 assertEquals(openNetwork.configKey(), mWifiConfigManager.getLastSelectedNetworkConfigKey()); 2455 2456 assertTrue(mWifiConfigManager.removeNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 2457 assertEquals( 2458 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork()); 2459 } 2460 2461 /** 2462 * Verifies that all the networks for the provided app is removed when 2463 * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked. 2464 */ 2465 @Test 2466 public void testRemoveNetworksForApp() throws Exception { 2467 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork()); 2468 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork()); 2469 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork()); 2470 2471 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2472 2473 ApplicationInfo app = new ApplicationInfo(); 2474 app.uid = TEST_CREATOR_UID; 2475 app.packageName = TEST_CREATOR_NAME; 2476 assertEquals(3, mWifiConfigManager.removeNetworksForApp(app).size()); 2477 2478 // Ensure all the networks are removed now. 2479 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2480 } 2481 2482 /** 2483 * Verifies that all the networks for the provided user is removed when 2484 * {@link WifiConfigManager#removeNetworksForUser(int)} is invoked. 2485 */ 2486 @Test 2487 public void testRemoveNetworksForUser() throws Exception { 2488 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork()); 2489 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork()); 2490 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork()); 2491 2492 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2493 2494 assertEquals(3, mWifiConfigManager.removeNetworksForUser(TEST_DEFAULT_USER).size()); 2495 2496 // Ensure all the networks are removed now. 2497 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 2498 } 2499 2500 /** 2501 * Verifies that the connect choice is removed from all networks when 2502 * {@link WifiConfigManager#removeNetwork(int, int)} is invoked. 2503 */ 2504 @Test 2505 public void testRemoveNetworkRemovesConnectChoice() throws Exception { 2506 WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork(); 2507 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 2508 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 2509 verifyAddNetworkToWifiConfigManager(network1); 2510 verifyAddNetworkToWifiConfigManager(network2); 2511 verifyAddNetworkToWifiConfigManager(network3); 2512 2513 // Set connect choice of network 2 over network 1. 2514 assertTrue( 2515 mWifiConfigManager.setNetworkConnectChoice( 2516 network1.networkId, network2.configKey(), 78L)); 2517 2518 WifiConfiguration retrievedNetwork = 2519 mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2520 assertEquals( 2521 network2.configKey(), 2522 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2523 2524 // Remove network 3 and ensure that the connect choice on network 1 is not removed. 2525 assertTrue(mWifiConfigManager.removeNetwork(network3.networkId, TEST_CREATOR_UID)); 2526 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2527 assertEquals( 2528 network2.configKey(), 2529 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2530 2531 // Now remove network 2 and ensure that the connect choice on network 1 is removed.. 2532 assertTrue(mWifiConfigManager.removeNetwork(network2.networkId, TEST_CREATOR_UID)); 2533 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId); 2534 assertNotEquals( 2535 network2.configKey(), 2536 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 2537 2538 // This should have triggered 2 buffered writes. 1 for setting the connect choice, 1 for 2539 // clearing it after network removal. 2540 mContextConfigStoreMockOrder.verify(mWifiConfigStore, times(2)).write(eq(false)); 2541 } 2542 2543 /** 2544 * Verifies that the modification of a single network using 2545 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that any 2546 * updates to the network config in 2547 * {@link WifiKeyStore#updateNetworkKeys(WifiConfiguration, WifiConfiguration)} is reflected 2548 * in the internal database. 2549 */ 2550 @Test 2551 public void testUpdateSingleNetworkWithKeysUpdate() { 2552 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 2553 network.enterpriseConfig = 2554 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 2555 verifyAddNetworkToWifiConfigManager(network); 2556 2557 // Now verify that network configurations match before we make any change. 2558 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2559 network, 2560 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 2561 2562 // Modify the network ca_cert field in updateNetworkKeys method during a network 2563 // config update. 2564 final String newCaCertAlias = "test"; 2565 assertNotEquals(newCaCertAlias, network.enterpriseConfig.getCaCertificateAlias()); 2566 2567 doAnswer(new AnswerWithArguments() { 2568 public boolean answer(WifiConfiguration newConfig, WifiConfiguration existingConfig) { 2569 newConfig.enterpriseConfig.setCaCertificateAlias(newCaCertAlias); 2570 return true; 2571 } 2572 }).when(mWifiKeyStore).updateNetworkKeys( 2573 any(WifiConfiguration.class), any(WifiConfiguration.class)); 2574 2575 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 2576 2577 // Now verify that the keys update is reflected in the configuration fetched from internal 2578 // db. 2579 network.enterpriseConfig.setCaCertificateAlias(newCaCertAlias); 2580 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2581 network, 2582 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 2583 } 2584 2585 /** 2586 * Verifies that the dump method prints out all the saved network details with passwords masked. 2587 * {@link WifiConfigManager#dump(FileDescriptor, PrintWriter, String[])}. 2588 */ 2589 @Test 2590 public void testDump() { 2591 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 2592 WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); 2593 eapNetwork.enterpriseConfig.setPassword("blah"); 2594 2595 verifyAddNetworkToWifiConfigManager(pskNetwork); 2596 verifyAddNetworkToWifiConfigManager(eapNetwork); 2597 2598 StringWriter stringWriter = new StringWriter(); 2599 mWifiConfigManager.dump( 2600 new FileDescriptor(), new PrintWriter(stringWriter), new String[0]); 2601 String dumpString = stringWriter.toString(); 2602 2603 // Ensure that the network SSIDs were dumped out. 2604 assertTrue(dumpString.contains(pskNetwork.SSID)); 2605 assertTrue(dumpString.contains(eapNetwork.SSID)); 2606 2607 // Ensure that the network passwords were not dumped out. 2608 assertFalse(dumpString.contains(pskNetwork.preSharedKey)); 2609 assertFalse(dumpString.contains(eapNetwork.enterpriseConfig.getPassword())); 2610 } 2611 2612 /** 2613 * Verifies the ordering of network list generated using 2614 * {@link WifiConfigManager#retrieveHiddenNetworkList()}. 2615 */ 2616 @Test 2617 public void testRetrieveHiddenList() { 2618 // Create and add 3 networks. 2619 WifiConfiguration network1 = WifiConfigurationTestUtil.createWepHiddenNetwork(); 2620 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskHiddenNetwork(); 2621 WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 2622 verifyAddNetworkToWifiConfigManager(network1); 2623 verifyAddNetworkToWifiConfigManager(network2); 2624 verifyAddNetworkToWifiConfigManager(network3); 2625 2626 // Enable all of them. 2627 assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID)); 2628 assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID)); 2629 assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID)); 2630 2631 // Now set scan results in 2 of them to set the corresponding 2632 // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field. 2633 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 2634 network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54)); 2635 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 2636 network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54)); 2637 2638 // Now increment |network3|'s association count. This should ensure that this network 2639 // is preferred over |network1|. 2640 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId)); 2641 2642 // Retrieve the hidden network list & verify the order of the networks returned. 2643 List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks = 2644 mWifiConfigManager.retrieveHiddenNetworkList(); 2645 assertEquals(3, hiddenNetworks.size()); 2646 assertEquals(network3.SSID, hiddenNetworks.get(0).ssid); 2647 assertEquals(network1.SSID, hiddenNetworks.get(1).ssid); 2648 assertEquals(network2.SSID, hiddenNetworks.get(2).ssid); 2649 2650 // Now permanently disable |network3|. This should remove network 3 from the list. 2651 assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID)); 2652 2653 // Retrieve the hidden network list again & verify the order of the networks returned. 2654 hiddenNetworks = mWifiConfigManager.retrieveHiddenNetworkList(); 2655 assertEquals(2, hiddenNetworks.size()); 2656 assertEquals(network1.SSID, hiddenNetworks.get(0).ssid); 2657 assertEquals(network2.SSID, hiddenNetworks.get(1).ssid); 2658 } 2659 2660 /** 2661 * Verifies the addition of network configurations using 2662 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and 2663 * default key mgmt does not add duplicate network configs. 2664 */ 2665 @Test 2666 public void testAddMultipleNetworksWithSameSSIDAndDefaultKeyMgmt() { 2667 final String ssid = "test_blah"; 2668 // Add a network with the above SSID and default key mgmt and ensure it was added 2669 // successfully. 2670 WifiConfiguration network1 = new WifiConfiguration(); 2671 network1.SSID = ssid; 2672 NetworkUpdateResult result = addNetworkToWifiConfigManager(network1); 2673 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2674 assertTrue(result.isNewNetwork()); 2675 2676 List<WifiConfiguration> retrievedNetworks = 2677 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2678 assertEquals(1, retrievedNetworks.size()); 2679 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2680 network1, retrievedNetworks.get(0)); 2681 2682 // Now add a second network with the same SSID and default key mgmt and ensure that it 2683 // didn't add a new duplicate network. 2684 WifiConfiguration network2 = new WifiConfiguration(); 2685 network2.SSID = ssid; 2686 result = addNetworkToWifiConfigManager(network2); 2687 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2688 assertFalse(result.isNewNetwork()); 2689 2690 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2691 assertEquals(1, retrievedNetworks.size()); 2692 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2693 network2, retrievedNetworks.get(0)); 2694 } 2695 2696 /** 2697 * Verifies the addition of network configurations using 2698 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with same SSID and 2699 * different key mgmt should add different network configs. 2700 */ 2701 @Test 2702 public void testAddMultipleNetworksWithSameSSIDAndDifferentKeyMgmt() { 2703 final String ssid = "test_blah"; 2704 // Add a network with the above SSID and WPA_PSK key mgmt and ensure it was added 2705 // successfully. 2706 WifiConfiguration network1 = new WifiConfiguration(); 2707 network1.SSID = ssid; 2708 network1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 2709 NetworkUpdateResult result = addNetworkToWifiConfigManager(network1); 2710 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2711 assertTrue(result.isNewNetwork()); 2712 2713 List<WifiConfiguration> retrievedNetworks = 2714 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2715 assertEquals(1, retrievedNetworks.size()); 2716 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2717 network1, retrievedNetworks.get(0)); 2718 2719 // Now add a second network with the same SSID and NONE key mgmt and ensure that it 2720 // does add a new network. 2721 WifiConfiguration network2 = new WifiConfiguration(); 2722 network2.SSID = ssid; 2723 network2.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 2724 result = addNetworkToWifiConfigManager(network2); 2725 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2726 assertTrue(result.isNewNetwork()); 2727 2728 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 2729 assertEquals(2, retrievedNetworks.size()); 2730 List<WifiConfiguration> networks = Arrays.asList(network1, network2); 2731 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 2732 networks, retrievedNetworks); 2733 } 2734 2735 /** 2736 * Verifies that adding a network with a proxy, without having permission OVERRIDE_WIFI_CONFIG, 2737 * holding device policy, or profile owner policy fails. 2738 */ 2739 @Test 2740 public void testAddNetworkWithProxyFails() { 2741 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2742 false, // withConfOverride 2743 false, // withProfileOwnerPolicy 2744 false, // withDeviceOwnerPolicy 2745 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2746 false, // assertSuccess 2747 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2748 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2749 false, // withConfOverride 2750 false, // withProfileOwnerPolicy 2751 false, // withDeviceOwnerPolicy 2752 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 2753 false, // assertSuccess 2754 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2755 } 2756 2757 /** 2758 * Verifies that adding a network with a PAC or STATIC proxy with permission 2759 * OVERRIDE_WIFI_CONFIG is successful 2760 */ 2761 @Test 2762 public void testAddNetworkWithProxyWithConfOverride() { 2763 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2764 true, // withConfOverride 2765 false, // withProfileOwnerPolicy 2766 false, // withDeviceOwnerPolicy 2767 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2768 true, // assertSuccess 2769 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2770 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2771 true, // withConfOverride 2772 false, // withProfileOwnerPolicy 2773 false, // withDeviceOwnerPolicy 2774 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 2775 true, // assertSuccess 2776 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2777 } 2778 2779 /** 2780 * Verifies that adding a network with a PAC or STATIC proxy, while holding policy 2781 * {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER} is successful 2782 */ 2783 @Test 2784 public void testAddNetworkWithProxyAsProfileOwner() { 2785 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2786 false, // withConfOverride 2787 true, // withProfileOwnerPolicy 2788 false, // withDeviceOwnerPolicy 2789 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2790 true, // assertSuccess 2791 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2792 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2793 false, // withConfOverride 2794 true, // withProfileOwnerPolicy 2795 false, // withDeviceOwnerPolicy 2796 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 2797 true, // assertSuccess 2798 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2799 } 2800 /** 2801 * Verifies that adding a network with a PAC or STATIC proxy, while holding policy 2802 * {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER} is successful 2803 */ 2804 @Test 2805 public void testAddNetworkWithProxyAsDeviceOwner() { 2806 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2807 false, // withConfOverride 2808 false, // withProfileOwnerPolicy 2809 true, // withDeviceOwnerPolicy 2810 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2811 true, // assertSuccess 2812 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2813 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2814 false, // withConfOverride 2815 false, // withProfileOwnerPolicy 2816 true, // withDeviceOwnerPolicy 2817 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 2818 true, // assertSuccess 2819 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2820 } 2821 /** 2822 * Verifies that updating a network (that has no proxy) and adding a PAC or STATIC proxy fails 2823 * without being able to override configs, or holding Device or Profile owner policies. 2824 */ 2825 @Test 2826 public void testUpdateNetworkAddProxyFails() { 2827 WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 2828 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network); 2829 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2830 false, // withConfOverride 2831 false, // withProfileOwnerPolicy 2832 false, // withDeviceOwnerPolicy 2833 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2834 false, // assertSuccess 2835 result.getNetworkId()); // Update networkID 2836 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2837 false, // withConfOverride 2838 false, // withProfileOwnerPolicy 2839 false, // withDeviceOwnerPolicy 2840 WifiConfigurationTestUtil.createDHCPIpConfigurationWithStaticProxy(), 2841 false, // assertSuccess 2842 result.getNetworkId()); // Update networkID 2843 } 2844 /** 2845 * Verifies that updating a network and adding a proxy is successful in the cases where app can 2846 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 2847 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 2848 * otherwise. 2849 */ 2850 @Test 2851 public void testUpdateNetworkAddProxyWithPermissionAndSystem() { 2852 // Testing updating network with uid permission OVERRIDE_WIFI_CONFIG 2853 WifiConfiguration network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 2854 NetworkUpdateResult result = 2855 mWifiConfigManager.addOrUpdateNetwork(network, TEST_CREATOR_UID); 2856 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2857 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2858 true, // withConfOverride 2859 false, // withProfileOwnerPolicy 2860 false, // withDeviceOwnerPolicy 2861 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2862 true, // assertSuccess 2863 result.getNetworkId()); // Update networkID 2864 2865 // Testing updating network with proxy while holding Profile Owner policy 2866 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 2867 result = mWifiConfigManager.addOrUpdateNetwork(network, TEST_NO_PERM_UID); 2868 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2869 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2870 false, // withConfOverride 2871 true, // withProfileOwnerPolicy 2872 false, // withDeviceOwnerPolicy 2873 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2874 true, // assertSuccess 2875 result.getNetworkId()); // Update networkID 2876 2877 // Testing updating network with proxy while holding Device Owner Policy 2878 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 2879 result = mWifiConfigManager.addOrUpdateNetwork(network, TEST_NO_PERM_UID); 2880 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2881 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2882 false, // withConfOverride 2883 false, // withProfileOwnerPolicy 2884 true, // withDeviceOwnerPolicy 2885 WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(), 2886 true, // assertSuccess 2887 result.getNetworkId()); // Update networkID 2888 } 2889 2890 /** 2891 * Verifies that updating a network that has a proxy without changing the proxy, can succeed 2892 * without proxy specific permissions. 2893 */ 2894 @Test 2895 public void testUpdateNetworkUnchangedProxy() { 2896 IpConfiguration ipConf = WifiConfigurationTestUtil.createDHCPIpConfigurationWithPacProxy(); 2897 // First create a WifiConfiguration with proxy 2898 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2899 false, // withConfOverride 2900 true, // withProfileOwnerPolicy 2901 false, // withDeviceOwnerPolicy 2902 ipConf, 2903 true, // assertSuccess 2904 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2905 // Update the network while using the same ipConf, and no proxy specific permissions 2906 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2907 false, // withConfOverride 2908 false, // withProfileOwnerPolicy 2909 false, // withDeviceOwnerPolicy 2910 ipConf, 2911 true, // assertSuccess 2912 result.getNetworkId()); // Update networkID 2913 } 2914 2915 /** 2916 * Verifies that updating a network with a different proxy succeeds in the cases where app can 2917 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 2918 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 2919 * otherwise. 2920 */ 2921 @Test 2922 public void testUpdateNetworkDifferentProxy() { 2923 // Create two proxy configurations of the same type, but different values 2924 IpConfiguration ipConf1 = 2925 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 2926 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 2927 TEST_STATIC_PROXY_HOST_1, 2928 TEST_STATIC_PROXY_PORT_1, 2929 TEST_STATIC_PROXY_EXCLUSION_LIST_1, 2930 TEST_PAC_PROXY_LOCATION_1); 2931 IpConfiguration ipConf2 = 2932 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 2933 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 2934 TEST_STATIC_PROXY_HOST_2, 2935 TEST_STATIC_PROXY_PORT_2, 2936 TEST_STATIC_PROXY_EXCLUSION_LIST_2, 2937 TEST_PAC_PROXY_LOCATION_2); 2938 2939 // Update with Conf Override 2940 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2941 true, // withConfOverride 2942 false, // withProfileOwnerPolicy 2943 false, // withDeviceOwnerPolicy 2944 ipConf1, 2945 true, // assertSuccess 2946 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2947 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2948 true, // withConfOverride 2949 false, // withProfileOwnerPolicy 2950 false, // withDeviceOwnerPolicy 2951 ipConf2, 2952 true, // assertSuccess 2953 result.getNetworkId()); // Update networkID 2954 2955 // Update as Device Owner 2956 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2957 false, // withConfOverride 2958 false, // withProfileOwnerPolicy 2959 true, // withDeviceOwnerPolicy 2960 ipConf1, 2961 true, // assertSuccess 2962 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2963 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2964 false, // withConfOverride 2965 false, // withProfileOwnerPolicy 2966 true, // withDeviceOwnerPolicy 2967 ipConf2, 2968 true, // assertSuccess 2969 result.getNetworkId()); // Update networkID 2970 2971 // Update as Profile Owner 2972 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2973 false, // withConfOverride 2974 true, // withProfileOwnerPolicy 2975 false, // withDeviceOwnerPolicy 2976 ipConf1, 2977 true, // assertSuccess 2978 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2979 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2980 false, // withConfOverride 2981 true, // withProfileOwnerPolicy 2982 false, // withDeviceOwnerPolicy 2983 ipConf2, 2984 true, // assertSuccess 2985 result.getNetworkId()); // Update networkID 2986 2987 // Update with no permissions (should fail) 2988 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2989 false, // withConfOverride 2990 true, // withProfileOwnerPolicy 2991 false, // withDeviceOwnerPolicy 2992 ipConf1, 2993 true, // assertSuccess 2994 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 2995 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 2996 false, // withConfOverride 2997 false, // withProfileOwnerPolicy 2998 false, // withDeviceOwnerPolicy 2999 ipConf2, 3000 false, // assertSuccess 3001 result.getNetworkId()); // Update networkID 3002 } 3003 /** 3004 * Verifies that updating a network removing its proxy succeeds in the cases where app can 3005 * override configs, holds policy {@link DeviceAdminInfo.USES_POLICY_PROFILE_OWNER}, 3006 * and holds policy {@link DeviceAdminInfo.USES_POLICY_DEVICE_OWNER}, and that it fails 3007 * otherwise. 3008 */ 3009 @Test 3010 public void testUpdateNetworkRemoveProxy() { 3011 // Create two different IP configurations, one with a proxy and another without. 3012 IpConfiguration ipConf1 = 3013 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3014 WifiConfigurationTestUtil.STATIC_PROXY_SETTING, 3015 TEST_STATIC_PROXY_HOST_1, 3016 TEST_STATIC_PROXY_PORT_1, 3017 TEST_STATIC_PROXY_EXCLUSION_LIST_1, 3018 TEST_PAC_PROXY_LOCATION_1); 3019 IpConfiguration ipConf2 = 3020 WifiConfigurationTestUtil.createDHCPIpConfigurationWithSpecificProxy( 3021 WifiConfigurationTestUtil.NONE_PROXY_SETTING, 3022 TEST_STATIC_PROXY_HOST_2, 3023 TEST_STATIC_PROXY_PORT_2, 3024 TEST_STATIC_PROXY_EXCLUSION_LIST_2, 3025 TEST_PAC_PROXY_LOCATION_2); 3026 3027 // Update with Conf Override 3028 NetworkUpdateResult result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3029 true, // withConfOverride 3030 false, // withProfileOwnerPolicy 3031 false, // withDeviceOwnerPolicy 3032 ipConf1, 3033 true, // assertSuccess 3034 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3035 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3036 true, // withConfOverride 3037 false, // withProfileOwnerPolicy 3038 false, // withDeviceOwnerPolicy 3039 ipConf2, 3040 true, // assertSuccess 3041 result.getNetworkId()); // Update networkID 3042 3043 // Update as Device Owner 3044 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3045 false, // withConfOverride 3046 false, // withProfileOwnerPolicy 3047 true, // withDeviceOwnerPolicy 3048 ipConf1, 3049 true, // assertSuccess 3050 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3051 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3052 false, // withConfOverride 3053 false, // withProfileOwnerPolicy 3054 true, // withDeviceOwnerPolicy 3055 ipConf2, 3056 true, // assertSuccess 3057 result.getNetworkId()); // Update networkID 3058 3059 // Update as Profile Owner 3060 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3061 false, // withConfOverride 3062 true, // withProfileOwnerPolicy 3063 false, // withDeviceOwnerPolicy 3064 ipConf1, 3065 true, // assertSuccess 3066 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3067 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3068 false, // withConfOverride 3069 true, // withProfileOwnerPolicy 3070 false, // withDeviceOwnerPolicy 3071 ipConf2, 3072 true, // assertSuccess 3073 result.getNetworkId()); // Update networkID 3074 3075 // Update with no permissions (should fail) 3076 result = verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3077 false, // withConfOverride 3078 true, // withProfileOwnerPolicy 3079 false, // withDeviceOwnerPolicy 3080 ipConf1, 3081 true, // assertSuccess 3082 WifiConfiguration.INVALID_NETWORK_ID); // Update networkID 3083 verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3084 false, // withConfOverride 3085 false, // withProfileOwnerPolicy 3086 false, // withDeviceOwnerPolicy 3087 ipConf2, 3088 false, // assertSuccess 3089 result.getNetworkId()); // Update networkID 3090 } 3091 3092 private NetworkUpdateResult verifyAddOrUpdateNetworkWithProxySettingsAndPermissions( 3093 boolean withConfOverride, 3094 boolean withProfileOwnerPolicy, 3095 boolean withDeviceOwnerPolicy, 3096 IpConfiguration ipConfiguration, 3097 boolean assertSuccess, 3098 int networkId) { 3099 WifiConfiguration network; 3100 if (networkId == WifiConfiguration.INVALID_NETWORK_ID) { 3101 network = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 3102 } else { 3103 network = mWifiConfigManager.getConfiguredNetwork(networkId); 3104 } 3105 network.setIpConfiguration(ipConfiguration); 3106 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), 3107 eq(DeviceAdminInfo.USES_POLICY_PROFILE_OWNER))) 3108 .thenReturn(withProfileOwnerPolicy); 3109 when(mDevicePolicyManagerInternal.isActiveAdminWithPolicy(anyInt(), 3110 eq(DeviceAdminInfo.USES_POLICY_DEVICE_OWNER))) 3111 .thenReturn(withDeviceOwnerPolicy); 3112 int uid = withConfOverride ? TEST_CREATOR_UID : TEST_NO_PERM_UID; 3113 NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork(network, uid); 3114 assertEquals(assertSuccess, result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3115 return result; 3116 } 3117 3118 private void createWifiConfigManager() { 3119 mWifiConfigManager = 3120 new WifiConfigManager( 3121 mContext, mFrameworkFacade, mClock, mUserManager, mTelephonyManager, 3122 mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy, 3123 mWifiPermissionsWrapper, mNetworkListStoreData, 3124 mDeletedEphemeralSsidsStoreData); 3125 mWifiConfigManager.enableVerboseLogging(1); 3126 } 3127 3128 /** 3129 * This method sets defaults in the provided WifiConfiguration object if not set 3130 * so that it can be used for comparison with the configuration retrieved from 3131 * WifiConfigManager. 3132 */ 3133 private void setDefaults(WifiConfiguration configuration) { 3134 if (configuration.allowedAuthAlgorithms.isEmpty()) { 3135 configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 3136 } 3137 if (configuration.allowedProtocols.isEmpty()) { 3138 configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); 3139 configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 3140 } 3141 if (configuration.allowedKeyManagement.isEmpty()) { 3142 configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 3143 configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); 3144 } 3145 if (configuration.allowedPairwiseCiphers.isEmpty()) { 3146 configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); 3147 configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); 3148 } 3149 if (configuration.allowedGroupCiphers.isEmpty()) { 3150 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 3151 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 3152 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 3153 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); 3154 } 3155 if (configuration.getIpAssignment() == IpConfiguration.IpAssignment.UNASSIGNED) { 3156 configuration.setIpAssignment(IpConfiguration.IpAssignment.DHCP); 3157 } 3158 if (configuration.getProxySettings() == IpConfiguration.ProxySettings.UNASSIGNED) { 3159 configuration.setProxySettings(IpConfiguration.ProxySettings.NONE); 3160 } 3161 configuration.status = WifiConfiguration.Status.DISABLED; 3162 configuration.getNetworkSelectionStatus().setNetworkSelectionStatus( 3163 NetworkSelectionStatus.NETWORK_SELECTION_PERMANENTLY_DISABLED); 3164 } 3165 3166 /** 3167 * Modifies the provided configuration with creator uid, package name 3168 * and time. 3169 */ 3170 private void setCreationDebugParams(WifiConfiguration configuration) { 3171 configuration.creatorUid = configuration.lastUpdateUid = TEST_CREATOR_UID; 3172 configuration.creatorName = configuration.lastUpdateName = TEST_CREATOR_NAME; 3173 configuration.creationTime = configuration.updateTime = 3174 WifiConfigManager.createDebugTimeStampString( 3175 TEST_WALLCLOCK_CREATION_TIME_MILLIS); 3176 } 3177 3178 /** 3179 * Modifies the provided configuration with update uid, package name 3180 * and time. 3181 */ 3182 private void setUpdateDebugParams(WifiConfiguration configuration) { 3183 configuration.lastUpdateUid = TEST_UPDATE_UID; 3184 configuration.lastUpdateName = TEST_UPDATE_NAME; 3185 configuration.updateTime = 3186 WifiConfigManager.createDebugTimeStampString(TEST_WALLCLOCK_UPDATE_TIME_MILLIS); 3187 } 3188 3189 private void assertNotEquals(Object expected, Object actual) { 3190 if (actual != null) { 3191 assertFalse(actual.equals(expected)); 3192 } else { 3193 assertNotNull(expected); 3194 } 3195 } 3196 3197 /** 3198 * Modifies the provided WifiConfiguration with the specified bssid value. Also, asserts that 3199 * the existing |BSSID| field is not the same value as the one being set 3200 */ 3201 private void assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid) { 3202 assertNotEquals(bssid, configuration.BSSID); 3203 configuration.BSSID = bssid; 3204 } 3205 3206 /** 3207 * Modifies the provided WifiConfiguration with the specified |IpConfiguration| object. Also, 3208 * asserts that the existing |mIpConfiguration| field is not the same value as the one being set 3209 */ 3210 private void assertAndSetNetworkIpConfiguration( 3211 WifiConfiguration configuration, IpConfiguration ipConfiguration) { 3212 assertNotEquals(ipConfiguration, configuration.getIpConfiguration()); 3213 configuration.setIpConfiguration(ipConfiguration); 3214 } 3215 3216 /** 3217 * Modifies the provided WifiConfiguration with the specified |wepKeys| value and 3218 * |wepTxKeyIndex|. 3219 */ 3220 private void assertAndSetNetworkWepKeysAndTxIndex( 3221 WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx) { 3222 assertNotEquals(wepKeys, configuration.wepKeys); 3223 assertNotEquals(wepTxKeyIdx, configuration.wepTxKeyIndex); 3224 configuration.wepKeys = Arrays.copyOf(wepKeys, wepKeys.length); 3225 configuration.wepTxKeyIndex = wepTxKeyIdx; 3226 } 3227 3228 /** 3229 * Modifies the provided WifiConfiguration with the specified |preSharedKey| value. 3230 */ 3231 private void assertAndSetNetworkPreSharedKey( 3232 WifiConfiguration configuration, String preSharedKey) { 3233 assertNotEquals(preSharedKey, configuration.preSharedKey); 3234 configuration.preSharedKey = preSharedKey; 3235 } 3236 3237 /** 3238 * Modifies the provided WifiConfiguration with the specified enteprise |password| value. 3239 */ 3240 private void assertAndSetNetworkEnterprisePassword( 3241 WifiConfiguration configuration, String password) { 3242 assertNotEquals(password, configuration.enterpriseConfig.getPassword()); 3243 configuration.enterpriseConfig.setPassword(password); 3244 } 3245 3246 /** 3247 * Helper method to capture the networks list store data that will be written by 3248 * WifiConfigStore.write() method. 3249 */ 3250 private Pair<List<WifiConfiguration>, List<WifiConfiguration>> 3251 captureWriteNetworksListStoreData() { 3252 try { 3253 ArgumentCaptor<ArrayList> sharedConfigsCaptor = 3254 ArgumentCaptor.forClass(ArrayList.class); 3255 ArgumentCaptor<ArrayList> userConfigsCaptor = 3256 ArgumentCaptor.forClass(ArrayList.class); 3257 mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData) 3258 .setSharedConfigurations(sharedConfigsCaptor.capture()); 3259 mNetworkListStoreDataMockOrder.verify(mNetworkListStoreData) 3260 .setUserConfigurations(userConfigsCaptor.capture()); 3261 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(anyBoolean()); 3262 return Pair.create(sharedConfigsCaptor.getValue(), userConfigsCaptor.getValue()); 3263 } catch (Exception e) { 3264 fail("Exception encountered during write " + e); 3265 } 3266 return null; 3267 } 3268 3269 /** 3270 * Returns whether the provided network was in the store data or not. 3271 */ 3272 private boolean isNetworkInConfigStoreData(WifiConfiguration configuration) { 3273 Pair<List<WifiConfiguration>, List<WifiConfiguration>> networkListStoreData = 3274 captureWriteNetworksListStoreData(); 3275 if (networkListStoreData == null) { 3276 return false; 3277 } 3278 List<WifiConfiguration> networkList = new ArrayList<>(); 3279 networkList.addAll(networkListStoreData.first); 3280 networkList.addAll(networkListStoreData.second); 3281 return isNetworkInConfigStoreData(configuration, networkList); 3282 } 3283 3284 /** 3285 * Returns whether the provided network was in the store data or not. 3286 */ 3287 private boolean isNetworkInConfigStoreData( 3288 WifiConfiguration configuration, List<WifiConfiguration> networkList) { 3289 boolean foundNetworkInStoreData = false; 3290 for (WifiConfiguration retrievedConfig : networkList) { 3291 if (retrievedConfig.configKey().equals(configuration.configKey())) { 3292 foundNetworkInStoreData = true; 3293 break; 3294 } 3295 } 3296 return foundNetworkInStoreData; 3297 } 3298 3299 /** 3300 * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData 3301 * after WifiConfigStore#read. 3302 */ 3303 private void setupStoreDataForRead(List<WifiConfiguration> sharedConfigurations, 3304 List<WifiConfiguration> userConfigurations, Set<String> deletedEphemeralSsids) { 3305 when(mNetworkListStoreData.getSharedConfigurations()) 3306 .thenReturn(sharedConfigurations); 3307 when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations); 3308 when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids); 3309 } 3310 3311 /** 3312 * Setup expectations for WifiNetworksListStoreData and DeletedEphemeralSsidsStoreData 3313 * after WifiConfigStore#switchUserStoreAndRead. 3314 */ 3315 private void setupStoreDataForUserRead(List<WifiConfiguration> userConfigurations, 3316 Set<String> deletedEphemeralSsids) { 3317 when(mNetworkListStoreData.getUserConfigurations()).thenReturn(userConfigurations); 3318 when(mDeletedEphemeralSsidsStoreData.getSsidList()).thenReturn(deletedEphemeralSsids); 3319 } 3320 3321 /** 3322 * Verifies that the provided network was not present in the last config store write. 3323 */ 3324 private void verifyNetworkNotInConfigStoreData(WifiConfiguration configuration) { 3325 assertFalse(isNetworkInConfigStoreData(configuration)); 3326 } 3327 3328 /** 3329 * Verifies that the provided network was present in the last config store write. 3330 */ 3331 private void verifyNetworkInConfigStoreData(WifiConfiguration configuration) { 3332 assertTrue(isNetworkInConfigStoreData(configuration)); 3333 } 3334 3335 private void assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration) { 3336 if (!TextUtils.isEmpty(configuration.preSharedKey)) { 3337 assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.preSharedKey); 3338 } 3339 if (configuration.wepKeys != null) { 3340 for (int i = 0; i < configuration.wepKeys.length; i++) { 3341 if (!TextUtils.isEmpty(configuration.wepKeys[i])) { 3342 assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.wepKeys[i]); 3343 } 3344 } 3345 } 3346 if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) { 3347 assertEquals( 3348 WifiConfigManager.PASSWORD_MASK, 3349 configuration.enterpriseConfig.getPassword()); 3350 } 3351 } 3352 3353 /** 3354 * Verifies that the network was present in the network change broadcast and returns the 3355 * change reason. 3356 */ 3357 private int verifyNetworkInBroadcastAndReturnReason(WifiConfiguration configuration) { 3358 ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); 3359 ArgumentCaptor<UserHandle> userHandleCaptor = ArgumentCaptor.forClass(UserHandle.class); 3360 mContextConfigStoreMockOrder.verify(mContext) 3361 .sendBroadcastAsUser(intentCaptor.capture(), userHandleCaptor.capture()); 3362 3363 assertEquals(userHandleCaptor.getValue(), UserHandle.ALL); 3364 Intent intent = intentCaptor.getValue(); 3365 3366 int changeReason = intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1); 3367 WifiConfiguration retrievedConfig = 3368 (WifiConfiguration) intent.getExtra(WifiManager.EXTRA_WIFI_CONFIGURATION); 3369 assertEquals(retrievedConfig.configKey(), configuration.configKey()); 3370 3371 // Verify that all the passwords are masked in the broadcast configuration. 3372 assertPasswordsMaskedInWifiConfiguration(retrievedConfig); 3373 3374 return changeReason; 3375 } 3376 3377 /** 3378 * Verifies that we sent out an add broadcast with the provided network. 3379 */ 3380 private void verifyNetworkAddBroadcast(WifiConfiguration configuration) { 3381 assertEquals( 3382 verifyNetworkInBroadcastAndReturnReason(configuration), 3383 WifiManager.CHANGE_REASON_ADDED); 3384 } 3385 3386 /** 3387 * Verifies that we sent out an update broadcast with the provided network. 3388 */ 3389 private void verifyNetworkUpdateBroadcast(WifiConfiguration configuration) { 3390 assertEquals( 3391 verifyNetworkInBroadcastAndReturnReason(configuration), 3392 WifiManager.CHANGE_REASON_CONFIG_CHANGE); 3393 } 3394 3395 /** 3396 * Verifies that we sent out a remove broadcast with the provided network. 3397 */ 3398 private void verifyNetworkRemoveBroadcast(WifiConfiguration configuration) { 3399 assertEquals( 3400 verifyNetworkInBroadcastAndReturnReason(configuration), 3401 WifiManager.CHANGE_REASON_REMOVED); 3402 } 3403 3404 /** 3405 * Adds the provided configuration to WifiConfigManager and modifies the provided configuration 3406 * with creator/update uid, package name and time. This also sets defaults for fields not 3407 * populated. 3408 * These fields are populated internally by WifiConfigManager and hence we need 3409 * to modify the configuration before we compare the added network with the retrieved network. 3410 */ 3411 private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration) { 3412 when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS); 3413 NetworkUpdateResult result = 3414 mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_CREATOR_UID); 3415 setDefaults(configuration); 3416 setCreationDebugParams(configuration); 3417 configuration.networkId = result.getNetworkId(); 3418 return result; 3419 } 3420 3421 /** 3422 * Add network to WifiConfigManager and ensure that it was successful. 3423 */ 3424 private NetworkUpdateResult verifyAddNetworkToWifiConfigManager( 3425 WifiConfiguration configuration) { 3426 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3427 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3428 assertTrue(result.isNewNetwork()); 3429 assertTrue(result.hasIpChanged()); 3430 assertTrue(result.hasProxyChanged()); 3431 3432 verifyNetworkAddBroadcast(configuration); 3433 // Verify that the config store write was triggered with this new configuration. 3434 verifyNetworkInConfigStoreData(configuration); 3435 return result; 3436 } 3437 3438 /** 3439 * Add ephemeral network to WifiConfigManager and ensure that it was successful. 3440 */ 3441 private NetworkUpdateResult verifyAddEphemeralNetworkToWifiConfigManager( 3442 WifiConfiguration configuration) throws Exception { 3443 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3444 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3445 assertTrue(result.isNewNetwork()); 3446 assertTrue(result.hasIpChanged()); 3447 assertTrue(result.hasProxyChanged()); 3448 3449 verifyNetworkAddBroadcast(configuration); 3450 // Ensure that the write was not invoked for ephemeral network addition. 3451 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3452 return result; 3453 } 3454 3455 /** 3456 * Add Passpoint network to WifiConfigManager and ensure that it was successful. 3457 */ 3458 private NetworkUpdateResult verifyAddPasspointNetworkToWifiConfigManager( 3459 WifiConfiguration configuration) throws Exception { 3460 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 3461 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3462 assertTrue(result.isNewNetwork()); 3463 assertTrue(result.hasIpChanged()); 3464 assertTrue(result.hasProxyChanged()); 3465 3466 // Verify keys are not being installed. 3467 verify(mWifiKeyStore, never()).updateNetworkKeys(any(WifiConfiguration.class), 3468 any(WifiConfiguration.class)); 3469 verifyNetworkAddBroadcast(configuration); 3470 // Ensure that the write was not invoked for Passpoint network addition. 3471 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3472 return result; 3473 } 3474 3475 /** 3476 * Updates the provided configuration to WifiConfigManager and modifies the provided 3477 * configuration with update uid, package name and time. 3478 * These fields are populated internally by WifiConfigManager and hence we need 3479 * to modify the configuration before we compare the added network with the retrieved network. 3480 */ 3481 private NetworkUpdateResult updateNetworkToWifiConfigManager(WifiConfiguration configuration) { 3482 when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_UPDATE_TIME_MILLIS); 3483 NetworkUpdateResult result = 3484 mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_UPDATE_UID); 3485 setUpdateDebugParams(configuration); 3486 return result; 3487 } 3488 3489 /** 3490 * Update network to WifiConfigManager config change and ensure that it was successful. 3491 */ 3492 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManager( 3493 WifiConfiguration configuration) { 3494 NetworkUpdateResult result = updateNetworkToWifiConfigManager(configuration); 3495 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 3496 assertFalse(result.isNewNetwork()); 3497 3498 verifyNetworkUpdateBroadcast(configuration); 3499 // Verify that the config store write was triggered with this new configuration. 3500 verifyNetworkInConfigStoreData(configuration); 3501 return result; 3502 } 3503 3504 /** 3505 * Update network to WifiConfigManager without IP config change and ensure that it was 3506 * successful. 3507 */ 3508 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithoutIpChange( 3509 WifiConfiguration configuration) { 3510 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration); 3511 assertFalse(result.hasIpChanged()); 3512 assertFalse(result.hasProxyChanged()); 3513 return result; 3514 } 3515 3516 /** 3517 * Update network to WifiConfigManager with IP config change and ensure that it was 3518 * successful. 3519 */ 3520 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithIpChange( 3521 WifiConfiguration configuration) { 3522 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration); 3523 assertTrue(result.hasIpChanged()); 3524 assertTrue(result.hasProxyChanged()); 3525 return result; 3526 } 3527 3528 /** 3529 * Removes network from WifiConfigManager and ensure that it was successful. 3530 */ 3531 private void verifyRemoveNetworkFromWifiConfigManager( 3532 WifiConfiguration configuration) { 3533 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3534 3535 verifyNetworkRemoveBroadcast(configuration); 3536 // Verify if the config store write was triggered without this new configuration. 3537 verifyNetworkNotInConfigStoreData(configuration); 3538 } 3539 3540 /** 3541 * Removes ephemeral network from WifiConfigManager and ensure that it was successful. 3542 */ 3543 private void verifyRemoveEphemeralNetworkFromWifiConfigManager( 3544 WifiConfiguration configuration) throws Exception { 3545 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3546 3547 verifyNetworkRemoveBroadcast(configuration); 3548 // Ensure that the write was not invoked for ephemeral network remove. 3549 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3550 } 3551 3552 /** 3553 * Removes Passpoint network from WifiConfigManager and ensure that it was successful. 3554 */ 3555 private void verifyRemovePasspointNetworkFromWifiConfigManager( 3556 WifiConfiguration configuration) throws Exception { 3557 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 3558 3559 // Verify keys are not being removed. 3560 verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class)); 3561 verifyNetworkRemoveBroadcast(configuration); 3562 // Ensure that the write was not invoked for Passpoint network remove. 3563 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean()); 3564 } 3565 3566 /** 3567 * Verifies the provided network's public status and ensures that the network change broadcast 3568 * has been sent out. 3569 */ 3570 private void verifyUpdateNetworkStatus(WifiConfiguration configuration, int status) { 3571 assertEquals(status, configuration.status); 3572 verifyNetworkUpdateBroadcast(configuration); 3573 } 3574 3575 /** 3576 * Verifies the network's selection status update. 3577 * 3578 * For temporarily disabled reasons, the method ensures that the status has changed only if 3579 * disable reason counter has exceeded the threshold. 3580 * 3581 * For permanently disabled/enabled reasons, the method ensures that the public status has 3582 * changed and the network change broadcast has been sent out. 3583 */ 3584 private void verifyUpdateNetworkSelectionStatus( 3585 int networkId, int reason, int temporaryDisableReasonCounter) { 3586 when(mClock.getElapsedSinceBootMillis()) 3587 .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS); 3588 3589 // Fetch the current status of the network before we try to update the status. 3590 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 3591 NetworkSelectionStatus currentStatus = retrievedNetwork.getNetworkSelectionStatus(); 3592 int currentDisableReason = currentStatus.getNetworkSelectionDisableReason(); 3593 3594 // First set the status to the provided reason. 3595 assertTrue(mWifiConfigManager.updateNetworkSelectionStatus(networkId, reason)); 3596 3597 // Now fetch the network configuration and verify the new status of the network. 3598 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 3599 3600 NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 3601 int retrievedDisableReason = retrievedStatus.getNetworkSelectionDisableReason(); 3602 long retrievedDisableTime = retrievedStatus.getDisableTime(); 3603 int retrievedDisableReasonCounter = retrievedStatus.getDisableReasonCounter(reason); 3604 int disableReasonThreshold = 3605 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[reason]; 3606 3607 if (reason == NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) { 3608 assertEquals(reason, retrievedDisableReason); 3609 assertTrue(retrievedStatus.isNetworkEnabled()); 3610 assertEquals( 3611 NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP, 3612 retrievedDisableTime); 3613 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED); 3614 } else if (reason < NetworkSelectionStatus.DISABLED_TLS_VERSION_MISMATCH) { 3615 // For temporarily disabled networks, we need to ensure that the current status remains 3616 // until the threshold is crossed. 3617 assertEquals(temporaryDisableReasonCounter, retrievedDisableReasonCounter); 3618 if (retrievedDisableReasonCounter < disableReasonThreshold) { 3619 assertEquals(currentDisableReason, retrievedDisableReason); 3620 assertEquals( 3621 currentStatus.getNetworkSelectionStatus(), 3622 retrievedStatus.getNetworkSelectionStatus()); 3623 } else { 3624 assertEquals(reason, retrievedDisableReason); 3625 assertTrue(retrievedStatus.isNetworkTemporaryDisabled()); 3626 assertEquals( 3627 TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS, retrievedDisableTime); 3628 } 3629 } else if (reason < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX) { 3630 assertEquals(reason, retrievedDisableReason); 3631 assertTrue(retrievedStatus.isNetworkPermanentlyDisabled()); 3632 assertEquals( 3633 NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP, 3634 retrievedDisableTime); 3635 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED); 3636 } 3637 } 3638 3639 /** 3640 * Creates a scan detail corresponding to the provided network and given BSSID, level &frequency 3641 * values. 3642 */ 3643 private ScanDetail createScanDetailForNetwork( 3644 WifiConfiguration configuration, String bssid, int level, int frequency) { 3645 String caps; 3646 if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) { 3647 caps = "[WPA2-PSK-CCMP]"; 3648 } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) 3649 || configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) { 3650 caps = "[WPA2-EAP-CCMP]"; 3651 } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE) 3652 && WifiConfigurationUtil.hasAnyValidWepKey(configuration.wepKeys)) { 3653 caps = "[WEP]"; 3654 } else { 3655 caps = "[]"; 3656 } 3657 WifiSsid ssid = WifiSsid.createFromAsciiEncoded(configuration.getPrintableSsid()); 3658 // Fill in 0's in the fields we don't care about. 3659 return new ScanDetail( 3660 ssid, bssid, caps, level, frequency, mClock.getUptimeSinceBootMillis(), 3661 mClock.getWallClockMillis()); 3662 } 3663 3664 /** 3665 * Creates a scan detail corresponding to the provided network and BSSID value. 3666 */ 3667 private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration, String bssid) { 3668 return createScanDetailForNetwork(configuration, bssid, 0, 0); 3669 } 3670 3671 /** 3672 * Creates a scan detail corresponding to the provided network and fixed BSSID value. 3673 */ 3674 private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration) { 3675 return createScanDetailForNetwork(configuration, TEST_BSSID); 3676 } 3677 3678 /** 3679 * Adds the provided network and then creates a scan detail corresponding to the network. The 3680 * method then creates a ScanDetail corresponding to the network and ensures that the network 3681 * is properly matched using 3682 * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)} and also 3683 * verifies that the provided scan detail was cached, 3684 */ 3685 private void verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 3686 WifiConfiguration network) { 3687 // First add the provided network. 3688 verifyAddNetworkToWifiConfigManager(network); 3689 3690 // Now create a dummy scan detail corresponding to the network. 3691 ScanDetail scanDetail = createScanDetailForNetwork(network); 3692 ScanResult scanResult = scanDetail.getScanResult(); 3693 3694 WifiConfiguration retrievedNetwork = 3695 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail); 3696 // Retrieve the network with password data for comparison. 3697 retrievedNetwork = 3698 mWifiConfigManager.getConfiguredNetworkWithPassword(retrievedNetwork.networkId); 3699 3700 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 3701 network, retrievedNetwork); 3702 3703 // Now retrieve the scan detail cache and ensure that the new scan detail is in cache. 3704 ScanDetailCache retrievedScanDetailCache = 3705 mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId); 3706 assertEquals(1, retrievedScanDetailCache.size()); 3707 ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID); 3708 3709 ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult); 3710 } 3711 3712 /** 3713 * Adds a new network and verifies that the |HasEverConnected| flag is set to false. 3714 */ 3715 private void verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network) { 3716 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network); 3717 WifiConfiguration retrievedNetwork = 3718 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 3719 assertFalse("Adding a new network should not have hasEverConnected set to true.", 3720 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 3721 } 3722 3723 /** 3724 * Updates an existing network with some credential change and verifies that the 3725 * |HasEverConnected| flag is set to false. 3726 */ 3727 private void verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse( 3728 WifiConfiguration network) { 3729 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 3730 WifiConfiguration retrievedNetwork = 3731 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 3732 assertFalse("Updating network credentials config should clear hasEverConnected.", 3733 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 3734 } 3735 3736 /** 3737 * Updates an existing network after connection using 3738 * {@link WifiConfigManager#updateNetworkAfterConnect(int)} and asserts that the 3739 * |HasEverConnected| flag is set to true. 3740 */ 3741 private void verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId) { 3742 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(networkId)); 3743 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 3744 assertTrue("hasEverConnected expected to be true after connection.", 3745 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 3746 } 3747 3748 /** 3749 * Sets up a user profiles for WifiConfigManager testing. 3750 * 3751 * @param userId Id of the user. 3752 */ 3753 private void setupUserProfiles(int userId) { 3754 final UserInfo userInfo = 3755 new UserInfo(userId, Integer.toString(userId), UserInfo.FLAG_PRIMARY); 3756 List<UserInfo> userProfiles = Arrays.asList(userInfo); 3757 when(mUserManager.getProfiles(userId)).thenReturn(userProfiles); 3758 when(mUserManager.isUserUnlockingOrUnlocked(userId)).thenReturn(true); 3759 } 3760 3761} 3762