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