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 17 package com.android.server.wifi; 18 19 import static android.Manifest.permission.ACCESS_WIFI_STATE; 20 import static android.Manifest.permission.MANAGE_WIFI_COUNTRY_CODE; 21 import static android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS; 22 import static android.Manifest.permission.WIFI_UPDATE_COEX_UNSAFE_CHANNELS; 23 import static android.content.Intent.ACTION_SHUTDOWN; 24 import static android.net.wifi.ScanResult.WIFI_BAND_60_GHZ; 25 import static android.net.wifi.ScanResult.WIFI_BAND_6_GHZ; 26 import static android.net.wifi.WifiAvailableChannel.FILTER_REGULATORY; 27 import static android.net.wifi.WifiAvailableChannel.OP_MODE_SAP; 28 import static android.net.wifi.WifiAvailableChannel.OP_MODE_STA; 29 import static android.net.wifi.WifiConfiguration.METERED_OVERRIDE_METERED; 30 import static android.net.wifi.WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT; 31 import static android.net.wifi.WifiManager.CHANNEL_DATA_KEY_FREQUENCY_MHZ; 32 import static android.net.wifi.WifiManager.CHANNEL_DATA_KEY_NUM_AP; 33 import static android.net.wifi.WifiManager.COEX_RESTRICTION_SOFTAP; 34 import static android.net.wifi.WifiManager.COEX_RESTRICTION_WIFI_AWARE; 35 import static android.net.wifi.WifiManager.COEX_RESTRICTION_WIFI_DIRECT; 36 import static android.net.wifi.WifiManager.DEVICE_MOBILITY_STATE_STATIONARY; 37 import static android.net.wifi.WifiManager.EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1; 38 import static android.net.wifi.WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE; 39 import static android.net.wifi.WifiManager.IFACE_IP_MODE_CONFIGURATION_ERROR; 40 import static android.net.wifi.WifiManager.IFACE_IP_MODE_LOCAL_ONLY; 41 import static android.net.wifi.WifiManager.IFACE_IP_MODE_TETHERED; 42 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_GENERIC; 43 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE; 44 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_NO_CHANNEL; 45 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_TETHERING_DISALLOWED; 46 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.REQUEST_REGISTERED; 47 import static android.net.wifi.WifiManager.NOT_OVERRIDE_EXISTING_NETWORKS_ON_RESTORE; 48 import static android.net.wifi.WifiManager.SAP_START_FAILURE_GENERAL; 49 import static android.net.wifi.WifiManager.SAP_START_FAILURE_NO_CHANNEL; 50 import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED; 51 import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING; 52 import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED; 53 import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED; 54 import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED; 55 import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED; 56 import static android.net.wifi.WifiScanner.WIFI_BAND_24_5_WITH_DFS_6_60_GHZ; 57 import static android.net.wifi.WifiScanner.WIFI_BAND_24_GHZ; 58 import static android.net.wifi.WifiScanner.WIFI_BAND_5_GHZ; 59 import static android.os.Process.WIFI_UID; 60 import static android.os.Process.myUid; 61 62 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession; 63 import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_LOCAL_ONLY; 64 import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_PRIMARY; 65 import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_SECONDARY_LONG_LIVED; 66 import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_SECONDARY_TRANSIENT; 67 import static com.android.server.wifi.LocalOnlyHotspotRequestInfo.HOTSPOT_NO_ERROR; 68 import static com.android.server.wifi.SelfRecovery.REASON_API_CALL; 69 import static com.android.server.wifi.TestUtil.createCapabilityBitset; 70 import static com.android.server.wifi.WifiConfigurationTestUtil.SECURITY_NONE; 71 import static com.android.server.wifi.WifiSettingsConfigStore.D2D_ALLOWED_WHEN_INFRA_STA_DISABLED; 72 import static com.android.server.wifi.WifiSettingsConfigStore.SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI; 73 import static com.android.server.wifi.WifiSettingsConfigStore.SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API; 74 import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_STA_FACTORY_MAC_ADDRESS; 75 import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_VERBOSE_LOGGING_ENABLED; 76 import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_WEP_ALLOWED; 77 78 import static com.google.common.truth.Truth.assertThat; 79 80 import static org.junit.Assert.assertArrayEquals; 81 import static org.junit.Assert.assertEquals; 82 import static org.junit.Assert.assertFalse; 83 import static org.junit.Assert.assertNotNull; 84 import static org.junit.Assert.assertNull; 85 import static org.junit.Assert.assertThrows; 86 import static org.junit.Assert.assertTrue; 87 import static org.junit.Assert.fail; 88 import static org.junit.Assume.assumeTrue; 89 import static org.mockito.AdditionalAnswers.returnsSecondArg; 90 import static org.mockito.AdditionalMatchers.aryEq; 91 import static org.mockito.ArgumentMatchers.anyList; 92 import static org.mockito.ArgumentMatchers.anySet; 93 import static org.mockito.ArgumentMatchers.notNull; 94 import static org.mockito.ArgumentMatchers.nullable; 95 import static org.mockito.ArgumentMatchers.any; 96 import static org.mockito.ArgumentMatchers.anyString; 97 import static org.mockito.ArgumentMatchers.eq; 98 import static org.mockito.Mockito.anyBoolean; 99 import static org.mockito.Mockito.anyInt; 100 import static org.mockito.Mockito.argThat; 101 import static org.mockito.Mockito.atLeastOnce; 102 import static org.mockito.Mockito.clearInvocations; 103 import static org.mockito.Mockito.doAnswer; 104 import static org.mockito.Mockito.doNothing; 105 import static org.mockito.Mockito.doReturn; 106 import static org.mockito.Mockito.doThrow; 107 import static org.mockito.Mockito.ignoreStubs; 108 import static org.mockito.Mockito.inOrder; 109 import static org.mockito.Mockito.isNull; 110 import static org.mockito.Mockito.lenient; 111 import static org.mockito.Mockito.mock; 112 import static org.mockito.Mockito.never; 113 import static org.mockito.Mockito.reset; 114 import static org.mockito.Mockito.spy; 115 import static org.mockito.Mockito.times; 116 import static org.mockito.Mockito.validateMockitoUsage; 117 import static org.mockito.Mockito.verify; 118 import static org.mockito.Mockito.verifyNoMoreInteractions; 119 import static org.mockito.Mockito.when; 120 121 import android.Manifest; 122 import android.app.ActivityManager; 123 import android.app.AppOpsManager; 124 import android.app.admin.DevicePolicyManager; 125 import android.app.admin.WifiSsidPolicy; 126 import android.app.compat.CompatChanges; 127 import android.app.test.MockAnswerUtil.AnswerWithArguments; 128 import android.bluetooth.BluetoothAdapter; 129 import android.compat.testing.PlatformCompatChangeRule; 130 import android.content.AttributionSource; 131 import android.content.BroadcastReceiver; 132 import android.content.ContentResolver; 133 import android.content.Context; 134 import android.content.Intent; 135 import android.content.IntentFilter; 136 import android.content.pm.ApplicationInfo; 137 import android.content.pm.PackageInfo; 138 import android.content.pm.PackageManager; 139 import android.content.res.Resources; 140 import android.hardware.wifi.WifiStatusCode; 141 import android.location.Location; 142 import android.location.LocationManager; 143 import android.net.DhcpInfo; 144 import android.net.DhcpOption; 145 import android.net.DhcpResultsParcelable; 146 import android.net.MacAddress; 147 import android.net.Network; 148 import android.net.NetworkStack; 149 import android.net.TetheringManager; 150 import android.net.Uri; 151 import android.net.wifi.BlockingOption; 152 import android.net.wifi.CoexUnsafeChannel; 153 import android.net.wifi.IActionListener; 154 import android.net.wifi.IBooleanListener; 155 import android.net.wifi.IByteArrayListener; 156 import android.net.wifi.ICoexCallback; 157 import android.net.wifi.IDppCallback; 158 import android.net.wifi.IIntegerListener; 159 import android.net.wifi.IInterfaceCreationInfoCallback; 160 import android.net.wifi.ILastCallerListener; 161 import android.net.wifi.IListListener; 162 import android.net.wifi.ILocalOnlyConnectionStatusListener; 163 import android.net.wifi.ILocalOnlyHotspotCallback; 164 import android.net.wifi.IMacAddressListListener; 165 import android.net.wifi.IMapListener; 166 import android.net.wifi.INetworkRequestMatchCallback; 167 import android.net.wifi.IOnWifiActivityEnergyInfoListener; 168 import android.net.wifi.IOnWifiDriverCountryCodeChangedListener; 169 import android.net.wifi.IOnWifiUsabilityStatsListener; 170 import android.net.wifi.IPnoScanResultsCallback; 171 import android.net.wifi.IScanResultsCallback; 172 import android.net.wifi.ISoftApCallback; 173 import android.net.wifi.IStringListener; 174 import android.net.wifi.ISubsystemRestartCallback; 175 import android.net.wifi.ISuggestionConnectionStatusListener; 176 import android.net.wifi.ISuggestionUserApprovalStatusListener; 177 import android.net.wifi.ITrafficStateCallback; 178 import android.net.wifi.ITwtCallback; 179 import android.net.wifi.ITwtCapabilitiesListener; 180 import android.net.wifi.ITwtStatsListener; 181 import android.net.wifi.IWifiBandsListener; 182 import android.net.wifi.IWifiConnectedNetworkScorer; 183 import android.net.wifi.IWifiLowLatencyLockListener; 184 import android.net.wifi.IWifiNetworkSelectionConfigListener; 185 import android.net.wifi.IWifiNetworkStateChangedListener; 186 import android.net.wifi.IWifiStateChangedListener; 187 import android.net.wifi.IWifiVerboseLoggingStatusChangedListener; 188 import android.net.wifi.MscsParams; 189 import android.net.wifi.QosCharacteristics; 190 import android.net.wifi.QosPolicyParams; 191 import android.net.wifi.ScanResult; 192 import android.net.wifi.SecurityParams; 193 import android.net.wifi.SoftApCapability; 194 import android.net.wifi.SoftApConfiguration; 195 import android.net.wifi.SoftApInfo; 196 import android.net.wifi.SoftApState; 197 import android.net.wifi.WifiAvailableChannel; 198 import android.net.wifi.WifiBands; 199 import android.net.wifi.WifiClient; 200 import android.net.wifi.WifiConfiguration; 201 import android.net.wifi.WifiConfiguration.KeyMgmt; 202 import android.net.wifi.WifiContext; 203 import android.net.wifi.WifiEnterpriseConfig; 204 import android.net.wifi.WifiInfo; 205 import android.net.wifi.WifiManager; 206 import android.net.wifi.WifiManager.LocalOnlyHotspotCallback; 207 import android.net.wifi.WifiNetworkSelectionConfig; 208 import android.net.wifi.WifiNetworkSuggestion; 209 import android.net.wifi.WifiScanner; 210 import android.net.wifi.WifiSsid; 211 import android.net.wifi.hotspot2.IProvisioningCallback; 212 import android.net.wifi.hotspot2.OsuProvider; 213 import android.net.wifi.hotspot2.PasspointConfiguration; 214 import android.net.wifi.hotspot2.pps.Credential; 215 import android.net.wifi.hotspot2.pps.HomeSp; 216 import android.net.wifi.twt.TwtRequest; 217 import android.net.wifi.twt.TwtSessionCallback; 218 import android.net.wifi.util.Environment; 219 import android.net.wifi.util.WifiResourceCache; 220 import android.os.Binder; 221 import android.os.Build; 222 import android.os.Bundle; 223 import android.os.Handler; 224 import android.os.HandlerThread; 225 import android.os.IBinder; 226 import android.os.IPowerManager; 227 import android.os.IThermalService; 228 import android.os.Parcel; 229 import android.os.ParcelFileDescriptor; 230 import android.os.PowerManager; 231 import android.os.Process; 232 import android.os.RemoteException; 233 import android.os.UserHandle; 234 import android.os.UserManager; 235 import android.os.WorkSource; 236 import android.os.connectivity.WifiActivityEnergyInfo; 237 import android.os.test.TestLooper; 238 import android.telephony.CarrierConfigManager; 239 import android.telephony.PhoneStateListener; 240 import android.telephony.SubscriptionManager; 241 import android.telephony.TelephonyManager; 242 import android.util.ArrayMap; 243 import android.util.ArraySet; 244 import android.util.Pair; 245 246 import androidx.test.filters.SmallTest; 247 248 import com.android.internal.os.PowerProfile; 249 import com.android.modules.utils.ParceledListSlice; 250 import com.android.modules.utils.StringParceledListSlice; 251 import com.android.modules.utils.build.SdkLevel; 252 import com.android.server.wifi.WifiServiceImpl.LocalOnlyRequestorCallback; 253 import com.android.server.wifi.WifiServiceImpl.SoftApCallbackInternal; 254 import com.android.server.wifi.WifiServiceImpl.ThreadStateListener; 255 import com.android.server.wifi.WifiServiceImpl.UwbAdapterStateListener; 256 import com.android.server.wifi.b2b.WifiRoamingModeManager; 257 import com.android.server.wifi.coex.CoexManager; 258 import com.android.server.wifi.entitlement.PseudonymInfo; 259 import com.android.server.wifi.hotspot2.PasspointManager; 260 import com.android.server.wifi.hotspot2.PasspointNetworkNominateHelper; 261 import com.android.server.wifi.hotspot2.PasspointProvisioningTestUtil; 262 import com.android.server.wifi.proto.WifiStatsLog; 263 import com.android.server.wifi.proto.nano.WifiMetricsProto.UserActionEvent; 264 import com.android.server.wifi.util.ActionListenerWrapper; 265 import com.android.server.wifi.util.ApConfigUtil; 266 import com.android.server.wifi.util.LastCallerInfoManager; 267 import com.android.server.wifi.util.WifiPermissionsUtil; 268 import com.android.server.wifi.util.WifiPermissionsWrapper; 269 import com.android.server.wifi.util.WorkSourceHelper; 270 import com.android.wifi.flags.FeatureFlags; 271 import com.android.wifi.resources.R; 272 273 import com.google.common.base.Strings; 274 275 import org.junit.After; 276 import org.junit.Before; 277 import org.junit.Rule; 278 import org.junit.Test; 279 import org.junit.rules.TestRule; 280 import org.mockito.ArgumentCaptor; 281 import org.mockito.ArgumentMatcher; 282 import org.mockito.Captor; 283 import org.mockito.InOrder; 284 import org.mockito.Mock; 285 import org.mockito.MockitoAnnotations; 286 import org.mockito.MockitoSession; 287 288 import java.io.FileDescriptor; 289 import java.io.PrintWriter; 290 import java.io.StringWriter; 291 import java.util.ArrayList; 292 import java.util.Arrays; 293 import java.util.BitSet; 294 import java.util.Collections; 295 import java.util.HashMap; 296 import java.util.List; 297 import java.util.Map; 298 import java.util.Optional; 299 import java.util.Set; 300 301 /** 302 * Unit tests for {@link WifiServiceImpl}. 303 * 304 * Note: this is intended to build up over time and will not immediately cover the entire file. 305 */ 306 @SmallTest 307 public class WifiServiceImplTest extends WifiBaseTest { 308 309 private static final String TAG = "WifiServiceImplTest"; 310 private static final String SCAN_PACKAGE_NAME = "scanPackage"; 311 private static final int DEFAULT_VERBOSE_LOGGING = 0; 312 private static final String ANDROID_SYSTEM_PACKAGE = "android"; 313 private static final String TEST_PACKAGE_NAME = "TestPackage"; 314 private static final String TEST_PACKAGE_NAME_OTHER = "TestPackageOther"; 315 private static final String TEST_FEATURE_ID = "TestFeature"; 316 private static final String TEST_FEATURE_ID_OTHER = "TestFeatureOther"; 317 private static final String SYSUI_PACKAGE_NAME = "com.android.systemui"; 318 private static final String CERT_INSTALLER_PACKAGE_NAME = "com.android.certinstaller"; 319 private static final int TEST_PID = 6789; 320 private static final int TEST_PID2 = 9876; 321 private static final int TEST_UID = 1200000; 322 private static final int OTHER_TEST_UID = 1300000; 323 private static final int TEST_USER_HANDLE = 13; 324 private static final int TEST_WIFI_CONNECTED_NETWORK_SCORER_IDENTIFIER = 1; 325 private static final String WIFI_IFACE_NAME = "wlan0"; 326 private static final String WIFI_IFACE_NAME2 = "wlan1"; 327 private static final String TEST_COUNTRY_CODE = "US"; 328 private static final String TEST_NEW_COUNTRY_CODE = "TW"; 329 private static final String TEST_FACTORY_MAC = "10:22:34:56:78:92"; 330 private static final MacAddress TEST_FACTORY_MAC_ADDR = MacAddress.fromString(TEST_FACTORY_MAC); 331 private static final String TEST_FQDN = "testfqdn"; 332 private static final String TEST_FRIENDLY_NAME = "testfriendlyname"; 333 private static final List<WifiConfiguration> TEST_WIFI_CONFIGURATION_LIST = Arrays.asList( 334 WifiConfigurationTestUtil.generateWifiConfig( 335 0, 1000000, "\"red\"", true, true, null, null, 336 SECURITY_NONE), 337 WifiConfigurationTestUtil.generateWifiConfig( 338 1, 1000001, "\"green\"", true, false, "example.com", "Green", 339 SECURITY_NONE), 340 WifiConfigurationTestUtil.generateWifiConfig( 341 2, 1200000, "\"blue\"", false, true, null, null, 342 SECURITY_NONE), 343 WifiConfigurationTestUtil.generateWifiConfig( 344 3, 1100000, "\"cyan\"", true, true, null, null, 345 SECURITY_NONE), 346 WifiConfigurationTestUtil.generateWifiConfig( 347 4, 1100001, "\"yellow\"", true, true, "example.org", "Yellow", 348 SECURITY_NONE), 349 WifiConfigurationTestUtil.generateWifiConfig( 350 5, 1100002, "\"magenta\"", false, false, null, null, 351 SECURITY_NONE)); 352 private static final int TEST_AP_FREQUENCY = 2412; 353 private static final int TEST_AP_BANDWIDTH = SoftApInfo.CHANNEL_WIDTH_20MHZ; 354 private static final TetheringManager.TetheringRequest TEST_TETHERING_REQUEST = 355 new TetheringManager.TetheringRequest.Builder(TetheringManager.TETHERING_WIFI).build(); 356 private static final String TEST_IFACE_NAME = "test-wlan0"; 357 private static final int NETWORK_CALLBACK_ID = 1100; 358 private static final String TEST_CAP = "[RSN-PSK-CCMP]"; 359 private static final String TEST_SSID = "Sid's Place"; 360 private static final String TEST_SSID_WITH_QUOTES = "\"" + TEST_SSID + "\""; 361 private static final String TEST_BSSID = "01:02:03:04:05:06"; 362 private static final String TEST_IP = "192.168.49.5"; 363 private static final String TEST_PACKAGE = "package"; 364 private static final int TEST_NETWORK_ID = 567; 365 private static final WorkSource TEST_SETTINGS_WORKSOURCE = new WorkSource(); 366 private static final int TEST_SUB_ID = 1; 367 private static final byte[] TEST_OUI = new byte[]{0x01, 0x02, 0x03}; 368 private static final int TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS = 1000; 369 370 private SoftApInfo mTestSoftApInfo; 371 private List<SoftApInfo> mTestSoftApInfoList; 372 private Map<String, List<WifiClient>> mTestSoftApClients; 373 private Map<String, SoftApInfo> mTestSoftApInfos; 374 private WifiServiceImpl mWifiServiceImpl; 375 private TestLooper mLooper; 376 private WifiThreadRunner mWifiThreadRunner; 377 private PowerManager mPowerManager; 378 private PhoneStateListener mPhoneStateListener; 379 private OsuProvider mOsuProvider; 380 private SoftApCallbackInternal mStateMachineSoftApCallback; 381 private SoftApCallbackInternal mLohsApCallback; 382 private String mLohsInterfaceName; 383 private ApplicationInfo mApplicationInfo; 384 private List<ClientModeManager> mClientModeManagers; 385 private Bundle mExtras = new Bundle(); 386 private Bundle mAttribution = new Bundle(); 387 private static final String DPP_URI = "DPP:some_dpp_uri"; 388 private static final String DPP_PRODUCT_INFO = "DPP:some_dpp_uri_info"; 389 private static final WorkSource SETTINGS_WORKSOURCE = 390 new WorkSource(Process.SYSTEM_UID, "system-service"); 391 private static final String EXTERNAL_SCORER_PKG_NAME = "com.scorer"; 392 private final ArgumentCaptor<BroadcastReceiver> mBroadcastReceiverCaptor = 393 ArgumentCaptor.forClass(BroadcastReceiver.class); 394 395 final ArgumentCaptor<SoftApModeConfiguration> mSoftApModeConfigCaptor = 396 ArgumentCaptor.forClass(SoftApModeConfiguration.class); 397 398 final ArgumentCaptor<WifiSettingsConfigStore.OnSettingsChangedListener> 399 mWepAllowedSettingChangedListenerCaptor = 400 ArgumentCaptor.forClass(WifiSettingsConfigStore.OnSettingsChangedListener.class); 401 402 @Mock Bundle mBundle; 403 @Mock WifiContext mContext; 404 @Mock Context mContextAsUser; 405 @Mock WifiInjector mWifiInjector; 406 @Mock WifiCountryCode mWifiCountryCode; 407 @Mock Clock mClock; 408 @Mock WifiTrafficPoller mWifiTrafficPoller; 409 @Mock ConcreteClientModeManager mClientModeManager; 410 @Mock ActiveModeWarden mActiveModeWarden; 411 @Mock HandlerThread mHandlerThread; 412 @Mock Resources mResources; 413 @Mock FrameworkFacade mFrameworkFacade; 414 @Mock WifiLockManager mLockManager; 415 @Mock WifiMulticastLockManager mWifiMulticastLockManager; 416 @Mock WifiLastResortWatchdog mWifiLastResortWatchdog; 417 @Mock WifiBackupRestore mWifiBackupRestore; 418 @Mock SoftApBackupRestore mSoftApBackupRestore; 419 @Mock WifiMetrics mWifiMetrics; 420 @Mock WifiPermissionsUtil mWifiPermissionsUtil; 421 @Mock WifiPermissionsWrapper mWifiPermissionsWrapper; 422 @Mock WifiSettingsStore mSettingsStore; 423 @Mock ContentResolver mContentResolver; 424 @Mock PackageManager mPackageManager; 425 @Mock UserManager mUserManager; 426 @Mock WifiApConfigStore mWifiApConfigStore; 427 @Mock WifiConfiguration mApConfig; 428 @Mock ActivityManager mActivityManager; 429 @Mock AppOpsManager mAppOpsManager; 430 @Mock IBinder mAppBinder; 431 @Mock IBinder mAnotherAppBinder; 432 @Mock LocalOnlyHotspotRequestInfo mRequestInfo; 433 @Mock LocalOnlyHotspotRequestInfo mRequestInfo2; 434 @Mock IProvisioningCallback mProvisioningCallback; 435 @Mock ISoftApCallback mClientSoftApCallback; 436 @Mock ISoftApCallback mAnotherSoftApCallback; 437 @Mock PowerProfile mPowerProfile; 438 @Mock WifiTrafficPoller mWifiTrafficPolller; 439 @Mock ScanRequestProxy mScanRequestProxy; 440 @Mock WakeupController mWakeupController; 441 @Mock ITrafficStateCallback mTrafficStateCallback; 442 @Mock INetworkRequestMatchCallback mNetworkRequestMatchCallback; 443 @Mock WifiNetworkSuggestionsManager mWifiNetworkSuggestionsManager; 444 @Mock TelephonyManager mTelephonyManager; 445 @Mock CoexManager mCoexManager; 446 @Mock IOnWifiUsabilityStatsListener mOnWifiUsabilityStatsListener; 447 @Mock WifiConfigManager mWifiConfigManager; 448 @Mock WifiBlocklistMonitor mWifiBlocklistMonitor; 449 @Mock WifiScoreCard mWifiScoreCard; 450 @Mock WifiHealthMonitor mWifiHealthMonitor; 451 @Mock PasspointManager mPasspointManager; 452 @Mock DeviceConfigFacade mDeviceConfigFacade; 453 @Mock FeatureFlags mFeatureFlags; 454 @Mock IDppCallback mDppCallback; 455 @Mock ILocalOnlyHotspotCallback mLohsCallback; 456 @Mock ICoexCallback mCoexCallback; 457 @Mock IWifiStateChangedListener mWifiStateChangedListener; 458 @Mock IScanResultsCallback mScanResultsCallback; 459 @Mock ISuggestionConnectionStatusListener mSuggestionConnectionStatusListener; 460 @Mock ILocalOnlyConnectionStatusListener mLocalOnlyConnectionStatusListener; 461 @Mock ISuggestionUserApprovalStatusListener mSuggestionUserApprovalStatusListener; 462 @Mock IOnWifiActivityEnergyInfoListener mOnWifiActivityEnergyInfoListener; 463 @Mock ISubsystemRestartCallback mSubsystemRestartCallback; 464 @Mock IWifiConnectedNetworkScorer mWifiConnectedNetworkScorer; 465 @Mock WifiSettingsConfigStore mWifiSettingsConfigStore; 466 @Mock WifiScanAlwaysAvailableSettingsCompatibility mScanAlwaysAvailableSettingsCompatibility; 467 @Mock PackageInfo mPackageInfo; 468 @Mock WifiConnectivityManager mWifiConnectivityManager; 469 @Mock WifiDataStall mWifiDataStall; 470 @Mock WifiNative mWifiNative; 471 @Mock ConnectHelper mConnectHelper; 472 @Mock IActionListener mActionListener; 473 @Mock WifiNetworkFactory mWifiNetworkFactory; 474 @Mock UntrustedWifiNetworkFactory mUntrustedWifiNetworkFactory; 475 @Mock OemWifiNetworkFactory mOemWifiNetworkFactory; 476 @Mock RestrictedWifiNetworkFactory mRestrictedWifiNetworkFactory; 477 @Mock MultiInternetManager mMultiInternetManager; 478 @Mock MultiInternetWifiNetworkFactory mMultiInternetWifiNetworkFactory; 479 @Mock WifiDiagnostics mWifiDiagnostics; 480 @Mock WifiP2pConnection mWifiP2pConnection; 481 @Mock SimRequiredNotifier mSimRequiredNotifier; 482 @Mock WifiGlobals mWifiGlobals; 483 @Mock AdaptiveConnectivityEnabledSettingObserver mAdaptiveConnectivityEnabledSettingObserver; 484 @Mock MakeBeforeBreakManager mMakeBeforeBreakManager; 485 @Mock WifiCarrierInfoManager mWifiCarrierInfoManager; 486 @Mock WifiPseudonymManager mWifiPseudonymManager; 487 @Mock OpenNetworkNotifier mOpenNetworkNotifier; 488 @Mock WifiNotificationManager mWifiNotificationManager; 489 @Mock SarManager mSarManager; 490 @Mock SelfRecovery mSelfRecovery; 491 @Mock LastCallerInfoManager mLastCallerInfoManager; 492 @Mock BuildProperties mBuildProperties; 493 @Mock IOnWifiDriverCountryCodeChangedListener mIOnWifiDriverCountryCodeChangedListener; 494 @Mock WifiShellCommand mWifiShellCommand; 495 @Mock AfcManager mAfcManager; 496 @Mock LocationManager mLocationManager; 497 @Mock DevicePolicyManager mDevicePolicyManager; 498 @Mock HalDeviceManager mHalDeviceManager; 499 @Mock WifiDialogManager mWifiDialogManager; 500 @Mock SsidTranslator mSsidTranslator; 501 @Mock InterfaceConflictManager mInterfaceConflictManager; 502 @Mock WifiKeyStore mWifiKeyStore; 503 @Mock WifiPulledAtomLogger mWifiPulledAtomLogger; 504 @Mock ScoringParams mScoringParams; 505 @Mock ApplicationQosPolicyRequestHandler mApplicationQosPolicyRequestHandler; 506 @Mock Location mLocation; 507 @Mock WifiDeviceStateChangeManager mWifiDeviceStateChangeManager; 508 @Mock PasspointNetworkNominateHelper mPasspointNetworkNominateHelper; 509 @Mock WifiRoamingModeManager mWifiRoamingModeManager; 510 @Mock BackupRestoreController mBackupRestoreController; 511 @Mock WifiSettingsBackupRestore mWifiSettingsBackupRestore; 512 @Captor ArgumentCaptor<Intent> mIntentCaptor; 513 @Captor ArgumentCaptor<List> mListCaptor; 514 @Mock TwtManager mTwtManager; 515 @Mock WifiResourceCache mResourceCache; 516 @Mock WorkSourceHelper mWorkSourceHelper; 517 518 @Rule 519 // For frameworks 520 public TestRule compatChangeRule = new PlatformCompatChangeRule(); 521 522 private MockitoSession mSession; 523 524 WifiConfiguration mWifiConfig; 525 526 WifiLog mLog; 527 setUp()528 @Before public void setUp() throws Exception { 529 MockitoAnnotations.initMocks(this); 530 mSession = mockitoSession() 531 .mockStatic(SubscriptionManager.class) 532 .mockStatic(CompatChanges.class) 533 .startMocking(); 534 535 mLog = spy(new LogcatLog(TAG)); 536 mLooper = new TestLooper(); 537 mApplicationInfo = new ApplicationInfo(); 538 mApplicationInfo.targetSdkVersion = Build.VERSION_CODES.CUR_DEVELOPMENT; 539 when(mResourceCache.getInteger(R.integer.config_wifiHardwareSoftapMaxClientCount)) 540 .thenReturn(10); 541 WifiInjector.sWifiInjector = mWifiInjector; 542 when(mRequestInfo.getPid()).thenReturn(TEST_PID); 543 when(mRequestInfo2.getPid()).thenReturn(TEST_PID2); 544 when(mWifiInjector.getContext()).thenReturn(mContext); 545 when(mWifiInjector.getUserManager()).thenReturn(mUserManager); 546 when(mWifiInjector.getWifiCountryCode()).thenReturn(mWifiCountryCode); 547 when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics); 548 when(mWifiInjector.getWifiNetworkFactory()).thenReturn(mWifiNetworkFactory); 549 when(mWifiInjector.getUntrustedWifiNetworkFactory()) 550 .thenReturn(mUntrustedWifiNetworkFactory); 551 when(mWifiInjector.getOemWifiNetworkFactory()).thenReturn(mOemWifiNetworkFactory); 552 when(mWifiInjector.getRestrictedWifiNetworkFactory()) 553 .thenReturn(mRestrictedWifiNetworkFactory); 554 when(mWifiInjector.getMultiInternetWifiNetworkFactory()) 555 .thenReturn(mMultiInternetWifiNetworkFactory); 556 when(mWifiInjector.getMultiInternetManager()).thenReturn(mMultiInternetManager); 557 when(mWifiInjector.getWifiDiagnostics()).thenReturn(mWifiDiagnostics); 558 when(mWifiInjector.getActiveModeWarden()).thenReturn(mActiveModeWarden); 559 when(mWifiInjector.getWifiHandlerThread()).thenReturn(mHandlerThread); 560 when(mWifiInjector.getMakeBeforeBreakManager()).thenReturn(mMakeBeforeBreakManager); 561 when(mWifiInjector.getWifiNotificationManager()).thenReturn(mWifiNotificationManager); 562 when(mWifiInjector.getBuildProperties()).thenReturn(mBuildProperties); 563 when(mWifiInjector.makeWifiShellCommand(any())).thenReturn(mWifiShellCommand); 564 when(mWifiInjector.getAfcManager()).thenReturn(mAfcManager); 565 when(mWifiInjector.getPasspointNetworkNominateHelper()) 566 .thenReturn(mPasspointNetworkNominateHelper); 567 // needed to mock this to call "handleBootCompleted" 568 when(mWifiInjector.getPasspointProvisionerHandlerThread()) 569 .thenReturn(mock(HandlerThread.class)); 570 when(mWifiInjector.getWifiDeviceStateChangeManager()) 571 .thenReturn(mWifiDeviceStateChangeManager); 572 when(mWifiInjector.getWifiSettingsBackupRestore()).thenReturn(mWifiSettingsBackupRestore); 573 when(mWifiInjector.getBackupRestoreController()).thenReturn(mBackupRestoreController); 574 when(mWifiInjector.makeWsHelper(any())).thenReturn(mWorkSourceHelper); 575 when(mHandlerThread.getThreadHandler()).thenReturn(new Handler(mLooper.getLooper())); 576 when(mHandlerThread.getLooper()).thenReturn(mLooper.getLooper()); 577 when(mContext.getResources()).thenReturn(mResources); 578 when(mContext.getResourceCache()).thenReturn(mResourceCache); 579 when(mContext.getContentResolver()).thenReturn(mContentResolver); 580 when(mContext.getPackageManager()).thenReturn(mPackageManager); 581 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(mPackageInfo); 582 when(mPackageManager.checkSignatures(anyInt(), anyInt())) 583 .thenReturn(PackageManager.SIGNATURE_NO_MATCH); 584 when(mWifiInjector.getWifiApConfigStore()).thenReturn(mWifiApConfigStore); 585 doNothing().when(mFrameworkFacade).registerContentObserver(eq(mContext), any(), 586 anyBoolean(), any()); 587 when(mFrameworkFacade.getSettingsWorkSource(any())).thenReturn(TEST_SETTINGS_WORKSOURCE); 588 when(mContext.getSystemService(ActivityManager.class)).thenReturn(mActivityManager); 589 when(mContext.getSystemService(Context.APP_OPS_SERVICE)).thenReturn(mAppOpsManager); 590 when(mContext.getSystemService(LocationManager.class)).thenReturn(mLocationManager); 591 IPowerManager powerManagerService = mock(IPowerManager.class); 592 IThermalService thermalService = mock(IThermalService.class); 593 mPowerManager = 594 new PowerManager(mContext, powerManagerService, thermalService, new Handler()); 595 when(mContext.getSystemServiceName(PowerManager.class)).thenReturn(Context.POWER_SERVICE); 596 when(mContext.getSystemService(PowerManager.class)).thenReturn(mPowerManager); 597 when(mContext.createContextAsUser(eq(UserHandle.CURRENT), anyInt())) 598 .thenReturn(mContextAsUser); 599 when(mWifiInjector.getFrameworkFacade()).thenReturn(mFrameworkFacade); 600 when(mWifiInjector.getWifiLockManager()).thenReturn(mLockManager); 601 when(mWifiInjector.getWifiMulticastLockManager()).thenReturn(mWifiMulticastLockManager); 602 when(mWifiInjector.getWifiLastResortWatchdog()).thenReturn(mWifiLastResortWatchdog); 603 when(mWifiInjector.getWifiBackupRestore()).thenReturn(mWifiBackupRestore); 604 when(mWifiInjector.getSoftApBackupRestore()).thenReturn(mSoftApBackupRestore); 605 when(mWifiInjector.makeLog(anyString())).thenReturn(mLog); 606 when(mWifiInjector.getWifiTrafficPoller()).thenReturn(mWifiTrafficPoller); 607 when(mWifiInjector.getWifiPermissionsUtil()).thenReturn(mWifiPermissionsUtil); 608 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 609 when(mWifiInjector.getWifiSettingsStore()).thenReturn(mSettingsStore); 610 when(mWifiInjector.getClock()).thenReturn(mClock); 611 when(mWifiInjector.getScanRequestProxy()).thenReturn(mScanRequestProxy); 612 when(mWifiInjector.getWakeupController()).thenReturn(mWakeupController); 613 when(mWifiInjector.getWifiNetworkSuggestionsManager()) 614 .thenReturn(mWifiNetworkSuggestionsManager); 615 when(mWifiInjector.makeTelephonyManager()).thenReturn(mTelephonyManager); 616 when(mWifiInjector.getWifiPulledAtomLogger()).thenReturn(mWifiPulledAtomLogger); 617 when(mContext.getSystemService(TelephonyManager.class)).thenReturn(mTelephonyManager); 618 when(mWifiInjector.getCoexManager()).thenReturn(mCoexManager); 619 when(mWifiInjector.getWifiConfigManager()).thenReturn(mWifiConfigManager); 620 when(mWifiInjector.getWifiBlocklistMonitor()).thenReturn(mWifiBlocklistMonitor); 621 when(mWifiInjector.getPasspointManager()).thenReturn(mPasspointManager); 622 when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade); 623 when(mDeviceConfigFacade.getFeatureFlags()).thenReturn(mFeatureFlags); 624 when(mFeatureFlags.delaySaveToStore()).thenReturn(true); 625 when(mActiveModeWarden.getPrimaryClientModeManager()).thenReturn(mClientModeManager); 626 when(mClientModeManager.getInterfaceName()).thenReturn(WIFI_IFACE_NAME); 627 when(mWifiInjector.getWifiScoreCard()).thenReturn(mWifiScoreCard); 628 when(mWifiInjector.getWifiHealthMonitor()).thenReturn(mWifiHealthMonitor); 629 630 mWifiThreadRunner = new WifiThreadRunner(new Handler(mLooper.getLooper())); 631 mWifiThreadRunner.setTimeoutsAreErrors(true); 632 when(mWifiInjector.getWifiThreadRunner()).thenReturn(mWifiThreadRunner); 633 634 when(mWifiInjector.getSettingsConfigStore()).thenReturn(mWifiSettingsConfigStore); 635 when(mWifiInjector.getWifiScanAlwaysAvailableSettingsCompatibility()) 636 .thenReturn(mScanAlwaysAvailableSettingsCompatibility); 637 when(mWifiInjector.getWifiConnectivityManager()).thenReturn(mWifiConnectivityManager); 638 when(mWifiInjector.getWifiDataStall()).thenReturn(mWifiDataStall); 639 when(mWifiInjector.getWifiNative()).thenReturn(mWifiNative); 640 when(mWifiInjector.getConnectHelper()).thenReturn(mConnectHelper); 641 when(mWifiInjector.getWifiP2pConnection()).thenReturn(mWifiP2pConnection); 642 when(mWifiInjector.getSimRequiredNotifier()).thenReturn(mSimRequiredNotifier); 643 when(mWifiInjector.getWifiGlobals()).thenReturn(mWifiGlobals); 644 when(mWifiInjector.getAdaptiveConnectivityEnabledSettingObserver()) 645 .thenReturn(mAdaptiveConnectivityEnabledSettingObserver); 646 when(mClientModeManager.syncStartSubscriptionProvisioning(anyInt(), 647 any(OsuProvider.class), any(IProvisioningCallback.class))).thenReturn(true); 648 // Create an OSU provider that can be provisioned via an open OSU AP 649 mOsuProvider = PasspointProvisioningTestUtil.generateOsuProvider(true); 650 when(mContext.getOpPackageName()).thenReturn(TEST_PACKAGE_NAME); 651 when(mContext.getAttributionTag()).thenReturn(TEST_FEATURE_ID); 652 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 653 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 654 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD), 655 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 656 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_STACK), 657 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 658 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_MANAGED_PROVISIONING), 659 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 660 when(mScanRequestProxy.startScan(anyInt(), anyString())).thenReturn(true); 661 when(mLohsCallback.asBinder()).thenReturn(mock(IBinder.class)); 662 when(mWifiSettingsConfigStore.get(eq(WIFI_VERBOSE_LOGGING_ENABLED))).thenReturn(true); 663 when(mWifiSettingsConfigStore.get( 664 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API))) 665 .thenReturn(false); 666 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(false); 667 when(mActiveModeWarden.getClientModeManagersInRoles( 668 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED)) 669 .thenReturn(Collections.emptyList()); 670 when(mWifiPermissionsUtil.doesUidBelongToCurrentUserOrDeviceOwner(anyInt())) 671 .thenReturn(true); 672 // Defaulting apps to target SDK level that's prior to T. This is needed to test for 673 // backward compatibility of API changes. 674 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 675 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(true); 676 when(mWifiPermissionsUtil.isTargetSdkLessThan(any(), 677 eq(Build.VERSION_CODES.UPSIDE_DOWN_CAKE), 678 anyInt())).thenReturn(true); 679 if (SdkLevel.isAtLeastS()) { 680 // AttributionSource arg is only available from S. 681 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 682 .thenReturn(true); 683 } 684 when(mWifiInjector.getWifiCarrierInfoManager()).thenReturn(mWifiCarrierInfoManager); 685 when(mWifiInjector.getWifiPseudonymManager()).thenReturn(mWifiPseudonymManager); 686 when(mWifiInjector.getOpenNetworkNotifier()).thenReturn(mOpenNetworkNotifier); 687 when(mClientSoftApCallback.asBinder()).thenReturn(mAppBinder); 688 when(mAnotherSoftApCallback.asBinder()).thenReturn(mAnotherAppBinder); 689 when(mIOnWifiDriverCountryCodeChangedListener.asBinder()).thenReturn(mAppBinder); 690 when(mWifiInjector.getSarManager()).thenReturn(mSarManager); 691 mClientModeManagers = Arrays.asList(mClientModeManager, mock(ClientModeManager.class)); 692 when(mActiveModeWarden.getClientModeManagers()).thenReturn(mClientModeManagers); 693 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(new BitSet()); 694 when(mWifiInjector.getSelfRecovery()).thenReturn(mSelfRecovery); 695 when(mWifiInjector.getLastCallerInfoManager()).thenReturn(mLastCallerInfoManager); 696 when(mUserManager.getUserRestrictions()).thenReturn(mBundle); 697 when(mContext.getSystemService(DevicePolicyManager.class)).thenReturn(mDevicePolicyManager); 698 when(mWifiInjector.getHalDeviceManager()).thenReturn(mHalDeviceManager); 699 when(mWifiInjector.getWifiDialogManager()).thenReturn(mWifiDialogManager); 700 when(mWifiInjector.getSsidTranslator()).thenReturn(mSsidTranslator); 701 when(mWifiInjector.getInterfaceConflictManager()).thenReturn(mInterfaceConflictManager); 702 when(mWifiInjector.getWifiKeyStore()).thenReturn(mWifiKeyStore); 703 when(mWifiInjector.getScoringParams()).thenReturn(mScoringParams); 704 when(mWifiInjector.getApplicationQosPolicyRequestHandler()) 705 .thenReturn(mApplicationQosPolicyRequestHandler); 706 when(mWifiInjector.getWifiRoamingModeManager()).thenReturn(mWifiRoamingModeManager); 707 when(mLocationManager.getProviders(anyBoolean())).thenReturn(List.of( 708 LocationManager.FUSED_PROVIDER, LocationManager.PASSIVE_PROVIDER, 709 LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER)); 710 when(mWifiInjector.getWifiRoamingModeManager()).thenReturn(mWifiRoamingModeManager); 711 when(mWifiInjector.getTwtManager()).thenReturn(mTwtManager); 712 713 doAnswer(new AnswerWithArguments() { 714 public void answer(Runnable onStoppedListener) throws Throwable { 715 onStoppedListener.run(); 716 } 717 }).when(mMakeBeforeBreakManager).stopAllSecondaryTransientClientModeManagers(any()); 718 719 doAnswer(new AnswerWithArguments() { 720 public void answer(boolean isWepAllowed) { 721 when(mWifiGlobals.isWepAllowed()).thenReturn(isWepAllowed); 722 } 723 }).when(mWifiGlobals).setWepAllowed(anyBoolean()); 724 725 when(mWifiSettingsConfigStore.get(eq(WIFI_WEP_ALLOWED))).thenReturn(true); 726 mWifiServiceImpl = makeWifiServiceImpl(); 727 mDppCallback = new IDppCallback() { 728 @Override 729 public void onSuccessConfigReceived(int newNetworkId) throws RemoteException { 730 731 } 732 733 @Override 734 public void onSuccess(int status) throws RemoteException { 735 736 } 737 738 @Override 739 public void onFailure(int status, String ssid, String channelList, int[] bandList) 740 throws RemoteException { 741 742 } 743 744 @Override 745 public void onProgress(int status) throws RemoteException { 746 747 } 748 749 @Override 750 public void onBootstrapUriGenerated(String uri) throws RemoteException { 751 752 } 753 754 @Override 755 public IBinder asBinder() { 756 return null; 757 } 758 }; 759 760 // permission not granted by default 761 doThrow(SecurityException.class).when(mContext).enforceCallingOrSelfPermission( 762 eq(Manifest.permission.NETWORK_SETUP_WIZARD), any()); 763 mTestSoftApInfo = new SoftApInfo(); 764 mTestSoftApInfo.setFrequency(TEST_AP_FREQUENCY); 765 mTestSoftApInfo.setBandwidth(TEST_AP_BANDWIDTH); 766 mTestSoftApInfo.setApInstanceIdentifier(WIFI_IFACE_NAME); 767 when(mWifiNative.getChannelsForBand(anyInt())).thenReturn(new int[0]); 768 769 mTestSoftApInfoList = new ArrayList<>(); 770 mTestSoftApInfoList.add(mTestSoftApInfo); 771 772 mTestSoftApClients = new HashMap<>(); 773 mTestSoftApClients.put(WIFI_IFACE_NAME, new ArrayList<WifiClient>()); 774 mTestSoftApInfos = new HashMap<>(); 775 mTestSoftApInfos.put(WIFI_IFACE_NAME, mTestSoftApInfo); 776 777 mWifiConfig = new WifiConfiguration(); 778 mWifiConfig.SSID = TEST_SSID; 779 mWifiConfig.networkId = TEST_NETWORK_ID; 780 781 setup24GhzSupported(); 782 SoftApConfiguration lohsConfig = createValidSoftApConfiguration(); 783 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 784 eq(mContext), eq(null), any(), eq(false))).thenReturn(lohsConfig); 785 } 786 787 /** 788 * Called after each test 789 */ 790 @After cleanup()791 public void cleanup() { 792 validateMockitoUsage(); 793 if (mSession != null) { 794 mSession.finishMocking(); 795 } 796 } 797 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(TestLooper looper)798 private void stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(TestLooper looper) { 799 looper.dispatchAll(); 800 looper.stopAutoDispatchAndIgnoreExceptions(); 801 } 802 makeWifiServiceImpl()803 private WifiServiceImpl makeWifiServiceImpl() { 804 WifiServiceImpl wifiServiceImpl = 805 new WifiServiceImpl(mContext, mWifiInjector); 806 ArgumentCaptor<SoftApCallbackInternal> softApCallbackCaptor = 807 ArgumentCaptor.forClass(SoftApCallbackInternal.class); 808 verify(mActiveModeWarden, atLeastOnce()).registerSoftApCallback( 809 softApCallbackCaptor.capture()); 810 mStateMachineSoftApCallback = softApCallbackCaptor.getValue(); 811 ArgumentCaptor<SoftApCallbackInternal> lohsCallbackCaptor = 812 ArgumentCaptor.forClass(SoftApCallbackInternal.class); 813 mLohsInterfaceName = WIFI_IFACE_NAME; 814 verify(mActiveModeWarden, atLeastOnce()).registerLohsCallback( 815 lohsCallbackCaptor.capture()); 816 mLohsApCallback = lohsCallbackCaptor.getValue(); 817 mLooper.dispatchAll(); 818 return wifiServiceImpl; 819 } 820 makeWifiServiceImplWithMockRunnerWhichTimesOut()821 private WifiServiceImpl makeWifiServiceImplWithMockRunnerWhichTimesOut() { 822 WifiThreadRunner mockRunner = mock(WifiThreadRunner.class); 823 when(mockRunner.call(any(), any(), anyString())).then(returnsSecondArg()); 824 when(mockRunner.call(any(), any(int.class), anyString())).then(returnsSecondArg()); 825 when(mockRunner.call(any(), any(boolean.class), anyString())).then(returnsSecondArg()); 826 when(mockRunner.post(any(), anyString())).thenReturn(false); 827 828 when(mWifiInjector.getWifiThreadRunner()).thenReturn(mockRunner); 829 // Reset mWifiCountryCode to avoid verify failure in makeWifiServiceImpl. 830 reset(mWifiCountryCode); 831 return makeWifiServiceImpl(); 832 } 833 834 /** 835 * Test that REMOVE_NETWORK returns failure to public API when WifiConfigManager returns 836 * failure. 837 */ 838 @Test testRemoveNetworkFailureAppBelowQSdk()839 public void testRemoveNetworkFailureAppBelowQSdk() { 840 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 841 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME, 842 TEST_FEATURE_ID, null); 843 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 844 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 845 when(mWifiConfigManager.removeNetwork(anyInt(), anyInt(), anyString())).thenReturn(false); 846 847 mLooper.startAutoDispatch(); 848 boolean succeeded = mWifiServiceImpl.removeNetwork(0, TEST_PACKAGE_NAME); 849 mLooper.stopAutoDispatchAndIgnoreExceptions(); 850 assertFalse(succeeded); 851 } 852 853 /** 854 * Ensure WifiMetrics.dump() is the only dump called when 'dumpsys wifi WifiMetricsProto' is 855 * called. This is required to support simple metrics collection via dumpsys 856 */ 857 @Test testWifiMetricsDump()858 public void testWifiMetricsDump() { 859 mWifiServiceImpl.checkAndStartWifi(); 860 mLooper.dispatchAll(); 861 mLooper.startAutoDispatch(); 862 mWifiServiceImpl.dump(new FileDescriptor(), new PrintWriter(new StringWriter()), 863 new String[]{mWifiMetrics.PROTO_DUMP_ARG}); 864 mLooper.stopAutoDispatchAndIgnoreExceptions(); 865 verify(mWifiMetrics).setNonPersistentMacRandomizationForceEnabled(anyBoolean()); 866 verify(mWifiMetrics).setIsScanningAlwaysEnabled(anyBoolean()); 867 verify(mWifiMetrics).setVerboseLoggingEnabled(anyBoolean()); 868 verify(mWifiMetrics) 869 .dump(any(FileDescriptor.class), any(PrintWriter.class), any(String[].class)); 870 verify(mClientModeManager, never()) 871 .dump(any(FileDescriptor.class), any(PrintWriter.class), any(String[].class)); 872 } 873 874 /** 875 * Ensure WifiServiceImpl.dump() doesn't throw an NPE when executed with null args 876 */ 877 @Test testDumpNullArgs()878 public void testDumpNullArgs() { 879 mWifiServiceImpl.checkAndStartWifi(); 880 mLooper.dispatchAll(); 881 mLooper.startAutoDispatch(); 882 mWifiServiceImpl.dump(new FileDescriptor(), new PrintWriter(new StringWriter()), null); 883 mLooper.stopAutoDispatchAndIgnoreExceptions(); 884 verify(mWifiDiagnostics).captureBugReportData( 885 WifiDiagnostics.REPORT_REASON_USER_ACTION); 886 verify(mWifiDiagnostics).dump(any(), any(), any()); 887 verify(mPasspointNetworkNominateHelper).dump(any()); 888 verify(mResourceCache).dump(any()); 889 } 890 891 @Test testWifiShellCommandIgnoredBeforeBoot()892 public void testWifiShellCommandIgnoredBeforeBoot() { 893 // verify shell command can't be called before boot complete 894 ParcelFileDescriptor mockDescriptor = mock(ParcelFileDescriptor.class); 895 assertEquals(-1, mWifiServiceImpl.handleShellCommand(mockDescriptor, 896 mockDescriptor, mockDescriptor, new String[0])); 897 898 // verify shell command can now be called after boot complete 899 mWifiServiceImpl.handleBootCompleted(); 900 mLooper.dispatchAll(); 901 assertEquals(0, mWifiServiceImpl.handleShellCommand(mockDescriptor, 902 mockDescriptor, mockDescriptor, new String[0])); 903 } 904 905 /** 906 * Verify that metrics is incremented correctly for Privileged Apps. 907 */ 908 @Test testSetWifiEnabledMetricsPrivilegedApp()909 public void testSetWifiEnabledMetricsPrivilegedApp() throws Exception { 910 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 911 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 912 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 913 when(mSettingsStore.handleWifiToggled(anyBoolean())).thenReturn(true); 914 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 915 when(mWakeupController.isUsable()).thenReturn(false); 916 917 InOrder inorder = inOrder(mWifiMetrics); 918 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 919 mLooper.dispatchAll(); 920 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 921 mLooper.dispatchAll(); 922 verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(true, false); 923 inorder.verify(mWifiMetrics).logUserActionEvent(UserActionEvent.EVENT_TOGGLE_WIFI_ON); 924 inorder.verify(mWifiMetrics).incrementNumWifiToggles(eq(true), eq(true)); 925 inorder.verify(mWifiMetrics).reportWifiStateChanged(true, false, false); 926 inorder.verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_TOGGLE_WIFI_OFF), 927 anyInt()); 928 inorder.verify(mWifiMetrics).incrementNumWifiToggles(eq(true), eq(false)); 929 inorder.verify(mWifiMetrics).reportWifiStateChanged(false, false, false); 930 verify(mLastCallerInfoManager).put(eq(WifiManager.API_WIFI_ENABLED), anyInt(), 931 anyInt(), anyInt(), anyString(), eq(false)); 932 } 933 934 /** 935 * Verify that metrics is incremented correctly for normal Apps targeting pre-Q. 936 */ 937 @Test testSetWifiEnabledMetricsNormalAppBelowQSdk()938 public void testSetWifiEnabledMetricsNormalAppBelowQSdk() throws Exception { 939 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 940 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 941 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 942 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 943 when(mSettingsStore.handleWifiToggled(anyBoolean())).thenReturn(true); 944 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 945 when(mWakeupController.isUsable()).thenReturn(true); 946 947 InOrder inorder = inOrder(mWifiMetrics); 948 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 949 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 950 inorder.verify(mWifiMetrics).incrementNumWifiToggles(eq(false), eq(true)); 951 inorder.verify(mWifiMetrics).reportWifiStateChanged(true, true, false); 952 inorder.verify(mWifiMetrics).incrementNumWifiToggles(eq(false), eq(false)); 953 inorder.verify(mWifiMetrics).reportWifiStateChanged(false, true, false); 954 } 955 956 /** 957 * Verify that metrics is not incremented by apps targeting Q SDK. 958 */ 959 @Test testSetWifiEnabledMetricsNormalAppTargetingQSdkNoIncrement()960 public void testSetWifiEnabledMetricsNormalAppTargetingQSdkNoIncrement() throws Exception { 961 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 962 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 963 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 964 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false); 965 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 966 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 967 968 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 969 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 970 verify(mWifiMetrics, never()).incrementNumWifiToggles(anyBoolean(), anyBoolean()); 971 verify(mWifiMetrics, never()).reportWifiStateChanged(anyBoolean(), anyBoolean(), 972 anyBoolean()); 973 } 974 975 /** 976 * Verify that wifi can be enabled by a caller with NETWORK_SETTINGS permission. 977 */ 978 @Test testSetWifiEnabledSuccessWithNetworkSettingsPermission()979 public void testSetWifiEnabledSuccessWithNetworkSettingsPermission() throws Exception { 980 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 981 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 982 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 983 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 984 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 985 verify(mActiveModeWarden).wifiToggled( 986 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 987 } 988 989 /** 990 * Verify that wifi can be enabled by a caller with NETWORK_MANAGED_PROVISIONING permission. 991 */ 992 @Test testSetWifiEnabledSuccessWithNetworkManagedProvisioningPermission()993 public void testSetWifiEnabledSuccessWithNetworkManagedProvisioningPermission() 994 throws Exception { 995 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_MANAGED_PROVISIONING), 996 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 997 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 998 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 999 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1000 verify(mActiveModeWarden).wifiToggled( 1001 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1002 } 1003 1004 /** 1005 * Verify that wifi can be enabled by the DO apps targeting Q SDK. 1006 */ 1007 @Test testSetWifiEnabledSuccessForDOAppsTargetingQSdk()1008 public void testSetWifiEnabledSuccessForDOAppsTargetingQSdk() throws Exception { 1009 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1010 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1011 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1012 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false); 1013 when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 1014 .thenReturn(true); 1015 1016 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1017 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1018 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1019 1020 verify(mActiveModeWarden).wifiToggled( 1021 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1022 } 1023 1024 /** 1025 * Verify that wifi can be enabled by the system apps targeting Q SDK. 1026 */ 1027 @Test testSetWifiEnabledSuccessForSystemAppsTargetingQSdk()1028 public void testSetWifiEnabledSuccessForSystemAppsTargetingQSdk() throws Exception { 1029 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1030 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1031 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1032 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false); 1033 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 1034 1035 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1036 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1037 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1038 1039 verify(mActiveModeWarden).wifiToggled( 1040 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1041 } 1042 1043 /** 1044 * Verify that wifi can be enabled by the apps targeting pre-Q SDK. 1045 */ 1046 @Test testSetWifiEnabledSuccessForAppsTargetingBelowQSdk()1047 public void testSetWifiEnabledSuccessForAppsTargetingBelowQSdk() throws Exception { 1048 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1049 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1050 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1051 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1052 1053 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1054 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1055 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1056 1057 verify(mActiveModeWarden).wifiToggled( 1058 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1059 } 1060 1061 /** 1062 * Verify that wifi cannot be enabled by the apps targeting Q SDK. 1063 */ 1064 @Test testSetWifiEnabledFailureForAppsTargetingQSdk()1065 public void testSetWifiEnabledFailureForAppsTargetingQSdk() throws Exception { 1066 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1067 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1068 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1069 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false); 1070 1071 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1072 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1073 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1074 1075 verify(mActiveModeWarden, never()).wifiToggled(any()); 1076 } 1077 1078 /** 1079 * Verify a SecurityException is thrown if OPSTR_CHANGE_WIFI_STATE is disabled for the app. 1080 */ 1081 @Test testSetWifiEnableAppOpsRejected()1082 public void testSetWifiEnableAppOpsRejected() throws Exception { 1083 doThrow(new SecurityException()).when(mAppOpsManager) 1084 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1085 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1086 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1087 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1088 try { 1089 mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true); 1090 fail(); 1091 } catch (SecurityException e) { 1092 1093 } 1094 verify(mActiveModeWarden, never()).wifiToggled(any()); 1095 } 1096 1097 /** 1098 * Verify a SecurityException is thrown if OP_CHANGE_WIFI_STATE is set to MODE_IGNORED 1099 * for the app. 1100 */ 1101 @Test // No exception expected, but the operation should not be done testSetWifiEnableAppOpsIgnored()1102 public void testSetWifiEnableAppOpsIgnored() throws Exception { 1103 doReturn(AppOpsManager.MODE_IGNORED).when(mAppOpsManager) 1104 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1105 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1106 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1107 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1108 1109 mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true); 1110 verify(mActiveModeWarden, never()).wifiToggled(any()); 1111 } 1112 1113 /** 1114 * Verify that a call from an app with the NETWORK_SETTINGS permission can enable wifi if we 1115 * are in airplane mode. 1116 */ 1117 @Test testSetWifiEnabledFromNetworkSettingsHolderWhenInAirplaneMode()1118 public void testSetWifiEnabledFromNetworkSettingsHolderWhenInAirplaneMode() throws Exception { 1119 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1120 when(mSettingsStore.isAirplaneModeOn()).thenReturn(true); 1121 when(mContext.checkPermission( 1122 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt())) 1123 .thenReturn(PackageManager.PERMISSION_GRANTED); 1124 1125 assertTrue(mWifiServiceImpl.setWifiEnabled(SYSUI_PACKAGE_NAME, true)); 1126 verify(mActiveModeWarden).wifiToggled( 1127 eq(new WorkSource(Binder.getCallingUid(), SYSUI_PACKAGE_NAME))); 1128 } 1129 1130 /** 1131 * Verify that a caller without the NETWORK_SETTINGS permission can't enable wifi 1132 * if we are in airplane mode. 1133 */ 1134 @Test testSetWifiEnabledFromAppFailsWhenInAirplaneMode()1135 public void testSetWifiEnabledFromAppFailsWhenInAirplaneMode() throws Exception { 1136 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1137 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1138 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1139 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1140 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1141 when(mSettingsStore.isAirplaneModeOn()).thenReturn(true); 1142 when(mContext.checkPermission( 1143 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt())) 1144 .thenReturn(PackageManager.PERMISSION_DENIED); 1145 1146 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1147 verify(mActiveModeWarden, never()).wifiToggled(any()); 1148 } 1149 1150 /** 1151 * Verify that a user (NETWORK_SETTINGS) cannot enable wifi if DISALLOW_CHANGE_WIFI_STATE 1152 * user restriction is set. 1153 */ 1154 @Test testSetWifiEnabledFromUserFailsWhenUserRestrictionSet()1155 public void testSetWifiEnabledFromUserFailsWhenUserRestrictionSet() throws Exception { 1156 assumeTrue(SdkLevel.isAtLeastT()); 1157 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 1158 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 1159 1160 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1161 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1162 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CHANGE_WIFI_STATE), 1163 any())).thenReturn(true); 1164 1165 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1166 verify(mActiveModeWarden, never()).wifiToggled(any()); 1167 } 1168 1169 /** 1170 * Verify that apps targeting pre-Q SDK cannot enable wifi if DISALLOW_CHANGE_WIFI_STATE 1171 * user restriction is set. 1172 */ 1173 @Test testSetWifiEnabledFromAppTargetingBelowQSdkFailsWhenUserRestrictionSet()1174 public void testSetWifiEnabledFromAppTargetingBelowQSdkFailsWhenUserRestrictionSet() 1175 throws Exception { 1176 assumeTrue(SdkLevel.isAtLeastT()); 1177 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1178 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1179 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1180 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1181 1182 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1183 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1184 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CHANGE_WIFI_STATE), 1185 any())).thenReturn(true); 1186 1187 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1188 verify(mActiveModeWarden, never()).wifiToggled(any()); 1189 } 1190 1191 /** 1192 * Verify that wifi can be enabled by the DO apps even when DISALLOW_CHANGE_WIFI_STATE 1193 * user restriction is set. 1194 */ 1195 @Test testSetWifiEnabledSuccessForDOAppsWhenUserRestrictionSet()1196 public void testSetWifiEnabledSuccessForDOAppsWhenUserRestrictionSet() throws Exception { 1197 assumeTrue(SdkLevel.isAtLeastT()); 1198 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1199 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1200 when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 1201 .thenReturn(true); 1202 1203 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1204 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1205 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CHANGE_WIFI_STATE), 1206 any())).thenReturn(true); 1207 1208 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1209 verify(mActiveModeWarden).wifiToggled( 1210 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1211 } 1212 1213 /** 1214 * Verify that a dialog is shown for third-party apps targeting pre-Q SDK enabling Wi-Fi. 1215 */ 1216 @Test testSetWifiEnabledDialogForThirdPartyAppsTargetingBelowQSdk()1217 public void testSetWifiEnabledDialogForThirdPartyAppsTargetingBelowQSdk() throws Exception { 1218 when(mResourceCache.getBoolean( 1219 R.bool.config_showConfirmationDialogForThirdPartyAppsEnablingWifi)) 1220 .thenReturn(true); 1221 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1222 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1223 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1224 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1225 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1226 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1227 ApplicationInfo applicationInfo = mock(ApplicationInfo.class); 1228 when(mPackageManager.getApplicationInfo(any(), anyInt())).thenReturn(applicationInfo); 1229 String appName = "appName"; 1230 when(applicationInfo.loadLabel(any())).thenReturn(appName); 1231 String title = "appName wants to enable Wi-Fi."; 1232 String message = "Enable Wi-Fi?"; 1233 String positiveButtonText = "Yes"; 1234 String negativeButtonText = "No"; 1235 when(mResources.getString(R.string.wifi_enable_request_dialog_title, appName)) 1236 .thenReturn(title); 1237 when(mResources.getString(R.string.wifi_enable_request_dialog_message)).thenReturn(message); 1238 when(mResources.getString(R.string.wifi_enable_request_dialog_positive_button)) 1239 .thenReturn(positiveButtonText); 1240 when(mResources.getString(R.string.wifi_enable_request_dialog_negative_button)) 1241 .thenReturn(negativeButtonText); 1242 1243 // Launch dialog 1244 WifiDialogManager.DialogHandle dialogHandle = mock(WifiDialogManager.DialogHandle.class); 1245 when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any())) 1246 .thenReturn(dialogHandle); 1247 ArgumentCaptor<WifiDialogManager.SimpleDialogCallback> callbackCaptor = 1248 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class); 1249 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1250 verify(mActiveModeWarden, times(0)).wifiToggled( 1251 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1252 mLooper.dispatchAll(); 1253 verify(mWifiDialogManager, times(1)).createSimpleDialog( 1254 eq(title), 1255 eq(message), 1256 eq(positiveButtonText), 1257 eq(negativeButtonText), 1258 eq(null), 1259 callbackCaptor.capture(), 1260 any()); 1261 verify(dialogHandle).launchDialog(); 1262 1263 // Verify extra call to setWifiEnabled won't launch a new dialog 1264 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1265 verify(mActiveModeWarden, times(0)).wifiToggled( 1266 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1267 mLooper.dispatchAll(); 1268 verify(mWifiDialogManager, times(1)).createSimpleDialog( 1269 eq(title), 1270 eq(message), 1271 eq(positiveButtonText), 1272 eq(negativeButtonText), 1273 eq(null), 1274 callbackCaptor.capture(), 1275 any()); 1276 1277 // Verify the negative reply does not enable wifi 1278 callbackCaptor.getValue().onNegativeButtonClicked(); 1279 verify(mActiveModeWarden, times(0)).wifiToggled( 1280 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1281 1282 // Verify the cancel reply does not enable wifi. 1283 dialogHandle = mock(WifiDialogManager.DialogHandle.class); 1284 when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any())) 1285 .thenReturn(dialogHandle); 1286 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1287 mLooper.dispatchAll(); 1288 verify(mActiveModeWarden, times(0)).wifiToggled( 1289 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1290 callbackCaptor = 1291 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class); 1292 verify(mWifiDialogManager, times(2)).createSimpleDialog( 1293 eq(title), 1294 eq(message), 1295 eq(positiveButtonText), 1296 eq(negativeButtonText), 1297 eq(null), 1298 callbackCaptor.capture(), 1299 any()); 1300 verify(dialogHandle).launchDialog(); 1301 callbackCaptor.getValue().onCancelled(); 1302 verify(mActiveModeWarden, times(0)).wifiToggled( 1303 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1304 1305 // Verify the positive reply will enable wifi. 1306 dialogHandle = mock(WifiDialogManager.DialogHandle.class); 1307 when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any())) 1308 .thenReturn(dialogHandle); 1309 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1310 mLooper.dispatchAll(); 1311 verify(mActiveModeWarden, times(0)).wifiToggled( 1312 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1313 callbackCaptor = 1314 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class); 1315 verify(mWifiDialogManager, times(3)).createSimpleDialog( 1316 eq(title), 1317 eq(message), 1318 eq(positiveButtonText), 1319 eq(negativeButtonText), 1320 eq(null), 1321 callbackCaptor.capture(), 1322 any()); 1323 verify(dialogHandle).launchDialog(); 1324 callbackCaptor.getValue().onPositiveButtonClicked(); 1325 verify(mActiveModeWarden, times(1)).wifiToggled( 1326 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1327 1328 // Verify disabling wifi works without dialog. 1329 when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true); 1330 dialogHandle = mock(WifiDialogManager.DialogHandle.class); 1331 when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any())) 1332 .thenReturn(dialogHandle); 1333 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 1334 mLooper.dispatchAll(); 1335 verify(mActiveModeWarden, times(2)).wifiToggled( 1336 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1337 verify(dialogHandle, never()).launchDialog(); 1338 1339 // Verify wifi becoming enabled will dismiss any outstanding dialogs. 1340 dialogHandle = mock(WifiDialogManager.DialogHandle.class); 1341 when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any())) 1342 .thenReturn(dialogHandle); 1343 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1344 mLooper.dispatchAll(); 1345 verify(mActiveModeWarden, times(2)).wifiToggled( 1346 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1347 callbackCaptor = 1348 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class); 1349 verify(mWifiDialogManager, times(4)).createSimpleDialog( 1350 eq(title), 1351 eq(message), 1352 eq(positiveButtonText), 1353 eq(negativeButtonText), 1354 eq(null), 1355 callbackCaptor.capture(), 1356 any()); 1357 verify(dialogHandle).launchDialog(); 1358 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 1359 // Enabled by privileged app 1360 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1361 mLooper.dispatchAll(); 1362 verify(mActiveModeWarden, times(3)).wifiToggled( 1363 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1364 verify(dialogHandle).dismissDialog(); 1365 1366 // Verify wifi already enabled will not trigger dialog. 1367 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(false); 1368 dialogHandle = mock(WifiDialogManager.DialogHandle.class); 1369 when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any())) 1370 .thenReturn(dialogHandle); 1371 when(mActiveModeWarden.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); 1372 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1373 mLooper.dispatchAll(); 1374 verify(mActiveModeWarden, times(3)).wifiToggled( 1375 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1376 verify(dialogHandle, never()).launchDialog(); 1377 } 1378 1379 /** 1380 * Verify that no dialog is shown for non-third-party apps targeting pre-Q SDK enabling Wi-Fi. 1381 */ 1382 @Test testSetWifiEnabledNoDialogForNonThirdPartyAppsTargetingBelowQSdk()1383 public void testSetWifiEnabledNoDialogForNonThirdPartyAppsTargetingBelowQSdk() { 1384 when(mResourceCache.getBoolean( 1385 R.bool.config_showConfirmationDialogForThirdPartyAppsEnablingWifi)) 1386 .thenReturn(true); 1387 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1388 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1389 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1390 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1391 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1392 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1393 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 1394 1395 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1396 verify(mActiveModeWarden).wifiToggled( 1397 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1398 } 1399 1400 /** 1401 * Helper to verify registering for state changes. 1402 */ verifyApRegistration()1403 private void verifyApRegistration() { 1404 assertNotNull(mLohsApCallback); 1405 } 1406 1407 /** 1408 * Helper to emulate local-only hotspot state changes. 1409 * 1410 * Must call verifyApRegistration first. 1411 */ changeLohsState(int apState, int previousState, int error)1412 private void changeLohsState(int apState, int previousState, int error) { 1413 // TestUtil.sendWifiApStateChanged(mBroadcastReceiverCaptor.getValue(), mContext, 1414 // apState, previousState, error, WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY); 1415 mLohsApCallback.onStateChanged(new SoftApState(apState, error, 1416 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 1417 } 1418 1419 /** 1420 * Verify that a call from an app with the NETWORK_SETTINGS permission can enable wifi if we 1421 * are in softap mode. 1422 */ 1423 @Test testSetWifiEnabledFromNetworkSettingsHolderWhenApEnabled()1424 public void testSetWifiEnabledFromNetworkSettingsHolderWhenApEnabled() throws Exception { 1425 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 1426 mWifiServiceImpl.checkAndStartWifi(); 1427 mLooper.dispatchAll(); 1428 1429 verifyApRegistration(); 1430 mStateMachineSoftApCallback.onStateChanged( 1431 new SoftApState(WIFI_AP_STATE_ENABLED, 0, 1432 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 1433 1434 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1435 when(mContext.checkPermission( 1436 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt())) 1437 .thenReturn(PackageManager.PERMISSION_GRANTED); 1438 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1439 assertTrue(mWifiServiceImpl.setWifiEnabled(SYSUI_PACKAGE_NAME, true)); 1440 verify(mActiveModeWarden).wifiToggled( 1441 eq(new WorkSource(Binder.getCallingUid(), SYSUI_PACKAGE_NAME))); 1442 } 1443 1444 /** 1445 * Verify that a call from an app cannot enable wifi if we are in softap mode for Pre-S 1446 */ 1447 @Test testSetWifiEnabledFromAppFailsWhenApEnabledForPreS()1448 public void testSetWifiEnabledFromAppFailsWhenApEnabledForPreS() throws Exception { 1449 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1450 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1451 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1452 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1453 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 1454 mWifiServiceImpl.checkAndStartWifi(); 1455 mLooper.dispatchAll(); 1456 1457 verifyApRegistration(); 1458 mStateMachineSoftApCallback.onStateChanged( 1459 new SoftApState(WIFI_AP_STATE_ENABLED, 0, 1460 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 1461 1462 when(mContext.checkPermission( 1463 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt())) 1464 .thenReturn(PackageManager.PERMISSION_DENIED); 1465 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1466 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true); 1467 if (!SdkLevel.isAtLeastS()) { 1468 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1469 verify(mSettingsStore, never()).handleWifiToggled(anyBoolean()); 1470 verify(mActiveModeWarden, never()).wifiToggled(any()); 1471 } else { 1472 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1473 verify(mActiveModeWarden).wifiToggled( 1474 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1475 } 1476 } 1477 1478 1479 /** 1480 * Verify that the CMD_TOGGLE_WIFI message won't be sent if wifi is already on. 1481 */ 1482 @Test testSetWifiEnabledNoToggle()1483 public void testSetWifiEnabledNoToggle() throws Exception { 1484 when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(false); 1485 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 1486 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 1487 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 1488 verify(mActiveModeWarden, never()).wifiToggled(any()); 1489 } 1490 1491 /** 1492 * Verify a SecurityException is thrown if a caller does not have the CHANGE_WIFI_STATE 1493 * permission to toggle wifi. 1494 */ 1495 @Test testSetWifiEnableWithoutChangeWifiStatePermission()1496 public void testSetWifiEnableWithoutChangeWifiStatePermission() throws Exception { 1497 doThrow(new SecurityException()).when(mContext) 1498 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.CHANGE_WIFI_STATE), 1499 eq("WifiService")); 1500 try { 1501 mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true); 1502 fail(); 1503 } catch (SecurityException e) { 1504 } 1505 } 1506 1507 /** 1508 * Verify that wifi can be disabled by a caller with NETWORK_SETTINGS permission. 1509 */ 1510 @Test testSetWifiDisabledSuccessWithNetworkSettingsPermission()1511 public void testSetWifiDisabledSuccessWithNetworkSettingsPermission() throws Exception { 1512 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 1513 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 1514 when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true); 1515 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 1516 verify(mActiveModeWarden).wifiToggled( 1517 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1518 verify(mInterfaceConflictManager).reset(); 1519 } 1520 1521 /** 1522 * Verify that wifi can be disabled by a caller with NETWORK_MANAGED_PROVISIONING permission. 1523 */ 1524 @Test testSetWifiDisabledSuccessWithNetworkManagedProvisioningPermission()1525 public void testSetWifiDisabledSuccessWithNetworkManagedProvisioningPermission() 1526 throws Exception { 1527 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_MANAGED_PROVISIONING), 1528 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 1529 when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true); 1530 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 1531 verify(mActiveModeWarden).wifiToggled( 1532 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1533 verify(mInterfaceConflictManager).reset(); 1534 } 1535 1536 /** 1537 * Verify that wifi can be disabled by the PO apps targeting Q SDK. 1538 */ 1539 @Test testSetWifiDisabledSuccessForPOAppsTargetingQSdk()1540 public void testSetWifiDisabledSuccessForPOAppsTargetingQSdk() throws Exception { 1541 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1542 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1543 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1544 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false); 1545 when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 1546 .thenReturn(true); 1547 1548 when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true); 1549 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1550 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 1551 1552 verify(mActiveModeWarden).wifiToggled( 1553 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1554 verify(mInterfaceConflictManager).reset(); 1555 } 1556 1557 /** 1558 * Verify that wifi can be disabled by the system apps targeting Q SDK. 1559 */ 1560 @Test testSetWifiDisabledSuccessForSystemAppsTargetingQSdk()1561 public void testSetWifiDisabledSuccessForSystemAppsTargetingQSdk() throws Exception { 1562 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1563 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1564 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1565 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false); 1566 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 1567 1568 when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true); 1569 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1570 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 1571 1572 verify(mActiveModeWarden).wifiToggled( 1573 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1574 verify(mInterfaceConflictManager).reset(); 1575 } 1576 1577 1578 /** 1579 * Verify that wifi can be disabled by the apps targeting pre-Q SDK. 1580 */ 1581 @Test testSetWifiDisabledSuccessForAppsTargetingBelowQSdk()1582 public void testSetWifiDisabledSuccessForAppsTargetingBelowQSdk() throws Exception { 1583 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1584 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1585 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1586 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 1587 1588 when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true); 1589 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1590 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 1591 1592 verify(mActiveModeWarden).wifiToggled( 1593 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 1594 verify(mInterfaceConflictManager).reset(); 1595 } 1596 1597 /** 1598 * Verify that wifi cannot be disabled by the apps targeting Q SDK. 1599 */ 1600 @Test testSetWifiDisabledFailureForAppsTargetingQSdk()1601 public void testSetWifiDisabledFailureForAppsTargetingQSdk() throws Exception { 1602 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 1603 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 1604 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 1605 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false); 1606 1607 when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true); 1608 when(mSettingsStore.isAirplaneModeOn()).thenReturn(false); 1609 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 1610 1611 verify(mActiveModeWarden, never()).wifiToggled(any()); 1612 verify(mInterfaceConflictManager, never()).reset(); 1613 } 1614 1615 /** 1616 * Verify that CMD_TOGGLE_WIFI message won't be sent if wifi is already off. 1617 */ 1618 @Test testSetWifiDisabledNoToggle()1619 public void testSetWifiDisabledNoToggle() throws Exception { 1620 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 1621 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 1622 when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(false); 1623 assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false)); 1624 verify(mActiveModeWarden, never()).wifiToggled(any()); 1625 verify(mInterfaceConflictManager, never()).reset(); 1626 } 1627 1628 /** 1629 * Verify a SecurityException is thrown if a caller does not have the CHANGE_WIFI_STATE 1630 * permission to toggle wifi. 1631 */ 1632 @Test testSetWifiDisabledWithoutChangeWifiStatePermission()1633 public void testSetWifiDisabledWithoutChangeWifiStatePermission() throws Exception { 1634 doThrow(new SecurityException()).when(mContext) 1635 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.CHANGE_WIFI_STATE), 1636 eq("WifiService")); 1637 try { 1638 mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false); 1639 fail(); 1640 } catch (SecurityException e) { } 1641 } 1642 1643 /** 1644 * Verify that the restartWifiSubsystem fails w/o the NETWORK_AIRPLANE_MODE permission. 1645 */ testRestartWifiSubsystemWithoutPermission()1646 @Test public void testRestartWifiSubsystemWithoutPermission() { 1647 assumeTrue(SdkLevel.isAtLeastS()); 1648 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 1649 eq(android.Manifest.permission.RESTART_WIFI_SUBSYSTEM), eq("WifiService")); 1650 1651 try { 1652 mWifiServiceImpl.restartWifiSubsystem(); 1653 fail("restartWifiSubsystem should fail w/o the APM permission!"); 1654 } catch (SecurityException e) { 1655 // empty clause 1656 } 1657 } 1658 1659 /** 1660 * Verify that a call to registerSubsystemRestartCallback throws a SecurityException if the 1661 * caller does not have the ACCESS_WIFI_STATE permission. 1662 */ 1663 @Test testRegisterSubsystemRestartThrowsSecurityExceptionOnMissingPermissions()1664 public void testRegisterSubsystemRestartThrowsSecurityExceptionOnMissingPermissions() { 1665 assumeTrue(SdkLevel.isAtLeastS()); 1666 assertThrows(IllegalArgumentException.class, 1667 () -> mWifiServiceImpl.registerSubsystemRestartCallback(null)); 1668 1669 doThrow(new SecurityException()).when(mContext) 1670 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), 1671 eq("WifiService")); 1672 assertThrows(SecurityException.class, 1673 () -> mWifiServiceImpl.registerSubsystemRestartCallback(mSubsystemRestartCallback)); 1674 } 1675 1676 /** 1677 * Verify that a call to unregisterSubsystemRestartCallback throws a SecurityException if the 1678 * caller does not have the ACCESS_WIFI_STATE permission. 1679 */ 1680 @Test testUnregisterSubsystemRestartThrowsSecurityExceptionOnMissingPermissions()1681 public void testUnregisterSubsystemRestartThrowsSecurityExceptionOnMissingPermissions() { 1682 assumeTrue(SdkLevel.isAtLeastS()); 1683 assertThrows(IllegalArgumentException.class, 1684 () -> mWifiServiceImpl.unregisterSubsystemRestartCallback(null)); 1685 1686 doThrow(new SecurityException()).when(mContext) 1687 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), 1688 eq("WifiService")); 1689 assertThrows(SecurityException.class, 1690 () -> mWifiServiceImpl.unregisterSubsystemRestartCallback( 1691 mSubsystemRestartCallback)); 1692 } 1693 1694 1695 /** 1696 * Test register and unregister subsystem restart callback will go to ActiveModeManager; 1697 */ 1698 @Test testRegisterUnregisterSubsystemRestartCallback()1699 public void testRegisterUnregisterSubsystemRestartCallback() throws Exception { 1700 assumeTrue(SdkLevel.isAtLeastS()); 1701 when(mCoexCallback.asBinder()).thenReturn(mAppBinder); 1702 mWifiServiceImpl.registerSubsystemRestartCallback(mSubsystemRestartCallback); 1703 mLooper.dispatchAll(); 1704 verify(mActiveModeWarden).registerSubsystemRestartCallback(mSubsystemRestartCallback); 1705 mWifiServiceImpl.unregisterSubsystemRestartCallback(mSubsystemRestartCallback); 1706 mLooper.dispatchAll(); 1707 verify(mActiveModeWarden).unregisterSubsystemRestartCallback(mSubsystemRestartCallback); 1708 } 1709 1710 @Test testAddWifiNetworkStateChangedListener()1711 public void testAddWifiNetworkStateChangedListener() throws Exception { 1712 IWifiNetworkStateChangedListener testListener = 1713 mock(IWifiNetworkStateChangedListener.class); 1714 1715 // Test success case 1716 mWifiServiceImpl.addWifiNetworkStateChangedListener(testListener); 1717 mLooper.dispatchAll(); 1718 verify(mActiveModeWarden).addWifiNetworkStateChangedListener(testListener); 1719 1720 // Expect exception for null listener 1721 assertThrows(IllegalArgumentException.class, 1722 () -> mWifiServiceImpl.addWifiNetworkStateChangedListener(null)); 1723 1724 // Expect exception when caller has no permission 1725 doThrow(new SecurityException()).when(mContext) 1726 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 1727 eq("WifiService")); 1728 assertThrows(SecurityException.class, 1729 () -> mWifiServiceImpl.addWifiNetworkStateChangedListener(testListener)); 1730 verify(mActiveModeWarden).addWifiNetworkStateChangedListener(testListener); 1731 } 1732 1733 private class GetBssidBlocklistMatcher implements 1734 ArgumentMatcher<ParceledListSlice<MacAddress>> { 1735 private boolean mDoMatching; GetBssidBlocklistMatcher(boolean doMatching)1736 GetBssidBlocklistMatcher(boolean doMatching) { 1737 // false to match empty 1738 // true to match some BSSID 1739 mDoMatching = doMatching; 1740 } 1741 @Override matches(ParceledListSlice<MacAddress> macAddresses)1742 public boolean matches(ParceledListSlice<MacAddress> macAddresses) { 1743 if (mDoMatching) { 1744 return macAddresses.getList().size() == 1 1745 && macAddresses.getList().get(0).toString().equals(TEST_BSSID); 1746 } 1747 return macAddresses.getList().isEmpty(); 1748 } 1749 } 1750 1751 @Test testGetBssidBlocklist()1752 public void testGetBssidBlocklist() throws Exception { 1753 IMacAddressListListener listener = mock(IMacAddressListListener.class); 1754 // verify null arguments throw exception 1755 assertThrows(IllegalArgumentException.class, 1756 () -> mWifiServiceImpl.getBssidBlocklist(null, listener)); 1757 assertThrows(IllegalArgumentException.class, 1758 () -> mWifiServiceImpl.getBssidBlocklist( 1759 new ParceledListSlice(Collections.EMPTY_LIST), null)); 1760 1761 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 1762 when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false); 1763 assertThrows(SecurityException.class, 1764 () -> mWifiServiceImpl.getBssidBlocklist( 1765 new ParceledListSlice(Collections.EMPTY_LIST), listener)); 1766 1767 // Verify calling with empty SSIDs with network settings permission 1768 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 1769 mWifiServiceImpl.getBssidBlocklist(new ParceledListSlice(Collections.EMPTY_LIST), listener); 1770 mLooper.dispatchAll(); 1771 verify(mWifiBlocklistMonitor).getBssidBlocklistForSsids(null); 1772 verify(listener).onResult(argThat(new GetBssidBlocklistMatcher(false))); 1773 1774 // Verify calling with non-null SSIDs with SUW permission, and verify dup SSID gets removed 1775 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 1776 when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(true); 1777 when(mWifiBlocklistMonitor.getBssidBlocklistForSsids(any())).thenReturn( 1778 Arrays.asList(new String[] {TEST_BSSID})); 1779 ParceledListSlice<MacAddress> expectedResult = new ParceledListSlice<>(Arrays.asList( 1780 new MacAddress[] {MacAddress.fromString(TEST_BSSID)})); 1781 WifiSsid ssid = WifiSsid.fromString(TEST_SSID_WITH_QUOTES); 1782 List<WifiSsid> ssidListWithDup = new ArrayList<>(); 1783 ssidListWithDup.add(ssid); 1784 ssidListWithDup.add(ssid); 1785 ParceledListSlice<WifiSsid> ssidsParceledListWithDup = 1786 new ParceledListSlice<>(ssidListWithDup); 1787 Set<String> ssidSet = new ArraySet<>(Arrays.asList(new String[]{TEST_SSID_WITH_QUOTES})); 1788 mWifiServiceImpl.getBssidBlocklist(ssidsParceledListWithDup, listener); 1789 mLooper.dispatchAll(); 1790 verify(mWifiBlocklistMonitor).getBssidBlocklistForSsids(ssidSet); 1791 verify(listener).onResult(argThat(new GetBssidBlocklistMatcher(true))); 1792 } 1793 1794 /** 1795 * Verify that the restartWifiSubsystem succeeds and passes correct parameters. 1796 */ 1797 @Test testRestartWifiSubsystem()1798 public void testRestartWifiSubsystem() { 1799 assumeTrue(SdkLevel.isAtLeastS()); 1800 when(mContext.checkPermission(eq(android.Manifest.permission.RESTART_WIFI_SUBSYSTEM), 1801 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 1802 1803 mWifiServiceImpl.restartWifiSubsystem(); 1804 mLooper.dispatchAll(); 1805 verify(mSelfRecovery).trigger(eq(REASON_API_CALL)); 1806 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_RESTART_WIFI_SUB_SYSTEM), 1807 anyInt()); 1808 } 1809 1810 /** 1811 * Ensure unpermitted callers cannot write the SoftApConfiguration. 1812 */ 1813 @Test testSetWifiApConfigurationNotSavedWithoutPermission()1814 public void testSetWifiApConfigurationNotSavedWithoutPermission() throws Exception { 1815 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false); 1816 WifiConfiguration apConfig = new WifiConfiguration(); 1817 try { 1818 mWifiServiceImpl.setWifiApConfiguration(apConfig, TEST_PACKAGE_NAME); 1819 fail("Expected SecurityException"); 1820 } catch (SecurityException e) { } 1821 } 1822 1823 /** 1824 * Ensure softap config is written when the caller has the correct permission. 1825 */ 1826 @Test testSetWifiApConfigurationSuccess()1827 public void testSetWifiApConfigurationSuccess() throws Exception { 1828 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1829 WifiConfiguration wifiApConfig = createValidWifiApConfiguration(); 1830 1831 assertTrue(mWifiServiceImpl.setWifiApConfiguration(wifiApConfig, TEST_PACKAGE_NAME)); 1832 mLooper.dispatchAll(); 1833 verifyCheckChangePermission(TEST_PACKAGE_NAME); 1834 verify(mWifiApConfigStore).setApConfiguration(eq( 1835 ApConfigUtil.fromWifiConfiguration(wifiApConfig))); 1836 } 1837 1838 /** 1839 * Ensure that a null config does not overwrite the saved ap config. 1840 */ 1841 @Test testSetWifiApConfigurationNullConfigNotSaved()1842 public void testSetWifiApConfigurationNullConfigNotSaved() throws Exception { 1843 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1844 assertFalse(mWifiServiceImpl.setWifiApConfiguration(null, TEST_PACKAGE_NAME)); 1845 verify(mWifiApConfigStore, never()).setApConfiguration(isNull()); 1846 } 1847 1848 /** 1849 * Ensure that an invalid config does not overwrite the saved ap config. 1850 */ 1851 @Test testSetWifiApConfigurationWithInvalidConfigNotSaved()1852 public void testSetWifiApConfigurationWithInvalidConfigNotSaved() throws Exception { 1853 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1854 assertFalse(mWifiServiceImpl.setWifiApConfiguration(new WifiConfiguration(), 1855 TEST_PACKAGE_NAME)); 1856 verify(mWifiApConfigStore, never()).setApConfiguration(any()); 1857 } 1858 1859 /** 1860 * Ensure unpermitted callers cannot write the SoftApConfiguration. 1861 */ 1862 @Test testSetSoftApConfigurationNotSavedWithoutPermission()1863 public void testSetSoftApConfigurationNotSavedWithoutPermission() throws Exception { 1864 SoftApConfiguration apConfig = createValidSoftApConfiguration(); 1865 try { 1866 mWifiServiceImpl.setSoftApConfiguration(apConfig, TEST_PACKAGE_NAME); 1867 fail("Expected SecurityException"); 1868 } catch (SecurityException e) { } 1869 } 1870 1871 /** 1872 * Ensure softap config is written when the caller has the correct permission. 1873 */ 1874 @Test testSetSoftApConfigurationSuccessWithSettingPermission()1875 public void testSetSoftApConfigurationSuccessWithSettingPermission() throws Exception { 1876 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 1877 SoftApConfiguration apConfig = createValidSoftApConfiguration(); 1878 1879 assertTrue(mWifiServiceImpl.setSoftApConfiguration(apConfig, TEST_PACKAGE_NAME)); 1880 verify(mWifiApConfigStore).setApConfiguration(eq(apConfig)); 1881 verify(mActiveModeWarden).updateSoftApConfiguration(apConfig); 1882 verify(mWifiPermissionsUtil).checkNetworkSettingsPermission(anyInt()); 1883 } 1884 1885 /** 1886 * Ensure softap config is written when the caller has the correct permission. 1887 */ 1888 @Test testSetSoftApConfigurationSuccessWithOverridePermission()1889 public void testSetSoftApConfigurationSuccessWithOverridePermission() throws Exception { 1890 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1891 SoftApConfiguration apConfig = createValidSoftApConfiguration(); 1892 1893 assertTrue(mWifiServiceImpl.setSoftApConfiguration(apConfig, TEST_PACKAGE_NAME)); 1894 verify(mWifiApConfigStore).setApConfiguration(eq(apConfig)); 1895 verify(mActiveModeWarden).updateSoftApConfiguration(apConfig); 1896 verify(mWifiPermissionsUtil).checkConfigOverridePermission(anyInt()); 1897 } 1898 1899 /** 1900 * Ensure that a null config does not overwrite the saved ap config. 1901 */ 1902 @Test testSetSoftApConfigurationNullConfigNotSaved()1903 public void testSetSoftApConfigurationNullConfigNotSaved() throws Exception { 1904 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1905 assertFalse(mWifiServiceImpl.setSoftApConfiguration(null, TEST_PACKAGE_NAME)); 1906 verify(mWifiApConfigStore, never()).setApConfiguration(isNull()); 1907 verify(mActiveModeWarden, never()).updateSoftApConfiguration(any()); 1908 verify(mWifiPermissionsUtil).checkConfigOverridePermission(anyInt()); 1909 } 1910 1911 /** 1912 * Ensure that an invalid config does not overwrite the saved ap config. 1913 */ 1914 @Test testSetSoftApConfigurationWithInvalidConfigNotSaved()1915 public void testSetSoftApConfigurationWithInvalidConfigNotSaved() throws Exception { 1916 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1917 assertFalse(mWifiServiceImpl.setSoftApConfiguration( 1918 new SoftApConfiguration.Builder().build(), TEST_PACKAGE_NAME)); 1919 verify(mWifiApConfigStore, never()).setApConfiguration(any()); 1920 verify(mWifiPermissionsUtil).checkConfigOverridePermission(anyInt()); 1921 } 1922 1923 /** 1924 * Ensure unpermitted callers are not able to retrieve the softap config. 1925 */ 1926 @Test testGetSoftApConfigurationNotReturnedWithoutPermission()1927 public void testGetSoftApConfigurationNotReturnedWithoutPermission() throws Exception { 1928 try { 1929 mWifiServiceImpl.getSoftApConfiguration(); 1930 fail("Expected a SecurityException"); 1931 } catch (SecurityException e) { 1932 } 1933 } 1934 1935 /** 1936 * Ensure permitted callers are able to retrieve the softap config. 1937 */ 1938 @Test testGetSoftApConfigurationSuccess()1939 public void testGetSoftApConfigurationSuccess() throws Exception { 1940 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 1941 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1942 SoftApConfiguration apConfig = createValidSoftApConfiguration(); 1943 when(mWifiApConfigStore.getApConfiguration()).thenReturn(apConfig); 1944 1945 mLooper.startAutoDispatch(); 1946 assertThat(apConfig).isEqualTo(mWifiServiceImpl.getSoftApConfiguration()); 1947 1948 mLooper.stopAutoDispatchAndIgnoreExceptions(); 1949 } 1950 1951 /** 1952 * Ensure unpermitted callers are not able to retrieve the softap config. 1953 */ 1954 @Test testGetWifiApConfigurationNotReturnedWithoutPermission()1955 public void testGetWifiApConfigurationNotReturnedWithoutPermission() throws Exception { 1956 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false); 1957 try { 1958 mWifiServiceImpl.getWifiApConfiguration(); 1959 fail("Expected a SecurityException"); 1960 } catch (SecurityException e) { 1961 } 1962 } 1963 1964 /** 1965 * Ensure permitted callers are able to retrieve the softap config. 1966 */ 1967 @Test testGetWifiApConfigurationSuccess()1968 public void testGetWifiApConfigurationSuccess() throws Exception { 1969 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 1970 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1971 SoftApConfiguration apConfig = new SoftApConfiguration.Builder().build(); 1972 when(mWifiApConfigStore.getApConfiguration()).thenReturn(apConfig); 1973 1974 mLooper.startAutoDispatch(); 1975 WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp( 1976 apConfig.toWifiConfiguration(), 1977 mWifiServiceImpl.getWifiApConfiguration()); 1978 1979 mLooper.stopAutoDispatchAndIgnoreExceptions(); 1980 } 1981 1982 /** 1983 * Ensure we return the proper variable for the softap state after getting an AP state change 1984 * broadcast. 1985 */ 1986 @Test testGetWifiApEnabled()1987 public void testGetWifiApEnabled() throws Exception { 1988 // ap should be disabled when wifi hasn't been started 1989 assertEquals(WifiManager.WIFI_AP_STATE_DISABLED, mWifiServiceImpl.getWifiApEnabledState()); 1990 1991 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 1992 mWifiServiceImpl.checkAndStartWifi(); 1993 mLooper.dispatchAll(); 1994 1995 // ap should be disabled initially 1996 assertEquals(WifiManager.WIFI_AP_STATE_DISABLED, mWifiServiceImpl.getWifiApEnabledState()); 1997 1998 // send an ap state change to verify WifiServiceImpl is updated 1999 verifyApRegistration(); 2000 mStateMachineSoftApCallback.onStateChanged( 2001 new SoftApState(WIFI_AP_STATE_ENABLED, 0, 2002 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 2003 mStateMachineSoftApCallback.onStateChanged( 2004 new SoftApState( 2005 WIFI_AP_STATE_FAILED, SAP_START_FAILURE_GENERAL, 2006 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 2007 mLooper.dispatchAll(); 2008 2009 assertEquals(WifiManager.WIFI_AP_STATE_FAILED, mWifiServiceImpl.getWifiApEnabledState()); 2010 } 2011 2012 /** 2013 * Ensure we do not allow unpermitted callers to get the wifi ap state. 2014 */ 2015 @Test testGetWifiApEnabledPermissionDenied()2016 public void testGetWifiApEnabledPermissionDenied() { 2017 // we should not be able to get the state 2018 doThrow(new SecurityException()).when(mContext) 2019 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), 2020 eq("WifiService")); 2021 2022 try { 2023 mWifiServiceImpl.getWifiApEnabledState(); 2024 fail("expected SecurityException"); 2025 } catch (SecurityException expected) { } 2026 } 2027 2028 /** 2029 * Make sure we do start WifiController (wifi disabled) if the device is already decrypted. 2030 */ 2031 @Test testWifiControllerStartsWhenDeviceBootsWithWifiDisabled()2032 public void testWifiControllerStartsWhenDeviceBootsWithWifiDisabled() { 2033 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 2034 mWifiServiceImpl.checkAndStartWifi(); 2035 mLooper.dispatchAll(); 2036 verify(mWifiConfigManager).loadFromStore(); 2037 verify(mActiveModeWarden).start(); 2038 verify(mActiveModeWarden, never()).wifiToggled(any()); 2039 } 2040 2041 @Test testWifiVerboseLoggingInitialization()2042 public void testWifiVerboseLoggingInitialization() { 2043 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 2044 when(mWifiSettingsConfigStore.get(eq(WIFI_VERBOSE_LOGGING_ENABLED))).thenReturn(true); 2045 mWifiServiceImpl.checkAndStartWifi(); 2046 mLooper.dispatchAll(); 2047 verify(mWifiConfigManager).loadFromStore(); 2048 verify(mActiveModeWarden).enableVerboseLogging(true); 2049 // show key mode is always disabled at the beginning. 2050 verify(mWifiGlobals).setVerboseLoggingLevel(eq(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED)); 2051 verify(mActiveModeWarden).start(); 2052 assertTrue(mWifiThreadRunner.mVerboseLoggingEnabled); 2053 } 2054 2055 /** 2056 * Make sure we do start WifiController (wifi enabled) if the device is already decrypted. 2057 */ 2058 @Test testWifiFullyStartsWhenDeviceBootsWithWifiEnabled()2059 public void testWifiFullyStartsWhenDeviceBootsWithWifiEnabled() { 2060 when(mSettingsStore.handleWifiToggled(true)).thenReturn(true); 2061 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(true); 2062 when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_DISABLED); 2063 when(mContext.getPackageName()).thenReturn(ANDROID_SYSTEM_PACKAGE); 2064 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 2065 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 2066 mWifiServiceImpl.checkAndStartWifi(); 2067 mLooper.dispatchAll(); 2068 verify(mWifiConfigManager).loadFromStore(); 2069 verify(mActiveModeWarden).start(); 2070 } 2071 2072 @Test testSetPnoScanEnabled()2073 public void testSetPnoScanEnabled() { 2074 assertThrows(SecurityException.class, 2075 () -> mWifiServiceImpl.setPnoScanEnabled(false, false, TEST_PACKAGE_NAME)); 2076 2077 if (SdkLevel.isAtLeastT()) { 2078 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 2079 .thenReturn(true); 2080 } else { 2081 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 2082 } 2083 mWifiServiceImpl.setPnoScanEnabled(false, false, TEST_PACKAGE_NAME); 2084 verify(mLastCallerInfoManager).put(eq(WifiManager.API_SET_PNO_SCAN_ENABLED), 2085 anyInt(), anyInt(), anyInt(), eq(TEST_PACKAGE_NAME), eq(false)); 2086 mLooper.dispatchAll(); 2087 verify(mWifiConnectivityManager).setPnoScanEnabledByFramework(false, false); 2088 } 2089 2090 @Test testSetPulledAtomCallbacks()2091 public void testSetPulledAtomCallbacks() { 2092 mWifiServiceImpl.checkAndStartWifi(); 2093 mWifiServiceImpl.handleBootCompleted(); 2094 mLooper.dispatchAll(); 2095 verify(mWifiPulledAtomLogger).setPullAtomCallback(WifiStatsLog.WIFI_MODULE_INFO); 2096 verify(mWifiPulledAtomLogger).setPullAtomCallback(WifiStatsLog.WIFI_SETTING_INFO); 2097 verify(mWifiPulledAtomLogger).setPullAtomCallback(WifiStatsLog.WIFI_COMPLEX_SETTING_INFO); 2098 verify(mWifiPulledAtomLogger).setPullAtomCallback( 2099 WifiStatsLog.WIFI_CONFIGURED_NETWORK_INFO); 2100 } 2101 2102 /** 2103 * Verify that the setCoexUnsafeChannels calls the corresponding CoexManager API if 2104 * the config_wifiDefaultCoexAlgorithmEnabled is false. 2105 */ 2106 @Test testSetCoexUnsafeChannelsDefaultAlgorithmDisabled()2107 public void testSetCoexUnsafeChannelsDefaultAlgorithmDisabled() { 2108 assumeTrue(SdkLevel.isAtLeastS()); 2109 when(mResourceCache.getBoolean(R.bool.config_wifiDefaultCoexAlgorithmEnabled)) 2110 .thenReturn(false); 2111 List<CoexUnsafeChannel> unsafeChannels = new ArrayList<>(); 2112 unsafeChannels.addAll(Arrays.asList(new CoexUnsafeChannel(WIFI_BAND_24_GHZ, 6), 2113 new CoexUnsafeChannel(WIFI_BAND_5_GHZ, 36))); 2114 int coexRestrictions = COEX_RESTRICTION_SOFTAP 2115 & COEX_RESTRICTION_WIFI_AWARE & COEX_RESTRICTION_WIFI_DIRECT; 2116 mWifiServiceImpl.setCoexUnsafeChannels(unsafeChannels, coexRestrictions); 2117 mLooper.dispatchAll(); 2118 verify(mCoexManager, times(1)).setCoexUnsafeChannels(any(), anyInt()); 2119 } 2120 2121 /** 2122 * Verify that the setCoexUnsafeChannels does not call the corresponding CoexManager API if 2123 * the config_wifiDefaultCoexAlgorithmEnabled is true. 2124 */ 2125 @Test testSetCoexUnsafeChannelsDefaultAlgorithmEnabled()2126 public void testSetCoexUnsafeChannelsDefaultAlgorithmEnabled() { 2127 assumeTrue(SdkLevel.isAtLeastS()); 2128 when(mResourceCache.getBoolean(R.bool.config_wifiDefaultCoexAlgorithmEnabled)) 2129 .thenReturn(true); 2130 List<CoexUnsafeChannel> unsafeChannels = new ArrayList<>(); 2131 unsafeChannels.add(new CoexUnsafeChannel(WIFI_BAND_24_GHZ, 6)); 2132 unsafeChannels.add(new CoexUnsafeChannel(WIFI_BAND_5_GHZ, 36)); 2133 int coexRestrictions = COEX_RESTRICTION_SOFTAP 2134 & COEX_RESTRICTION_WIFI_AWARE & COEX_RESTRICTION_WIFI_DIRECT; 2135 mWifiServiceImpl.setCoexUnsafeChannels(unsafeChannels, coexRestrictions); 2136 mLooper.dispatchAll(); 2137 verify(mCoexManager, never()).setCoexUnsafeChannels(any(), anyInt()); 2138 } 2139 2140 /** 2141 * Verify that setCoexUnsafeChannels throws an IllegalArgumentException if passed a null set. 2142 */ 2143 @Test testSetCoexUnsafeChannelsNullSet()2144 public void testSetCoexUnsafeChannelsNullSet() { 2145 assumeTrue(SdkLevel.isAtLeastS()); 2146 try { 2147 mWifiServiceImpl.setCoexUnsafeChannels(null, 0); 2148 fail("Expected IllegalArgumentException"); 2149 } catch (IllegalArgumentException e) { 2150 } 2151 } 2152 2153 /** 2154 * Test register and unregister callback will go to CoexManager; 2155 */ 2156 @Test testRegisterUnregisterCoexCallback()2157 public void testRegisterUnregisterCoexCallback() throws Exception { 2158 assumeTrue(SdkLevel.isAtLeastS()); 2159 when(mCoexCallback.asBinder()).thenReturn(mAppBinder); 2160 mWifiServiceImpl.registerCoexCallback(mCoexCallback); 2161 mLooper.dispatchAll(); 2162 verify(mCoexManager).registerRemoteCoexCallback(mCoexCallback); 2163 mWifiServiceImpl.unregisterCoexCallback(mCoexCallback); 2164 mLooper.dispatchAll(); 2165 verify(mCoexManager).unregisterRemoteCoexCallback(mCoexCallback); 2166 } 2167 2168 /** 2169 * Verify that a call to setCoexUnsafeChannels throws a SecurityException if the caller does 2170 * not have the WIFI_UPDATE_COEX_UNSAFE_CHANNELS permission. 2171 */ 2172 @Test testSetCoexUnsafeChannelsThrowsSecurityExceptionOnMissingPermissions()2173 public void testSetCoexUnsafeChannelsThrowsSecurityExceptionOnMissingPermissions() { 2174 assumeTrue(SdkLevel.isAtLeastS()); 2175 doThrow(new SecurityException()).when(mContext) 2176 .enforceCallingOrSelfPermission(eq(WIFI_UPDATE_COEX_UNSAFE_CHANNELS), 2177 eq("WifiService")); 2178 try { 2179 mWifiServiceImpl.setCoexUnsafeChannels(new ArrayList<>(), 0); 2180 fail("expected SecurityException"); 2181 } catch (SecurityException expected) { } 2182 } 2183 2184 /** 2185 * Verify that a call to registerCoexCallback throws a SecurityException if the caller does 2186 * not have the WIFI_ACCESS_COEX_UNSAFE_CHANNELS permission. 2187 */ 2188 @Test testRegisterCoexCallbackThrowsSecurityExceptionOnMissingPermissions()2189 public void testRegisterCoexCallbackThrowsSecurityExceptionOnMissingPermissions() { 2190 assumeTrue(SdkLevel.isAtLeastS()); 2191 doThrow(new SecurityException()).when(mContext) 2192 .enforceCallingOrSelfPermission(eq(WIFI_ACCESS_COEX_UNSAFE_CHANNELS), 2193 eq("WifiService")); 2194 try { 2195 mWifiServiceImpl.registerCoexCallback(mCoexCallback); 2196 fail("expected SecurityException"); 2197 } catch (SecurityException expected) { } 2198 } 2199 2200 /** 2201 * Verify that a call to unregisterCoexCallback throws a SecurityException if the caller does 2202 * not have the WIFI_ACCESS_COEX_UNSAFE_CHANNELS permission. 2203 */ 2204 @Test testUnregisterCoexCallbackThrowsSecurityExceptionOnMissingPermissions()2205 public void testUnregisterCoexCallbackThrowsSecurityExceptionOnMissingPermissions() { 2206 assumeTrue(SdkLevel.isAtLeastS()); 2207 doThrow(new SecurityException()).when(mContext) 2208 .enforceCallingOrSelfPermission(eq(WIFI_ACCESS_COEX_UNSAFE_CHANNELS), 2209 eq("WifiService")); 2210 try { 2211 mWifiServiceImpl.unregisterCoexCallback(mCoexCallback); 2212 fail("expected SecurityException"); 2213 } catch (SecurityException expected) { } 2214 } 2215 2216 /** 2217 * Verify caller with proper permission can call startSoftAp. 2218 */ 2219 @Test testStartSoftApWithPermissionsAndNullConfig()2220 public void testStartSoftApWithPermissionsAndNullConfig() { 2221 mLooper.startAutoDispatch(); 2222 boolean result = mWifiServiceImpl.startSoftAp(null, TEST_PACKAGE_NAME); 2223 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2224 assertTrue(result); 2225 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2226 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2227 assertNull(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2228 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2229 } 2230 2231 /** 2232 * Verify caller with proper permissions but an invalid config does not start softap. 2233 */ 2234 @Test testStartSoftApWithPermissionsAndInvalidConfig()2235 public void testStartSoftApWithPermissionsAndInvalidConfig() { 2236 mLooper.startAutoDispatch(); 2237 boolean result = mWifiServiceImpl.startSoftAp(mApConfig, TEST_PACKAGE_NAME); 2238 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2239 assertFalse(result); 2240 verify(mActiveModeWarden, never()).startSoftAp(any(), 2241 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2242 } 2243 2244 /** 2245 * Verify caller with proper permission and valid config does start softap. 2246 */ 2247 @Test testStartSoftApWithPermissionsAndValidConfig()2248 public void testStartSoftApWithPermissionsAndValidConfig() { 2249 WifiConfiguration config = createValidWifiApConfiguration(); 2250 mLooper.startAutoDispatch(); 2251 boolean result = mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME); 2252 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2253 assertTrue(result); 2254 verify(mActiveModeWarden).startSoftAp( 2255 mSoftApModeConfigCaptor.capture(), 2256 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2257 WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp( 2258 config, 2259 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration().toWifiConfiguration()); 2260 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2261 verify(mLastCallerInfoManager).put(eq(WifiManager.API_SOFT_AP), anyInt(), 2262 anyInt(), anyInt(), anyString(), eq(true)); 2263 } 2264 2265 /** 2266 * Verify a SecurityException is thrown when a caller without the correct permission attempts to 2267 * start softap. 2268 */ 2269 @Test(expected = SecurityException.class) testStartSoftApWithoutPermissionThrowsException()2270 public void testStartSoftApWithoutPermissionThrowsException() throws Exception { 2271 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK)) 2272 .thenReturn(PackageManager.PERMISSION_DENIED); 2273 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 2274 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any()); 2275 mLooper.startAutoDispatch(); 2276 mWifiServiceImpl.startSoftAp(null, TEST_PACKAGE_NAME); 2277 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2278 } 2279 2280 /** 2281 * Verify that startSoftAP() succeeds if the caller does not have the NETWORK_STACK permission 2282 * but does have the MAINLINE_NETWORK_STACK permission. 2283 */ 2284 @Test testStartSoftApWithoutNetworkStackWithMainlineNetworkStackSucceeds()2285 public void testStartSoftApWithoutNetworkStackWithMainlineNetworkStackSucceeds() { 2286 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK)) 2287 .thenReturn(PackageManager.PERMISSION_DENIED); 2288 WifiConfiguration config = createValidWifiApConfiguration(); 2289 mLooper.startAutoDispatch(); 2290 boolean result = mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME); 2291 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2292 assertTrue(result); 2293 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2294 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2295 WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp( 2296 config, 2297 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration().toWifiConfiguration()); 2298 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2299 verify(mContext).enforceCallingOrSelfPermission( 2300 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any()); 2301 } 2302 2303 /** 2304 * Verify that startSoftAp() with valid config succeeds after a failed call 2305 */ 2306 @Test testStartSoftApWithValidConfigSucceedsAfterFailure()2307 public void testStartSoftApWithValidConfigSucceedsAfterFailure() { 2308 // First initiate a failed call 2309 mLooper.startAutoDispatch(); 2310 assertFalse(mWifiServiceImpl.startSoftAp(mApConfig, TEST_PACKAGE_NAME)); 2311 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2312 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2313 2314 // Next attempt a valid config 2315 WifiConfiguration config = createValidWifiApConfiguration(); 2316 mLooper.startAutoDispatch(); 2317 assertTrue(mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME)); 2318 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2319 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2320 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2321 WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp( 2322 config, 2323 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration().toWifiConfiguration()); 2324 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2325 } 2326 2327 /** 2328 * Verify caller with proper permission can call startTetheredHotspot. 2329 */ 2330 @Test testStartTetheredHotspotWithPermissionsAndNullConfig()2331 public void testStartTetheredHotspotWithPermissionsAndNullConfig() { 2332 boolean result = mWifiServiceImpl.startTetheredHotspot(null, TEST_PACKAGE_NAME); 2333 assertTrue(result); 2334 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2335 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2336 assertNull(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2337 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2338 verify(mLastCallerInfoManager).put(eq(WifiManager.API_TETHERED_HOTSPOT), anyInt(), 2339 anyInt(), anyInt(), anyString(), eq(true)); 2340 } 2341 2342 /** 2343 * Verify a SecurityException is thrown when a caller without the correct permission attempts to 2344 * call startTetheredHotspot(). 2345 */ 2346 @Test(expected = SecurityException.class) testStartTetheredHotspotRequestWithoutPermissionThrowsException()2347 public void testStartTetheredHotspotRequestWithoutPermissionThrowsException() throws Exception { 2348 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK)) 2349 .thenReturn(PackageManager.PERMISSION_DENIED); 2350 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 2351 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any()); 2352 mLooper.startAutoDispatch(); 2353 TetheringManager.TetheringRequest request = new TetheringManager.TetheringRequest.Builder( 2354 TetheringManager.TETHERING_WIFI).build(); 2355 mWifiServiceImpl.startTetheredHotspotRequest(request, mClientSoftApCallback, 2356 TEST_PACKAGE_NAME); 2357 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2358 } 2359 2360 /** 2361 * Verify that startTetheredHotspotRequest succeeds if the caller does not have the 2362 * NETWORK_STACK permission but does have the MAINLINE_NETWORK_STACK permission. 2363 */ 2364 @Test testStartTetheredHotspotRequestNetworkStackWithMainlineNetworkStackSucceeds()2365 public void testStartTetheredHotspotRequestNetworkStackWithMainlineNetworkStackSucceeds() { 2366 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK)) 2367 .thenReturn(PackageManager.PERMISSION_DENIED); 2368 mLooper.startAutoDispatch(); 2369 TetheringManager.TetheringRequest request = new TetheringManager.TetheringRequest.Builder( 2370 TetheringManager.TETHERING_WIFI).build(); 2371 mWifiServiceImpl.startTetheredHotspotRequest(request, mClientSoftApCallback, 2372 TEST_PACKAGE_NAME); 2373 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2374 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2375 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2376 assertThat(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()).isNull(); 2377 assertThat(mSoftApModeConfigCaptor.getValue().getTetheringRequest()).isEqualTo(request); 2378 verify(mContext).enforceCallingOrSelfPermission( 2379 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any()); 2380 } 2381 2382 /** 2383 * Verify startTetheredHotspotRequest fails with a null request. 2384 */ 2385 @Test(expected = IllegalArgumentException.class) testStartTetheredHotspotNullRequestFails()2386 public void testStartTetheredHotspotNullRequestFails() { 2387 mLooper.startAutoDispatch(); 2388 mWifiServiceImpl.startTetheredHotspotRequest(null, mClientSoftApCallback, 2389 TEST_PACKAGE_NAME); 2390 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2391 } 2392 2393 /** 2394 * Verify caller with proper permission can call startTetheredHotspot from a TetheringRequest. 2395 */ 2396 @Test testStartTetheredHotspotRequestWithPermissions()2397 public void testStartTetheredHotspotRequestWithPermissions() { 2398 assumeTrue(Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA); 2399 TetheringManager.TetheringRequest request = new TetheringManager.TetheringRequest.Builder( 2400 TetheringManager.TETHERING_WIFI).build(); 2401 mWifiServiceImpl.startTetheredHotspotRequest(request, 2402 mClientSoftApCallback, TEST_PACKAGE_NAME); 2403 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2404 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2405 assertNull(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2406 assertThat(mSoftApModeConfigCaptor.getValue().getTetheringRequest()).isEqualTo(request); 2407 verify(mLastCallerInfoManager).put(eq(WifiManager.API_TETHERED_HOTSPOT), anyInt(), 2408 anyInt(), anyInt(), anyString(), eq(true)); 2409 } 2410 2411 /** 2412 * Verify startTetheredHotspot with TetheringRequest use the TetheringRequest's config. 2413 */ 2414 @Test 2415 public void testStartTetheredHotspotRequestWithSoftApConfiguration() { 2416 assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA); 2417 SoftApConfiguration config = createValidSoftApConfiguration(); 2418 TetheringManager.TetheringRequest request = new TetheringManager.TetheringRequest.Builder( 2419 TetheringManager.TETHERING_WIFI) 2420 .setSoftApConfiguration(config) 2421 .build(); 2422 mWifiServiceImpl.startTetheredHotspotRequest(request, 2423 mClientSoftApCallback, TEST_PACKAGE_NAME); 2424 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2425 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2426 assertThat(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()).isEqualTo(config); 2427 assertThat(mSoftApModeConfigCaptor.getValue().getTetheringRequest()).isEqualTo(request); 2428 verify(mLastCallerInfoManager).put(eq(WifiManager.API_TETHERED_HOTSPOT), anyInt(), 2429 anyInt(), anyInt(), anyString(), eq(true)); 2430 } 2431 2432 /** 2433 * Verify caller with proper permissions but an invalid config does not start softap. 2434 */ 2435 @Test testStartTetheredHotspotWithPermissionsAndInvalidConfig()2436 public void testStartTetheredHotspotWithPermissionsAndInvalidConfig() { 2437 boolean result = mWifiServiceImpl.startTetheredHotspot( 2438 new SoftApConfiguration.Builder().build(), TEST_PACKAGE_NAME); 2439 assertFalse(result); 2440 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2441 } 2442 2443 /** 2444 * Verify caller with proper permission and valid config does start softap. 2445 */ 2446 @Test testStartTetheredHotspotWithPermissionsAndValidConfig()2447 public void testStartTetheredHotspotWithPermissionsAndValidConfig() { 2448 SoftApConfiguration config = createValidSoftApConfiguration(); 2449 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2450 assertTrue(result); 2451 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2452 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2453 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2454 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2455 } 2456 2457 /** 2458 * Verify that while the DISALLOW_WIFI_TETHERING user restriction is set, softap does not start. 2459 */ 2460 @Test testStartTetheredHotspotWithUserRestriction()2461 public void testStartTetheredHotspotWithUserRestriction() { 2462 assumeTrue(SdkLevel.isAtLeastT()); 2463 when(mBundle.getBoolean(UserManager.DISALLOW_WIFI_TETHERING)).thenReturn(true); 2464 mWifiServiceImpl.checkAndStartWifi(); 2465 mLooper.dispatchAll(); 2466 SoftApConfiguration config = createValidSoftApConfiguration(); 2467 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2468 assertFalse(result); 2469 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2470 } 2471 2472 /** 2473 * Verify that while the DISALLOW_WIFI_TETHERING user restriction is set, 2474 * startTetheredHotspotRequest fails and notifies the callback. 2475 */ 2476 @Test testStartTetheredHotspotRequestWithUserRestriction()2477 public void testStartTetheredHotspotRequestWithUserRestriction() throws Exception { 2478 assumeTrue(SdkLevel.isAtLeastT()); 2479 when(mBundle.getBoolean(UserManager.DISALLOW_WIFI_TETHERING)).thenReturn(true); 2480 mWifiServiceImpl.checkAndStartWifi(); 2481 mLooper.dispatchAll(); 2482 SoftApConfiguration config = createValidSoftApConfiguration(); 2483 mWifiServiceImpl.startTetheredHotspotRequest(TEST_TETHERING_REQUEST, mClientSoftApCallback, 2484 TEST_PACKAGE_NAME); 2485 verify(mClientSoftApCallback).onStateChanged(eq(new SoftApState(WIFI_AP_STATE_FAILED, 2486 SAP_START_FAILURE_GENERAL, TEST_TETHERING_REQUEST, null))); 2487 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2488 } 2489 2490 /** 2491 * Verify that when the DISALLOW_WIFI_TETHERING user restriction is set, softap stops. 2492 */ 2493 @Test testTetheredHotspotDisabledWhenUserRestrictionSet()2494 public void testTetheredHotspotDisabledWhenUserRestrictionSet() { 2495 assumeTrue(SdkLevel.isAtLeastT()); 2496 when(mBundle.getBoolean(UserManager.DISALLOW_WIFI_TETHERING)).thenReturn(true); 2497 mLooper.startAutoDispatch(); 2498 mWifiServiceImpl.onUserRestrictionsChanged(); 2499 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2500 verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_TETHERED); 2501 } 2502 2503 /** 2504 * Verify isWifiBandSupported for 24GHz with an overlay override config 2505 */ 2506 @Test testIsWifiBandSupported24gWithOverride()2507 public void testIsWifiBandSupported24gWithOverride() throws Exception { 2508 when(mResourceCache.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(true); 2509 assertTrue(mWifiServiceImpl.is24GHzBandSupported()); 2510 verify(mActiveModeWarden, never()).isBandSupportedForSta(anyInt()); 2511 } 2512 2513 /** 2514 * Verify isWifiBandSupported for 5GHz with an overlay override config 2515 */ 2516 @Test testIsWifiBandSupported5gWithOverride()2517 public void testIsWifiBandSupported5gWithOverride() throws Exception { 2518 when(mResourceCache.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(true); 2519 assertTrue(mWifiServiceImpl.is5GHzBandSupported()); 2520 verify(mActiveModeWarden, never()).isBandSupportedForSta(anyInt()); 2521 } 2522 2523 /** 2524 * Verify isWifiBandSupported for 6GHz with an overlay override config 2525 */ 2526 @Test testIsWifiBandSupported6gWithOverride()2527 public void testIsWifiBandSupported6gWithOverride() throws Exception { 2528 when(mResourceCache.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(true); 2529 assertTrue(mWifiServiceImpl.is6GHzBandSupported()); 2530 verify(mActiveModeWarden, never()).isBandSupportedForSta(anyInt()); 2531 } 2532 2533 /** 2534 * Verify isWifiBandSupported for 24GHz with no overlay override config no channels 2535 */ 2536 @Test testIsWifiBandSupported24gNoOverrideNoChannels()2537 public void testIsWifiBandSupported24gNoOverrideNoChannels() throws Exception { 2538 when(mResourceCache.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(false); 2539 when(mActiveModeWarden.isBandSupportedForSta(WIFI_BAND_24_GHZ)).thenReturn(false); 2540 assertFalse(mWifiServiceImpl.is24GHzBandSupported()); 2541 verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_24_GHZ); 2542 } 2543 2544 /** 2545 * Verify isWifiBandSupported for 5GHz with no overlay override config no channels 2546 */ 2547 @Test testIsWifiBandSupported5gNoOverrideNoChannels()2548 public void testIsWifiBandSupported5gNoOverrideNoChannels() throws Exception { 2549 when(mResourceCache.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(false); 2550 when(mActiveModeWarden.isBandSupportedForSta(WIFI_BAND_5_GHZ)).thenReturn(false); 2551 assertFalse(mWifiServiceImpl.is5GHzBandSupported()); 2552 verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_5_GHZ); 2553 } 2554 2555 /** 2556 * Verify isWifiBandSupported for 24GHz with no overlay override config with channels 2557 */ 2558 @Test testIsWifiBandSupported24gNoOverrideWithChannels()2559 public void testIsWifiBandSupported24gNoOverrideWithChannels() throws Exception { 2560 when(mResourceCache.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(false); 2561 when(mActiveModeWarden.isBandSupportedForSta(WIFI_BAND_24_GHZ)).thenReturn(true); 2562 assertTrue(mWifiServiceImpl.is24GHzBandSupported()); 2563 verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_24_GHZ); 2564 } 2565 2566 /** 2567 * Verify isWifiBandSupported for 5GHz with no overlay override config with channels 2568 */ 2569 @Test testIsWifiBandSupported5gNoOverrideWithChannels()2570 public void testIsWifiBandSupported5gNoOverrideWithChannels() throws Exception { 2571 when(mResourceCache.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(false); 2572 when(mActiveModeWarden.isBandSupportedForSta(WIFI_BAND_5_GHZ)).thenReturn(true); 2573 assertTrue(mWifiServiceImpl.is5GHzBandSupported()); 2574 verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_5_GHZ); 2575 } 2576 2577 /** 2578 * Verify isWifiBandSupported for 6GHz with no overlay override config no channels 2579 */ 2580 @Test testIsWifiBandSupported6gNoOverrideNoChannels()2581 public void testIsWifiBandSupported6gNoOverrideNoChannels() throws Exception { 2582 when(mResourceCache.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(false); 2583 when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ)).thenReturn( 2584 false); 2585 assertFalse(mWifiServiceImpl.is6GHzBandSupported()); 2586 verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ); 2587 } 2588 2589 /** 2590 * Verify isWifiBandSupported for 6GHz with no overlay override config with channels 2591 */ 2592 @Test testIsWifiBandSupported6gNoOverrideWithChannels()2593 public void testIsWifiBandSupported6gNoOverrideWithChannels() throws Exception { 2594 when(mResourceCache.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(false); 2595 when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ)).thenReturn( 2596 true); 2597 assertTrue(mWifiServiceImpl.is6GHzBandSupported()); 2598 verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ); 2599 } 2600 setup24GhzSupported()2601 private void setup24GhzSupported() { 2602 when(mResourceCache.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(true); 2603 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap24ghzSupported)).thenReturn(true); 2604 } 2605 setup24GhzUnsupported(boolean isOnlyUnsupportedSoftAp)2606 private void setup24GhzUnsupported(boolean isOnlyUnsupportedSoftAp) { 2607 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap24ghzSupported)).thenReturn(false); 2608 if (!isOnlyUnsupportedSoftAp) { 2609 when(mResourceCache.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(false); 2610 when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_24_GHZ)) 2611 .thenReturn(false); 2612 } 2613 } 2614 setup5GhzSupported()2615 private void setup5GhzSupported() { 2616 when(mResourceCache.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(true); 2617 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap5ghzSupported)).thenReturn(true); 2618 } 2619 setup5GhzUnsupported(boolean isOnlyUnsupportedSoftAp)2620 private void setup5GhzUnsupported(boolean isOnlyUnsupportedSoftAp) { 2621 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap5ghzSupported)).thenReturn(false); 2622 if (!isOnlyUnsupportedSoftAp) { 2623 when(mResourceCache.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(false); 2624 when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_5_GHZ)) 2625 .thenReturn(false); 2626 } 2627 } 2628 setup6GhzSupported()2629 private void setup6GhzSupported() { 2630 when(mResourceCache.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(true); 2631 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap6ghzSupported)).thenReturn(true); 2632 } 2633 setup6GhzUnsupported(boolean isOnlyUnsupportedSoftAp)2634 private void setup6GhzUnsupported(boolean isOnlyUnsupportedSoftAp) { 2635 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap6ghzSupported)).thenReturn(false); 2636 if (!isOnlyUnsupportedSoftAp) { 2637 when(mResourceCache.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(false); 2638 when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ)) 2639 .thenReturn(false); 2640 } 2641 } 2642 setup60GhzSupported()2643 private void setup60GhzSupported() { 2644 when(mResourceCache.getBoolean(R.bool.config_wifi60ghzSupport)).thenReturn(true); 2645 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap60ghzSupported)).thenReturn(true); 2646 } 2647 setup60GhzUnsupported(boolean isOnlyUnsupportedSoftAp)2648 private void setup60GhzUnsupported(boolean isOnlyUnsupportedSoftAp) { 2649 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap60ghzSupported)).thenReturn(false); 2650 if (!isOnlyUnsupportedSoftAp) { 2651 when(mResourceCache.getBoolean(R.bool.config_wifi60ghzSupport)).thenReturn(false); 2652 when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_60_GHZ)) 2653 .thenReturn(false); 2654 } 2655 } 2656 2657 /** 2658 * Verify attempt to start softAp with a supported 24GHz band succeeds. 2659 */ 2660 @Test testStartTetheredHotspotWithSupported24gBand()2661 public void testStartTetheredHotspotWithSupported24gBand() { 2662 setup24GhzSupported(); 2663 2664 SoftApConfiguration config = new SoftApConfiguration.Builder() 2665 .setSsid("TestAp") 2666 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2667 .setBand(SoftApConfiguration.BAND_2GHZ) 2668 .build(); 2669 2670 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2671 assertTrue(result); 2672 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2673 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2674 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2675 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2676 } 2677 2678 /** 2679 * Verify attempt to start softAp with a non-supported 2.4GHz band fails. 2680 */ 2681 @Test testStartTetheredHotspotWithUnSupported24gBand()2682 public void testStartTetheredHotspotWithUnSupported24gBand() { 2683 setup24GhzUnsupported(false); 2684 2685 SoftApConfiguration config = new SoftApConfiguration.Builder() 2686 .setSsid("TestAp") 2687 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2688 .setBand(SoftApConfiguration.BAND_2GHZ) 2689 .build(); 2690 2691 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2692 assertFalse(result); 2693 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2694 } 2695 2696 /** 2697 * Verify attempt to start softAp with a non-supported 2.4GHz band fails. 2698 */ 2699 @Test testStartTetheredHotspotWithUnSupportedSoftAp24gBand()2700 public void testStartTetheredHotspotWithUnSupportedSoftAp24gBand() { 2701 setup24GhzSupported(); 2702 setup24GhzUnsupported(true); 2703 2704 SoftApConfiguration config = new SoftApConfiguration.Builder() 2705 .setSsid("TestAp") 2706 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2707 .setBand(SoftApConfiguration.BAND_2GHZ) 2708 .build(); 2709 2710 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2711 assertFalse(result); 2712 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2713 } 2714 2715 /** 2716 * Verify attempt to start softAp with a supported 5GHz band succeeds. 2717 */ 2718 @Test testStartTetheredHotspotWithSupported5gBand()2719 public void testStartTetheredHotspotWithSupported5gBand() { 2720 setup5GhzSupported(); 2721 2722 SoftApConfiguration config = new SoftApConfiguration.Builder() 2723 .setSsid("TestAp") 2724 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2725 .setBand(SoftApConfiguration.BAND_5GHZ) 2726 .build(); 2727 2728 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2729 2730 assertTrue(result); 2731 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2732 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2733 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2734 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2735 } 2736 2737 /** 2738 * Verify attempt to start softAp with a non-supported 5GHz band fails. 2739 */ 2740 @Test testStartTetheredHotspotWithUnSupported5gBand()2741 public void testStartTetheredHotspotWithUnSupported5gBand() { 2742 setup5GhzUnsupported(false); 2743 2744 SoftApConfiguration config = new SoftApConfiguration.Builder() 2745 .setSsid("TestAp") 2746 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2747 .setBand(SoftApConfiguration.BAND_5GHZ) 2748 .build(); 2749 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2750 2751 assertFalse(result); 2752 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2753 } 2754 2755 /** 2756 * Verify attempt to start softAp with a non-supported 5GHz band fails. 2757 */ 2758 @Test testStartTetheredHotspotWithUnSupportedSoftAp5gBand()2759 public void testStartTetheredHotspotWithUnSupportedSoftAp5gBand() { 2760 setup5GhzSupported(); 2761 setup5GhzUnsupported(true); 2762 2763 SoftApConfiguration config = new SoftApConfiguration.Builder() 2764 .setSsid("TestAp") 2765 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2766 .setBand(SoftApConfiguration.BAND_5GHZ) 2767 .build(); 2768 2769 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2770 2771 assertFalse(result); 2772 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2773 } 2774 2775 /** 2776 * Verify attempt to start softAp with a supported 6GHz band succeeds. 2777 */ 2778 @Test testStartTetheredHotspotWithSupported6gBand()2779 public void testStartTetheredHotspotWithSupported6gBand() { 2780 setup6GhzSupported(); 2781 2782 SoftApConfiguration config = new SoftApConfiguration.Builder() 2783 .setSsid("TestAp") 2784 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE) 2785 .setBand(SoftApConfiguration.BAND_6GHZ) 2786 .build(); 2787 2788 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2789 2790 assertTrue(result); 2791 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2792 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2793 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2794 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2795 } 2796 2797 /** 2798 * Verify attempt to start softAp with a non-supported 6GHz band fails. 2799 */ 2800 @Test testStartTetheredHotspotWithUnSupported6gBand()2801 public void testStartTetheredHotspotWithUnSupported6gBand() { 2802 setup6GhzUnsupported(false); 2803 2804 SoftApConfiguration config = new SoftApConfiguration.Builder() 2805 .setSsid("TestAp") 2806 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE) 2807 .setBand(SoftApConfiguration.BAND_6GHZ) 2808 .build(); 2809 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2810 2811 assertFalse(result); 2812 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2813 } 2814 2815 /** 2816 * Verify attempt to start softAp with a non-supported 6GHz band fails. 2817 */ 2818 @Test testStartTetheredHotspotWithUnSupportedSoftAp6gBand()2819 public void testStartTetheredHotspotWithUnSupportedSoftAp6gBand() { 2820 setup6GhzSupported(); 2821 setup6GhzUnsupported(true); 2822 2823 SoftApConfiguration config = new SoftApConfiguration.Builder() 2824 .setSsid("TestAp") 2825 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE) 2826 .setBand(SoftApConfiguration.BAND_6GHZ) 2827 .build(); 2828 2829 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2830 assertFalse(result); 2831 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2832 } 2833 2834 2835 /** 2836 * Verify attempt to start softAp with a supported 60GHz band succeeds. 2837 */ 2838 @Test testStartTetheredHotspotWithSupported60gBand()2839 public void testStartTetheredHotspotWithSupported60gBand() { 2840 setup60GhzSupported(); 2841 2842 SoftApConfiguration config = new SoftApConfiguration.Builder() 2843 .setSsid("TestAp") 2844 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2845 .setBand(SoftApConfiguration.BAND_60GHZ) 2846 .build(); 2847 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2848 2849 assertTrue(result); 2850 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2851 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2852 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2853 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2854 } 2855 2856 /** 2857 * Verify attempt to start softAp with a non-supported 60GHz band fails. 2858 */ 2859 @Test testStartTetheredHotspotWithUnSupported60gBand()2860 public void testStartTetheredHotspotWithUnSupported60gBand() { 2861 setup60GhzUnsupported(false); 2862 2863 SoftApConfiguration config = new SoftApConfiguration.Builder() 2864 .setSsid("TestAp") 2865 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2866 .setBand(SoftApConfiguration.BAND_60GHZ) 2867 .build(); 2868 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2869 2870 assertFalse(result); 2871 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2872 } 2873 2874 /** 2875 * Verify attempt to start softAp with a non-supported 60GHz band fails. 2876 */ 2877 @Test testStartTetheredHotspotWithUnSupportedSoftAp60gBand()2878 public void testStartTetheredHotspotWithUnSupportedSoftAp60gBand() { 2879 setup60GhzSupported(); 2880 setup60GhzUnsupported(true); 2881 2882 SoftApConfiguration config = new SoftApConfiguration.Builder() 2883 .setSsid("TestAp") 2884 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2885 .setBand(SoftApConfiguration.BAND_60GHZ) 2886 .build(); 2887 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2888 2889 assertFalse(result); 2890 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2891 } 2892 2893 /** 2894 * Verify attempt to start softAp with a supported band succeeds. 2895 */ 2896 @Test testStartTetheredHotspotWithSupportedBand()2897 public void testStartTetheredHotspotWithSupportedBand() { 2898 setup5GhzSupported(); 2899 2900 SoftApConfiguration config = new SoftApConfiguration.Builder() 2901 .setSsid("TestAp") 2902 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 2903 .setBand(SoftApConfiguration.BAND_5GHZ) 2904 .build(); 2905 2906 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2907 assertTrue(result); 2908 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2909 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2910 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2911 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2912 } 2913 2914 /** 2915 * Verify a SecurityException is thrown when a caller without the correct permission attempts to 2916 * start softap. 2917 */ 2918 @Test(expected = SecurityException.class) testStartTetheredHotspotWithoutPermissionThrowsException()2919 public void testStartTetheredHotspotWithoutPermissionThrowsException() throws Exception { 2920 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK)) 2921 .thenReturn(PackageManager.PERMISSION_DENIED); 2922 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 2923 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any()); 2924 mWifiServiceImpl.startTetheredHotspot(null, TEST_PACKAGE_NAME); 2925 } 2926 2927 /** 2928 * Verify that startTetheredHotspot() succeeds if the caller does not have the 2929 * NETWORK_STACK permission but does have the MAINLINE_NETWORK_STACK permission. 2930 */ 2931 @Test testStartTetheredHotspotWithoutNetworkStackWithMainlineNetworkStackSucceeds()2932 public void testStartTetheredHotspotWithoutNetworkStackWithMainlineNetworkStackSucceeds() { 2933 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK)) 2934 .thenReturn(PackageManager.PERMISSION_DENIED); 2935 SoftApConfiguration config = createValidSoftApConfiguration(); 2936 boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME); 2937 assertTrue(result); 2938 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2939 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2940 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2941 verify(mContext).enforceCallingOrSelfPermission( 2942 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any()); 2943 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2944 } 2945 2946 /** 2947 * Verify a valied call to startTetheredHotspot succeeds after a failed call. 2948 */ 2949 @Test testStartTetheredHotspotWithValidConfigSucceedsAfterFailedCall()2950 public void testStartTetheredHotspotWithValidConfigSucceedsAfterFailedCall() { 2951 // First issue an invalid call 2952 assertFalse(mWifiServiceImpl.startTetheredHotspot( 2953 new SoftApConfiguration.Builder().build(), TEST_PACKAGE_NAME)); 2954 verify(mActiveModeWarden, never()).startSoftAp(any(), any()); 2955 2956 assertTrue(mWifiServiceImpl.startTetheredHotspot(null, TEST_PACKAGE_NAME)); 2957 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 2958 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 2959 assertNull(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 2960 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 2961 } 2962 2963 /** 2964 * Verify caller with proper permission can call stopSoftAp. 2965 */ 2966 @Test testStopSoftApWithPermissions()2967 public void testStopSoftApWithPermissions() { 2968 boolean result = mWifiServiceImpl.stopSoftAp(); 2969 assertTrue(result); 2970 verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_TETHERED); 2971 verify(mLastCallerInfoManager).put(eq(WifiManager.API_SOFT_AP), anyInt(), 2972 anyInt(), anyInt(), anyString(), eq(false)); 2973 } 2974 2975 /** 2976 * Verify SecurityException is thrown when a caller without the correct permission attempts to 2977 * stop softap. 2978 */ 2979 @Test(expected = SecurityException.class) testStopSoftApWithoutPermissionThrowsException()2980 public void testStopSoftApWithoutPermissionThrowsException() throws Exception { 2981 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK)) 2982 .thenReturn(PackageManager.PERMISSION_DENIED); 2983 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 2984 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any()); 2985 mWifiServiceImpl.stopSoftAp(); 2986 } 2987 2988 /** 2989 * Ensure that we handle app ops check failure when handling scan request. 2990 */ 2991 @Test testStartScanFailureAppOpsIgnored()2992 public void testStartScanFailureAppOpsIgnored() { 2993 doReturn(AppOpsManager.MODE_IGNORED).when(mAppOpsManager) 2994 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), SCAN_PACKAGE_NAME); 2995 mLooper.startAutoDispatch(); 2996 assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID)); 2997 mLooper.stopAutoDispatchAndIgnoreExceptions(); 2998 verify(mScanRequestProxy, never()).startScan(Process.myUid(), SCAN_PACKAGE_NAME); 2999 } 3000 3001 /** 3002 * Ensure that we handle scan access permission check failure when handling scan request. 3003 */ 3004 @Test testStartScanFailureInCanAccessScanResultsPermission()3005 public void testStartScanFailureInCanAccessScanResultsPermission() { 3006 doThrow(new SecurityException()).when(mWifiPermissionsUtil) 3007 .enforceCanAccessScanResults(SCAN_PACKAGE_NAME, TEST_FEATURE_ID, Process.myUid(), 3008 null); 3009 mLooper.startAutoDispatch(); 3010 assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID)); 3011 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3012 verify(mScanRequestProxy, never()).startScan(Process.myUid(), SCAN_PACKAGE_NAME); 3013 } 3014 3015 /** 3016 * Ensure that we handle scan request failure when posting the runnable to handler fails. 3017 */ 3018 @Test testStartScanFailureInRunWithScissors()3019 public void testStartScanFailureInRunWithScissors() { 3020 mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut(); 3021 3022 mLooper.startAutoDispatch(); 3023 assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID)); 3024 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3025 verify(mScanRequestProxy, never()).startScan(anyInt(), eq(SCAN_PACKAGE_NAME)); 3026 verify(mLastCallerInfoManager).put(eq(WifiManager.API_START_SCAN), anyInt(), 3027 anyInt(), anyInt(), anyString(), eq(true)); 3028 } 3029 3030 /** 3031 * Ensure that we handle scan request failure from ScanRequestProxy fails. 3032 */ 3033 @Test testStartScanFailureFromScanRequestProxy()3034 public void testStartScanFailureFromScanRequestProxy() { 3035 when(mScanRequestProxy.startScan(anyInt(), anyString())).thenReturn(false); 3036 3037 mLooper.startAutoDispatch(); 3038 assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID)); 3039 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3040 verify(mScanRequestProxy).startScan(Binder.getCallingUid(), SCAN_PACKAGE_NAME); 3041 } 3042 setupForGetConnectionInfo()3043 private WifiInfo setupForGetConnectionInfo() { 3044 WifiInfo wifiInfo = new WifiInfo(); 3045 wifiInfo.setSSID(WifiSsid.fromUtf8Text(TEST_SSID)); 3046 wifiInfo.setBSSID(TEST_BSSID); 3047 wifiInfo.setNetworkId(TEST_NETWORK_ID); 3048 wifiInfo.setFQDN(TEST_FQDN); 3049 wifiInfo.setProviderFriendlyName(TEST_FRIENDLY_NAME); 3050 return wifiInfo; 3051 } 3052 parcelingRoundTrip(WifiInfo wifiInfo)3053 private WifiInfo parcelingRoundTrip(WifiInfo wifiInfo) { 3054 Parcel parcel = Parcel.obtain(); 3055 wifiInfo.writeToParcel(parcel, 0); 3056 // Rewind the pointer to the head of the parcel. 3057 parcel.setDataPosition(0); 3058 return WifiInfo.CREATOR.createFromParcel(parcel); 3059 } 3060 3061 /** 3062 * Test that connected SSID and BSSID are not exposed to an app that does not have the 3063 * appropriate permissions. 3064 */ 3065 @Test testConnectedIdsAreHiddenFromAppWithoutPermission()3066 public void testConnectedIdsAreHiddenFromAppWithoutPermission() throws Exception { 3067 WifiInfo wifiInfo = setupForGetConnectionInfo(); 3068 when(mActiveModeWarden.getConnectionInfo()).thenReturn(wifiInfo); 3069 when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_ENABLED); 3070 doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults( 3071 anyString(), nullable(String.class), anyInt(), nullable(String.class)); 3072 3073 mLooper.startAutoDispatch(); 3074 WifiInfo connectionInfo = parcelingRoundTrip( 3075 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID)); 3076 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3077 3078 assertEquals(WifiManager.UNKNOWN_SSID, connectionInfo.getSSID()); 3079 assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, connectionInfo.getBSSID()); 3080 assertEquals(WifiConfiguration.INVALID_NETWORK_ID, connectionInfo.getNetworkId()); 3081 assertNull(connectionInfo.getPasspointFqdn()); 3082 assertNull(connectionInfo.getPasspointProviderFriendlyName()); 3083 if (SdkLevel.isAtLeastS()) { 3084 try { 3085 connectionInfo.isPrimary(); 3086 fail(); 3087 } catch (SecurityException e) { /* pass */ } 3088 } 3089 } 3090 3091 /** 3092 * Test that connected SSID and BSSID are not exposed to an app that does not have the 3093 * appropriate permissions, when enforceCanAccessScanResults raises a SecurityException. 3094 */ 3095 @Test testConnectedIdsAreHiddenOnSecurityException()3096 public void testConnectedIdsAreHiddenOnSecurityException() throws Exception { 3097 WifiInfo wifiInfo = setupForGetConnectionInfo(); 3098 when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_ENABLED); 3099 when(mActiveModeWarden.getConnectionInfo()).thenReturn(wifiInfo); 3100 3101 doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults( 3102 anyString(), nullable(String.class), anyInt(), nullable(String.class)); 3103 3104 mLooper.startAutoDispatch(); 3105 WifiInfo connectionInfo = parcelingRoundTrip( 3106 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID)); 3107 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3108 3109 assertEquals(WifiManager.UNKNOWN_SSID, connectionInfo.getSSID()); 3110 assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, connectionInfo.getBSSID()); 3111 assertEquals(WifiConfiguration.INVALID_NETWORK_ID, connectionInfo.getNetworkId()); 3112 assertNull(connectionInfo.getPasspointFqdn()); 3113 assertNull(connectionInfo.getPasspointProviderFriendlyName()); 3114 } 3115 3116 /** 3117 * Test that connected SSID and BSSID are exposed to an app that does have the 3118 * appropriate permissions. 3119 */ 3120 @Test testConnectedIdsAreVisibleFromPermittedApp()3121 public void testConnectedIdsAreVisibleFromPermittedApp() throws Exception { 3122 WifiInfo wifiInfo = setupForGetConnectionInfo(); 3123 when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_ENABLED); 3124 when(mActiveModeWarden.getConnectionInfo()).thenReturn(wifiInfo); 3125 3126 mLooper.startAutoDispatch(); 3127 WifiInfo connectionInfo = parcelingRoundTrip( 3128 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID)); 3129 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3130 3131 assertEquals(TEST_SSID_WITH_QUOTES, connectionInfo.getSSID()); 3132 assertEquals(TEST_BSSID, connectionInfo.getBSSID()); 3133 assertEquals(TEST_NETWORK_ID, connectionInfo.getNetworkId()); 3134 assertEquals(TEST_FQDN, connectionInfo.getPasspointFqdn()); 3135 assertEquals(TEST_FRIENDLY_NAME, connectionInfo.getPasspointProviderFriendlyName()); 3136 } 3137 3138 /** 3139 * Test that connected SSID and BSSID for secondary CMM are exposed to an app that requests 3140 * the second STA on a device that supports STA + STA. 3141 */ 3142 @Test testConnectedIdsFromSecondaryCmmAreVisibleFromAppRequestingSecondaryCmm()3143 public void testConnectedIdsFromSecondaryCmmAreVisibleFromAppRequestingSecondaryCmm() 3144 throws Exception { 3145 WifiInfo wifiInfo = setupForGetConnectionInfo(); 3146 when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_ENABLED); 3147 when(mActiveModeWarden.getSecondaryRequestWs()) 3148 .thenReturn(Set.of(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE))); 3149 ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class); 3150 when(secondaryCmm.getRequestorWs()) 3151 .thenReturn(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE)); 3152 when(secondaryCmm.getConnectionInfo()).thenReturn(wifiInfo); 3153 when(mActiveModeWarden.getClientModeManagersInRoles( 3154 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED)) 3155 .thenReturn(Arrays.asList(secondaryCmm)); 3156 3157 mLooper.startAutoDispatch(); 3158 WifiInfo connectionInfo = parcelingRoundTrip( 3159 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID)); 3160 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3161 3162 assertEquals(TEST_SSID_WITH_QUOTES, connectionInfo.getSSID()); 3163 assertEquals(TEST_BSSID, connectionInfo.getBSSID()); 3164 assertEquals(TEST_NETWORK_ID, connectionInfo.getNetworkId()); 3165 assertEquals(TEST_FQDN, connectionInfo.getPasspointFqdn()); 3166 assertEquals(TEST_FRIENDLY_NAME, connectionInfo.getPasspointProviderFriendlyName()); 3167 } 3168 3169 /** 3170 * Test that connected SSID and BSSID for secondary CMM are exposed to an app that requests 3171 * the second STA on a device that supports STA + STA. The request WorkSource of CMM is settings 3172 * promoted. 3173 */ 3174 @Test testConnectedIdsAreVisibleFromAppRequestingSecondaryCmmWIthPromotesSettingsWs()3175 public void testConnectedIdsAreVisibleFromAppRequestingSecondaryCmmWIthPromotesSettingsWs() 3176 throws Exception { 3177 WifiInfo wifiInfo = setupForGetConnectionInfo(); 3178 when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_ENABLED); 3179 when(mActiveModeWarden.getConnectionInfo()).thenReturn(new WifiInfo()); 3180 ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class); 3181 WorkSource ws = new WorkSource(Binder.getCallingUid(), TEST_PACKAGE); 3182 ws.add(SETTINGS_WORKSOURCE); 3183 when(secondaryCmm.getRequestorWs()).thenReturn(ws); 3184 when(mActiveModeWarden.getSecondaryRequestWs()).thenReturn(Set.of(ws)); 3185 when(secondaryCmm.getConnectionInfo()).thenReturn(wifiInfo); 3186 when(mActiveModeWarden.getClientModeManagersInRoles( 3187 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED)) 3188 .thenReturn(Arrays.asList(secondaryCmm)); 3189 ConcreteClientModeManager primaryCmm = mock(ConcreteClientModeManager.class); 3190 when(primaryCmm.getConnectionInfo()).thenReturn(new WifiInfo()); 3191 when(mActiveModeWarden.getPrimaryClientModeManager()).thenReturn(primaryCmm); 3192 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(SETTINGS_WORKSOURCE.getUid(0))) 3193 .thenReturn(true); 3194 3195 mLooper.startAutoDispatch(); 3196 WifiInfo connectionInfo = parcelingRoundTrip( 3197 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID)); 3198 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3199 3200 assertEquals(TEST_SSID_WITH_QUOTES, connectionInfo.getSSID()); 3201 assertEquals(TEST_BSSID, connectionInfo.getBSSID()); 3202 assertEquals(TEST_NETWORK_ID, connectionInfo.getNetworkId()); 3203 assertEquals(TEST_FQDN, connectionInfo.getPasspointFqdn()); 3204 assertEquals(TEST_FRIENDLY_NAME, connectionInfo.getPasspointProviderFriendlyName()); 3205 verify(mActiveModeWarden, never()).getPrimaryClientModeManager(); 3206 3207 mLooper.startAutoDispatch(); 3208 connectionInfo = parcelingRoundTrip(mWifiServiceImpl 3209 .getConnectionInfo(SETTINGS_WORKSOURCE.getPackageName(0), TEST_FEATURE_ID)); 3210 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3211 3212 assertEquals(WifiManager.UNKNOWN_SSID, connectionInfo.getSSID()); 3213 verify(mActiveModeWarden).getConnectionInfo(); 3214 } 3215 3216 /** 3217 * Test that connected SSID and BSSID for primary CMM are exposed to an app that is not the one 3218 * that requests the second STA on a device that supports STA + STA. 3219 */ 3220 @Test testConnectedIdsFromPrimaryCmmAreVisibleFromAppNotRequestingSecondaryCmm()3221 public void testConnectedIdsFromPrimaryCmmAreVisibleFromAppNotRequestingSecondaryCmm() 3222 throws Exception { 3223 WifiInfo wifiInfo = setupForGetConnectionInfo(); 3224 when(mActiveModeWarden.getConnectionInfo()).thenReturn(wifiInfo); 3225 when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_ENABLED); 3226 when(mActiveModeWarden.getSecondaryRequestWs()) 3227 .thenReturn( 3228 Set.of(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME_OTHER))); 3229 3230 mLooper.startAutoDispatch(); 3231 WifiInfo connectionInfo = parcelingRoundTrip( 3232 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID)); 3233 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3234 3235 assertEquals(TEST_SSID_WITH_QUOTES, connectionInfo.getSSID()); 3236 assertEquals(TEST_BSSID, connectionInfo.getBSSID()); 3237 assertEquals(TEST_NETWORK_ID, connectionInfo.getNetworkId()); 3238 assertEquals(TEST_FQDN, connectionInfo.getPasspointFqdn()); 3239 assertEquals(TEST_FRIENDLY_NAME, connectionInfo.getPasspointProviderFriendlyName()); 3240 } 3241 3242 /** 3243 * Test that configured network list are exposed empty list to an app that does not have the 3244 * appropriate permissions. 3245 */ 3246 @Test testConfiguredNetworkListAreEmptyFromAppWithoutPermission()3247 public void testConfiguredNetworkListAreEmptyFromAppWithoutPermission() throws Exception { 3248 when(mWifiConfigManager.getSavedNetworks(anyInt())) 3249 .thenReturn(TEST_WIFI_CONFIGURATION_LIST); 3250 3251 // no permission = target SDK=Q && not a carrier app 3252 when(mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(anyString())).thenReturn( 3253 TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS); 3254 3255 ParceledListSlice<WifiConfiguration> configs = 3256 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false); 3257 3258 assertEquals(0, configs.getList().size()); 3259 } 3260 3261 /** 3262 * Test that configured network list are exposed empty list to an app that does not have the 3263 * appropriate permissions, when enforceCanAccessScanResults raises a SecurityException. 3264 */ 3265 @Test testConfiguredNetworkListAreEmptyOnSecurityException()3266 public void testConfiguredNetworkListAreEmptyOnSecurityException() throws Exception { 3267 when(mWifiConfigManager.getSavedNetworks(anyInt())) 3268 .thenReturn(TEST_WIFI_CONFIGURATION_LIST); 3269 3270 doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults( 3271 anyString(), nullable(String.class), anyInt(), nullable(String.class)); 3272 3273 ParceledListSlice<WifiConfiguration> configs = 3274 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false); 3275 3276 assertEquals(0, configs.getList().size()); 3277 3278 } 3279 3280 /** 3281 * Test that configured network list are exposed to an app that does have the 3282 * appropriate permissions. 3283 */ 3284 @Test testConfiguredNetworkListAreVisibleFromPermittedApp()3285 public void testConfiguredNetworkListAreVisibleFromPermittedApp() throws Exception { 3286 when(mWifiConfigManager.getSavedNetworks(anyInt())) 3287 .thenReturn(TEST_WIFI_CONFIGURATION_LIST); 3288 3289 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 3290 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 3291 3292 mLooper.startAutoDispatch(); 3293 ParceledListSlice<WifiConfiguration> configs = 3294 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false); 3295 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3296 3297 verify(mWifiConfigManager).getSavedNetworks(eq(WIFI_UID)); 3298 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 3299 TEST_WIFI_CONFIGURATION_LIST, configs.getList()); 3300 } 3301 3302 @Test(expected = SecurityException.class) testGetCallerConfiguredNetworks_ThrowExceptionIfNotDoOrPO()3303 public void testGetCallerConfiguredNetworks_ThrowExceptionIfNotDoOrPO() { 3304 when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 3305 .thenReturn(false); 3306 when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 3307 .thenReturn(false); 3308 3309 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE_NAME, TEST_FEATURE_ID, true); 3310 } 3311 3312 @Test testGetCallerConfiguredNetworks_ReturnsCallerNetworks()3313 public void testGetCallerConfiguredNetworks_ReturnsCallerNetworks() { 3314 final int callerUid = Binder.getCallingUid(); 3315 WifiConfiguration callerNetwork0 = WifiConfigurationTestUtil.generateWifiConfig( 3316 0, callerUid, "\"red\"", true, true, null, null, SECURITY_NONE); 3317 WifiConfiguration callerNetwork1 = WifiConfigurationTestUtil.generateWifiConfig( 3318 1, callerUid, "\"red\"", true, true, null, null, SECURITY_NONE); 3319 WifiConfiguration nonCallerNetwork0 = WifiConfigurationTestUtil.generateWifiConfig( 3320 2, 1200000, "\"blue\"", false, true, null, null, SECURITY_NONE); 3321 WifiConfiguration nonCallerNetwork1 = WifiConfigurationTestUtil.generateWifiConfig( 3322 3, 1100000, "\"cyan\"", true, true, null, null, SECURITY_NONE); 3323 when(mWifiConfigManager.getSavedNetworks(anyInt())).thenReturn(Arrays.asList( 3324 callerNetwork0, callerNetwork1, nonCallerNetwork0, nonCallerNetwork1)); 3325 3326 // Caller does NOT need to have location permission to be able to retrieve its own networks. 3327 doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults( 3328 anyString(), nullable(String.class), anyInt(), nullable(String.class)); 3329 when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 3330 .thenReturn(true); 3331 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 3332 .thenReturn(true); 3333 3334 mLooper.startAutoDispatch(); 3335 ParceledListSlice<WifiConfiguration> configs = 3336 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE_NAME, TEST_FEATURE_ID, true); 3337 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3338 3339 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 3340 Arrays.asList(callerNetwork0, callerNetwork1), configs.getList()); 3341 } 3342 3343 /** 3344 * Test that admin may retrieve all networks but mac address is set to default for networks 3345 * they do not own. 3346 */ 3347 @Test testGetConfiguredNetworksAdmin_ReturnsNetworksWithDefaultMac()3348 public void testGetConfiguredNetworksAdmin_ReturnsNetworksWithDefaultMac() { 3349 final int callerUid = Binder.getCallingUid(); 3350 WifiConfiguration callerNetwork = WifiConfigurationTestUtil.generateWifiConfig( 3351 0, callerUid, "\"red\"", true, true, null, null, SECURITY_NONE); 3352 WifiConfiguration nonCallerNetwork = WifiConfigurationTestUtil.generateWifiConfig( 3353 2, 1200000, "\"blue\"", true, true, null, null, SECURITY_NONE); 3354 callerNetwork.setRandomizedMacAddress(TEST_FACTORY_MAC_ADDR); 3355 3356 when(mWifiConfigManager.getSavedNetworks(callerUid)).thenReturn(Arrays.asList( 3357 callerNetwork, nonCallerNetwork)); 3358 3359 when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 3360 .thenReturn(true); 3361 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 3362 .thenReturn(true); 3363 3364 mLooper.startAutoDispatch(); 3365 ParceledListSlice<WifiConfiguration> configs = 3366 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE_NAME, TEST_FEATURE_ID, false); 3367 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3368 3369 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 3370 Arrays.asList(callerNetwork, nonCallerNetwork), configs.getList()); 3371 3372 for (WifiConfiguration config : configs.getList()) { 3373 if (config.getProfileKey().equals(callerNetwork.getProfileKey())) { 3374 assertEquals(TEST_FACTORY_MAC, config.getRandomizedMacAddress().toString()); 3375 } else { 3376 assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, 3377 config.getRandomizedMacAddress().toString()); 3378 } 3379 } 3380 } 3381 3382 /** 3383 * Test that privileged network list are exposed null to an app that targets T or later and does 3384 * not have nearby devices permission. 3385 */ 3386 @Test testPrivilegedConfiguredNetworkListNullOnSecurityExceptionPostT()3387 public void testPrivilegedConfiguredNetworkListNullOnSecurityExceptionPostT() { 3388 assumeTrue(SdkLevel.isAtLeastT()); 3389 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 3390 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false); 3391 when(mWifiConfigManager.getConfiguredNetworksWithPasswords()) 3392 .thenReturn(TEST_WIFI_CONFIGURATION_LIST); 3393 3394 doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceNearbyDevicesPermission( 3395 any(), anyBoolean(), any()); 3396 3397 mLooper.startAutoDispatch(); 3398 ParceledListSlice<WifiConfiguration> configs = 3399 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, 3400 mExtras); 3401 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3402 3403 assertNull(configs); 3404 } 3405 3406 /** 3407 * Test that privileged network list are exposed null to an app that does not have the 3408 * appropriate permissions, when enforceCanAccessScanResults raises a SecurityException. 3409 */ 3410 @Test testPrivilegedConfiguredNetworkListAreEmptyOnSecurityException()3411 public void testPrivilegedConfiguredNetworkListAreEmptyOnSecurityException() { 3412 when(mWifiConfigManager.getConfiguredNetworksWithPasswords()) 3413 .thenReturn(TEST_WIFI_CONFIGURATION_LIST); 3414 3415 doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults( 3416 anyString(), nullable(String.class), anyInt(), nullable(String.class)); 3417 3418 mLooper.startAutoDispatch(); 3419 ParceledListSlice<WifiConfiguration> configs = 3420 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, 3421 mExtras); 3422 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3423 3424 assertNull(configs); 3425 } 3426 3427 /** 3428 * Test that privileged network list are exposed to an app that does have the 3429 * appropriate permissions (simulated by not throwing an exception for READ_WIFI_CREDENTIAL). 3430 */ 3431 @Test testPrivilegedConfiguredNetworkListAreVisibleFromPermittedApp()3432 public void testPrivilegedConfiguredNetworkListAreVisibleFromPermittedApp() { 3433 when(mWifiConfigManager.getConfiguredNetworksWithPasswords()) 3434 .thenReturn(TEST_WIFI_CONFIGURATION_LIST); 3435 3436 mLooper.startAutoDispatch(); 3437 ParceledListSlice<WifiConfiguration> configs = 3438 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, 3439 mExtras); 3440 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3441 3442 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 3443 TEST_WIFI_CONFIGURATION_LIST, configs.getList()); 3444 } 3445 3446 /** 3447 * Test fetching of scan results. 3448 */ 3449 @Test testGetScanResults()3450 public void testGetScanResults() { 3451 ScanResult[] scanResults = 3452 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0] 3453 .getResults(); 3454 List<ScanResult> scanResultList = 3455 new ArrayList<>(Arrays.asList(scanResults)); 3456 when(mScanRequestProxy.getScanResults()).thenReturn(scanResultList); 3457 3458 String packageName = "test.com"; 3459 String featureId = "test.com.featureId"; 3460 mLooper.startAutoDispatch(); 3461 List<ScanResult> retrievedScanResultList = mWifiServiceImpl.getScanResults(packageName, 3462 featureId).getList(); 3463 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3464 verify(mScanRequestProxy).getScanResults(); 3465 3466 ScanTestUtil.assertScanResultsEquals(scanResults, 3467 retrievedScanResultList.toArray(new ScanResult[retrievedScanResultList.size()])); 3468 } 3469 3470 /** 3471 * Ensure that we handle scan results failure when posting the runnable to handler fails. 3472 */ 3473 @Test testGetScanResultsFailureInRunWithScissors()3474 public void testGetScanResultsFailureInRunWithScissors() { 3475 mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut(); 3476 3477 ScanResult[] scanResults = 3478 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0] 3479 .getResults(); 3480 List<ScanResult> scanResultList = 3481 new ArrayList<>(Arrays.asList(scanResults)); 3482 when(mScanRequestProxy.getScanResults()).thenReturn(scanResultList); 3483 3484 String packageName = "test.com"; 3485 String featureId = "test.com.featureId"; 3486 mLooper.startAutoDispatch(); 3487 List<ScanResult> retrievedScanResultList = mWifiServiceImpl.getScanResults(packageName, 3488 featureId).getList(); 3489 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3490 verify(mScanRequestProxy, never()).getScanResults(); 3491 3492 assertTrue(retrievedScanResultList.isEmpty()); 3493 } 3494 3495 /** 3496 * Test fetching of matching scan results with provided WifiNetworkSuggestion, but it doesn't 3497 * specify the scan results to be filtered. 3498 */ 3499 @Test testGetMatchingScanResultsWithoutSpecifiedScanResults()3500 public void testGetMatchingScanResultsWithoutSpecifiedScanResults() { 3501 ScanResult[] scanResults = 3502 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0] 3503 .getResults(); 3504 List<ScanResult> scanResultList = 3505 new ArrayList<>(Arrays.asList(scanResults)); 3506 when(mScanRequestProxy.getScanResults()).thenReturn(scanResultList); 3507 WifiNetworkSuggestion mockSuggestion = mock(WifiNetworkSuggestion.class); 3508 List<WifiNetworkSuggestion> matchingSuggestions = List.of(mockSuggestion); 3509 Map<WifiNetworkSuggestion, List<ScanResult>> result = Map.of( 3510 mockSuggestion, scanResultList); 3511 when(mWifiNetworkSuggestionsManager.getMatchingScanResults(eq(matchingSuggestions), 3512 eq(scanResultList))).thenReturn(result); 3513 3514 String packageName = "test.com"; 3515 String featureId = "test.com.featureId"; 3516 mLooper.startAutoDispatch(); 3517 Map<WifiNetworkSuggestion, List<ScanResult>> retrievedScanResults = 3518 mWifiServiceImpl.getMatchingScanResults( 3519 new ParceledListSlice<>(matchingSuggestions), 3520 new ParceledListSlice<>(null), packageName, featureId); 3521 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3522 3523 ScanTestUtil.assertScanResultsEquals(scanResults, 3524 retrievedScanResults.get(mockSuggestion) 3525 .toArray(new ScanResult[retrievedScanResults.size()])); 3526 } 3527 3528 /** 3529 * Test fetching of matching scan results with provided WifiNetworkSuggestion and ScanResults. 3530 */ 3531 @Test testGetMatchingScanResultsWithSpecifiedScanResults()3532 public void testGetMatchingScanResultsWithSpecifiedScanResults() { 3533 ScanResult[] scanResults = 3534 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0] 3535 .getResults(); 3536 List<ScanResult> scanResultList = 3537 new ArrayList<>(Arrays.asList(scanResults)); 3538 WifiNetworkSuggestion mockSuggestion = mock(WifiNetworkSuggestion.class); 3539 List<WifiNetworkSuggestion> matchingSuggestions = List.of(mockSuggestion); 3540 Map<WifiNetworkSuggestion, List<ScanResult>> result = Map.of( 3541 mockSuggestion, scanResultList); 3542 3543 when(mWifiNetworkSuggestionsManager.getMatchingScanResults(eq(matchingSuggestions), 3544 eq(scanResultList))).thenReturn(result); 3545 3546 String packageName = "test.com"; 3547 String featureId = "test.com.featureId"; 3548 mLooper.startAutoDispatch(); 3549 Map<WifiNetworkSuggestion, List<ScanResult>> retrievedScanResults = 3550 mWifiServiceImpl.getMatchingScanResults( 3551 new ParceledListSlice<>(matchingSuggestions), 3552 new ParceledListSlice<>(scanResultList), packageName, featureId); 3553 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3554 3555 ScanTestUtil.assertScanResultsEquals(scanResults, 3556 retrievedScanResults.get(mockSuggestion) 3557 .toArray(new ScanResult[retrievedScanResults.size()])); 3558 } 3559 3560 /** 3561 * Ensure that we handle failure when posting the runnable to handler fails. 3562 */ 3563 @Test testGetMatchingScanResultsFailureInRunWithScissors()3564 public void testGetMatchingScanResultsFailureInRunWithScissors() { 3565 mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut(); 3566 3567 ScanResult[] scanResults = 3568 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0] 3569 .getResults(); 3570 List<ScanResult> scanResultList = 3571 new ArrayList<>(Arrays.asList(scanResults)); 3572 when(mScanRequestProxy.getScanResults()).thenReturn(scanResultList); 3573 WifiNetworkSuggestion mockSuggestion = mock(WifiNetworkSuggestion.class); 3574 List<WifiNetworkSuggestion> matchingSuggestions = List.of(mockSuggestion); 3575 Map<WifiNetworkSuggestion, List<ScanResult>> result = Map.of( 3576 mockSuggestion, scanResultList); 3577 3578 when(mWifiNetworkSuggestionsManager.getMatchingScanResults(eq(matchingSuggestions), 3579 eq(scanResultList))).thenReturn(result); 3580 3581 String packageName = "test.com"; 3582 String featureId = "test.com.featureId"; 3583 mLooper.startAutoDispatch(); 3584 Map<WifiNetworkSuggestion, List<ScanResult>> retrievedScanResults = 3585 mWifiServiceImpl.getMatchingScanResults( 3586 new ParceledListSlice<>(matchingSuggestions), null, packageName, featureId); 3587 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3588 3589 assertTrue(retrievedScanResults.isEmpty()); 3590 } 3591 setupLohsPermissions()3592 private void setupLohsPermissions() { 3593 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 3594 when(mFrameworkFacade.isAppForeground(any(), anyInt())).thenReturn(true); 3595 when(mUserManager.hasUserRestrictionForUser( 3596 eq(UserManager.DISALLOW_CONFIG_TETHERING), any())) 3597 .thenReturn(false); 3598 } 3599 registerLOHSRequestFull()3600 private void registerLOHSRequestFull() { 3601 mLooper.startAutoDispatch(); 3602 setupLohsPermissions(); 3603 int result = mWifiServiceImpl.startLocalOnlyHotspot(mLohsCallback, TEST_PACKAGE_NAME, 3604 TEST_FEATURE_ID, null, mExtras, false); 3605 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3606 assertEquals(LocalOnlyHotspotCallback.REQUEST_REGISTERED, result); 3607 verifyCheckChangePermission(TEST_PACKAGE_NAME); 3608 mLooper.dispatchAll(); 3609 } 3610 3611 /** 3612 * Verify that the call to startLocalOnlyHotspot returns REQUEST_REGISTERED when successfully 3613 * called. 3614 */ 3615 @Test testStartLocalOnlyHotspotSingleRegistrationReturnsRequestRegistered()3616 public void testStartLocalOnlyHotspotSingleRegistrationReturnsRequestRegistered() { 3617 registerLOHSRequestFull(); 3618 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), any()); 3619 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 3620 } 3621 3622 /** 3623 * Verify that a call to startLocalOnlyHotspot throws a SecurityException if the caller does not 3624 * have the CHANGE_WIFI_STATE permission. 3625 */ 3626 @Test(expected = SecurityException.class) testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutCorrectPermission()3627 public void testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutCorrectPermission() { 3628 doThrow(new SecurityException()).when(mContext) 3629 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.CHANGE_WIFI_STATE), 3630 eq("WifiService")); 3631 mWifiServiceImpl.startLocalOnlyHotspot( 3632 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3633 } 3634 3635 /** 3636 * Verify that a call to startLocalOnlyHotspot throws a SecurityException if the caller does not 3637 * have Location permission. 3638 */ 3639 @Test(expected = SecurityException.class) testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutLocationPermission()3640 public void testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutLocationPermission() { 3641 doThrow(new SecurityException()) 3642 .when(mWifiPermissionsUtil).enforceLocationPermission(eq(TEST_PACKAGE_NAME), 3643 eq(TEST_FEATURE_ID), 3644 anyInt()); 3645 mWifiServiceImpl.startLocalOnlyHotspot( 3646 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3647 } 3648 3649 /** 3650 * Verify that a call to startLocalOnlyHotspot throws a SecurityException if the caller targets 3651 * Android T or later and does not have nearby devices permission. 3652 */ 3653 @Test(expected = SecurityException.class) testStartLocalOnlyHotspotThrowsExceptionWithoutNearbyDevicesPermissionOnT()3654 public void testStartLocalOnlyHotspotThrowsExceptionWithoutNearbyDevicesPermissionOnT() { 3655 assumeTrue(SdkLevel.isAtLeastT()); 3656 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 3657 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false); 3658 doThrow(new SecurityException()) 3659 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission( 3660 any(), anyBoolean(), any()); 3661 mWifiServiceImpl.startLocalOnlyHotspot( 3662 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3663 } 3664 3665 /** 3666 * Verify that a call to startLocalOnlyHotspot will not check nearby devices permission if the 3667 * caller does not target T. 3668 */ 3669 @Test testStartLocalOnlyHotspotDoesNotCheckNearbyPermissionIfTargetPreT()3670 public void testStartLocalOnlyHotspotDoesNotCheckNearbyPermissionIfTargetPreT() { 3671 assumeTrue(SdkLevel.isAtLeastT()); 3672 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 3673 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 3674 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(true); 3675 mWifiServiceImpl.startLocalOnlyHotspot( 3676 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3677 verify(mWifiPermissionsUtil, never()).enforceNearbyDevicesPermission(any(), anyBoolean(), 3678 any()); 3679 } 3680 3681 /** 3682 * Verify that a call to startLocalOnlyHotspot throws a SecurityException if Location mode is 3683 * disabled. 3684 */ 3685 @Test(expected = SecurityException.class) testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutLocationEnabled()3686 public void testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutLocationEnabled() { 3687 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(false); 3688 mWifiServiceImpl.startLocalOnlyHotspot( 3689 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3690 } 3691 3692 /** 3693 * Only start LocalOnlyHotspot if the caller is the foreground app at the time of the request. 3694 */ 3695 @Test testStartLocalOnlyHotspotFailsIfRequestorNotForegroundApp()3696 public void testStartLocalOnlyHotspotFailsIfRequestorNotForegroundApp() throws Exception { 3697 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 3698 3699 when(mFrameworkFacade.isAppForeground(any(), anyInt())).thenReturn(false); 3700 int result = mWifiServiceImpl.startLocalOnlyHotspot( 3701 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3702 assertEquals(LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE, result); 3703 } 3704 3705 /** 3706 * Only start tethering if we are not tethering. 3707 */ 3708 @Test testTetheringDoesNotStartWhenAlreadyTetheringActive()3709 public void testTetheringDoesNotStartWhenAlreadyTetheringActive() throws Exception { 3710 WifiConfiguration config = createValidWifiApConfiguration(); 3711 mLooper.startAutoDispatch(); 3712 assertTrue(mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME)); 3713 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3714 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 3715 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 3716 WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp( 3717 config, 3718 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration().toWifiConfiguration()); 3719 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 3720 mStateMachineSoftApCallback.onStateChanged( 3721 new SoftApState(WIFI_AP_STATE_ENABLED, 0, 3722 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 3723 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED); 3724 mLooper.dispatchAll(); 3725 assertEquals(WIFI_AP_STATE_ENABLED, mWifiServiceImpl.getWifiApEnabledState()); 3726 reset(mActiveModeWarden); 3727 3728 // Start another session without a stop, that should fail. 3729 mLooper.startAutoDispatch(); 3730 assertFalse(mWifiServiceImpl.startSoftAp( 3731 createValidWifiApConfiguration(), TEST_PACKAGE_NAME)); 3732 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3733 3734 verifyNoMoreInteractions(mActiveModeWarden); 3735 } 3736 3737 /** 3738 * Only start tethering if we are not tethering in new API: startTetheredHotspot. 3739 */ 3740 @Test testStartTetheredHotspotDoesNotStartWhenAlreadyTetheringActive()3741 public void testStartTetheredHotspotDoesNotStartWhenAlreadyTetheringActive() throws Exception { 3742 SoftApConfiguration config = createValidSoftApConfiguration(); 3743 assertTrue(mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME)); 3744 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 3745 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 3746 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 3747 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 3748 mStateMachineSoftApCallback.onStateChanged( 3749 new SoftApState(WIFI_AP_STATE_ENABLED, 0, 3750 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 3751 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED); 3752 mLooper.dispatchAll(); 3753 assertEquals(WIFI_AP_STATE_ENABLED, mWifiServiceImpl.getWifiApEnabledState()); 3754 reset(mActiveModeWarden); 3755 3756 // Start another session without a stop, that should fail. 3757 assertFalse(mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME)); 3758 3759 verifyNoMoreInteractions(mActiveModeWarden); 3760 } 3761 3762 /** 3763 * Verify startTetheredHotspotRequest fails if we are already tethering. 3764 */ 3765 @Test testStartTetheredHotspotRequestDoesNotStartWhenAlreadyTetheringActive()3766 public void testStartTetheredHotspotRequestDoesNotStartWhenAlreadyTetheringActive() 3767 throws Exception { 3768 SoftApConfiguration config = createValidSoftApConfiguration(); 3769 assertTrue(mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME)); 3770 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), 3771 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 3772 assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration()); 3773 assertNull(mSoftApModeConfigCaptor.getValue().getTetheringRequest()); 3774 mStateMachineSoftApCallback.onStateChanged( 3775 new SoftApState(WIFI_AP_STATE_ENABLED, 0, 3776 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 3777 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED); 3778 mLooper.dispatchAll(); 3779 assertEquals(WIFI_AP_STATE_ENABLED, mWifiServiceImpl.getWifiApEnabledState()); 3780 reset(mActiveModeWarden); 3781 3782 // Start another session without a stop, that should fail. 3783 mWifiServiceImpl.startTetheredHotspotRequest(TEST_TETHERING_REQUEST, mClientSoftApCallback, 3784 TEST_PACKAGE_NAME); 3785 verify(mClientSoftApCallback).onStateChanged(eq(new SoftApState(WIFI_AP_STATE_FAILED, 3786 SAP_START_FAILURE_GENERAL, TEST_TETHERING_REQUEST, null))); 3787 3788 verifyNoMoreInteractions(mActiveModeWarden); 3789 } 3790 3791 /** 3792 * Only start LocalOnlyHotspot if we are not tethering. 3793 */ 3794 @Test testHotspotDoesNotStartWhenAlreadyTethering()3795 public void testHotspotDoesNotStartWhenAlreadyTethering() throws Exception { 3796 WifiConfiguration config = createValidWifiApConfiguration(); 3797 mLooper.startAutoDispatch(); 3798 assertTrue(mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME)); 3799 mStateMachineSoftApCallback.onStateChanged( 3800 new SoftApState(WIFI_AP_STATE_ENABLED, 0, 3801 TEST_TETHERING_REQUEST, TEST_IFACE_NAME)); 3802 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED); 3803 mLooper.stopAutoDispatchAndIgnoreExceptions(); 3804 3805 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 3806 when(mFrameworkFacade.isAppForeground(any(), anyInt())).thenReturn(true); 3807 mLooper.dispatchAll(); 3808 int returnCode = mWifiServiceImpl.startLocalOnlyHotspot( 3809 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3810 assertEquals(ERROR_INCOMPATIBLE_MODE, returnCode); 3811 } 3812 3813 /** 3814 * Only start LocalOnlyHotspot if admin setting does not disallow tethering. 3815 */ 3816 @Test testHotspotDoesNotStartWhenTetheringDisallowed()3817 public void testHotspotDoesNotStartWhenTetheringDisallowed() throws Exception { 3818 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 3819 when(mFrameworkFacade.isAppForeground(any(), anyInt())).thenReturn(true); 3820 when(mUserManager.hasUserRestrictionForUser( 3821 eq(UserManager.DISALLOW_CONFIG_TETHERING), any())) 3822 .thenReturn(true); 3823 int returnCode = mWifiServiceImpl.startLocalOnlyHotspot( 3824 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3825 assertEquals(ERROR_TETHERING_DISALLOWED, returnCode); 3826 } 3827 3828 /** 3829 * Verify that callers can only have one registered LOHS request. 3830 */ 3831 @Test(expected = IllegalStateException.class) testStartLocalOnlyHotspotThrowsExceptionWhenCallerAlreadyRegistered()3832 public void testStartLocalOnlyHotspotThrowsExceptionWhenCallerAlreadyRegistered() { 3833 registerLOHSRequestFull(); 3834 3835 // now do the second request that will fail 3836 mWifiServiceImpl.startLocalOnlyHotspot( 3837 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 3838 } 3839 3840 /** 3841 * Verify that the call to stopLocalOnlyHotspot does not do anything when there aren't any 3842 * registered callers. 3843 */ 3844 @Test testStopLocalOnlyHotspotDoesNothingWithoutRegisteredRequests()3845 public void testStopLocalOnlyHotspotDoesNothingWithoutRegisteredRequests() throws Exception { 3846 // allow test to proceed without a permission check failure 3847 mWifiServiceImpl.stopLocalOnlyHotspot(); 3848 mLooper.dispatchAll(); 3849 // there is nothing registered, so this shouldn't do anything 3850 verify(mActiveModeWarden, never()).stopSoftAp(anyInt()); 3851 } 3852 3853 /** 3854 * Verify that the call to stopLocalOnlyHotspot does not do anything when one caller unregisters 3855 * but there is still an active request 3856 */ 3857 @Test testStopLocalOnlyHotspotDoesNothingWithRemainingRequest()3858 public void testStopLocalOnlyHotspotDoesNothingWithRemainingRequest() throws Exception { 3859 // register a request that will remain after the stopLOHS call 3860 mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo); 3861 mLooper.dispatchAll(); 3862 setupLocalOnlyHotspot(); 3863 // Since we are calling with the same pid, the second register call will be removed 3864 mWifiServiceImpl.stopLocalOnlyHotspot(); 3865 mLooper.dispatchAll(); 3866 // there is still a valid registered request - do not tear down LOHS 3867 verify(mActiveModeWarden, never()).stopSoftAp(anyInt()); 3868 } 3869 3870 /** 3871 * Verify that the call to stopLocalOnlyHotspot sends a message to WifiController to stop 3872 * the softAp when there is one registered caller when that caller is removed. 3873 */ 3874 @Test testStopLocalOnlyHotspotTriggersStopWithOneRegisteredRequest()3875 public void testStopLocalOnlyHotspotTriggersStopWithOneRegisteredRequest() throws Exception { 3876 setupLocalOnlyHotspot(); 3877 3878 verify(mActiveModeWarden).startSoftAp(any(), any()); 3879 3880 mWifiServiceImpl.stopLocalOnlyHotspot(); 3881 mLooper.dispatchAll(); 3882 3883 // No permission check required for change_wifi_state. 3884 verify(mContext, never()).enforceCallingOrSelfPermission( 3885 eq("android.Manifest.permission.CHANGE_WIFI_STATE"), anyString()); 3886 3887 // there is was only one request registered, we should tear down LOHS 3888 verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY); 3889 } 3890 3891 /** 3892 * Verify that by default startLocalOnlyHotspot starts access point at 2 GHz. 3893 */ 3894 @Test testStartLocalOnlyHotspotAt2Ghz()3895 public void testStartLocalOnlyHotspotAt2Ghz() { 3896 SoftApConfiguration lohsConfig = createValidSoftApConfiguration(); 3897 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 3898 eq(mContext), eq(null), any(), eq(false))).thenReturn(lohsConfig); 3899 registerLOHSRequestFull(); 3900 verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig( 3901 eq(mContext), eq(null), any(), eq(false)); 3902 verifyLohsBand(SoftApConfiguration.BAND_2GHZ); 3903 } 3904 verifyLohsBand(int expectedBand)3905 private void verifyLohsBand(int expectedBand) { 3906 verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), any()); 3907 final SoftApConfiguration configuration = 3908 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration(); 3909 assertNotNull(configuration); 3910 assertEquals(expectedBand, configuration.getBand()); 3911 } 3912 3913 private static class FakeLohsCallback extends ILocalOnlyHotspotCallback.Stub { 3914 boolean mIsStarted = false; 3915 SoftApConfiguration mSoftApConfig = null; 3916 3917 @Override onHotspotStarted(SoftApConfiguration softApConfig)3918 public void onHotspotStarted(SoftApConfiguration softApConfig) { 3919 mIsStarted = true; 3920 this.mSoftApConfig = softApConfig; 3921 } 3922 3923 @Override onHotspotStopped()3924 public void onHotspotStopped() { 3925 mIsStarted = false; 3926 mSoftApConfig = null; 3927 } 3928 3929 @Override onHotspotFailed(int i)3930 public void onHotspotFailed(int i) { 3931 mIsStarted = false; 3932 mSoftApConfig = null; 3933 } 3934 } 3935 setupForCustomLohs()3936 private void setupForCustomLohs() { 3937 setupLohsPermissions(); 3938 when(mContext.checkPermission(eq(Manifest.permission.NETWORK_SETUP_WIZARD), 3939 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 3940 setupWardenForCustomLohs(); 3941 } 3942 setupWardenForCustomLohs()3943 private void setupWardenForCustomLohs() { 3944 doAnswer(invocation -> { 3945 changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR); 3946 mWifiServiceImpl.updateInterfaceIpState(mLohsInterfaceName, IFACE_IP_MODE_LOCAL_ONLY); 3947 return null; 3948 }).when(mActiveModeWarden).startSoftAp(any(), any()); 3949 } 3950 3951 @Test(expected = SecurityException.class) testCustomLohs_FailsWithoutPermission()3952 public void testCustomLohs_FailsWithoutPermission() { 3953 SoftApConfiguration.Builder customConfigBuilder = new SoftApConfiguration.Builder() 3954 .setSsid("customConfig"); 3955 if (Environment.isSdkAtLeastB()) { 3956 customConfigBuilder.setUserConfiguration(false); 3957 } 3958 // set up basic permissions, but not NETWORK_SETUP_WIZARD 3959 setupLohsPermissions(); 3960 setupWardenForCustomLohs(); 3961 mWifiServiceImpl.startLocalOnlyHotspot(mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, 3962 customConfigBuilder.build(), mExtras, true); 3963 } 3964 nopDeathCallback(LocalOnlyHotspotRequestInfo requestor)3965 private static void nopDeathCallback(LocalOnlyHotspotRequestInfo requestor) { 3966 } 3967 3968 @Test testCustomLohs_ExclusiveAfterShared()3969 public void testCustomLohs_ExclusiveAfterShared() { 3970 mLooper.startAutoDispatch(); 3971 FakeLohsCallback sharedCallback = new FakeLohsCallback(); 3972 FakeLohsCallback exclusiveCallback = new FakeLohsCallback(); 3973 SoftApConfiguration exclusiveConfig = new SoftApConfiguration.Builder() 3974 .setSsid("customSsid") 3975 .build(); 3976 3977 setupForCustomLohs(); 3978 mWifiServiceImpl.registerLOHSForTest(TEST_PID, 3979 new LocalOnlyHotspotRequestInfo(mLooper.getLooper(), new WorkSource(), 3980 sharedCallback, WifiServiceImplTest::nopDeathCallback, null)); 3981 assertThat(mWifiServiceImpl.startLocalOnlyHotspot(exclusiveCallback, TEST_PACKAGE_NAME, 3982 TEST_FEATURE_ID, exclusiveConfig, mExtras, true)).isEqualTo(ERROR_GENERIC); 3983 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 3984 assertThat(sharedCallback.mIsStarted).isTrue(); 3985 assertThat(exclusiveCallback.mIsStarted).isFalse(); 3986 } 3987 3988 @Test testCustomLohs_ExclusiveBeforeShared()3989 public void testCustomLohs_ExclusiveBeforeShared() { 3990 when(mWorkSourceHelper.getRequestorWsPriority()) 3991 .thenReturn(WorkSourceHelper.PRIORITY_SYSTEM); 3992 mLooper.startAutoDispatch(); 3993 FakeLohsCallback sharedCallback = new FakeLohsCallback(); 3994 FakeLohsCallback exclusiveCallback = new FakeLohsCallback(); 3995 SoftApConfiguration exclusiveConfig = new SoftApConfiguration.Builder() 3996 .setSsid("customSsid") 3997 .build(); 3998 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 3999 eq(mContext), eq(exclusiveConfig), any(), eq(true))).thenReturn(exclusiveConfig); 4000 setupForCustomLohs(); 4001 mWifiServiceImpl.registerLOHSForTest(TEST_PID, 4002 new LocalOnlyHotspotRequestInfo(mLooper.getLooper(), new WorkSource(), 4003 exclusiveCallback, WifiServiceImplTest::nopDeathCallback, exclusiveConfig)); 4004 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 4005 assertThat(mWifiServiceImpl.startLocalOnlyHotspot(sharedCallback, TEST_PACKAGE_NAME, 4006 TEST_FEATURE_ID, null, mExtras, false)).isEqualTo(ERROR_GENERIC); 4007 assertThat(exclusiveCallback.mIsStarted).isTrue(); 4008 assertThat(sharedCallback.mIsStarted).isFalse(); 4009 } 4010 4011 @Test testCustomLohs_Wpa2()4012 public void testCustomLohs_Wpa2() { 4013 SoftApConfiguration config = new SoftApConfiguration.Builder() 4014 .setSsid("customSsid") 4015 .setPassphrase("passphrase", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 4016 .build(); 4017 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 4018 eq(mContext), eq(config), any(), eq(true))).thenReturn(config); 4019 FakeLohsCallback callback = new FakeLohsCallback(); 4020 mLooper.startAutoDispatch(); 4021 setupForCustomLohs(); 4022 assertThat( 4023 mWifiServiceImpl.startLocalOnlyHotspot(callback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, 4024 config, mExtras, true)).isEqualTo(REQUEST_REGISTERED); 4025 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 4026 verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig( 4027 eq(mContext), eq(config), any(), eq(true)); 4028 // Use app's worksouce. 4029 verify(mActiveModeWarden).startSoftAp(any(), 4030 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 4031 assertThat(callback.mIsStarted).isTrue(); 4032 assertThat(callback.mSoftApConfig.getWifiSsid().getUtf8Text()).isEqualTo("customSsid"); 4033 assertThat(callback.mSoftApConfig.getSecurityType()) 4034 .isEqualTo(SoftApConfiguration.SECURITY_TYPE_WPA2_PSK); 4035 assertThat(callback.mSoftApConfig.getPassphrase()).isEqualTo("passphrase"); 4036 } 4037 4038 @Test testCustomLohs_Open()4039 public void testCustomLohs_Open() { 4040 SoftApConfiguration config = new SoftApConfiguration.Builder() 4041 .setSsid("customSsid") 4042 .build(); 4043 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 4044 eq(mContext), eq(config), any(), eq(true))).thenReturn(config); 4045 FakeLohsCallback callback = new FakeLohsCallback(); 4046 mLooper.startAutoDispatch(); 4047 setupForCustomLohs(); 4048 assertThat( 4049 mWifiServiceImpl.startLocalOnlyHotspot(callback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, 4050 config, mExtras, true)).isEqualTo(REQUEST_REGISTERED); 4051 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 4052 verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig( 4053 eq(mContext), eq(config), any(), eq(true)); 4054 // Use app's worksouce. 4055 verify(mActiveModeWarden).startSoftAp(any(), 4056 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 4057 assertThat(callback.mIsStarted).isTrue(); 4058 assertThat(callback.mSoftApConfig.getWifiSsid().getUtf8Text()).isEqualTo("customSsid"); 4059 assertThat(callback.mSoftApConfig.getSecurityType()) 4060 .isEqualTo(SoftApConfiguration.SECURITY_TYPE_OPEN); 4061 assertThat(callback.mSoftApConfig.getPassphrase()).isNull(); 4062 } 4063 4064 @Test testCustomLohs_GeneratesSsidIfAbsent()4065 public void testCustomLohs_GeneratesSsidIfAbsent() { 4066 SoftApConfiguration lohsConfig = createValidSoftApConfiguration(); 4067 SoftApConfiguration customizedConfig = new SoftApConfiguration.Builder() 4068 .setPassphrase("passphrase", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 4069 .build(); 4070 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 4071 eq(mContext), eq(customizedConfig), any(), eq(true))) 4072 .thenReturn(lohsConfig); 4073 mLooper.startAutoDispatch(); 4074 FakeLohsCallback callback = new FakeLohsCallback(); 4075 4076 setupForCustomLohs(); 4077 assertThat( 4078 mWifiServiceImpl.startLocalOnlyHotspot(callback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, 4079 customizedConfig, mExtras, true)).isEqualTo(REQUEST_REGISTERED); 4080 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 4081 verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig( 4082 eq(mContext), eq(customizedConfig), any(), eq(true)); 4083 // Use app's worksouce. 4084 verify(mActiveModeWarden).startSoftAp(any(), 4085 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 4086 assertThat(callback.mIsStarted).isTrue(); 4087 assertThat(callback.mSoftApConfig.getWifiSsid()).isNotNull(); 4088 } 4089 4090 @Test testCustomLohs_ForwardsBssid()4091 public void testCustomLohs_ForwardsBssid() { 4092 mLooper.startAutoDispatch(); 4093 SoftApConfiguration lohsConfig = createValidSoftApConfiguration(); 4094 SoftApConfiguration.Builder customizedConfigBuilder = 4095 new SoftApConfiguration.Builder(lohsConfig) 4096 .setBssid(MacAddress.fromString("aa:bb:cc:dd:ee:ff")); 4097 if (SdkLevel.isAtLeastS()) { 4098 customizedConfigBuilder.setMacRandomizationSetting( 4099 SoftApConfiguration.RANDOMIZATION_NONE); 4100 } 4101 SoftApConfiguration customizedConfig = customizedConfigBuilder.build(); 4102 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 4103 eq(mContext), eq(customizedConfig), any(), eq(true))) 4104 .thenReturn(customizedConfig); 4105 FakeLohsCallback callback = new FakeLohsCallback(); 4106 4107 setupForCustomLohs(); 4108 assertThat( 4109 mWifiServiceImpl.startLocalOnlyHotspot(callback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, 4110 customizedConfig, mExtras, true)).isEqualTo(REQUEST_REGISTERED); 4111 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 4112 4113 // Use app's worksouce. 4114 verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig( 4115 eq(mContext), eq(customizedConfig), any(), eq(true)); 4116 verify(mActiveModeWarden).startSoftAp(any(), 4117 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 4118 assertThat(callback.mIsStarted).isTrue(); 4119 assertThat(callback.mSoftApConfig.getBssid().toString()) 4120 .ignoringCase().isEqualTo("aa:bb:cc:dd:ee:ff"); 4121 } 4122 4123 /** 4124 * Verify that WifiServiceImpl does not send the stop ap message if there were no 4125 * pending LOHS requests upon a binder death callback. 4126 */ 4127 @Test testServiceImplNotCalledWhenBinderDeathTriggeredNoRequests()4128 public void testServiceImplNotCalledWhenBinderDeathTriggeredNoRequests() { 4129 LocalOnlyRequestorCallback binderDeathCallback = 4130 mWifiServiceImpl.new LocalOnlyRequestorCallback(); 4131 4132 binderDeathCallback.onLocalOnlyHotspotRequestorDeath(mRequestInfo); 4133 verify(mActiveModeWarden, never()).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY); 4134 } 4135 4136 /** 4137 * Verify that WifiServiceImpl does not send the stop ap message if there are remaining 4138 * registered LOHS requests upon a binder death callback. Additionally verify that softap mode 4139 * will be stopped if that remaining request is removed (to verify the binder death properly 4140 * cleared the requestor that died). 4141 */ 4142 @Test testServiceImplNotCalledWhenBinderDeathTriggeredWithRequests()4143 public void testServiceImplNotCalledWhenBinderDeathTriggeredWithRequests() throws Exception { 4144 LocalOnlyRequestorCallback binderDeathCallback = 4145 mWifiServiceImpl.new LocalOnlyRequestorCallback(); 4146 4147 // registering a request directly from the test will not trigger a message to start 4148 // softap mode 4149 mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo); 4150 mLooper.dispatchAll(); 4151 4152 setupLocalOnlyHotspot(); 4153 4154 binderDeathCallback.onLocalOnlyHotspotRequestorDeath(mRequestInfo); 4155 mLooper.dispatchAll(); 4156 verify(mActiveModeWarden, never()).stopSoftAp(anyInt()); 4157 4158 reset(mActiveModeWarden); 4159 4160 // now stop as the second request and confirm CMD_SET_AP will be sent to make sure binder 4161 // death requestor was removed 4162 mWifiServiceImpl.stopLocalOnlyHotspot(); 4163 mLooper.dispatchAll(); 4164 verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY); 4165 } 4166 4167 /** 4168 * Verify that a call to registerSoftApCallback throws a SecurityException if the caller does 4169 * not have neither NETWORK_SETTINGS nor MAINLINE_NETWORK_STACK permission. 4170 */ 4171 @Test(expected = SecurityException.class) registerSoftApCallbackThrowsSecurityExceptionOnMissingPermissions()4172 public void registerSoftApCallbackThrowsSecurityExceptionOnMissingPermissions() { 4173 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 4174 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 4175 when(mContext.checkPermission(eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), 4176 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 4177 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false); 4178 mWifiServiceImpl.registerSoftApCallback(mClientSoftApCallback); 4179 } 4180 4181 /** 4182 * Verify that a call to registerSoftApCallback throws an IllegalArgumentException if the 4183 * parameters are not provided. 4184 */ 4185 @Test registerSoftApCallbackThrowsIllegalArgumentExceptionOnInvalidArguments()4186 public void registerSoftApCallbackThrowsIllegalArgumentExceptionOnInvalidArguments() { 4187 try { 4188 mWifiServiceImpl.registerSoftApCallback(null); 4189 fail("expected IllegalArgumentException"); 4190 } catch (IllegalArgumentException expected) { 4191 } 4192 } 4193 4194 /** 4195 * Verify that a call to unregisterSoftApCallback throws a SecurityException if the caller does 4196 * not have neither NETWORK_SETTINGS nor MAINLINE_NETWORK_STACK permission. 4197 */ 4198 @Test(expected = SecurityException.class) unregisterSoftApCallbackThrowsSecurityExceptionOnMissingPermissions()4199 public void unregisterSoftApCallbackThrowsSecurityExceptionOnMissingPermissions() { 4200 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 4201 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 4202 when(mContext.checkPermission(eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), 4203 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 4204 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false); 4205 mWifiServiceImpl.unregisterSoftApCallback(mClientSoftApCallback); 4206 } 4207 4208 /** 4209 * Verifies that we handle softap callback registration failure if we encounter an exception 4210 * while linking to death. 4211 */ 4212 @Test registerSoftApCallbackFailureOnLinkToDeath()4213 public void registerSoftApCallbackFailureOnLinkToDeath() throws Exception { 4214 doThrow(new RemoteException()) 4215 .when(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt()); 4216 mWifiServiceImpl.registerSoftApCallback(mClientSoftApCallback); 4217 mLooper.dispatchAll(); 4218 verify(mClientSoftApCallback, never()).onStateChanged(any()); 4219 verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged( 4220 any(), any(), anyBoolean(), anyBoolean()); 4221 verify(mClientSoftApCallback, never()).onCapabilityChanged(any()); 4222 } 4223 4224 /** 4225 * Registers a soft AP callback, then verifies that the current soft AP state and num clients 4226 * are sent to caller immediately after callback is registered. 4227 */ registerSoftApCallbackAndVerify(ISoftApCallback callback)4228 private void registerSoftApCallbackAndVerify(ISoftApCallback callback) throws Exception { 4229 mWifiServiceImpl.registerSoftApCallback(callback); 4230 mLooper.dispatchAll(); 4231 verify(callback).onStateChanged( 4232 eq(new SoftApState(WIFI_AP_STATE_DISABLED, 0, null, null))); 4233 verify(callback).onConnectedClientsOrInfoChanged(new HashMap<String, SoftApInfo>(), 4234 new HashMap<String, List<WifiClient>>(), false, true); 4235 verify(callback).onCapabilityChanged(ApConfigUtil.updateCapabilityFromResource(mContext)); 4236 // Don't need to invoke callback when register. 4237 verify(callback, never()).onBlockedClientConnecting(any(), anyInt()); 4238 } 4239 4240 /** 4241 * Verify that unregisterSoftApCallback removes callback from registered callbacks list 4242 */ 4243 @Test unregisterSoftApCallbackRemovesCallback()4244 public void unregisterSoftApCallbackRemovesCallback() throws Exception { 4245 registerSoftApCallbackAndVerify(mClientSoftApCallback); 4246 4247 mWifiServiceImpl.unregisterSoftApCallback(mClientSoftApCallback); 4248 mLooper.dispatchAll(); 4249 4250 reset(mClientSoftApCallback); 4251 mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged( 4252 mTestSoftApInfos, mTestSoftApClients, false); 4253 mLooper.dispatchAll(); 4254 verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged( 4255 any(), any(), anyBoolean(), anyBoolean()); 4256 } 4257 4258 /** 4259 * Verify that unregisterSoftApCallback is no-op if callback not registered. 4260 */ 4261 @Test unregisterSoftApCallbackDoesNotRemoveCallbackIfCallbackNotMatching()4262 public void unregisterSoftApCallbackDoesNotRemoveCallbackIfCallbackNotMatching() 4263 throws Exception { 4264 registerSoftApCallbackAndVerify(mClientSoftApCallback); 4265 4266 mWifiServiceImpl.unregisterSoftApCallback(mAnotherSoftApCallback); 4267 mLooper.dispatchAll(); 4268 mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged( 4269 mTestSoftApInfos, mTestSoftApClients, false); 4270 mLooper.dispatchAll(); 4271 verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged( 4272 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(false)); 4273 } 4274 4275 /** 4276 * Registers two callbacks, remove one then verify the right callback is being called on events. 4277 */ 4278 @Test correctCallbackIsCalledAfterAddingTwoCallbacksAndRemovingOne()4279 public void correctCallbackIsCalledAfterAddingTwoCallbacksAndRemovingOne() throws Exception { 4280 WifiClient testWifiClient = new WifiClient(MacAddress.fromString("22:33:44:55:66:77"), 4281 WIFI_IFACE_NAME2); 4282 mWifiServiceImpl.registerSoftApCallback(mClientSoftApCallback); 4283 mLooper.dispatchAll(); 4284 4285 reset(mClientSoftApCallback); 4286 when(mClientSoftApCallback.asBinder()).thenReturn(mAppBinder); 4287 // Change state from default before registering the second callback 4288 SoftApState state = new SoftApState(WIFI_AP_STATE_ENABLED, 0, 4289 TEST_TETHERING_REQUEST, TEST_IFACE_NAME); 4290 mStateMachineSoftApCallback.onStateChanged(state); 4291 mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged( 4292 mTestSoftApInfos, mTestSoftApClients, false); 4293 mStateMachineSoftApCallback.onBlockedClientConnecting(testWifiClient, 0); 4294 4295 4296 // Register another callback and verify the new state is returned in the immediate callback 4297 mWifiServiceImpl.registerSoftApCallback(mAnotherSoftApCallback); 4298 mLooper.dispatchAll(); 4299 verify(mAnotherSoftApCallback).onStateChanged(eq(state)); 4300 verify(mAnotherSoftApCallback).onConnectedClientsOrInfoChanged( 4301 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(true)); 4302 // Verify only first callback will receive onBlockedClientConnecting since it call after 4303 // first callback register but before another callback register. 4304 verify(mClientSoftApCallback).onBlockedClientConnecting(testWifiClient, 0); 4305 verify(mAnotherSoftApCallback, never()).onBlockedClientConnecting(testWifiClient, 0); 4306 4307 // unregister the fisrt callback 4308 mWifiServiceImpl.unregisterSoftApCallback(mClientSoftApCallback); 4309 mLooper.dispatchAll(); 4310 4311 // Update soft AP state and verify the remaining callback receives the event 4312 state = new SoftApState( 4313 WIFI_AP_STATE_FAILED, SAP_START_FAILURE_NO_CHANNEL, 4314 TEST_TETHERING_REQUEST, TEST_IFACE_NAME); 4315 mStateMachineSoftApCallback.onStateChanged(state); 4316 mLooper.dispatchAll(); 4317 verify(mClientSoftApCallback, never()).onStateChanged(eq(state)); 4318 verify(mAnotherSoftApCallback).onStateChanged(eq(state)); 4319 } 4320 4321 /** 4322 * Verify that wifi service registers for callers BinderDeath event 4323 */ 4324 @Test registersForBinderDeathOnRegisterSoftApCallback()4325 public void registersForBinderDeathOnRegisterSoftApCallback() throws Exception { 4326 registerSoftApCallbackAndVerify(mClientSoftApCallback); 4327 verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt()); 4328 } 4329 4330 /** 4331 * Verify that we un-register the soft AP callback on receiving BinderDied event. 4332 */ 4333 @Test unregistersSoftApCallbackOnBinderDied()4334 public void unregistersSoftApCallbackOnBinderDied() throws Exception { 4335 ArgumentCaptor<IBinder.DeathRecipient> drCaptor = 4336 ArgumentCaptor.forClass(IBinder.DeathRecipient.class); 4337 registerSoftApCallbackAndVerify(mClientSoftApCallback); 4338 verify(mAppBinder).linkToDeath(drCaptor.capture(), anyInt()); 4339 4340 drCaptor.getValue().binderDied(); 4341 mLooper.dispatchAll(); 4342 reset(mClientSoftApCallback); 4343 // Verify callback is removed from the list as well 4344 Map<String, List<WifiClient>> mTestSoftApClients = mock(Map.class); 4345 Map<String, SoftApInfo> mTestSoftApInfos = mock(Map.class); 4346 mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged( 4347 mTestSoftApInfos, mTestSoftApClients, false); 4348 mLooper.dispatchAll(); 4349 verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged( 4350 any(), any(), anyBoolean(), anyBoolean()); 4351 } 4352 4353 /** 4354 * Verify that soft AP callback is called on NumClientsChanged event 4355 */ 4356 @Test callsRegisteredCallbacksOnConnectedClientsChangedEvent()4357 public void callsRegisteredCallbacksOnConnectedClientsChangedEvent() throws Exception { 4358 registerSoftApCallbackAndVerify(mClientSoftApCallback); 4359 4360 mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged( 4361 mTestSoftApInfos, mTestSoftApClients, false); 4362 mLooper.dispatchAll(); 4363 verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged( 4364 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(false)); 4365 } 4366 4367 /** 4368 * Verify that soft AP callback is called on SoftApStateChanged event 4369 */ 4370 @Test callsRegisteredCallbacksOnSoftApStateChangedEvent()4371 public void callsRegisteredCallbacksOnSoftApStateChangedEvent() throws Exception { 4372 registerSoftApCallbackAndVerify(mClientSoftApCallback); 4373 4374 SoftApState state = new SoftApState( 4375 WIFI_AP_STATE_ENABLED, 0, 4376 TEST_TETHERING_REQUEST, TEST_IFACE_NAME); 4377 mStateMachineSoftApCallback.onStateChanged(state); 4378 mLooper.dispatchAll(); 4379 verify(mClientSoftApCallback).onStateChanged(eq(state)); 4380 } 4381 4382 /** 4383 * Verify that soft AP callback is called on ClientsDisconnected event 4384 */ 4385 @Test callsRegisteredCallbacksOnClientsDisconnectedEvent()4386 public void callsRegisteredCallbacksOnClientsDisconnectedEvent() throws Exception { 4387 List<WifiClient> testClients = new ArrayList<>(); 4388 registerSoftApCallbackAndVerify(mClientSoftApCallback); 4389 4390 mStateMachineSoftApCallback.onClientsDisconnected(mTestSoftApInfo, testClients); 4391 mLooper.dispatchAll(); 4392 verify(mClientSoftApCallback).onClientsDisconnected(eq(mTestSoftApInfo), eq(testClients)); 4393 } 4394 4395 /** 4396 * Verify that mSoftApState and mSoftApNumClients in WifiServiceImpl are being updated on soft 4397 * Ap events, even when no callbacks are registered. 4398 */ 4399 @Test updatesSoftApStateAndConnectedClientsOnSoftApEvents()4400 public void updatesSoftApStateAndConnectedClientsOnSoftApEvents() throws Exception { 4401 WifiClient testWifiClient = new WifiClient(MacAddress.fromString("22:33:44:55:66:77"), 4402 WIFI_IFACE_NAME2); 4403 SoftApState state = new SoftApState(WIFI_AP_STATE_ENABLED, 0, 4404 TEST_TETHERING_REQUEST, TEST_IFACE_NAME); 4405 mStateMachineSoftApCallback.onStateChanged(state); 4406 mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged( 4407 mTestSoftApInfos, mTestSoftApClients, false); 4408 mStateMachineSoftApCallback.onBlockedClientConnecting(testWifiClient, 0); 4409 4410 // Register callback after num clients and soft AP are changed. 4411 mWifiServiceImpl.registerSoftApCallback(mClientSoftApCallback); 4412 mLooper.dispatchAll(); 4413 verify(mClientSoftApCallback).onStateChanged(eq(state)); 4414 verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged( 4415 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(true)); 4416 // Don't need to invoke callback when register. 4417 verify(mClientSoftApCallback, never()).onBlockedClientConnecting(any(), anyInt()); 4418 } 4419 4420 private class IntentFilterMatcher implements ArgumentMatcher<IntentFilter> { 4421 @Override matches(IntentFilter filter)4422 public boolean matches(IntentFilter filter) { 4423 return filter.hasAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); 4424 } 4425 } 4426 4427 /** 4428 * Verify that onFailed is called for registered LOHS callers on SAP_START_FAILURE_GENERAL. 4429 */ 4430 @Test testRegisteredCallbacksTriggeredOnSoftApFailureGeneric()4431 public void testRegisteredCallbacksTriggeredOnSoftApFailureGeneric() throws Exception { 4432 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 4433 mWifiServiceImpl.checkAndStartWifi(); 4434 mLooper.dispatchAll(); 4435 4436 verifyApRegistration(); 4437 4438 registerLOHSRequestFull(); 4439 4440 changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_DISABLED, SAP_START_FAILURE_GENERAL); 4441 mLooper.dispatchAll(); 4442 4443 verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC); 4444 } 4445 4446 /** 4447 * Verify that onFailed is called for registered LOHS callers on SAP_START_FAILURE_NO_CHANNEL. 4448 */ 4449 @Test testRegisteredCallbacksTriggeredOnSoftApFailureNoChannel()4450 public void testRegisteredCallbacksTriggeredOnSoftApFailureNoChannel() throws Exception { 4451 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 4452 mWifiServiceImpl.checkAndStartWifi(); 4453 mLooper.dispatchAll(); 4454 4455 verifyApRegistration(); 4456 4457 registerLOHSRequestFull(); 4458 4459 changeLohsState(WIFI_AP_STATE_FAILED, 4460 WIFI_AP_STATE_DISABLED, SAP_START_FAILURE_NO_CHANNEL); 4461 4462 mLooper.dispatchAll(); 4463 verify(mLohsCallback).onHotspotFailed(ERROR_NO_CHANNEL); 4464 } 4465 4466 /** 4467 * Common setup for starting a LOHS. 4468 */ setupLocalOnlyHotspot()4469 private void setupLocalOnlyHotspot() throws Exception { 4470 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 4471 mWifiServiceImpl.checkAndStartWifi(); 4472 mLooper.dispatchAll(); 4473 4474 verifyApRegistration(); 4475 4476 registerLOHSRequestFull(); 4477 4478 changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR); 4479 mWifiServiceImpl.updateInterfaceIpState(mLohsInterfaceName, IFACE_IP_MODE_LOCAL_ONLY); 4480 mLooper.dispatchAll(); 4481 verify(mLohsCallback).onHotspotStarted(any()); 4482 } 4483 4484 /** 4485 * Verify that onStopped is called for registered LOHS callers when a callback is 4486 * received with WIFI_AP_STATE_DISABLING and LOHS was active. 4487 */ 4488 @Test testRegisteredCallbacksTriggeredOnSoftApDisabling()4489 public void testRegisteredCallbacksTriggeredOnSoftApDisabling() throws Exception { 4490 setupLocalOnlyHotspot(); 4491 4492 changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR); 4493 4494 mLooper.dispatchAll(); 4495 verify(mLohsCallback).onHotspotStopped(); 4496 } 4497 4498 4499 /** 4500 * Verify that onStopped is called for registered LOHS callers when a callback is 4501 * received with WIFI_AP_STATE_DISABLED and LOHS was enabled. 4502 */ 4503 @Test testRegisteredCallbacksTriggeredOnSoftApDisabled()4504 public void testRegisteredCallbacksTriggeredOnSoftApDisabled() throws Exception { 4505 setupLocalOnlyHotspot(); 4506 4507 changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR); 4508 4509 mLooper.dispatchAll(); 4510 verify(mLohsCallback).onHotspotStopped(); 4511 } 4512 4513 /** 4514 * Verify that no callbacks are called for registered LOHS callers when a callback is 4515 * received and the softap started. 4516 */ 4517 @Test testRegisteredCallbacksNotTriggeredOnSoftApStart()4518 public void testRegisteredCallbacksNotTriggeredOnSoftApStart() throws Exception { 4519 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 4520 mWifiServiceImpl.checkAndStartWifi(); 4521 mLooper.dispatchAll(); 4522 4523 verifyApRegistration(); 4524 4525 registerLOHSRequestFull(); 4526 4527 changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR); 4528 4529 mLooper.dispatchAll(); 4530 verifyNoMoreInteractions(ignoreStubs(mLohsCallback)); 4531 } 4532 4533 /** 4534 * Verify that onStopped is called only once for registered LOHS callers when 4535 * callbacks are received with WIFI_AP_STATE_DISABLING and 4536 * WIFI_AP_STATE_DISABLED when LOHS was enabled. 4537 */ 4538 @Test testRegisteredCallbacksTriggeredOnlyOnceWhenSoftApDisabling()4539 public void testRegisteredCallbacksTriggeredOnlyOnceWhenSoftApDisabling() throws Exception { 4540 setupLocalOnlyHotspot(); 4541 4542 changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR); 4543 changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR); 4544 4545 mLooper.dispatchAll(); 4546 verify(mLohsCallback).onHotspotStopped(); 4547 } 4548 4549 /** 4550 * Verify that onFailed is called only once for registered LOHS callers when 4551 * callbacks are received with WIFI_AP_STATE_FAILED twice. 4552 */ 4553 @Test testRegisteredCallbacksTriggeredOnlyOnceWhenSoftApFailsTwice()4554 public void testRegisteredCallbacksTriggeredOnlyOnceWhenSoftApFailsTwice() throws Exception { 4555 setupLocalOnlyHotspot(); 4556 4557 changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_FAILED, ERROR_GENERIC); 4558 changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_FAILED, ERROR_GENERIC); 4559 4560 mLooper.dispatchAll(); 4561 verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC); 4562 } 4563 4564 /** 4565 * Verify that onFailed is called for all registered LOHS callers when 4566 * callbacks are received with WIFI_AP_STATE_FAILED. 4567 */ 4568 @Test testAllRegisteredCallbacksTriggeredWhenSoftApFails()4569 public void testAllRegisteredCallbacksTriggeredWhenSoftApFails() throws Exception { 4570 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 4571 mWifiServiceImpl.checkAndStartWifi(); 4572 mLooper.dispatchAll(); 4573 4574 verifyApRegistration(); 4575 4576 // make an additional request for this test 4577 mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo); 4578 4579 registerLOHSRequestFull(); 4580 4581 changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_FAILED, ERROR_GENERIC); 4582 changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_FAILED, ERROR_GENERIC); 4583 4584 verify(mRequestInfo).sendHotspotFailedMessage(ERROR_GENERIC); 4585 mLooper.dispatchAll(); 4586 verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC); 4587 } 4588 4589 /** 4590 * Verify that onStopped is called for all registered LOHS callers when 4591 * callbacks are received with WIFI_AP_STATE_DISABLED when LOHS was 4592 * active. 4593 */ 4594 @Test testAllRegisteredCallbacksTriggeredWhenSoftApStops()4595 public void testAllRegisteredCallbacksTriggeredWhenSoftApStops() throws Exception { 4596 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 4597 mWifiServiceImpl.checkAndStartWifi(); 4598 mLooper.dispatchAll(); 4599 4600 verifyApRegistration(); 4601 4602 mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo); 4603 4604 registerLOHSRequestFull(); 4605 4606 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY); 4607 mLooper.dispatchAll(); 4608 verify(mRequestInfo).sendHotspotStartedMessage(any()); 4609 verify(mLohsCallback).onHotspotStarted(any()); 4610 4611 reset(mRequestInfo); 4612 clearInvocations(mLohsCallback); 4613 4614 changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR); 4615 changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR); 4616 4617 verify(mRequestInfo).sendHotspotStoppedMessage(); 4618 mLooper.dispatchAll(); 4619 verify(mLohsCallback).onHotspotStopped(); 4620 } 4621 4622 /** 4623 * Verify that onFailed is called for all registered LOHS callers when 4624 * callbacks are received with WIFI_AP_STATE_DISABLED when LOHS was 4625 * not active. 4626 */ 4627 @Test testAllRegisteredCallbacksTriggeredWhenSoftApStopsLOHSNotActive()4628 public void testAllRegisteredCallbacksTriggeredWhenSoftApStopsLOHSNotActive() throws Exception { 4629 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 4630 mWifiServiceImpl.checkAndStartWifi(); 4631 mLooper.dispatchAll(); 4632 4633 verifyApRegistration(); 4634 4635 mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo); 4636 mWifiServiceImpl.registerLOHSForTest(TEST_PID2, mRequestInfo2); 4637 4638 changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR); 4639 changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR); 4640 4641 verify(mRequestInfo).sendHotspotFailedMessage(ERROR_GENERIC); 4642 verify(mRequestInfo2).sendHotspotFailedMessage(ERROR_GENERIC); 4643 } 4644 4645 /** 4646 * Verify that if we do not have registered LOHS requestors and we receive an update that LOHS 4647 * is up and ready for use, we tell WifiController to tear it down. This can happen if softap 4648 * mode fails to come up properly and we get an onFailed message for a tethering call and we 4649 * had registered callers for LOHS. 4650 */ 4651 @Test testLOHSReadyWithoutRegisteredRequestsStopsSoftApMode()4652 public void testLOHSReadyWithoutRegisteredRequestsStopsSoftApMode() { 4653 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY); 4654 mLooper.dispatchAll(); 4655 4656 verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY); 4657 } 4658 4659 /** 4660 * Verify that all registered LOHS requestors are notified via a HOTSPOT_STARTED message that 4661 * the hotspot is up and ready to use. 4662 */ 4663 @Test testRegisteredLocalOnlyHotspotRequestorsGetOnStartedCallbackWhenReady()4664 public void testRegisteredLocalOnlyHotspotRequestorsGetOnStartedCallbackWhenReady() 4665 throws Exception { 4666 SoftApConfiguration lohsConfig = createValidSoftApConfiguration(); 4667 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 4668 eq(mContext), eq(null), any(), eq(false))).thenReturn(lohsConfig); 4669 registerLOHSRequestFull(); 4670 verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig( 4671 eq(mContext), eq(null), any(), eq(false)); 4672 mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo); 4673 4674 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY); 4675 mLooper.dispatchAll(); 4676 verify(mRequestInfo).sendHotspotStartedMessage(any(SoftApConfiguration.class)); 4677 4678 mLooper.dispatchAll(); 4679 verify(mLohsCallback).onHotspotStarted(notNull()); 4680 } 4681 4682 /** 4683 * Verify that if a LOHS is already active, a new call to register a request will trigger the 4684 * onStarted callback. 4685 */ 4686 @Test testRegisterLocalOnlyHotspotRequestAfterAlreadyStartedGetsOnStartedCallback()4687 public void testRegisterLocalOnlyHotspotRequestAfterAlreadyStartedGetsOnStartedCallback() 4688 throws Exception { 4689 mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo); 4690 mLooper.dispatchAll(); 4691 4692 changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR); 4693 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY); 4694 4695 registerLOHSRequestFull(); 4696 verify(mLohsCallback).onHotspotStarted(any()); 4697 } 4698 4699 /** 4700 * Verify that if a LOHS request is active and we receive an update with an ip mode 4701 * configuration error, callers are notified via the onFailed callback with the generic 4702 * error and are unregistered. 4703 */ 4704 @Test testCallOnFailedLocalOnlyHotspotRequestWhenIpConfigFails()4705 public void testCallOnFailedLocalOnlyHotspotRequestWhenIpConfigFails() throws Exception { 4706 setupLocalOnlyHotspot(); 4707 reset(mActiveModeWarden); 4708 4709 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_CONFIGURATION_ERROR); 4710 mLooper.dispatchAll(); 4711 4712 verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC); 4713 verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY); 4714 4715 clearInvocations(mLohsCallback); 4716 4717 // send HOTSPOT_FAILED message should only happen once since the requestor should be 4718 // unregistered 4719 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_CONFIGURATION_ERROR); 4720 mLooper.dispatchAll(); 4721 verifyNoMoreInteractions(ignoreStubs(mLohsCallback)); 4722 } 4723 4724 /** 4725 * Verify that softap mode is stopped for tethering if we receive an update with an ip mode 4726 * configuration error. 4727 */ 4728 @Test testStopSoftApWhenIpConfigFails()4729 public void testStopSoftApWhenIpConfigFails() throws Exception { 4730 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED); 4731 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_CONFIGURATION_ERROR); 4732 mLooper.dispatchAll(); 4733 4734 verify(mActiveModeWarden).stopSoftAp(IFACE_IP_MODE_TETHERED); 4735 } 4736 4737 /** 4738 * Verify that if a LOHS request is active and tethering starts, callers are notified on the 4739 * incompatible mode and are unregistered. 4740 */ 4741 @Test testCallOnFailedLocalOnlyHotspotRequestWhenTetheringStarts()4742 public void testCallOnFailedLocalOnlyHotspotRequestWhenTetheringStarts() throws Exception { 4743 registerLOHSRequestFull(); 4744 4745 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY); 4746 mLooper.dispatchAll(); 4747 verify(mLohsCallback).onHotspotStarted(any()); 4748 clearInvocations(mLohsCallback); 4749 4750 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED); 4751 mLooper.dispatchAll(); 4752 4753 verify(mLohsCallback).onHotspotFailed(ERROR_INCOMPATIBLE_MODE); 4754 4755 // sendMessage should only happen once since the requestor should be unregistered 4756 clearInvocations(mLohsCallback); 4757 4758 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED); 4759 verifyNoMoreInteractions(ignoreStubs(mLohsCallback)); 4760 } 4761 4762 /** 4763 * Verify that if LOHS is disabled, a new call to register a request will not trigger the 4764 * onStopped callback. 4765 */ 4766 @Test testRegisterLocalOnlyHotspotRequestWhenStoppedDoesNotGetOnStoppedCallback()4767 public void testRegisterLocalOnlyHotspotRequestWhenStoppedDoesNotGetOnStoppedCallback() 4768 throws Exception { 4769 registerLOHSRequestFull(); 4770 verifyNoMoreInteractions(ignoreStubs(mLohsCallback)); 4771 } 4772 4773 /** 4774 * Verify that if a LOHS was active and then stopped, a new call to register a request will 4775 * not trigger the onStarted callback. 4776 */ 4777 @Test testRegisterLocalOnlyHotspotRequestAfterStoppedNoOnStartedCallback()4778 public void testRegisterLocalOnlyHotspotRequestAfterStoppedNoOnStartedCallback() 4779 throws Exception { 4780 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 4781 mWifiServiceImpl.checkAndStartWifi(); 4782 mLooper.dispatchAll(); 4783 verifyApRegistration(); 4784 4785 // register a request so we don't drop the LOHS interface ip update 4786 mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo); 4787 changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR); 4788 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY); 4789 mLooper.dispatchAll(); 4790 4791 registerLOHSRequestFull(); 4792 mLooper.dispatchAll(); 4793 4794 verify(mLohsCallback).onHotspotStarted(any()); 4795 4796 clearInvocations(mLohsCallback); 4797 4798 // now stop the hotspot 4799 changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR); 4800 changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR); 4801 mLooper.dispatchAll(); 4802 verify(mLohsCallback).onHotspotStopped(); 4803 4804 clearInvocations(mLohsCallback); 4805 4806 // now register a new caller - they should not get the onStarted callback 4807 ILocalOnlyHotspotCallback callback2 = mock(ILocalOnlyHotspotCallback.class); 4808 when(callback2.asBinder()).thenReturn(mock(IBinder.class)); 4809 4810 int result = mWifiServiceImpl.startLocalOnlyHotspot( 4811 callback2, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras, false); 4812 assertEquals(LocalOnlyHotspotCallback.REQUEST_REGISTERED, result); 4813 mLooper.dispatchAll(); 4814 4815 verify(mLohsCallback, never()).onHotspotStarted(any()); 4816 verify(mLastCallerInfoManager, atLeastOnce()).put( 4817 eq(WifiManager.API_START_LOCAL_ONLY_HOTSPOT), anyInt(), anyInt(), anyInt(), 4818 anyString(), eq(true)); 4819 } 4820 4821 /** 4822 * Verify that a call to startWatchLocalOnlyHotspot is only allowed from callers with the 4823 * signature only NETWORK_SETTINGS permission. 4824 * 4825 * This test is expecting the permission check to enforce the permission and throw a 4826 * SecurityException for callers without the permission. This exception should be bubbled up to 4827 * the caller of startLocalOnlyHotspot. 4828 */ 4829 @Test(expected = SecurityException.class) testStartWatchLocalOnlyHotspotNotApprovedCaller()4830 public void testStartWatchLocalOnlyHotspotNotApprovedCaller() { 4831 doThrow(new SecurityException()).when(mContext) 4832 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 4833 eq("WifiService")); 4834 mWifiServiceImpl.startWatchLocalOnlyHotspot(mLohsCallback); 4835 } 4836 4837 /** 4838 * Verify that the call to startWatchLocalOnlyHotspot throws the UnsupportedOperationException 4839 * when called until the implementation is complete. 4840 */ 4841 @Test(expected = UnsupportedOperationException.class) testStartWatchLocalOnlyHotspotNotSupported()4842 public void testStartWatchLocalOnlyHotspotNotSupported() { 4843 mWifiServiceImpl.startWatchLocalOnlyHotspot(mLohsCallback); 4844 } 4845 4846 /** 4847 * Verify that a call to stopWatchLocalOnlyHotspot is only allowed from callers with the 4848 * signature only NETWORK_SETTINGS permission. 4849 */ 4850 @Test(expected = SecurityException.class) testStopWatchLocalOnlyHotspotNotApprovedCaller()4851 public void testStopWatchLocalOnlyHotspotNotApprovedCaller() { 4852 doThrow(new SecurityException()).when(mContext) 4853 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 4854 eq("WifiService")); 4855 mWifiServiceImpl.stopWatchLocalOnlyHotspot(); 4856 } 4857 4858 /** 4859 * Verify that the call to stopWatchLocalOnlyHotspot throws the UnsupportedOperationException 4860 * until the implementation is complete. 4861 */ 4862 @Test(expected = UnsupportedOperationException.class) testStopWatchLocalOnlyHotspotNotSupported()4863 public void testStopWatchLocalOnlyHotspotNotSupported() { 4864 mWifiServiceImpl.stopWatchLocalOnlyHotspot(); 4865 } 4866 4867 /** 4868 * Verify that the call to addOrUpdateNetwork for installing Passpoint profile is redirected 4869 * to the Passpoint specific API addOrUpdatePasspointConfiguration. 4870 */ 4871 @Test testAddPasspointProfileViaAddNetwork()4872 public void testAddPasspointProfileViaAddNetwork() throws Exception { 4873 WifiConfiguration config = WifiConfigurationTestUtil.createPasspointNetwork(); 4874 config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS); 4875 4876 PackageManager pm = mock(PackageManager.class); 4877 when(mContext.getPackageManager()).thenReturn(pm); 4878 when(pm.getApplicationInfoAsUser(any(), anyInt(), any())).thenReturn(mApplicationInfo); 4879 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 4880 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 4881 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 4882 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(true); 4883 4884 when(mPasspointManager.addOrUpdateProvider( 4885 any(PasspointConfiguration.class), anyInt(), eq(TEST_PACKAGE_NAME), eq(false), 4886 eq(true), eq(false))).thenReturn(true); 4887 mLooper.startAutoDispatch(); 4888 assertEquals(0, 4889 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 4890 mLooper.stopAutoDispatchAndIgnoreExceptions(); 4891 verifyCheckChangePermission(TEST_PACKAGE_NAME); 4892 verify(mPasspointManager).addOrUpdateProvider( 4893 any(PasspointConfiguration.class), anyInt(), eq(TEST_PACKAGE_NAME), eq(false), 4894 eq(true), eq(false)); 4895 reset(mPasspointManager); 4896 4897 when(mPasspointManager.addOrUpdateProvider( 4898 any(PasspointConfiguration.class), anyInt(), eq(TEST_PACKAGE_NAME), anyBoolean(), 4899 anyBoolean(), eq(false))).thenReturn(false); 4900 mLooper.startAutoDispatch(); 4901 assertEquals(-1, 4902 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 4903 mLooper.stopAutoDispatchAndIgnoreExceptions(); 4904 verifyCheckChangePermission(TEST_PACKAGE_NAME); 4905 verify(mPasspointManager).addOrUpdateProvider( 4906 any(PasspointConfiguration.class), anyInt(), eq(TEST_PACKAGE_NAME), anyBoolean(), 4907 anyBoolean(), eq(false)); 4908 } 4909 4910 /** 4911 * Verify that the call to getAllMatchingPasspointProfilesForScanResults is not redirected to 4912 * specific API getAllMatchingPasspointProfilesForScanResults when the caller doesn't have 4913 * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD. 4914 */ 4915 @Test(expected = SecurityException.class) testGetAllMatchingPasspointProfilesForScanResultsWithoutPermissions()4916 public void testGetAllMatchingPasspointProfilesForScanResultsWithoutPermissions() { 4917 mWifiServiceImpl.getAllMatchingPasspointProfilesForScanResults( 4918 new ParceledListSlice<>(Collections.emptyList())); 4919 } 4920 4921 /** 4922 * Verify that the call to getAllMatchingPasspointProfilesForScanResults is redirected to 4923 * specific API getAllMatchingPasspointProfilesForScanResults when the caller have 4924 * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD. 4925 */ 4926 @Test testGetAllMatchingPasspointProfilesForScanResultsWithPermissions()4927 public void testGetAllMatchingPasspointProfilesForScanResultsWithPermissions() { 4928 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 4929 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 4930 mLooper.startAutoDispatch(); 4931 mWifiServiceImpl.getAllMatchingPasspointProfilesForScanResults( 4932 new ParceledListSlice<>(createScanResultList())); 4933 mLooper.stopAutoDispatchAndIgnoreExceptions(); 4934 verify(mPasspointManager).getAllMatchingPasspointProfilesForScanResults(any()); 4935 } 4936 4937 /** 4938 * Verify that the call to getAllMatchingPasspointProfilesForScanResults is not redirected to 4939 * specific API getAllMatchingPasspointProfilesForScanResults when the caller provider invalid 4940 * ScanResult. 4941 */ 4942 @Test testGetAllMatchingPasspointProfilesForScanResultsWithInvalidScanResult()4943 public void testGetAllMatchingPasspointProfilesForScanResultsWithInvalidScanResult() { 4944 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 4945 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 4946 mLooper.startAutoDispatch(); 4947 mWifiServiceImpl.getAllMatchingPasspointProfilesForScanResults( 4948 new ParceledListSlice<>(Collections.emptyList())); 4949 mLooper.stopAutoDispatchAndIgnoreExceptions(); 4950 verify(mPasspointManager, never()).getAllMatchingPasspointProfilesForScanResults(any()); 4951 } 4952 4953 /** 4954 * Verify that the call to getWifiConfigsForPasspointProfiles is not redirected to specific API 4955 * syncGetWifiConfigsForPasspointProfiles when the caller doesn't have NETWORK_SETTINGS 4956 * permissions and NETWORK_SETUP_WIZARD. 4957 */ 4958 @Test(expected = SecurityException.class) testGetWifiConfigsForPasspointProfilesWithoutPermissions()4959 public void testGetWifiConfigsForPasspointProfilesWithoutPermissions() { 4960 mWifiServiceImpl.getWifiConfigsForPasspointProfiles( 4961 new StringParceledListSlice(Collections.emptyList())); 4962 } 4963 4964 /** 4965 * Verify that the call to getMatchingOsuProviders is not redirected to specific API 4966 * syncGetMatchingOsuProviders when the caller doesn't have NETWORK_SETTINGS 4967 * permissions and NETWORK_SETUP_WIZARD. 4968 */ 4969 @Test(expected = SecurityException.class) testGetMatchingOsuProvidersWithoutPermissions()4970 public void testGetMatchingOsuProvidersWithoutPermissions() { 4971 mWifiServiceImpl.getMatchingOsuProviders(new ParceledListSlice<>(Collections.emptyList())); 4972 } 4973 4974 /** 4975 * Verify that the call to getMatchingOsuProviders is redirected to specific API 4976 * syncGetMatchingOsuProviders when the caller have NETWORK_SETTINGS 4977 * permissions and NETWORK_SETUP_WIZARD. 4978 */ 4979 @Test testGetMatchingOsuProvidersWithPermissions()4980 public void testGetMatchingOsuProvidersWithPermissions() { 4981 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 4982 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 4983 mLooper.startAutoDispatch(); 4984 mWifiServiceImpl.getMatchingOsuProviders(new ParceledListSlice<>(createScanResultList())); 4985 mLooper.stopAutoDispatch(); 4986 verify(mPasspointManager).getMatchingOsuProviders(any()); 4987 } 4988 4989 /** 4990 * Verify that the call to getMatchingOsuProviders is not redirected to specific API 4991 * syncGetMatchingOsuProviders when the caller provider invalid ScanResult 4992 */ 4993 @Test testGetMatchingOsuProvidersWithInvalidScanResult()4994 public void testGetMatchingOsuProvidersWithInvalidScanResult() { 4995 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 4996 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 4997 mWifiServiceImpl.getMatchingOsuProviders(new ParceledListSlice<>(Collections.emptyList())); 4998 mLooper.dispatchAll(); 4999 verify(mPasspointManager, never()).getMatchingOsuProviders(any()); 5000 } 5001 5002 /** 5003 * Verify that the call to getMatchingPasspointConfigsForOsuProviders is not redirected to 5004 * specific API syncGetMatchingPasspointConfigsForOsuProviders when the caller doesn't have 5005 * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD. 5006 */ 5007 @Test(expected = SecurityException.class) testGetMatchingPasspointConfigsForOsuProvidersWithoutPermissions()5008 public void testGetMatchingPasspointConfigsForOsuProvidersWithoutPermissions() { 5009 mWifiServiceImpl.getMatchingPasspointConfigsForOsuProviders( 5010 new ParceledListSlice<>(Collections.emptyList())); 5011 } 5012 5013 /** 5014 * Verify that the call to startSubscriptionProvisioning is redirected to the Passpoint 5015 * specific API startSubscriptionProvisioning when the caller has the right permissions. 5016 */ 5017 @Test testStartSubscriptionProvisioningWithPermission()5018 public void testStartSubscriptionProvisioningWithPermission() throws Exception { 5019 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5020 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5021 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD), 5022 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5023 5024 mLooper.startAutoDispatch(); 5025 mWifiServiceImpl.startSubscriptionProvisioning(mOsuProvider, mProvisioningCallback); 5026 mLooper.stopAutoDispatch(); 5027 verify(mClientModeManager).syncStartSubscriptionProvisioning(anyInt(), 5028 eq(mOsuProvider), eq(mProvisioningCallback)); 5029 } 5030 5031 /** 5032 * Verify that the call to startSubscriptionProvisioning is not redirected to the Passpoint 5033 * specific API startSubscriptionProvisioning when the caller provides invalid arguments 5034 */ 5035 @Test(expected = IllegalArgumentException.class) testStartSubscriptionProvisioningWithInvalidProvider()5036 public void testStartSubscriptionProvisioningWithInvalidProvider() throws Exception { 5037 mWifiServiceImpl.startSubscriptionProvisioning(null, mProvisioningCallback); 5038 } 5039 5040 5041 /** 5042 * Verify that the call to startSubscriptionProvisioning is not redirected to the Passpoint 5043 * specific API startSubscriptionProvisioning when the caller provides invalid callback 5044 */ 5045 @Test(expected = IllegalArgumentException.class) testStartSubscriptionProvisioningWithInvalidCallback()5046 public void testStartSubscriptionProvisioningWithInvalidCallback() throws Exception { 5047 mWifiServiceImpl.startSubscriptionProvisioning(mOsuProvider, null); 5048 } 5049 5050 /** 5051 * Verify that the call to startSubscriptionProvisioning is not redirected to the Passpoint 5052 * specific API startSubscriptionProvisioning when the caller doesn't have NETWORK_SETTINGS 5053 * permissions and NETWORK_SETUP_WIZARD. 5054 */ 5055 @Test(expected = SecurityException.class) testStartSubscriptionProvisioningWithoutPermissions()5056 public void testStartSubscriptionProvisioningWithoutPermissions() throws Exception { 5057 when(mContext.checkCallingOrSelfPermission( 5058 eq(android.Manifest.permission.NETWORK_SETTINGS))).thenReturn( 5059 PackageManager.PERMISSION_DENIED); 5060 when(mContext.checkSelfPermission( 5061 eq(android.Manifest.permission.NETWORK_SETUP_WIZARD))).thenReturn( 5062 PackageManager.PERMISSION_DENIED); 5063 5064 mWifiServiceImpl.startSubscriptionProvisioning(mOsuProvider, mProvisioningCallback); 5065 } 5066 5067 /** 5068 * Verify the call to getPasspointConfigurations when the caller doesn't have 5069 * NETWORK_SETTINGS and NETWORK_SETUP_WIZARD permissions. 5070 */ 5071 @Test testGetPasspointConfigurationsWithOutPrivilegedPermissions()5072 public void testGetPasspointConfigurationsWithOutPrivilegedPermissions() { 5073 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 5074 when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false); 5075 5076 mLooper.startAutoDispatch(); 5077 mWifiServiceImpl.getPasspointConfigurations(TEST_PACKAGE_NAME); 5078 mLooper.stopAutoDispatchAndIgnoreExceptions(); 5079 verify(mPasspointManager).getProviderConfigs(Binder.getCallingUid(), false); 5080 } 5081 5082 /** 5083 * Verify that the call to getPasspointConfigurations when the caller does have 5084 * NETWORK_SETTINGS permission. 5085 */ 5086 @Test testGetPasspointConfigurationsWithPrivilegedPermissions()5087 public void testGetPasspointConfigurationsWithPrivilegedPermissions() { 5088 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5089 5090 mLooper.startAutoDispatch(); 5091 mWifiServiceImpl.getPasspointConfigurations(TEST_PACKAGE_NAME); 5092 mLooper.stopAutoDispatchAndIgnoreExceptions(); 5093 verify(mPasspointManager).getProviderConfigs(Binder.getCallingUid(), true); 5094 } 5095 5096 /** 5097 * Verify that GetPasspointConfigurations will redirect calls to {@link PasspointManager} 5098 * and returning the result that's returned from {@link PasspointManager}. 5099 */ 5100 @Test testGetPasspointConfigurations()5101 public void testGetPasspointConfigurations() throws Exception { 5102 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5103 5104 // Setup expected configs. 5105 List<PasspointConfiguration> expectedConfigs = new ArrayList<>(); 5106 PasspointConfiguration config = new PasspointConfiguration(); 5107 HomeSp homeSp = new HomeSp(); 5108 homeSp.setFqdn("test.com"); 5109 config.setHomeSp(homeSp); 5110 expectedConfigs.add(config); 5111 5112 when(mPasspointManager.getProviderConfigs(anyInt(), anyBoolean())) 5113 .thenReturn(expectedConfigs); 5114 mLooper.startAutoDispatch(); 5115 assertEquals(expectedConfigs, 5116 mWifiServiceImpl.getPasspointConfigurations(TEST_PACKAGE).getList()); 5117 mLooper.stopAutoDispatchAndIgnoreExceptions(); 5118 reset(mPasspointManager); 5119 5120 when(mPasspointManager.getProviderConfigs(anyInt(), anyBoolean())) 5121 .thenReturn(new ArrayList<PasspointConfiguration>()); 5122 mLooper.startAutoDispatch(); 5123 assertTrue(mWifiServiceImpl.getPasspointConfigurations(TEST_PACKAGE).getList().isEmpty()); 5124 mLooper.stopAutoDispatchAndIgnoreExceptions(); 5125 } 5126 5127 /** 5128 * Verify the call to removePasspointConfigurations when the caller doesn't have 5129 * NETWORK_SETTINGS and NETWORK_CARRIER_PROVISIONING permissions. 5130 */ 5131 @Test testRemovePasspointConfigurationWithOutPrivilegedPermissions()5132 public void testRemovePasspointConfigurationWithOutPrivilegedPermissions() { 5133 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 5134 when(mWifiPermissionsUtil.checkNetworkCarrierProvisioningPermission(anyInt())).thenReturn( 5135 false); 5136 5137 mLooper.startAutoDispatch(); 5138 mWifiServiceImpl.removePasspointConfiguration(TEST_FQDN, TEST_PACKAGE_NAME); 5139 mLooper.stopAutoDispatchAndIgnoreExceptions(); 5140 verify(mPasspointManager).removeProvider(Binder.getCallingUid(), false, null, 5141 TEST_FQDN); 5142 } 5143 5144 /** 5145 * Verify the call to removePasspointConfigurations when the caller does have 5146 * NETWORK_CARRIER_PROVISIONING permission. 5147 */ 5148 @Test testRemovePasspointConfigurationWithPrivilegedPermissions()5149 public void testRemovePasspointConfigurationWithPrivilegedPermissions() { 5150 when(mWifiPermissionsUtil.checkNetworkCarrierProvisioningPermission(anyInt())).thenReturn( 5151 true); 5152 5153 mLooper.startAutoDispatch(); 5154 mWifiServiceImpl.removePasspointConfiguration(TEST_FQDN, TEST_PACKAGE_NAME); 5155 mLooper.stopAutoDispatchAndIgnoreExceptions(); 5156 verify(mPasspointManager).removeProvider(Binder.getCallingUid(), true, null, 5157 TEST_FQDN); 5158 } 5159 5160 /** 5161 * Verify that a call to {@link WifiServiceImpl#restoreBackupData(byte[])} is only allowed from 5162 * callers with the signature only NETWORK_SETTINGS permission. 5163 */ 5164 @Test(expected = SecurityException.class) testRestoreBackupDataNotApprovedCaller()5165 public void testRestoreBackupDataNotApprovedCaller() { 5166 doThrow(new SecurityException()).when(mContext) 5167 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5168 eq("WifiService")); 5169 mWifiServiceImpl.restoreBackupData(null); 5170 verify(mWifiBackupRestore, never()).retrieveConfigurationsFromBackupData(any(byte[].class)); 5171 } 5172 testRestoreNetworkConfiguration(int configNum, int batchNum, boolean allowOverride)5173 private void testRestoreNetworkConfiguration(int configNum, int batchNum, 5174 boolean allowOverride) { 5175 List<WifiConfiguration> configurations = new ArrayList<>(); 5176 when(mResourceCache.getInteger( 5177 eq(R.integer.config_wifiConfigurationRestoreNetworksBatchNum))) 5178 .thenReturn(batchNum); 5179 WifiConfiguration config = new WifiConfiguration(); 5180 config.SSID = TEST_SSID; 5181 for (int i = 0; i < configNum; i++) { 5182 configurations.add(config); 5183 } 5184 reset(mWifiConfigManager); 5185 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt())) 5186 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 5187 when(mWifiConfigManager.addNetwork(any(), anyInt())) 5188 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 5189 mWifiServiceImpl.restoreNetworks(configurations); 5190 mLooper.dispatchAll(); 5191 if (allowOverride) { 5192 verify(mWifiConfigManager, times(configNum)).addOrUpdateNetwork(eq(config), anyInt()); 5193 verify(mWifiConfigManager, never()).addNetwork(eq(config), anyInt()); 5194 } else { 5195 verify(mWifiConfigManager, never()).addOrUpdateNetwork(eq(config), anyInt()); 5196 verify(mWifiConfigManager, times(configNum)).addNetwork(eq(config), anyInt()); 5197 } 5198 verify(mWifiConfigManager, times(configNum)).enableNetwork( 5199 eq(TEST_NETWORK_ID), eq(false), anyInt(), eq(null)); 5200 verify(mWifiConfigManager, times(configNum)).allowAutojoin(eq(TEST_NETWORK_ID), 5201 anyBoolean()); 5202 } 5203 5204 /** 5205 * Verify that a call to 5206 * {@link WifiServiceImpl#restoreNetworks(List)} 5207 * trigeering the process of the network restoration in batches. 5208 */ 5209 @Test testRestoreNetworksWithBatchOverrideDisallowed()5210 public void testRestoreNetworksWithBatchOverrideDisallowed() { 5211 lenient().when(CompatChanges.isChangeEnabled(eq(NOT_OVERRIDE_EXISTING_NETWORKS_ON_RESTORE), 5212 anyInt())).thenReturn(true); 5213 testRestoreNetworkConfiguration(0 /* configNum */, 50 /* batchNum*/, false); 5214 testRestoreNetworkConfiguration(1 /* configNum */, 50 /* batchNum*/, false); 5215 testRestoreNetworkConfiguration(20 /* configNum */, 50 /* batchNum*/, false); 5216 testRestoreNetworkConfiguration(700 /* configNum */, 50 /* batchNum*/, false); 5217 testRestoreNetworkConfiguration(700 /* configNum */, 0 /* batchNum*/, false); 5218 } 5219 5220 /** 5221 * Verify that a call to {@link WifiServiceImpl#restoreSupplicantBackupData(byte[], byte[])} is 5222 * only allowed from callers with the signature only NETWORK_SETTINGS permission. 5223 */ 5224 @Test(expected = SecurityException.class) testRestoreSupplicantBackupDataNotApprovedCaller()5225 public void testRestoreSupplicantBackupDataNotApprovedCaller() { 5226 doThrow(new SecurityException()).when(mContext) 5227 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5228 eq("WifiService")); 5229 mWifiServiceImpl.restoreSupplicantBackupData(null, null); 5230 verify(mWifiBackupRestore, never()).retrieveConfigurationsFromSupplicantBackupData( 5231 any(byte[].class), any(byte[].class)); 5232 } 5233 5234 /** 5235 * Verify that a call to {@link WifiServiceImpl#retrieveBackupData()} is only allowed from 5236 * callers with the signature only NETWORK_SETTINGS permission. 5237 */ 5238 @Test(expected = SecurityException.class) testRetrieveBackupDataNotApprovedCaller()5239 public void testRetrieveBackupDataNotApprovedCaller() { 5240 doThrow(new SecurityException()).when(mContext) 5241 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5242 eq("WifiService")); 5243 mWifiServiceImpl.retrieveBackupData(); 5244 verify(mWifiBackupRestore, never()).retrieveBackupDataFromConfigurations(any(List.class)); 5245 } 5246 5247 /** 5248 * Verify that a call to {@link WifiServiceImpl#restoreSoftApBackupData(byte[])} 5249 * is only allowed from callers with the signature only NETWORK_SETTINGS permission. 5250 */ 5251 @Test(expected = SecurityException.class) testRestoreSoftApBackupDataNotApprovedCaller()5252 public void testRestoreSoftApBackupDataNotApprovedCaller() { 5253 doThrow(new SecurityException()).when(mContext) 5254 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5255 eq("WifiService")); 5256 mWifiServiceImpl.restoreSoftApBackupData(null); 5257 verify(mSoftApBackupRestore, never()) 5258 .retrieveSoftApConfigurationFromBackupData(any(byte[].class)); 5259 } 5260 5261 /** 5262 * Verify that a call to {@link WifiServiceImpl#restoreSoftApBackupData(byte[])} 5263 * will call WifiApConfigStore#upgradeSoftApConfiguration and 5264 * WifiApConfigStore#resetToDefaultForUnsupportedConfig. 5265 */ 5266 @Test testRestoreSoftApBackupData()5267 public void testRestoreSoftApBackupData() { 5268 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5269 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5270 InOrder inorder = inOrder(mWifiApConfigStore); 5271 SoftApConfiguration testConfig = new SoftApConfiguration.Builder() 5272 .setSsid("test").build(); 5273 byte[] testData = testConfig.toString().getBytes(); 5274 when(mSoftApBackupRestore.retrieveSoftApConfigurationFromBackupData(testData)) 5275 .thenReturn(testConfig); 5276 mWifiServiceImpl.restoreSoftApBackupData(testData); 5277 mLooper.dispatchAll(); 5278 inorder.verify(mWifiApConfigStore).upgradeSoftApConfiguration(testConfig); 5279 inorder.verify(mWifiApConfigStore).resetToDefaultForUnsupportedConfig(any()); 5280 inorder.verify(mWifiApConfigStore).setApConfiguration(any()); 5281 } 5282 5283 /** 5284 * Verify that a call to {@link WifiServiceImpl#retrieveSoftApBackupData()} is only allowed from 5285 * callers with the signature only NETWORK_SETTINGS permission. 5286 */ 5287 @Test(expected = SecurityException.class) testRetrieveSoftApBackupDataNotApprovedCaller()5288 public void testRetrieveSoftApBackupDataNotApprovedCaller() { 5289 doThrow(new SecurityException()).when(mContext) 5290 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5291 eq("WifiService")); 5292 mWifiServiceImpl.retrieveSoftApBackupData(); 5293 verify(mSoftApBackupRestore, never()) 5294 .retrieveBackupDataFromSoftApConfiguration(any(SoftApConfiguration.class)); 5295 } 5296 5297 class TestWifiVerboseLoggingStatusChangedListener extends 5298 IWifiVerboseLoggingStatusChangedListener.Stub { 5299 public int numStatusChangedCounts; 5300 public boolean lastReceivedValue; 5301 @Override onStatusChanged(boolean enabled)5302 public void onStatusChanged(boolean enabled) throws RemoteException { 5303 numStatusChangedCounts++; 5304 lastReceivedValue = enabled; 5305 } 5306 } 5307 5308 /** 5309 * Verify that a call to {@link WifiServiceImpl#enableVerboseLogging(int)} is propagated to 5310 * registered {@link IWifiVerboseLoggingStatusChangedListener}. Then, verify that changes are no 5311 * longer propagated when the listener gets unregistered. 5312 */ 5313 @Test testVerboseLoggingListener()5314 public void testVerboseLoggingListener() throws Exception { 5315 doNothing().when(mContext) 5316 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5317 eq("WifiService")); 5318 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5319 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5320 // Verbose logging is enabled first in the constructor for WifiServiceImpl, so reset 5321 // before invocation. 5322 reset(mClientModeManager); 5323 TestWifiVerboseLoggingStatusChangedListener listener = 5324 new TestWifiVerboseLoggingStatusChangedListener(); 5325 mWifiServiceImpl.addWifiVerboseLoggingStatusChangedListener(listener); 5326 mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED); 5327 verify(mWifiSettingsConfigStore).put(WIFI_VERBOSE_LOGGING_ENABLED, true); 5328 verify(mActiveModeWarden).enableVerboseLogging(anyBoolean()); 5329 assertEquals(1, listener.numStatusChangedCounts); 5330 assertTrue(listener.lastReceivedValue); 5331 5332 mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_DISABLED); 5333 assertEquals(2, listener.numStatusChangedCounts); 5334 assertFalse(listener.lastReceivedValue); 5335 5336 // unregister the callback and verify no more updates happen. 5337 mWifiServiceImpl.removeWifiVerboseLoggingStatusChangedListener(listener); 5338 mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED); 5339 assertEquals(2, listener.numStatusChangedCounts); 5340 assertFalse(listener.lastReceivedValue); 5341 } 5342 5343 /** 5344 * Verify an exception is thrown for invalid inputs to 5345 * addWifiVerboseLoggingStatusChangedListener and removeWifiVerboseLoggingStatusChangedListener. 5346 */ 5347 @Test testVerboseLoggingListenerInvalidInput()5348 public void testVerboseLoggingListenerInvalidInput() throws Exception { 5349 try { 5350 mWifiServiceImpl.addWifiVerboseLoggingStatusChangedListener(null); 5351 fail("expected IllegalArgumentException in addWifiVerboseLoggingStatusChangedListener"); 5352 } catch (IllegalArgumentException e) { 5353 } 5354 try { 5355 mWifiServiceImpl.removeWifiVerboseLoggingStatusChangedListener(null); 5356 fail("expected IllegalArgumentException in " 5357 + "removeWifiVerboseLoggingStatusChangedListener"); 5358 } catch (IllegalArgumentException e) { 5359 } 5360 } 5361 5362 /** 5363 * Verify a SecurityException if the caller doesn't have sufficient permissions. 5364 */ 5365 @Test testVerboseLoggingListenerNoPermission()5366 public void testVerboseLoggingListenerNoPermission() throws Exception { 5367 doThrow(new SecurityException()).when(mContext) 5368 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), 5369 eq("WifiService")); 5370 TestWifiVerboseLoggingStatusChangedListener listener = 5371 new TestWifiVerboseLoggingStatusChangedListener(); 5372 try { 5373 mWifiServiceImpl.addWifiVerboseLoggingStatusChangedListener(listener); 5374 fail("expected IllegalArgumentException in addWifiVerboseLoggingStatusChangedListener"); 5375 } catch (SecurityException e) { 5376 } 5377 try { 5378 mWifiServiceImpl.removeWifiVerboseLoggingStatusChangedListener(listener); 5379 fail("expected IllegalArgumentException in " 5380 + "removeWifiVerboseLoggingStatusChangedListener"); 5381 } catch (SecurityException e) { 5382 } 5383 } 5384 5385 /** 5386 * Verify that a call to {@link WifiServiceImpl#enableVerboseLogging(int)} is allowed from 5387 * callers with the signature only NETWORK_SETTINGS permission. 5388 */ 5389 @Test testEnableVerboseLoggingWithNetworkSettingsPermission()5390 public void testEnableVerboseLoggingWithNetworkSettingsPermission() throws Exception { 5391 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5392 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5393 // Verbose logging is enabled first in the constructor for WifiServiceImpl, so reset 5394 // before invocation. 5395 reset(mClientModeManager); 5396 mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED); 5397 verify(mWifiSettingsConfigStore).put(WIFI_VERBOSE_LOGGING_ENABLED, true); 5398 verify(mActiveModeWarden).enableVerboseLogging(anyBoolean()); 5399 assertTrue(mWifiThreadRunner.mVerboseLoggingEnabled); 5400 } 5401 5402 /** 5403 * Verify that setting verbose logging mode to 5404 * {@link WifiManager#VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY)} is allowed from 5405 * callers with the signature only NETWORK_SETTINGS permission. 5406 */ 5407 @Test testEnableShowKeyVerboseLoggingWithNetworkSettingsPermission()5408 public void testEnableShowKeyVerboseLoggingWithNetworkSettingsPermission() throws Exception { 5409 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5410 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5411 // Verbose logging is enabled first in the constructor for WifiServiceImpl, so reset 5412 // before invocation. 5413 reset(mClientModeManager); 5414 mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY); 5415 verify(mWifiSettingsConfigStore).put(WIFI_VERBOSE_LOGGING_ENABLED, true); 5416 verify(mActiveModeWarden).enableVerboseLogging(anyBoolean()); 5417 verify(mWifiGlobals).setVerboseLoggingLevel( 5418 eq(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY)); 5419 5420 // After auto disable show key mode after the countdown 5421 mLooper.moveTimeForward(WifiServiceImpl.AUTO_DISABLE_SHOW_KEY_COUNTDOWN_MILLIS + 1); 5422 mLooper.dispatchAll(); 5423 verify(mWifiGlobals).setVerboseLoggingLevel(eq(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED)); 5424 } 5425 5426 /** 5427 * Verify that setting verbose logging level to 5428 * {@link WifiManager#VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY)} is not allowed for 5429 * the user build. 5430 */ 5431 @Test(expected = SecurityException.class) testEnableShowKeyVerboseLoggingNotAllowedForUserBuild()5432 public void testEnableShowKeyVerboseLoggingNotAllowedForUserBuild() throws Exception { 5433 when(mBuildProperties.isUserBuild()).thenReturn(true); 5434 doNothing().when(mContext) 5435 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5436 eq("WifiService")); 5437 // Verbose logging is enabled first in the constructor for WifiServiceImpl, so reset 5438 // before invocation. 5439 reset(mClientModeManager); 5440 mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY); 5441 } 5442 5443 /** 5444 * Verify that a call to {@link WifiServiceImpl#enableVerboseLogging(int)} is not allowed from 5445 * callers without the signature only NETWORK_SETTINGS permission. 5446 */ 5447 @Test(expected = SecurityException.class) testEnableVerboseLoggingWithNoNetworkSettingsPermission()5448 public void testEnableVerboseLoggingWithNoNetworkSettingsPermission() { 5449 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5450 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 5451 when(mContext.checkPermission(eq(android.Manifest.permission.DUMP), 5452 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 5453 // Vebose logging is enabled first in the constructor for WifiServiceImpl, so reset 5454 // before invocation. 5455 reset(mClientModeManager); 5456 mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED); 5457 verify(mWifiSettingsConfigStore, never()).put( 5458 WIFI_VERBOSE_LOGGING_ENABLED, anyBoolean()); 5459 verify(mActiveModeWarden, never()).enableVerboseLogging(anyBoolean()); 5460 } 5461 5462 /** 5463 * Verify that the CONNECT_NETWORK message received from an app without 5464 * one of the privileged permission is rejected with a security exception. 5465 */ 5466 @Test testConnectNetworkWithoutPrivilegedPermission()5467 public void testConnectNetworkWithoutPrivilegedPermission() throws Exception { 5468 try { 5469 mWifiServiceImpl.connect(mock(WifiConfiguration.class), TEST_NETWORK_ID, 5470 mock(IActionListener.class), TEST_PACKAGE_NAME, mExtras); 5471 fail(); 5472 } catch (SecurityException e) { 5473 mLooper.dispatchAll(); 5474 verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any(), any()); 5475 } 5476 } 5477 5478 /** 5479 * Verify that the FORGET_NETWORK message received from an app without 5480 * one of the privileged permission is rejected with a security exception. 5481 */ 5482 @Test testForgetNetworkWithoutPrivilegedPermission()5483 public void testForgetNetworkWithoutPrivilegedPermission() throws Exception { 5484 try { 5485 mWifiServiceImpl.forget(TEST_NETWORK_ID, mock(IActionListener.class)); 5486 fail(); 5487 } catch (SecurityException e) { 5488 mLooper.dispatchAll(); 5489 verify(mWifiConfigManager, never()).removeNetwork(anyInt(), anyInt(), any()); 5490 } 5491 } 5492 5493 /** 5494 * Verify that the SAVE_NETWORK message received from an app without 5495 * one of the privileged permission is rejected with a security exception. 5496 */ 5497 @Test testSaveNetworkWithoutPrivilegedPermission()5498 public void testSaveNetworkWithoutPrivilegedPermission() throws Exception { 5499 try { 5500 mWifiServiceImpl.save(mock(WifiConfiguration.class), mock(IActionListener.class), 5501 TEST_PACKAGE_NAME); 5502 fail(); 5503 } catch (SecurityException e) { 5504 mLooper.dispatchAll(); 5505 verify(mWifiConfigManager, never()).updateBeforeSaveNetwork(any(), anyInt(), any()); 5506 } 5507 } 5508 5509 /** 5510 * Verify that the CONNECT_NETWORK message received from an app with 5511 * one of the privileged permission is forwarded to ClientModeManager. 5512 */ 5513 @Test testConnectNetworkWithPrivilegedPermission()5514 public void testConnectNetworkWithPrivilegedPermission() throws Exception { 5515 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5516 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5517 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5518 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt())) 5519 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 5520 WifiConfiguration config = new WifiConfiguration(); 5521 config.SSID = TEST_SSID; 5522 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 5523 mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class), 5524 TEST_PACKAGE_NAME, mExtras); 5525 mLooper.dispatchAll(); 5526 verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt()); 5527 verify(mConnectHelper).connectToNetwork(any(NetworkUpdateResult.class), 5528 any(ActionListenerWrapper.class), anyInt(), any(), any()); 5529 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_ADD_OR_UPDATE_NETWORK), 5530 anyInt()); 5531 verify(mLastCallerInfoManager).put(eq(WifiManager.API_CONNECT_CONFIG), anyInt(), 5532 anyInt(), anyInt(), anyString(), eq(true)); 5533 } 5534 5535 /** 5536 * Verify that the CONNECT_NETWORK message received from NF is forwarded to 5537 * ClientModeManager. 5538 */ 5539 @Test testConnectNetworkWithNfcUid()5540 public void testConnectNetworkWithNfcUid() throws Exception { 5541 final int origCallingUid = Binder.getCallingUid(); 5542 BinderUtil.setUid(Process.NFC_UID); 5543 try { 5544 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt())) 5545 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 5546 WifiConfiguration config = new WifiConfiguration(); 5547 config.SSID = TEST_SSID; 5548 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)) 5549 .thenReturn(config); 5550 mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class), 5551 TEST_PACKAGE_NAME, mExtras); 5552 mLooper.dispatchAll(); 5553 verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt()); 5554 verify(mConnectHelper).connectToNetwork(any(NetworkUpdateResult.class), 5555 any(ActionListenerWrapper.class), anyInt(), any(), any()); 5556 verify(mLastCallerInfoManager).put(eq(WifiManager.API_CONNECT_CONFIG), anyInt(), 5557 anyInt(), anyInt(), anyString(), eq(true)); 5558 } finally { 5559 BinderUtil.setUid(origCallingUid); 5560 } 5561 } 5562 5563 /** 5564 * Verify the secondary internet CMM is stopped when explicit connection is initiated on the 5565 * primary. 5566 */ 5567 @Test testConnectNetworkStopConnectedSecondaryInternetCmm()5568 public void testConnectNetworkStopConnectedSecondaryInternetCmm() throws Exception { 5569 // grant permissions to access WifiServiceImpl#connect 5570 when(mContext.checkPermission( 5571 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt())) 5572 .thenReturn(PackageManager.PERMISSION_GRANTED); 5573 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5574 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt())) 5575 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 5576 WifiConfiguration config = WifiConfigurationTestUtil.createWpa2Wpa3EnterpriseNetwork(); 5577 config.SSID = TEST_SSID; 5578 WifiConfiguration otherConfig = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 5579 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 5580 5581 // Mock ActiveModeWarden to return a primary CMM and a secondary CMM to be already 5582 // connected to the target network. 5583 List<ClientModeManager> clientModeManagers = new ArrayList<>(); 5584 ClientModeManager primaryCmm = mock(ClientModeManager.class); 5585 when(primaryCmm.getRole()).thenReturn(ROLE_CLIENT_PRIMARY); 5586 ConcreteClientModeManager secondaryInternetCmm = mock(ConcreteClientModeManager.class); 5587 when(secondaryInternetCmm.getRole()).thenReturn(ROLE_CLIENT_SECONDARY_LONG_LIVED); 5588 when(secondaryInternetCmm.isSecondaryInternet()).thenReturn(true); 5589 when(secondaryInternetCmm.isConnected()).thenReturn(true); 5590 when(secondaryInternetCmm.getConnectedWifiConfiguration()).thenReturn(otherConfig); 5591 clientModeManagers.add(primaryCmm); 5592 clientModeManagers.add(secondaryInternetCmm); 5593 when(mActiveModeWarden.getClientModeManagers()).thenReturn(clientModeManagers); 5594 5595 // Verify that the secondary internet CMM is stopped when manual connection is started 5596 mWifiServiceImpl.connect( 5597 config, TEST_NETWORK_ID, mock(IActionListener.class), TEST_PACKAGE_NAME, mExtras); 5598 mLooper.dispatchAll(); 5599 verify(primaryCmm, never()).stop(); 5600 verify(secondaryInternetCmm).stop(); 5601 } 5602 5603 /** 5604 * Verify that the CONNECT_NETWORK message received from an app with 5605 * one of the privileged permission will stop secondary CMMs that are alraedy connected to 5606 * the same network before initiating the connection. 5607 */ 5608 @Test testConnectNetworkStopSecondaryCmmOnSameNetwork()5609 public void testConnectNetworkStopSecondaryCmmOnSameNetwork() throws Exception { 5610 // grant permissions to access WifiServiceImpl#connect 5611 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5612 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5613 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5614 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt())) 5615 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 5616 WifiConfiguration config = WifiConfigurationTestUtil.createWpa2Wpa3EnterpriseNetwork(); 5617 config.SSID = TEST_SSID; 5618 WifiConfiguration localOnlyConfig = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 5619 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 5620 5621 // Mock ActiveModeWarden to return a primary CMM and a secondary CMM to be already 5622 // connected to the target network. 5623 List<ClientModeManager> clientModeManagers = new ArrayList<>(); 5624 ClientModeManager primaryCmm = mock(ClientModeManager.class); 5625 when(primaryCmm.getRole()).thenReturn(ROLE_CLIENT_PRIMARY); 5626 ConcreteClientModeManager localOnlyCmm = mock(ConcreteClientModeManager.class); 5627 when(localOnlyCmm.getRole()).thenReturn(ROLE_CLIENT_LOCAL_ONLY); 5628 when(localOnlyCmm.isConnected()).thenReturn(true); 5629 when(localOnlyCmm.getConnectedWifiConfiguration()).thenReturn(localOnlyConfig); 5630 clientModeManagers.add(primaryCmm); 5631 clientModeManagers.add(localOnlyCmm); 5632 when(mActiveModeWarden.getClientModeManagers()).thenReturn(clientModeManagers); 5633 5634 // Verify that the localOnlyCmm is not stopped since security type is different 5635 mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class), 5636 TEST_PACKAGE_NAME, mExtras); 5637 mLooper.dispatchAll(); 5638 verify(primaryCmm, never()).stop(); 5639 verify(localOnlyCmm, never()).stop(); 5640 verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt()); 5641 verify(mConnectHelper).connectToNetwork(any(NetworkUpdateResult.class), 5642 any(ActionListenerWrapper.class), anyInt(), any(), any()); 5643 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_ADD_OR_UPDATE_NETWORK), 5644 anyInt()); 5645 5646 // update mock so that the localOnlyConfig matches with target config. 5647 localOnlyConfig = WifiConfigurationTestUtil.createWpa3EnterpriseNetwork(TEST_SSID); 5648 when(localOnlyCmm.getConnectedWifiConfiguration()).thenReturn(localOnlyConfig); 5649 5650 // Verify that the localOnlyCmm is stopped this time 5651 mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class), 5652 TEST_PACKAGE_NAME, mExtras); 5653 mLooper.dispatchAll(); 5654 verify(primaryCmm, never()).stop(); 5655 verify(localOnlyCmm).stop(); 5656 verify(mWifiConfigManager, times(2)).addOrUpdateNetwork(eq(config), anyInt()); 5657 verify(mConnectHelper, times(2)).connectToNetwork(any(NetworkUpdateResult.class), 5658 any(ActionListenerWrapper.class), anyInt(), any(), any()); 5659 verify(mWifiMetrics, times(2)).logUserActionEvent( 5660 eq(UserActionEvent.EVENT_ADD_OR_UPDATE_NETWORK), anyInt()); 5661 } 5662 5663 @Test connectToNewNetwork_success()5664 public void connectToNewNetwork_success() throws Exception { 5665 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5666 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5667 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5668 NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID); 5669 when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt())) 5670 .thenReturn(result); 5671 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig); 5672 5673 mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID, 5674 mActionListener, TEST_PACKAGE_NAME, mExtras); 5675 mLooper.dispatchAll(); 5676 5677 ArgumentCaptor<WifiConfiguration> configCaptor = 5678 ArgumentCaptor.forClass(WifiConfiguration.class); 5679 verify(mWifiConfigManager).addOrUpdateNetwork(configCaptor.capture(), anyInt()); 5680 assertThat(configCaptor.getValue().networkId).isEqualTo(TEST_NETWORK_ID); 5681 5682 verify(mConnectHelper).connectToNetwork(eq(result), any(), anyInt(), any(), any()); 5683 verify(mContextAsUser).sendBroadcastWithMultiplePermissions( 5684 mIntentCaptor.capture(), 5685 aryEq(new String[]{ 5686 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE, 5687 android.Manifest.permission.ACCESS_FINE_LOCATION, 5688 })); 5689 5690 Intent intent = mIntentCaptor.getValue(); 5691 assertThat(intent.getAction()).isEqualTo(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 5692 assertThat(intent.getStringExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID)) 5693 .isEqualTo(TEST_SSID); 5694 assertThat(intent.getIntExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, -1)) 5695 .isEqualTo(WifiManager.WIFI_CREDENTIAL_SAVED); 5696 } 5697 5698 @Test connectToNewNetwork_failure()5699 public void connectToNewNetwork_failure() throws Exception { 5700 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5701 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5702 when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt())) 5703 .thenReturn(NetworkUpdateResult.makeFailed()); 5704 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5705 5706 mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID, 5707 mActionListener, TEST_PACKAGE_NAME, mExtras); 5708 mLooper.dispatchAll(); 5709 5710 verify(mWifiConfigManager).addOrUpdateNetwork(eq(mWifiConfig), anyInt()); 5711 5712 verify(mClientModeManager, never()).connectNetwork(any(), any(), anyInt(), any(), any()); 5713 verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any()); 5714 verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR); 5715 verify(mActionListener, never()).onSuccess(); 5716 } 5717 5718 @Test connectToExistingNetwork()5719 public void connectToExistingNetwork() throws Exception { 5720 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5721 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5722 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5723 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5724 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig); 5725 5726 mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME, 5727 mExtras); 5728 mLooper.dispatchAll(); 5729 5730 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt()); 5731 5732 verify(mConnectHelper).connectToNetwork( 5733 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any(), any()); 5734 verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any()); 5735 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt()); 5736 verify(mLastCallerInfoManager).put(eq(WifiManager.API_CONNECT_NETWORK_ID), anyInt(), 5737 anyInt(), anyInt(), anyString(), eq(true)); 5738 } 5739 5740 @Test connectToSimBasedNetworkWhenSimPresent()5741 public void connectToSimBasedNetworkWhenSimPresent() { 5742 WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork( 5743 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE); 5744 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5745 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5746 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5747 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5748 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 5749 when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID); 5750 when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(true); 5751 5752 mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME, 5753 mExtras); 5754 mLooper.dispatchAll(); 5755 5756 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt()); 5757 5758 verify(mConnectHelper).connectToNetwork( 5759 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any(), any()); 5760 verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any()); 5761 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt()); 5762 } 5763 5764 @Test connectToSimBasedNetworkWhenSimAbsent()5765 public void connectToSimBasedNetworkWhenSimAbsent() { 5766 WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork( 5767 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE); 5768 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5769 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5770 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5771 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5772 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 5773 when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID); 5774 when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(false); 5775 5776 mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME, 5777 mExtras); 5778 mLooper.dispatchAll(); 5779 5780 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt()); 5781 5782 verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any(), any()); 5783 verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any()); 5784 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt()); 5785 } 5786 5787 @Test connectToSimBasedNetworkRequiresImsiEncryptionButNotReady()5788 public void connectToSimBasedNetworkRequiresImsiEncryptionButNotReady() { 5789 WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork( 5790 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE); 5791 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5792 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5793 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5794 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5795 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 5796 when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID); 5797 when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(false); 5798 when(mWifiCarrierInfoManager.requiresImsiEncryption(TEST_SUB_ID)).thenReturn(true); 5799 when(mWifiCarrierInfoManager.isImsiEncryptionInfoAvailable(TEST_SUB_ID)).thenReturn(false); 5800 5801 mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME, 5802 mExtras); 5803 mLooper.dispatchAll(); 5804 5805 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt()); 5806 5807 verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any(), any()); 5808 verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any()); 5809 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt()); 5810 } 5811 5812 @Test connectToSimBasedNetworkOobPseudonymEnabledButNotAvailable()5813 public void connectToSimBasedNetworkOobPseudonymEnabledButNotAvailable() { 5814 WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork( 5815 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE); 5816 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5817 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5818 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5819 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5820 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 5821 when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID); 5822 when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(true); 5823 when(mWifiCarrierInfoManager.isOobPseudonymFeatureEnabled(anyInt())).thenReturn(true); 5824 when(mWifiPseudonymManager.getValidPseudonymInfo(anyInt())).thenReturn(Optional.empty()); 5825 5826 mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME, 5827 mExtras); 5828 mLooper.dispatchAll(); 5829 5830 verify(mWifiPseudonymManager).retrievePseudonymOnFailureTimeoutExpired(any()); 5831 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt()); 5832 5833 verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any(), any()); 5834 verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any()); 5835 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt()); 5836 } 5837 5838 @Test connectToSimBasedNetworkWhenOobPseudonymEnabledAndAvailable()5839 public void connectToSimBasedNetworkWhenOobPseudonymEnabledAndAvailable() { 5840 WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork( 5841 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE); 5842 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5843 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5844 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5845 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5846 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 5847 when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID); 5848 when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(true); 5849 when(mWifiCarrierInfoManager.isOobPseudonymFeatureEnabled(anyInt())).thenReturn(true); 5850 when(mWifiPseudonymManager.getValidPseudonymInfo(anyInt())) 5851 .thenReturn(Optional.of(mock(PseudonymInfo.class))); 5852 5853 mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME, 5854 mExtras); 5855 mLooper.dispatchAll(); 5856 5857 verify(mWifiPseudonymManager).updateWifiConfiguration(any()); 5858 verify(mConnectHelper).connectToNetwork( 5859 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any(), any()); 5860 verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any()); 5861 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt()); 5862 } 5863 5864 /** 5865 * Verify that connecting to an admin restricted network fails to connect but saves the network 5866 */ 5867 @Test connectToAdminRestrictedNetwork_failure()5868 public void connectToAdminRestrictedNetwork_failure() throws Exception { 5869 assumeTrue(SdkLevel.isAtLeastT()); 5870 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5871 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5872 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5873 NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID); 5874 when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt())) 5875 .thenReturn(result); 5876 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig); 5877 when(mWifiPermissionsUtil.isAdminRestrictedNetwork(mWifiConfig)).thenReturn(true); 5878 5879 mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID, 5880 mActionListener, TEST_PACKAGE_NAME, mExtras); 5881 mLooper.dispatchAll(); 5882 5883 ArgumentCaptor<WifiConfiguration> configCaptor = 5884 ArgumentCaptor.forClass(WifiConfiguration.class); 5885 verify(mWifiConfigManager).addOrUpdateNetwork(configCaptor.capture(), anyInt()); 5886 assertThat(configCaptor.getValue().networkId).isEqualTo(TEST_NETWORK_ID); 5887 5888 verify(mWifiConfigManager).addOrUpdateNetwork(eq(mWifiConfig), anyInt()); 5889 verify(mClientModeManager, never()).connectNetwork(any(), any(), anyInt(), any(), any()); 5890 verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR); 5891 verify(mActionListener, never()).onSuccess(); 5892 } 5893 5894 /** 5895 * Verify that the SAVE_NETWORK message received from an app with 5896 * one of the privileged permission is forwarded to ClientModeManager. 5897 */ 5898 @Test testSaveNetworkWithPrivilegedPermission()5899 public void testSaveNetworkWithPrivilegedPermission() throws Exception { 5900 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5901 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5902 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5903 when(mWifiConfigManager.updateBeforeSaveNetwork(any(), anyInt(), any())) 5904 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 5905 mWifiServiceImpl.save(mock(WifiConfiguration.class), mock(IActionListener.class), 5906 TEST_PACKAGE_NAME); 5907 mLooper.dispatchAll(); 5908 verify(mWifiConfigManager).updateBeforeSaveNetwork(any(WifiConfiguration.class), anyInt(), 5909 any()); 5910 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_ADD_OR_UPDATE_NETWORK), 5911 anyInt()); 5912 verify(mLastCallerInfoManager).put(eq(WifiManager.API_SAVE), anyInt(), 5913 anyInt(), anyInt(), anyString(), eq(true)); 5914 } 5915 5916 @Test saveNetwork_success()5917 public void saveNetwork_success() throws Exception { 5918 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5919 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5920 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5921 5922 NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID); 5923 when(mWifiConfigManager.updateBeforeSaveNetwork(eq(mWifiConfig), anyInt(), any())) 5924 .thenReturn(result); 5925 5926 mWifiServiceImpl.save(mWifiConfig, mActionListener, TEST_PACKAGE_NAME); 5927 mLooper.dispatchAll(); 5928 5929 verify(mWifiConfigManager).updateBeforeSaveNetwork(eq(mWifiConfig), anyInt(), any()); 5930 5931 verify(mClientModeManager).saveNetwork(eq(result), any(), anyInt(), any()); 5932 verify(mContextAsUser).sendBroadcastWithMultiplePermissions( 5933 mIntentCaptor.capture(), 5934 aryEq(new String[]{ 5935 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE, 5936 android.Manifest.permission.ACCESS_FINE_LOCATION, 5937 })); 5938 5939 Intent intent = mIntentCaptor.getValue(); 5940 assertThat(intent.getAction()).isEqualTo(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 5941 assertThat(intent.getStringExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID)) 5942 .isEqualTo(TEST_SSID); 5943 assertThat(intent.getIntExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, -1)) 5944 .isEqualTo(WifiManager.WIFI_CREDENTIAL_SAVED); 5945 } 5946 5947 @Test saveNetwork_failure()5948 public void saveNetwork_failure() throws Exception { 5949 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5950 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5951 when(mWifiConfigManager.updateBeforeSaveNetwork(eq(mWifiConfig), anyInt(), any())) 5952 .thenReturn(NetworkUpdateResult.makeFailed()); 5953 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5954 5955 mWifiServiceImpl.save(mWifiConfig, mActionListener, TEST_PACKAGE_NAME); 5956 mLooper.dispatchAll(); 5957 5958 verify(mWifiConfigManager).updateBeforeSaveNetwork(eq(mWifiConfig), anyInt(), any()); 5959 5960 verify(mClientModeManager, never()).saveNetwork(any(), any(), anyInt(), any()); 5961 verify(mContext, never()).sendBroadcastWithMultiplePermissions(any(), any()); 5962 verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR); 5963 verify(mActionListener, never()).onSuccess(); 5964 } 5965 5966 /** 5967 * Verify that the FORGET_NETWORK message received from an app with 5968 * one of the privileged permission is forwarded to ClientModeManager. 5969 */ 5970 @Test testForgetNetworkWithPrivilegedPermission()5971 public void testForgetNetworkWithPrivilegedPermission() throws Exception { 5972 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5973 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5974 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 5975 when(mWifiConfigManager.removeNetwork(anyInt(), anyInt(), any())).thenReturn(true); 5976 mWifiServiceImpl.forget(TEST_NETWORK_ID, mock(IActionListener.class)); 5977 5978 InOrder inOrder = inOrder(mWifiConfigManager, mWifiMetrics); 5979 inOrder.verify(mWifiMetrics).logUserActionEvent( 5980 UserActionEvent.EVENT_FORGET_WIFI, TEST_NETWORK_ID); 5981 5982 mLooper.dispatchAll(); 5983 inOrder.verify(mWifiConfigManager).removeNetwork(anyInt(), anyInt(), any()); 5984 verify(mLastCallerInfoManager).put(eq(WifiManager.API_FORGET), anyInt(), 5985 anyInt(), anyInt(), anyString(), eq(true)); 5986 } 5987 5988 @Test forgetNetwork_success()5989 public void forgetNetwork_success() throws Exception { 5990 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 5991 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 5992 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig); 5993 when(mWifiConfigManager.removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any())) 5994 .thenReturn(true); 5995 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 5996 5997 mWifiServiceImpl.forget(TEST_NETWORK_ID, mActionListener); 5998 mLooper.dispatchAll(); 5999 6000 verify(mWifiConfigManager).removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any()); 6001 verify(mActionListener).onSuccess(); 6002 verify(mActionListener, never()) 6003 .onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR); 6004 6005 verify(mContextAsUser).sendBroadcastWithMultiplePermissions( 6006 mIntentCaptor.capture(), 6007 aryEq(new String[]{ 6008 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE, 6009 android.Manifest.permission.ACCESS_FINE_LOCATION, 6010 })); 6011 6012 Intent intent = mIntentCaptor.getValue(); 6013 assertThat(intent.getAction()).isEqualTo(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 6014 assertThat(intent.getStringExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID)) 6015 .isEqualTo(TEST_SSID); 6016 assertThat(intent.getIntExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, -1)) 6017 .isEqualTo(WifiManager.WIFI_CREDENTIAL_FORGOT); 6018 } 6019 6020 @Test forgetNetwork_successNoLocation_dontBroadcastSsid()6021 public void forgetNetwork_successNoLocation_dontBroadcastSsid() throws Exception { 6022 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(false); 6023 6024 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6025 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 6026 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig); 6027 when(mWifiConfigManager.removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any())) 6028 .thenReturn(true); 6029 6030 mWifiServiceImpl.forget(TEST_NETWORK_ID, mActionListener); 6031 mLooper.dispatchAll(); 6032 6033 verify(mWifiConfigManager).removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any()); 6034 verify(mActionListener).onSuccess(); 6035 verify(mActionListener, never()) 6036 .onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR); 6037 6038 verify(mContextAsUser).sendBroadcastWithMultiplePermissions( 6039 mIntentCaptor.capture(), 6040 aryEq(new String[]{ 6041 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE, 6042 android.Manifest.permission.ACCESS_FINE_LOCATION, 6043 })); 6044 6045 Intent intent = mIntentCaptor.getValue(); 6046 assertThat(intent.getAction()).isEqualTo(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 6047 // SSID is null if location is disabled 6048 assertThat(intent.getStringExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID)).isNull(); 6049 assertThat(intent.getIntExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, -1)) 6050 .isEqualTo(WifiManager.WIFI_CREDENTIAL_FORGOT); 6051 } 6052 6053 @Test forgetNetwork_failed()6054 public void forgetNetwork_failed() throws Exception { 6055 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6056 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 6057 when(mWifiConfigManager.removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any())) 6058 .thenReturn(false); 6059 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 6060 6061 mWifiServiceImpl.forget(TEST_NETWORK_ID, mActionListener); 6062 mLooper.dispatchAll(); 6063 6064 verify(mActionListener, never()).onSuccess(); 6065 verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR); 6066 verify(mWifiConfigManager).removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any()); 6067 verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any()); 6068 } 6069 6070 /** 6071 * Verify that connecting to a supported security type network succeeds 6072 */ 6073 @Test connectToSupportedSecurityTypeNetwork_success()6074 public void connectToSupportedSecurityTypeNetwork_success() throws Exception { 6075 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6076 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 6077 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 6078 NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID); 6079 when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt())) 6080 .thenReturn(result); 6081 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig); 6082 when(mWifiGlobals.isDeprecatedSecurityTypeNetwork(mWifiConfig)).thenReturn(false); 6083 6084 mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID, 6085 mActionListener, TEST_PACKAGE_NAME, mExtras); 6086 mLooper.dispatchAll(); 6087 6088 ArgumentCaptor<WifiConfiguration> configCaptor = 6089 ArgumentCaptor.forClass(WifiConfiguration.class); 6090 verify(mWifiConfigManager).addOrUpdateNetwork(configCaptor.capture(), anyInt()); 6091 assertThat(configCaptor.getValue().networkId).isEqualTo(TEST_NETWORK_ID); 6092 6093 verify(mConnectHelper).connectToNetwork(eq(result), any(), anyInt(), any(), any()); 6094 } 6095 6096 /** 6097 * Verify that connecting to a deprecated security type network fails, 6098 * but saves the network instead 6099 */ 6100 @Test connectToDeprecatedSecurityTypeNetwork_failure()6101 public void connectToDeprecatedSecurityTypeNetwork_failure() throws Exception { 6102 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6103 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 6104 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 6105 NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID); 6106 when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt())) 6107 .thenReturn(result); 6108 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig); 6109 when(mWifiGlobals.isDeprecatedSecurityTypeNetwork(mWifiConfig)).thenReturn(true); 6110 6111 mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID, 6112 mActionListener, TEST_PACKAGE_NAME, mExtras); 6113 mLooper.dispatchAll(); 6114 6115 ArgumentCaptor<WifiConfiguration> configCaptor = 6116 ArgumentCaptor.forClass(WifiConfiguration.class); 6117 verify(mWifiConfigManager).addOrUpdateNetwork(configCaptor.capture(), anyInt()); 6118 assertThat(configCaptor.getValue().networkId).isEqualTo(TEST_NETWORK_ID); 6119 6120 verify(mWifiConfigManager).addOrUpdateNetwork(eq(mWifiConfig), anyInt()); 6121 verify(mClientModeManager, never()).connectNetwork(any(), any(), anyInt(), any(), any()); 6122 verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR); 6123 verify(mActionListener, never()).onSuccess(); 6124 } 6125 6126 /** 6127 * Tests the scenario when a scan request arrives while the device is idle. In this case 6128 * the scan is done when idle mode ends. 6129 */ 6130 @Test testHandleDelayedScanAfterIdleMode()6131 public void testHandleDelayedScanAfterIdleMode() throws Exception { 6132 when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false); 6133 mWifiServiceImpl.checkAndStartWifi(); 6134 mWifiServiceImpl.handleBootCompleted(); 6135 mLooper.dispatchAll(); 6136 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6137 (IntentFilter) argThat(new IdleModeIntentMatcher()), 6138 isNull(), 6139 any(Handler.class)); 6140 6141 // Tell the wifi service that the device became idle. 6142 when(mPowerManager.isDeviceIdleMode()).thenReturn(true); 6143 TestUtil.sendIdleModeChanged(mBroadcastReceiverCaptor.getValue(), mContext); 6144 6145 // Send a scan request while the device is idle. 6146 mLooper.startAutoDispatch(); 6147 assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID)); 6148 mLooper.stopAutoDispatchAndIgnoreExceptions(); 6149 // No scans must be made yet as the device is idle. 6150 verify(mScanRequestProxy, never()).startScan(Process.myUid(), SCAN_PACKAGE_NAME); 6151 // Verify ActiveModeWarden is notified of the idle mode change 6152 verify(mActiveModeWarden).onIdleModeChanged(true); 6153 6154 // Tell the wifi service that idle mode ended. 6155 when(mPowerManager.isDeviceIdleMode()).thenReturn(false); 6156 mLooper.startAutoDispatch(); 6157 TestUtil.sendIdleModeChanged(mBroadcastReceiverCaptor.getValue(), mContext); 6158 mLooper.stopAutoDispatchAndIgnoreExceptions(); 6159 // Verify ActiveModeWarden is notified of the idle mode change 6160 verify(mActiveModeWarden).onIdleModeChanged(false); 6161 6162 // Must scan now. 6163 verify(mScanRequestProxy).startScan(Process.myUid(), TEST_PACKAGE_NAME); 6164 // The app ops check is executed with this package's identity (not the identity of the 6165 // original remote caller who requested the scan while idle). 6166 verify(mAppOpsManager).noteOp( 6167 AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 6168 6169 // Send another scan request. The device is not idle anymore, so it must be executed 6170 // immediately. 6171 mLooper.startAutoDispatch(); 6172 assertTrue(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID)); 6173 mLooper.stopAutoDispatchAndIgnoreExceptions(); 6174 verify(mScanRequestProxy).startScan(Process.myUid(), SCAN_PACKAGE_NAME); 6175 } 6176 6177 /** 6178 * Verify that if the caller has NETWORK_SETTINGS permission, then it doesn't need 6179 * CHANGE_WIFI_STATE permission. 6180 */ 6181 @Test testDisconnectWithNetworkSettingsPerm()6182 public void testDisconnectWithNetworkSettingsPerm() throws Exception { 6183 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6184 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 6185 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 6186 android.Manifest.permission.CHANGE_WIFI_STATE, "WifiService"); 6187 doThrow(new SecurityException()).when(mAppOpsManager) 6188 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 6189 assertTrue(mWifiServiceImpl.disconnect(TEST_PACKAGE_NAME)); 6190 mLooper.dispatchAll(); 6191 verify(mClientModeManager).disconnect(); 6192 } 6193 6194 /** 6195 * Verify that if the caller doesn't have NETWORK_SETTINGS permission, it could still 6196 * get access with the CHANGE_WIFI_STATE permission. 6197 */ 6198 @Test testDisconnectWithChangeWifiStatePerm()6199 public void testDisconnectWithChangeWifiStatePerm() throws Exception { 6200 assertFalse(mWifiServiceImpl.disconnect(TEST_PACKAGE_NAME)); 6201 mLooper.dispatchAll(); 6202 verifyCheckChangePermission(TEST_PACKAGE_NAME); 6203 verify(mClientModeManager, never()).disconnect(); 6204 } 6205 6206 /** 6207 * Verify that the operation fails if the caller has neither NETWORK_SETTINGS or 6208 * CHANGE_WIFI_STATE permissions. 6209 */ 6210 @Test testDisconnectRejected()6211 public void testDisconnectRejected() throws Exception { 6212 doThrow(new SecurityException()).when(mAppOpsManager) 6213 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 6214 try { 6215 mWifiServiceImpl.disconnect(TEST_PACKAGE_NAME); 6216 fail(); 6217 } catch (SecurityException e) { 6218 6219 } 6220 verifyCheckChangePermission(TEST_PACKAGE_NAME); 6221 verify(mClientModeManager, never()).disconnect(); 6222 } 6223 6224 @Test testPackageFullyRemovedBroadcastHandling()6225 public void testPackageFullyRemovedBroadcastHandling() throws Exception { 6226 mWifiServiceImpl.checkAndStartWifi(); 6227 mLooper.dispatchAll(); 6228 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6229 argThat((IntentFilter filter) -> 6230 filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED) 6231 && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED) 6232 && filter.hasAction(Intent.ACTION_PACKAGE_CHANGED)), 6233 isNull(), 6234 any(Handler.class)); 6235 int uid = TEST_UID; 6236 String packageName = TEST_PACKAGE_NAME; 6237 doThrow(new PackageManager.NameNotFoundException()).when(mPackageManager) 6238 .getApplicationInfo(TEST_PACKAGE_NAME, 0); 6239 // Send the broadcast 6240 Intent intent = new Intent(Intent.ACTION_PACKAGE_FULLY_REMOVED); 6241 intent.putExtra(Intent.EXTRA_UID, uid); 6242 intent.setData(Uri.fromParts("package", packageName, "")); 6243 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6244 mLooper.dispatchAll(); 6245 6246 ArgumentCaptor<ApplicationInfo> aiCaptor = ArgumentCaptor.forClass(ApplicationInfo.class); 6247 verify(mWifiConfigManager).removeNetworksForApp(aiCaptor.capture()); 6248 assertNotNull(aiCaptor.getValue()); 6249 assertEquals(uid, aiCaptor.getValue().uid); 6250 assertEquals(packageName, aiCaptor.getValue().packageName); 6251 6252 verify(mScanRequestProxy).clearScanRequestTimestampsForApp(packageName, uid); 6253 verify(mWifiNetworkSuggestionsManager).removeApp(packageName); 6254 verify(mWifiNetworkFactory).removeApp(packageName); 6255 verify(mPasspointManager).removePasspointProviderWithPackage(packageName); 6256 } 6257 6258 @Test testPackageRemovedBroadcastHandling()6259 public void testPackageRemovedBroadcastHandling() throws Exception { 6260 mWifiServiceImpl.checkAndStartWifi(); 6261 mLooper.dispatchAll(); 6262 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6263 argThat((IntentFilter filter) -> 6264 filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED) 6265 && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED) 6266 && filter.hasAction(Intent.ACTION_PACKAGE_CHANGED)), 6267 isNull(), 6268 any(Handler.class)); 6269 int uid = TEST_UID; 6270 String packageName = TEST_PACKAGE_NAME; 6271 // Send the broadcast 6272 Intent intent = new Intent(Intent.ACTION_PACKAGE_REMOVED); 6273 intent.putExtra(Intent.EXTRA_UID, uid); 6274 intent.setData(Uri.fromParts("package", packageName, "")); 6275 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6276 mLooper.dispatchAll(); 6277 6278 ArgumentCaptor<ApplicationInfo> aiCaptor = ArgumentCaptor.forClass(ApplicationInfo.class); 6279 verify(mWifiConfigManager).removeNetworksForApp(aiCaptor.capture()); 6280 assertNotNull(aiCaptor.getValue()); 6281 assertEquals(uid, aiCaptor.getValue().uid); 6282 assertEquals(packageName, aiCaptor.getValue().packageName); 6283 6284 verify(mScanRequestProxy).clearScanRequestTimestampsForApp(packageName, uid); 6285 verify(mWifiNetworkSuggestionsManager).removeApp(packageName); 6286 verify(mWifiNetworkFactory).removeApp(packageName); 6287 verify(mPasspointManager).removePasspointProviderWithPackage(packageName); 6288 } 6289 6290 @Test testPackageRemovedWithReplacingBroadcastHandling()6291 public void testPackageRemovedWithReplacingBroadcastHandling() throws Exception { 6292 mWifiServiceImpl.checkAndStartWifi(); 6293 mLooper.dispatchAll(); 6294 verify(mContext) 6295 .registerReceiver( 6296 mBroadcastReceiverCaptor.capture(), 6297 argThat( 6298 (IntentFilter filter) -> 6299 filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED) 6300 && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED) 6301 && filter.hasAction(Intent.ACTION_PACKAGE_CHANGED)), 6302 isNull(), 6303 any(Handler.class)); 6304 int uid = TEST_UID; 6305 String packageName = TEST_PACKAGE_NAME; 6306 // Send the broadcast 6307 Intent intent = new Intent(Intent.ACTION_PACKAGE_REMOVED); 6308 intent.putExtra(Intent.EXTRA_UID, uid); 6309 intent.setData(Uri.fromParts("package", packageName, "")); 6310 intent.putExtra(Intent.EXTRA_REPLACING, true); 6311 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6312 mLooper.dispatchAll(); 6313 verify(mWifiConfigManager, never()).removeNetworksForApp(any()); 6314 verify(mScanRequestProxy, never()).clearScanRequestTimestampsForApp(anyString(), anyInt()); 6315 verify(mWifiNetworkSuggestionsManager, never()).removeApp(anyString()); 6316 verify(mWifiNetworkFactory, never()).removeApp(anyString()); 6317 verify(mPasspointManager, never()).removePasspointProviderWithPackage(anyString()); 6318 } 6319 6320 @Test testPackageDisableBroadcastHandling()6321 public void testPackageDisableBroadcastHandling() throws Exception { 6322 mWifiServiceImpl.checkAndStartWifi(); 6323 mLooper.dispatchAll(); 6324 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6325 argThat((IntentFilter filter) -> 6326 filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED) 6327 && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED) 6328 && filter.hasAction(Intent.ACTION_PACKAGE_CHANGED)), 6329 isNull(), 6330 any(Handler.class)); 6331 int uid = TEST_UID; 6332 String packageName = TEST_PACKAGE_NAME; 6333 mPackageInfo.applicationInfo = mApplicationInfo; 6334 mApplicationInfo.enabled = false; 6335 // Send the broadcast 6336 Intent intent = new Intent(Intent.ACTION_PACKAGE_CHANGED); 6337 intent.putExtra(Intent.EXTRA_UID, uid); 6338 intent.setData(Uri.fromParts("package", packageName, "")); 6339 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6340 mLooper.dispatchAll(); 6341 6342 ArgumentCaptor<ApplicationInfo> aiCaptor = ArgumentCaptor.forClass(ApplicationInfo.class); 6343 verify(mWifiConfigManager).removeNetworksForApp(aiCaptor.capture()); 6344 assertNotNull(aiCaptor.getValue()); 6345 assertEquals(uid, aiCaptor.getValue().uid); 6346 assertEquals(packageName, aiCaptor.getValue().packageName); 6347 6348 verify(mScanRequestProxy).clearScanRequestTimestampsForApp(packageName, uid); 6349 verify(mWifiNetworkSuggestionsManager).removeApp(packageName); 6350 verify(mWifiNetworkFactory).removeApp(packageName); 6351 verify(mPasspointManager).removePasspointProviderWithPackage(packageName); 6352 } 6353 6354 @Test testPackageRemovedBroadcastHandlingWithNoUid()6355 public void testPackageRemovedBroadcastHandlingWithNoUid() { 6356 mWifiServiceImpl.checkAndStartWifi(); 6357 mLooper.dispatchAll(); 6358 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6359 argThat((IntentFilter filter) -> 6360 filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)), 6361 isNull(), 6362 any(Handler.class)); 6363 6364 String packageName = TEST_PACKAGE_NAME; 6365 // Send the broadcast 6366 Intent intent = new Intent(Intent.ACTION_PACKAGE_REMOVED); 6367 intent.setData(Uri.fromParts("package", packageName, "")); 6368 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6369 6370 verify(mWifiConfigManager, never()).removeNetworksForApp(any()); 6371 6372 mLooper.dispatchAll(); 6373 verify(mScanRequestProxy, never()).clearScanRequestTimestampsForApp(anyString(), anyInt()); 6374 verify(mWifiNetworkSuggestionsManager, never()).removeApp(anyString()); 6375 verify(mWifiNetworkFactory, never()).removeApp(anyString()); 6376 verify(mPasspointManager, never()).removePasspointProviderWithPackage(anyString()); 6377 } 6378 6379 @Test testPackageRemovedBroadcastHandlingWithNoPackageName()6380 public void testPackageRemovedBroadcastHandlingWithNoPackageName() { 6381 mWifiServiceImpl.checkAndStartWifi(); 6382 mLooper.dispatchAll(); 6383 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6384 argThat((IntentFilter filter) -> 6385 filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)), 6386 isNull(), 6387 any(Handler.class)); 6388 6389 int uid = TEST_UID; 6390 // Send the broadcast 6391 Intent intent = new Intent(Intent.ACTION_PACKAGE_FULLY_REMOVED); 6392 intent.putExtra(Intent.EXTRA_UID, uid); 6393 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6394 6395 verify(mWifiConfigManager, never()).removeNetworksForApp(any()); 6396 6397 mLooper.dispatchAll(); 6398 verify(mScanRequestProxy, never()).clearScanRequestTimestampsForApp(anyString(), anyInt()); 6399 verify(mWifiNetworkSuggestionsManager, never()).removeApp(anyString()); 6400 verify(mWifiNetworkFactory, never()).removeApp(anyString()); 6401 verify(mPasspointManager, never()).removePasspointProviderWithPackage(anyString()); 6402 } 6403 6404 @Test testUserRemovedBroadcastHandling()6405 public void testUserRemovedBroadcastHandling() { 6406 mWifiServiceImpl.checkAndStartWifi(); 6407 mWifiServiceImpl.handleBootCompleted(); 6408 mLooper.dispatchAll(); 6409 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6410 argThat((IntentFilter filter) -> 6411 filter.hasAction(Intent.ACTION_USER_REMOVED)), 6412 isNull(), 6413 any(Handler.class)); 6414 6415 UserHandle userHandle = UserHandle.of(TEST_USER_HANDLE); 6416 // Send the broadcast 6417 Intent intent = new Intent(Intent.ACTION_USER_REMOVED); 6418 intent.putExtra(Intent.EXTRA_USER, userHandle); 6419 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6420 mLooper.dispatchAll(); 6421 6422 verify(mWifiConfigManager).removeNetworksForUser(userHandle.getIdentifier()); 6423 } 6424 6425 @Test testBluetoothBroadcastHandling()6426 public void testBluetoothBroadcastHandling() { 6427 mWifiServiceImpl.checkAndStartWifi(); 6428 mWifiServiceImpl.handleBootCompleted(); 6429 mLooper.dispatchAll(); 6430 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6431 argThat((IntentFilter filter) -> 6432 filter.hasAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED) 6433 && filter.hasAction(BluetoothAdapter.ACTION_STATE_CHANGED)), 6434 isNull(), 6435 any(Handler.class)); 6436 6437 { 6438 Intent intent = new Intent(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); 6439 intent.putExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 6440 BluetoothAdapter.STATE_DISCONNECTED); 6441 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6442 mLooper.dispatchAll(); 6443 6444 verify(mWifiGlobals).setBluetoothConnected(false); 6445 for (ClientModeManager cmm : mClientModeManagers) { 6446 verify(cmm).onBluetoothConnectionStateChanged(); 6447 } 6448 } 6449 6450 { 6451 Intent intent = new Intent(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); 6452 intent.putExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 6453 BluetoothAdapter.STATE_CONNECTED); 6454 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6455 mLooper.dispatchAll(); 6456 6457 verify(mWifiGlobals).setBluetoothConnected(true); 6458 for (ClientModeManager cmm : mClientModeManagers) { 6459 verify(cmm, times(2)).onBluetoothConnectionStateChanged(); 6460 } 6461 } 6462 6463 { 6464 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED); 6465 intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF); 6466 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6467 mLooper.dispatchAll(); 6468 6469 verify(mWifiGlobals).setBluetoothEnabled(false); 6470 for (ClientModeManager cmm : mClientModeManagers) { 6471 verify(cmm, times(3)).onBluetoothConnectionStateChanged(); 6472 } 6473 } 6474 6475 { 6476 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED); 6477 intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON); 6478 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6479 mLooper.dispatchAll(); 6480 6481 verify(mWifiGlobals).setBluetoothEnabled(true); 6482 for (ClientModeManager cmm : mClientModeManagers) { 6483 verify(cmm, times(4)).onBluetoothConnectionStateChanged(); 6484 } 6485 } 6486 } 6487 6488 @Test testUserRemovedBroadcastHandlingWithWrongIntentAction()6489 public void testUserRemovedBroadcastHandlingWithWrongIntentAction() { 6490 mWifiServiceImpl.checkAndStartWifi(); 6491 mWifiServiceImpl.handleBootCompleted(); 6492 mLooper.dispatchAll(); 6493 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6494 argThat((IntentFilter filter) -> 6495 filter.hasAction(Intent.ACTION_USER_REMOVED)), 6496 isNull(), 6497 any(Handler.class)); 6498 6499 UserHandle userHandle = UserHandle.of(TEST_USER_HANDLE); 6500 // Send the broadcast with wrong action 6501 Intent intent = new Intent(Intent.ACTION_USER_FOREGROUND); 6502 intent.putExtra(Intent.EXTRA_USER, userHandle); 6503 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6504 6505 verify(mWifiConfigManager, never()).removeNetworksForUser(anyInt()); 6506 } 6507 6508 private class IdleModeIntentMatcher implements ArgumentMatcher<IntentFilter> { 6509 @Override matches(IntentFilter filter)6510 public boolean matches(IntentFilter filter) { 6511 return filter.hasAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED); 6512 } 6513 } 6514 6515 /** 6516 * Verifies that enforceChangePermission(String package) is called and the caller doesn't 6517 * have NETWORK_SETTINGS permission 6518 */ verifyCheckChangePermission(String callingPackageName)6519 private void verifyCheckChangePermission(String callingPackageName) { 6520 verify(mContext, atLeastOnce()) 6521 .checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6522 anyInt(), anyInt()); 6523 verify(mContext, atLeastOnce()).enforceCallingOrSelfPermission( 6524 android.Manifest.permission.CHANGE_WIFI_STATE, "WifiService"); 6525 verify(mAppOpsManager, atLeastOnce()).noteOp( 6526 AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), callingPackageName); 6527 } 6528 createValidWifiApConfiguration()6529 private WifiConfiguration createValidWifiApConfiguration() { 6530 WifiConfiguration apConfig = new WifiConfiguration(); 6531 apConfig.SSID = "TestAp"; 6532 apConfig.preSharedKey = "thisIsABadPassword"; 6533 apConfig.allowedKeyManagement.set(KeyMgmt.WPA2_PSK); 6534 apConfig.apBand = WifiConfiguration.AP_BAND_2GHZ; 6535 6536 return apConfig; 6537 } 6538 createValidSoftApConfiguration()6539 private SoftApConfiguration createValidSoftApConfiguration() { 6540 return new SoftApConfiguration.Builder() 6541 .setSsid("TestAp") 6542 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) 6543 .setBand(SoftApConfiguration.BAND_2GHZ) 6544 .build(); 6545 } 6546 6547 /** 6548 * Verifies that sim state change does not set or reset the country code 6549 */ 6550 @Test testSimStateChangeDoesNotResetCountryCode()6551 public void testSimStateChangeDoesNotResetCountryCode() { 6552 mWifiServiceImpl.checkAndStartWifi(); 6553 mLooper.dispatchAll(); 6554 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6555 (IntentFilter) argThat((IntentFilter filter) -> 6556 filter.hasAction(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED)), 6557 isNull(), 6558 any(Handler.class)); 6559 6560 int userHandle = TEST_USER_HANDLE; 6561 // Send the broadcast 6562 Intent intent = new Intent(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED); 6563 intent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle); 6564 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6565 verify(mWifiCountryCode, never()).setTelephonyCountryCodeAndUpdate(any()); 6566 } 6567 6568 /** 6569 * Verifies that sim state change does not set or reset the country code 6570 */ 6571 @Test testSimStateChangeDoesNotResetCountryCodeForRebroadcastedIntent()6572 public void testSimStateChangeDoesNotResetCountryCodeForRebroadcastedIntent() { 6573 mWifiServiceImpl.checkAndStartWifi(); 6574 mLooper.dispatchAll(); 6575 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6576 (IntentFilter) argThat((IntentFilter filter) -> 6577 filter.hasAction(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED)), 6578 isNull(), 6579 any(Handler.class)); 6580 6581 int userHandle = TEST_USER_HANDLE; 6582 // Send the broadcast 6583 Intent intent = new Intent(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED); 6584 intent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle); 6585 intent.putExtra(TelephonyManager.EXTRA_SIM_STATE, Intent.SIM_STATE_ABSENT); 6586 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6587 verify(mWifiCountryCode, never()).setTelephonyCountryCodeAndUpdate(any()); 6588 } 6589 6590 /** 6591 * Verify removing sim will also remove an ephemeral Passpoint Provider. And reset carrier 6592 * privileged suggestor apps. 6593 */ 6594 @Test testResetSimNetworkWhenRemovingSim()6595 public void testResetSimNetworkWhenRemovingSim() throws Exception { 6596 mWifiServiceImpl.checkAndStartWifi(); 6597 mLooper.dispatchAll(); 6598 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6599 argThat((IntentFilter filter) -> 6600 filter.hasAction(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED)), 6601 isNull(), 6602 any(Handler.class)); 6603 6604 Intent intent = new Intent(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED); 6605 intent.putExtra(TelephonyManager.EXTRA_SIM_STATE, TelephonyManager.SIM_STATE_ABSENT); 6606 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6607 mLooper.dispatchAll(); 6608 6609 verify(mResourceCache).reset(); 6610 verify(mWifiConfigManager).resetSimNetworks(); 6611 verify(mWifiConfigManager).stopRestrictingAutoJoinToSubscriptionId(); 6612 verify(mSimRequiredNotifier, never()).dismissSimRequiredNotification(); 6613 verify(mWifiNetworkSuggestionsManager).updateCarrierPrivilegedApps(); 6614 verify(mWifiConfigManager, never()).removeAllEphemeralOrPasspointConfiguredNetworks(); 6615 verify(mWifiNetworkSuggestionsManager).resetSimNetworkSuggestions(); 6616 verify(mPasspointManager).resetSimPasspointNetwork(); 6617 } 6618 6619 /** 6620 * Verify inserting sim will reset carrier privileged suggestor apps. 6621 * and remove any previous notifications due to sim removal 6622 */ 6623 @Test testResetCarrierPrivilegedAppsWhenInsertingSim()6624 public void testResetCarrierPrivilegedAppsWhenInsertingSim() throws Exception { 6625 mWifiServiceImpl.checkAndStartWifi(); 6626 mLooper.dispatchAll(); 6627 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6628 argThat((IntentFilter filter) -> 6629 filter.hasAction(TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED)), 6630 isNull(), 6631 any(Handler.class)); 6632 6633 Intent intent = new Intent(TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED); 6634 intent.putExtra(TelephonyManager.EXTRA_SIM_STATE, TelephonyManager.SIM_STATE_LOADED); 6635 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6636 mLooper.dispatchAll(); 6637 6638 verify(mResourceCache).reset(); 6639 verify(mWifiConfigManager, never()).resetSimNetworks(); 6640 verify(mPasspointManager, never()).resetSimPasspointNetwork(); 6641 verify(mWifiNetworkSuggestionsManager, never()).resetSimNetworkSuggestions(); 6642 verify(mWifiConfigManager, never()).stopRestrictingAutoJoinToSubscriptionId(); 6643 verify(mSimRequiredNotifier).dismissSimRequiredNotification(); 6644 verify(mWifiNetworkSuggestionsManager).updateCarrierPrivilegedApps(); 6645 verify(mWifiConfigManager, never()).removeAllEphemeralOrPasspointConfiguredNetworks(); 6646 verify(mWifiConfigManager).enableTemporaryDisabledNetworks(); 6647 verify(mWifiConnectivityManager).forceConnectivityScan(any()); 6648 } 6649 6650 @Test testResetSimNetworkWhenDefaultDataSimChanged()6651 public void testResetSimNetworkWhenDefaultDataSimChanged() throws Exception { 6652 mWifiServiceImpl.checkAndStartWifi(); 6653 mLooper.dispatchAll(); 6654 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 6655 argThat((IntentFilter filter) -> 6656 filter.hasAction( 6657 TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED)), 6658 isNull(), 6659 any(Handler.class)); 6660 6661 Intent intent = new Intent(TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED); 6662 intent.putExtra("subscription", 1); 6663 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 6664 mLooper.dispatchAll(); 6665 6666 verify(mResourceCache).reset(); 6667 verify(mWifiConfigManager).resetSimNetworks(); 6668 verify(mWifiConfigManager).stopRestrictingAutoJoinToSubscriptionId(); 6669 verify(mSimRequiredNotifier, never()).dismissSimRequiredNotification(); 6670 verify(mWifiNetworkSuggestionsManager).updateCarrierPrivilegedApps(); 6671 verify(mWifiConfigManager).removeEphemeralCarrierNetworks(anySet()); 6672 verify(mWifiNetworkSuggestionsManager).resetSimNetworkSuggestions(); 6673 verify(mPasspointManager).resetSimPasspointNetwork(); 6674 verify(mWifiDataStall).resetPhoneStateListener(); 6675 } 6676 6677 /** 6678 * Verify that a call to registerTrafficStateCallback throws a SecurityException if the caller 6679 * does not have NETWORK_SETTINGS permission. 6680 */ 6681 @Test registerTrafficStateCallbackThrowsSecurityExceptionOnMissingPermissions()6682 public void registerTrafficStateCallbackThrowsSecurityExceptionOnMissingPermissions() { 6683 doThrow(new SecurityException()).when(mContext) 6684 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6685 eq("WifiService")); 6686 try { 6687 mWifiServiceImpl.registerTrafficStateCallback(mTrafficStateCallback); 6688 fail("expected SecurityException"); 6689 } catch (SecurityException expected) { 6690 } 6691 } 6692 6693 /** 6694 * Verify that a call to registerTrafficStateCallback throws an IllegalArgumentException if the 6695 * parameters are not provided. 6696 */ 6697 @Test registerTrafficStateCallbackThrowsIllegalArgumentExceptionOnInvalidArguments()6698 public void registerTrafficStateCallbackThrowsIllegalArgumentExceptionOnInvalidArguments() { 6699 try { 6700 mWifiServiceImpl.registerTrafficStateCallback(null); 6701 fail("expected IllegalArgumentException"); 6702 } catch (IllegalArgumentException expected) { 6703 } 6704 } 6705 6706 /** 6707 * Verify that a call to unregisterTrafficStateCallback throws a SecurityException if the caller 6708 * does not have NETWORK_SETTINGS permission. 6709 */ 6710 @Test unregisterTrafficStateCallbackThrowsSecurityExceptionOnMissingPermissions()6711 public void unregisterTrafficStateCallbackThrowsSecurityExceptionOnMissingPermissions() { 6712 doThrow(new SecurityException()).when(mContext) 6713 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6714 eq("WifiService")); 6715 try { 6716 mWifiServiceImpl.unregisterTrafficStateCallback(mTrafficStateCallback); 6717 fail("expected SecurityException"); 6718 } catch (SecurityException expected) { 6719 } 6720 } 6721 6722 /** 6723 * Verify that registerTrafficStateCallback adds callback to {@link WifiTrafficPoller}. 6724 */ 6725 @Test registerTrafficStateCallbackAndVerify()6726 public void registerTrafficStateCallbackAndVerify() throws Exception { 6727 mWifiServiceImpl.registerTrafficStateCallback(mTrafficStateCallback); 6728 mLooper.dispatchAll(); 6729 verify(mWifiTrafficPoller).addCallback(mTrafficStateCallback); 6730 } 6731 6732 /** 6733 * Verify that unregisterTrafficStateCallback removes callback from {@link WifiTrafficPoller}. 6734 */ 6735 @Test unregisterTrafficStateCallbackAndVerify()6736 public void unregisterTrafficStateCallbackAndVerify() throws Exception { 6737 mWifiServiceImpl.unregisterTrafficStateCallback(mTrafficStateCallback); 6738 mLooper.dispatchAll(); 6739 verify(mWifiTrafficPoller).removeCallback(mTrafficStateCallback); 6740 } 6741 6742 /** 6743 * Verify that a call to registerNetworkRequestMatchCallback throws a SecurityException if the 6744 * caller does not have NETWORK_SETTINGS permission. 6745 */ 6746 @Test registerNetworkRequestMatchCallbackThrowsSecurityExceptionOnMissingPermissions()6747 public void registerNetworkRequestMatchCallbackThrowsSecurityExceptionOnMissingPermissions() { 6748 doThrow(new SecurityException()).when(mContext) 6749 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6750 eq("WifiService")); 6751 try { 6752 mWifiServiceImpl.registerNetworkRequestMatchCallback(mNetworkRequestMatchCallback); 6753 fail("expected SecurityException"); 6754 } catch (SecurityException expected) { 6755 } 6756 } 6757 6758 /** 6759 * Verify that a call to registerNetworkRequestMatchCallback throws an IllegalArgumentException 6760 * if the parameters are not provided. 6761 */ 6762 @Test 6763 public void registerNetworkRequestMatchCallbackThrowsIllegalArgumentExceptionOnInvalidArguments()6764 registerNetworkRequestMatchCallbackThrowsIllegalArgumentExceptionOnInvalidArguments() { 6765 try { 6766 mWifiServiceImpl.registerNetworkRequestMatchCallback(null); 6767 fail("expected IllegalArgumentException"); 6768 } catch (IllegalArgumentException expected) { 6769 } 6770 } 6771 6772 /** 6773 * Verify that a call to unregisterNetworkRequestMatchCallback throws a SecurityException if the 6774 * caller does not have NETWORK_SETTINGS permission. 6775 */ 6776 @Test unregisterNetworkRequestMatchCallbackThrowsSecurityExceptionOnMissingPermissions()6777 public void unregisterNetworkRequestMatchCallbackThrowsSecurityExceptionOnMissingPermissions() { 6778 doThrow(new SecurityException()).when(mContext) 6779 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6780 eq("WifiService")); 6781 try { 6782 mWifiServiceImpl.unregisterNetworkRequestMatchCallback(mNetworkRequestMatchCallback); 6783 fail("expected SecurityException"); 6784 } catch (SecurityException expected) { 6785 } 6786 } 6787 6788 /** 6789 * Verify that registerNetworkRequestMatchCallback adds callback to 6790 * {@link ClientModeManager}. 6791 */ 6792 @Test registerNetworkRequestMatchCallbackAndVerify()6793 public void registerNetworkRequestMatchCallbackAndVerify() throws Exception { 6794 mWifiServiceImpl.registerNetworkRequestMatchCallback(mNetworkRequestMatchCallback); 6795 mLooper.dispatchAll(); 6796 verify(mWifiNetworkFactory).addCallback(mNetworkRequestMatchCallback); 6797 } 6798 6799 /** 6800 * Verify that unregisterNetworkRequestMatchCallback removes callback from 6801 * {@link ClientModeManager}. 6802 */ 6803 @Test unregisterNetworkRequestMatchCallbackAndVerify()6804 public void unregisterNetworkRequestMatchCallbackAndVerify() throws Exception { 6805 mWifiServiceImpl.unregisterNetworkRequestMatchCallback(mNetworkRequestMatchCallback); 6806 mLooper.dispatchAll(); 6807 verify(mWifiNetworkFactory).removeCallback(mNetworkRequestMatchCallback); 6808 } 6809 6810 /** 6811 * Verify that Wifi configuration and Passpoint configuration are removed in factoryReset. 6812 */ 6813 @Test testFactoryReset()6814 public void testFactoryReset() throws Exception { 6815 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 6816 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 6817 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 6818 final String fqdn = "example.com"; 6819 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 6820 openNetwork.networkId = TEST_NETWORK_ID; 6821 WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork( 6822 WifiEnterpriseConfig.Eap.TLS, WifiEnterpriseConfig.Phase2.NONE); 6823 eapNetwork.networkId = TEST_NETWORK_ID + 1; 6824 PasspointConfiguration config = new PasspointConfiguration(); 6825 HomeSp homeSp = new HomeSp(); 6826 homeSp.setFqdn(fqdn); 6827 config.setHomeSp(homeSp); 6828 Credential credential = new Credential(); 6829 credential.setRealm("example.com"); 6830 config.setCredential(credential); 6831 6832 when(mWifiConfigManager.getSavedNetworks(anyInt())) 6833 .thenReturn(Arrays.asList(openNetwork, eapNetwork)); 6834 when(mPasspointManager.getProviderConfigs(anyInt(), anyBoolean())) 6835 .thenReturn(Arrays.asList(config)); 6836 6837 mLooper.startAutoDispatch(); 6838 mWifiServiceImpl.factoryReset(TEST_PACKAGE_NAME); 6839 mLooper.stopAutoDispatchAndIgnoreExceptions(); 6840 6841 // Let the final post inside the |factoryReset| method run to completion. 6842 mLooper.dispatchAll(); 6843 6844 verify(mWifiApConfigStore).setApConfiguration(null); 6845 verify(mWifiConfigManager).removeNetwork( 6846 openNetwork.networkId, Binder.getCallingUid(), TEST_PACKAGE_NAME); 6847 verify(mWifiConfigManager).removeNetwork( 6848 eapNetwork.networkId, Binder.getCallingUid(), TEST_PACKAGE_NAME); 6849 verify(mWifiKeyStore).removeKeys(eapNetwork.enterpriseConfig, true); 6850 verify(mPasspointManager).removeProvider(anyInt(), anyBoolean(), eq(config.getUniqueId()), 6851 isNull()); 6852 verify(mPasspointManager).clearAnqpRequestsAndFlushCache(); 6853 verify(mWifiConfigManager).clearUserTemporarilyDisabledList(); 6854 verify(mWifiConfigManager).removeAllEphemeralOrPasspointConfiguredNetworks(); 6855 verify(mWifiNetworkFactory).clear(); 6856 verify(mWifiNetworkSuggestionsManager).clear(); 6857 verify(mWifiScoreCard).clear(); 6858 verify(mWifiHealthMonitor).clear(); 6859 verify(mPasspointManager).getProviderConfigs(anyInt(), anyBoolean()); 6860 verify(mContext).resetResourceCache(); 6861 } 6862 6863 /** 6864 * Verify that a call to factoryReset throws a SecurityException if the caller does not have 6865 * the NETWORK_SETTINGS permission. 6866 */ 6867 @Test testFactoryResetWithoutNetworkSettingsPermission()6868 public void testFactoryResetWithoutNetworkSettingsPermission() throws Exception { 6869 doThrow(new SecurityException()).when(mContext) 6870 .enforceCallingOrSelfPermission(eq(Manifest.permission.NETWORK_SETTINGS), 6871 eq("WifiService")); 6872 try { 6873 mWifiServiceImpl.factoryReset(TEST_PACKAGE_NAME); 6874 fail(); 6875 } catch (SecurityException e) { 6876 } 6877 verify(mWifiConfigManager, never()).getSavedNetworks(anyInt()); 6878 verify(mPasspointManager, never()).getProviderConfigs(anyInt(), anyBoolean()); 6879 } 6880 6881 /** 6882 * Verify that add or update networks is not allowed for apps targeting Q SDK. 6883 */ 6884 @Test testAddOrUpdateNetworkIsNotAllowedForAppsTargetingQSdk()6885 public void testAddOrUpdateNetworkIsNotAllowedForAppsTargetingQSdk() throws Exception { 6886 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 6887 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 6888 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 6889 new NetworkUpdateResult(0)); 6890 6891 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 6892 mLooper.startAutoDispatch(); 6893 assertEquals(-1, 6894 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 6895 mLooper.stopAutoDispatchAndIgnoreExceptions(); 6896 6897 verifyCheckChangePermission(TEST_PACKAGE_NAME); 6898 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 6899 verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls(); 6900 } 6901 6902 /** 6903 * Verify that add or update networks is allowed for apps targeting below Q SDK. 6904 */ 6905 @Test testAddOrUpdateNetworkIsAllowedForAppsTargetingBelowQSdk()6906 public void testAddOrUpdateNetworkIsAllowedForAppsTargetingBelowQSdk() throws Exception { 6907 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 6908 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 6909 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 6910 new NetworkUpdateResult(0)); 6911 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 6912 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 6913 6914 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 6915 mLooper.startAutoDispatch(); 6916 assertEquals(0, 6917 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 6918 mLooper.stopAutoDispatchAndIgnoreExceptions(); 6919 6920 verifyCheckChangePermission(TEST_PACKAGE_NAME); 6921 verify(mWifiConfigManager).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 6922 verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls(); 6923 } 6924 6925 /** 6926 * Verify that add or update networks is allowed for apps targeting below Q SDK. 6927 */ 6928 @Test testAddOrUpdateNetworkWithBssidAllowListIsNotAllowedForAppsNotPrivileged()6929 public void testAddOrUpdateNetworkWithBssidAllowListIsNotAllowedForAppsNotPrivileged() 6930 throws Exception { 6931 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 6932 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 6933 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 6934 new NetworkUpdateResult(0)); 6935 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 6936 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 6937 6938 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 6939 config.setBssidAllowlist(Collections.emptyList()); 6940 mLooper.startAutoDispatch(); 6941 assertEquals(-1, 6942 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 6943 mLooper.stopAutoDispatchAndIgnoreExceptions(); 6944 6945 verifyCheckChangePermission(TEST_PACKAGE_NAME); 6946 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 6947 verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls(); 6948 } 6949 6950 /** 6951 * Verify that add or update networks is not allowed for apps targeting below Q SDK 6952 * when DISALLOW_ADD_WIFI_CONFIG user restriction is set. 6953 */ 6954 @Test testAddOrUpdateNetworkIsNotAllowedForAppsTargetingBelowQSdkWithUserRestriction()6955 public void testAddOrUpdateNetworkIsNotAllowedForAppsTargetingBelowQSdkWithUserRestriction() 6956 throws Exception { 6957 assumeTrue(SdkLevel.isAtLeastT()); 6958 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 6959 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 6960 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 6961 new NetworkUpdateResult(0)); 6962 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 6963 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 6964 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 6965 any())).thenReturn(true); 6966 6967 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 6968 mLooper.startAutoDispatch(); 6969 assertEquals(-1, 6970 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 6971 mLooper.stopAutoDispatchAndIgnoreExceptions(); 6972 6973 verifyCheckChangePermission(TEST_PACKAGE_NAME); 6974 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 6975 verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls(); 6976 } 6977 6978 /** 6979 * Verify that add or update networks is not allowed for camera app when 6980 * DISALLOW_CONFIG_WIFI user restriction is set. 6981 */ 6982 @Test testAddOrUpdateNetworkIsNotAllowedForCameraDisallowConfigWifi()6983 public void testAddOrUpdateNetworkIsNotAllowedForCameraDisallowConfigWifi() throws Exception { 6984 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 6985 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 6986 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 6987 when(mWifiPermissionsUtil.checkCameraPermission(Binder.getCallingUid())).thenReturn(true); 6988 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 6989 .thenReturn(false); 6990 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 6991 new NetworkUpdateResult(0)); 6992 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), 6993 any())).thenReturn(true); 6994 6995 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 6996 mLooper.startAutoDispatch(); 6997 assertEquals(-1, 6998 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 6999 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7000 7001 verifyCheckChangePermission(TEST_PACKAGE_NAME); 7002 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 7003 verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls(); 7004 } 7005 7006 /** 7007 * Verify that add or update networks is not allowed for camera app when 7008 * DISALLOW_ADD_WIFI_CONFIG user restriction is set. 7009 */ 7010 @Test testAddOrUpdateNetworkIsNotAllowedForCameraDisallowAddWifiConfig()7011 public void testAddOrUpdateNetworkIsNotAllowedForCameraDisallowAddWifiConfig() 7012 throws Exception { 7013 assumeTrue(SdkLevel.isAtLeastT()); 7014 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7015 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7016 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 7017 when(mWifiPermissionsUtil.checkCameraPermission(Binder.getCallingUid())).thenReturn(true); 7018 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 7019 .thenReturn(false); 7020 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 7021 new NetworkUpdateResult(0)); 7022 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 7023 any())).thenReturn(true); 7024 7025 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7026 mLooper.startAutoDispatch(); 7027 assertEquals(-1, 7028 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 7029 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7030 7031 verifyCheckChangePermission(TEST_PACKAGE_NAME); 7032 verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 7033 verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls(); 7034 } 7035 7036 /** 7037 * Verify that add or update networks is allowed for settings app. 7038 */ 7039 @Test testAddOrUpdateNetworkIsAllowedForSettingsApp()7040 public void testAddOrUpdateNetworkIsAllowedForSettingsApp() throws Exception { 7041 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 7042 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 7043 mApplicationInfo.targetSdkVersion = Build.VERSION_CODES.P; 7044 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 7045 new NetworkUpdateResult(0)); 7046 7047 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7048 mLooper.startAutoDispatch(); 7049 assertEquals(0, 7050 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 7051 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7052 7053 // Ensure that we don't check for change permission. 7054 verify(mContext, never()).enforceCallingOrSelfPermission( 7055 android.Manifest.permission.CHANGE_WIFI_STATE, "WifiService"); 7056 verify(mAppOpsManager, never()).noteOp( 7057 AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7058 verify(mWifiConfigManager).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 7059 verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls(); 7060 } 7061 7062 /** 7063 * Verify that add or update networks is allowed for system apps. 7064 */ 7065 @Test testAddOrUpdateNetworkIsAllowedForSystemApp()7066 public void testAddOrUpdateNetworkIsAllowedForSystemApp() throws Exception { 7067 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7068 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7069 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 7070 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 7071 new NetworkUpdateResult(0)); 7072 7073 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7074 mLooper.startAutoDispatch(); 7075 assertEquals(0, 7076 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 7077 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7078 7079 verifyCheckChangePermission(TEST_PACKAGE_NAME); 7080 verify(mWifiConfigManager).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 7081 verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls(); 7082 } 7083 7084 /** 7085 * Verify that add or update networks is allowed for DeviceOwner app. 7086 */ 7087 @Test testAddOrUpdateNetworkIsAllowedForDOApp()7088 public void testAddOrUpdateNetworkIsAllowedForDOApp() throws Exception { 7089 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7090 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7091 when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 7092 .thenReturn(true); 7093 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 7094 new NetworkUpdateResult(0)); 7095 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 7096 .thenReturn(true); 7097 7098 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7099 mLooper.startAutoDispatch(); 7100 assertEquals(0, 7101 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 7102 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7103 7104 verifyCheckChangePermission(TEST_PACKAGE_NAME); 7105 verify(mWifiConfigManager).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 7106 verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls(); 7107 } 7108 7109 /** 7110 * Verify that add or update networks is allowed for ProfileOwner app. 7111 */ 7112 @Test testAddOrUpdateNetworkIsAllowedForPOApp()7113 public void testAddOrUpdateNetworkIsAllowedForPOApp() throws Exception { 7114 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7115 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7116 when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 7117 .thenReturn(true); 7118 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 7119 new NetworkUpdateResult(0)); 7120 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 7121 .thenReturn(true); 7122 7123 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7124 mLooper.startAutoDispatch(); 7125 assertEquals(0, 7126 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 7127 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7128 7129 verifyCheckChangePermission(TEST_PACKAGE_NAME); 7130 verify(mWifiConfigManager).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 7131 verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls(); 7132 } 7133 7134 /** 7135 * Verify that add or update networks is allowed for an admin app. 7136 */ 7137 @Test testAddOrUpdateNetworkIsAllowedForAdminApp()7138 public void testAddOrUpdateNetworkIsAllowedForAdminApp() throws Exception { 7139 assumeTrue(SdkLevel.isAtLeastT()); 7140 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7141 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7142 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 7143 .thenReturn(true); 7144 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn( 7145 new NetworkUpdateResult(0)); 7146 7147 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7148 mLooper.startAutoDispatch(); 7149 assertEquals(0, 7150 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution)); 7151 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7152 7153 verifyCheckChangePermission(TEST_PACKAGE_NAME); 7154 verify(mWifiConfigManager).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 7155 verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls(); 7156 } 7157 verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException()7158 private void verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException() { 7159 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7160 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false))) 7161 .thenReturn(new NetworkUpdateResult(0)); 7162 mLooper.startAutoDispatch(); 7163 mWifiServiceImpl.addOrUpdateNetworkPrivileged(config, TEST_PACKAGE_NAME); 7164 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7165 7166 verify(mWifiConfigManager).addOrUpdateNetwork(any(), anyInt(), any(), eq(false)); 7167 verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls(); 7168 } 7169 7170 /** 7171 * Verify that addOrUpdateNetworkPrivileged throws a SecurityException if the calling app 7172 * has no permissions. 7173 */ 7174 @Test testAddOrUpdateNetworkPrivilegedNotAllowedForNormalApps()7175 public void testAddOrUpdateNetworkPrivilegedNotAllowedForNormalApps() throws Exception { 7176 try { 7177 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7178 mWifiServiceImpl.addOrUpdateNetworkPrivileged(config, TEST_PACKAGE_NAME); 7179 fail("Expected SecurityException for apps without permission"); 7180 } catch (SecurityException e) { 7181 } 7182 } 7183 7184 /** 7185 * Verify that a privileged app with NETWORK_SETTINGS permission is allowed to call 7186 * addOrUpdateNetworkPrivileged. 7187 */ 7188 @Test testAddOrUpdateNetworkPrivilegedIsAllowedForPrivilegedApp()7189 public void testAddOrUpdateNetworkPrivilegedIsAllowedForPrivilegedApp() throws Exception { 7190 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 7191 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 7192 verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException(); 7193 } 7194 7195 /** 7196 * Verify that a system app is allowed to call addOrUpdateNetworkPrivileged. 7197 */ 7198 @Test testAddOrUpdateNetworkPrivilegedIsAllowedForSystemApp()7199 public void testAddOrUpdateNetworkPrivilegedIsAllowedForSystemApp() throws Exception { 7200 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 7201 verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException(); 7202 } 7203 7204 /** 7205 * Verify that an admin app is allowed to call addOrUpdateNetworkPrivileged. 7206 */ 7207 @Test testAddOrUpdateNetworkPrivilegedIsAllowedForAdminApp()7208 public void testAddOrUpdateNetworkPrivilegedIsAllowedForAdminApp() throws Exception { 7209 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 7210 .thenReturn(true); 7211 verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException(); 7212 } 7213 7214 /** 7215 * Verify the proper status code is returned when addOrUpdateNetworkPrivileged failed due to 7216 * a failure in WifiConfigManager.addOrUpdateNetwork(). 7217 */ 7218 @Test testAddOrUpdateNetworkInvalidConfiguration()7219 public void testAddOrUpdateNetworkInvalidConfiguration() throws Exception { 7220 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 7221 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false))) 7222 .thenReturn(new NetworkUpdateResult(-1)); 7223 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7224 mLooper.startAutoDispatch(); 7225 WifiManager.AddNetworkResult result = mWifiServiceImpl.addOrUpdateNetworkPrivileged( 7226 config, TEST_PACKAGE_NAME); 7227 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7228 7229 assertEquals(WifiManager.AddNetworkResult.STATUS_ADD_WIFI_CONFIG_FAILURE, 7230 result.statusCode); 7231 assertEquals(-1, result.networkId); 7232 } 7233 7234 /** 7235 * Verify that enableNetwork is allowed for privileged Apps 7236 */ 7237 @Test testEnableNetworkWithDisableOthersAllowedForPrivilegedApps()7238 public void testEnableNetworkWithDisableOthersAllowedForPrivilegedApps() throws Exception { 7239 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 7240 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 7241 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7242 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7243 7244 doAnswer(new AnswerWithArguments() { 7245 public void answer(NetworkUpdateResult result, ActionListenerWrapper callback, 7246 int callingUid, String packageName, String attributionTag) { 7247 callback.sendSuccess(); // return success 7248 } 7249 }).when(mConnectHelper).connectToNetwork( 7250 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any(), any()); 7251 7252 mLooper.startAutoDispatch(); 7253 assertTrue(mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME)); 7254 mLooper.stopAutoDispatch(); 7255 7256 verify(mConnectHelper).connectToNetwork( 7257 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any(), any()); 7258 verify(mWifiMetrics).incrementNumEnableNetworkCalls(); 7259 verify(mLastCallerInfoManager).put(eq(WifiManager.API_ENABLE_NETWORK), anyInt(), 7260 anyInt(), anyInt(), anyString(), eq(true)); 7261 } 7262 7263 /** 7264 * Verify that enableNetwork (with disableOthers=true) is allowed for Apps targeting a SDK 7265 * version less than Q 7266 */ 7267 @Test testEnabledNetworkWithDisableOthersAllowedForAppsTargetingBelowQSdk()7268 public void testEnabledNetworkWithDisableOthersAllowedForAppsTargetingBelowQSdk() 7269 throws Exception { 7270 mLooper.dispatchAll(); 7271 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7272 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7273 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 7274 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 7275 7276 doAnswer(new AnswerWithArguments() { 7277 public void answer(NetworkUpdateResult result, ActionListenerWrapper callback, 7278 int callingUid, String packageName, String attributionTag) { 7279 callback.sendSuccess(); // return success 7280 } 7281 }).when(mConnectHelper).connectToNetwork( 7282 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any(), any()); 7283 7284 mLooper.startAutoDispatch(); 7285 assertTrue(mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME)); 7286 mLooper.stopAutoDispatch(); 7287 7288 verify(mConnectHelper).connectToNetwork( 7289 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any(), any()); 7290 verify(mWifiMetrics).incrementNumEnableNetworkCalls(); 7291 } 7292 7293 /** 7294 * Verify that enableNetwork (with disableOthers=false) is allowed for Apps targeting a SDK 7295 * version less than Q 7296 */ 7297 @Test testEnabledNetworkWithoutDisableOthersAllowedForAppsTargetingBelowQSdk()7298 public void testEnabledNetworkWithoutDisableOthersAllowedForAppsTargetingBelowQSdk() 7299 throws Exception { 7300 mLooper.dispatchAll(); 7301 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7302 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7303 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 7304 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 7305 7306 when(mWifiConfigManager.enableNetwork(anyInt(), anyBoolean(), anyInt(), anyString())) 7307 .thenReturn(true); 7308 mLooper.startAutoDispatch(); 7309 assertTrue(mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, false, TEST_PACKAGE_NAME)); 7310 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7311 verify(mWifiConfigManager).enableNetwork(eq(TEST_NETWORK_ID), eq(false), 7312 eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME)); 7313 verify(mWifiMetrics).incrementNumEnableNetworkCalls(); 7314 } 7315 7316 /** 7317 * Verify that enableNetwork is not allowed for Apps targeting Q SDK 7318 */ 7319 @Test testEnableNetworkNotAllowedForAppsTargetingQ()7320 public void testEnableNetworkNotAllowedForAppsTargetingQ() throws Exception { 7321 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7322 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7323 7324 mLooper.startAutoDispatch(); 7325 mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME); 7326 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7327 7328 verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any(), any()); 7329 verify(mWifiMetrics, never()).incrementNumEnableNetworkCalls(); 7330 } 7331 7332 /** 7333 * Verify that enableNetwork is not allowed for admin restricted network 7334 */ 7335 @Test testEnableNetworkNotAllowedForAdminRestrictedNetwork()7336 public void testEnableNetworkNotAllowedForAdminRestrictedNetwork() throws Exception { 7337 assumeTrue(SdkLevel.isAtLeastT()); 7338 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7339 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7340 when(mWifiPermissionsUtil.isSystem(TEST_PACKAGE_NAME, Process.myUid())).thenReturn(true); 7341 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7342 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 7343 when(mWifiPermissionsUtil.isAdminRestrictedNetwork(config)).thenReturn(true); 7344 7345 mLooper.startAutoDispatch(); 7346 mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME); 7347 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7348 7349 verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any(), any()); 7350 verify(mWifiMetrics, never()).incrementNumEnableNetworkCalls(); 7351 } 7352 7353 /** 7354 * Verify that enableNetwork is not allowed for deprecated security type network 7355 */ 7356 @Test testEnableNetworkNotAllowedForDeprecatedSecurityTypeNetwork()7357 public void testEnableNetworkNotAllowedForDeprecatedSecurityTypeNetwork() throws Exception { 7358 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 7359 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 7360 when(mWifiPermissionsUtil.isSystem(TEST_PACKAGE_NAME, Process.myUid())).thenReturn(true); 7361 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(); 7362 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 7363 when(mWifiGlobals.isDeprecatedSecurityTypeNetwork(config)).thenReturn(true); 7364 7365 mLooper.startAutoDispatch(); 7366 mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME); 7367 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7368 7369 verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any(), any()); 7370 verify(mWifiMetrics, never()).incrementNumEnableNetworkCalls(); 7371 } 7372 7373 /** 7374 * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network 7375 * suggestions. 7376 */ 7377 @Test testAddNetworkSuggestions()7378 public void testAddNetworkSuggestions() { 7379 when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(), 7380 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS); 7381 mLooper.startAutoDispatch(); 7382 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS, 7383 mWifiServiceImpl.addNetworkSuggestions(mock(ParceledListSlice.class), 7384 TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 7385 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7386 7387 when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(), 7388 nullable(String.class))).thenReturn( 7389 WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE); 7390 mLooper.startAutoDispatch(); 7391 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE, 7392 mWifiServiceImpl.addNetworkSuggestions(mock(ParceledListSlice.class), 7393 TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 7394 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7395 7396 verify(mWifiNetworkSuggestionsManager, times(2)).add( 7397 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID)); 7398 } 7399 7400 /** 7401 * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network 7402 * suggestions for carrier app when DISALLOW_ADD_WIFI_CONFIG user restriction is set. 7403 */ 7404 @Test testAddNetworkSuggestionsIsAllowedForCarrierAppWithUserRestriction()7405 public void testAddNetworkSuggestionsIsAllowedForCarrierAppWithUserRestriction() { 7406 assumeTrue(SdkLevel.isAtLeastT()); 7407 when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(), 7408 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS); 7409 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 7410 any())).thenReturn(true); 7411 when(mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(anyString())).thenReturn( 7412 TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS); 7413 7414 mLooper.startAutoDispatch(); 7415 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS, 7416 mWifiServiceImpl.addNetworkSuggestions(mock(ParceledListSlice.class), 7417 TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 7418 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7419 7420 verify(mWifiNetworkSuggestionsManager).add( 7421 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID)); 7422 } 7423 7424 /** 7425 * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network 7426 * suggestions for privileged app when DISALLOW_ADD_WIFI_CONFIG user restriction is set. 7427 */ 7428 @Test testAddNetworkSuggestionsIsAllowedForPrivilegedAppWithUserRestriction()7429 public void testAddNetworkSuggestionsIsAllowedForPrivilegedAppWithUserRestriction() { 7430 assumeTrue(SdkLevel.isAtLeastT()); 7431 when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(), 7432 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS); 7433 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 7434 any())).thenReturn(true); 7435 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 7436 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 7437 7438 mLooper.startAutoDispatch(); 7439 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS, 7440 mWifiServiceImpl.addNetworkSuggestions(mock(ParceledListSlice.class), 7441 TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 7442 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7443 7444 verify(mWifiNetworkSuggestionsManager).add( 7445 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID)); 7446 } 7447 7448 /** 7449 * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network 7450 * suggestions for system app when DISALLOW_ADD_WIFI_CONFIG user restriction is set. 7451 */ 7452 @Test testAddNetworkSuggestionsIsAllowedForSystemAppWithUserRestriction()7453 public void testAddNetworkSuggestionsIsAllowedForSystemAppWithUserRestriction() { 7454 assumeTrue(SdkLevel.isAtLeastT()); 7455 when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(), 7456 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS); 7457 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 7458 any())).thenReturn(true); 7459 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 7460 7461 mLooper.startAutoDispatch(); 7462 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS, 7463 mWifiServiceImpl.addNetworkSuggestions(mock(ParceledListSlice.class), 7464 TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 7465 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7466 7467 verify(mWifiNetworkSuggestionsManager).add( 7468 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID)); 7469 } 7470 7471 /** 7472 * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network 7473 * suggestions for admin app when DISALLOW_ADD_WIFI_CONFIG user restriction is set. 7474 */ 7475 @Test testAddNetworkSuggestionsIsAllowedForAdminAppWithUserRestriction()7476 public void testAddNetworkSuggestionsIsAllowedForAdminAppWithUserRestriction() { 7477 assumeTrue(SdkLevel.isAtLeastT()); 7478 when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(), 7479 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS); 7480 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 7481 any())).thenReturn(true); 7482 when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(true); 7483 7484 mLooper.startAutoDispatch(); 7485 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS, 7486 mWifiServiceImpl.addNetworkSuggestions(mock(ParceledListSlice.class), 7487 TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 7488 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7489 7490 verify(mWifiNetworkSuggestionsManager).add( 7491 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID)); 7492 } 7493 7494 /** 7495 * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to add network 7496 * suggestions for normal app when DISALLOW_ADD_WIFI_CONFIG user restriction is set. 7497 */ 7498 @Test testAddNetworkSuggestionsIsNotAllowedForNormalAppWithUserRestriction()7499 public void testAddNetworkSuggestionsIsNotAllowedForNormalAppWithUserRestriction() { 7500 assumeTrue(SdkLevel.isAtLeastT()); 7501 when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(), 7502 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS); 7503 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 7504 any())).thenReturn(true); 7505 7506 mLooper.startAutoDispatch(); 7507 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_RESTRICTED_BY_ADMIN, 7508 mWifiServiceImpl.addNetworkSuggestions(mock(ParceledListSlice.class), 7509 TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 7510 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7511 7512 verify(mWifiNetworkSuggestionsManager, never()).add(any(), eq(Binder.getCallingUid()), 7513 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID)); 7514 } 7515 7516 /** 7517 * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to add network 7518 * suggestions when the looper sync call times out. 7519 */ 7520 @Test testAddNetworkSuggestionsFailureInRunWithScissors()7521 public void testAddNetworkSuggestionsFailureInRunWithScissors() { 7522 mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut(); 7523 7524 mLooper.startAutoDispatch(); 7525 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL, 7526 mWifiServiceImpl.addNetworkSuggestions(mock(ParceledListSlice.class), 7527 TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 7528 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7529 7530 verify(mWifiNetworkSuggestionsManager, never()).add(any(), eq(Binder.getCallingUid()), 7531 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID)); 7532 } 7533 7534 /** 7535 * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to remove network 7536 * suggestions. 7537 */ 7538 @Test testRemoveNetworkSuggestions()7539 public void testRemoveNetworkSuggestions() { 7540 when(mWifiNetworkSuggestionsManager.remove(any(), anyInt(), anyString(), anyInt())) 7541 .thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID); 7542 mLooper.startAutoDispatch(); 7543 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID, 7544 mWifiServiceImpl.removeNetworkSuggestions(mock(ParceledListSlice.class), 7545 TEST_PACKAGE_NAME, ACTION_REMOVE_SUGGESTION_DISCONNECT)); 7546 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7547 7548 when(mWifiNetworkSuggestionsManager.remove(any(), anyInt(), anyString(), 7549 anyInt())) 7550 .thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS); 7551 mLooper.startAutoDispatch(); 7552 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS, 7553 mWifiServiceImpl.removeNetworkSuggestions(mock(ParceledListSlice.class), 7554 TEST_PACKAGE_NAME, ACTION_REMOVE_SUGGESTION_DISCONNECT)); 7555 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7556 7557 verify(mWifiNetworkSuggestionsManager, times(2)).remove(any(), anyInt(), 7558 eq(TEST_PACKAGE_NAME), eq(ACTION_REMOVE_SUGGESTION_DISCONNECT)); 7559 } 7560 7561 /** 7562 * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to remove network 7563 * suggestions when the looper sync call times out. 7564 */ 7565 @Test testRemoveNetworkSuggestionsFailureInRunWithScissors()7566 public void testRemoveNetworkSuggestionsFailureInRunWithScissors() { 7567 mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut(); 7568 7569 mLooper.startAutoDispatch(); 7570 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL, 7571 mWifiServiceImpl.removeNetworkSuggestions(mock(ParceledListSlice.class), 7572 TEST_PACKAGE_NAME, ACTION_REMOVE_SUGGESTION_DISCONNECT)); 7573 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7574 7575 verify(mWifiNetworkSuggestionsManager, never()).remove(any(), anyInt(), 7576 eq(TEST_PACKAGE_NAME), eq(ACTION_REMOVE_SUGGESTION_DISCONNECT)); 7577 } 7578 7579 /** 7580 * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to remove network 7581 * suggestions when the action is invalid. 7582 */ 7583 @Test testRemoveNetworkSuggestionsFailureWithInvalidAction()7584 public void testRemoveNetworkSuggestionsFailureWithInvalidAction() { 7585 mLooper.startAutoDispatch(); 7586 assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID, 7587 mWifiServiceImpl.removeNetworkSuggestions(mock(ParceledListSlice.class), 7588 TEST_PACKAGE_NAME, 0)); 7589 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7590 verify(mWifiNetworkSuggestionsManager, never()).remove(any(), anyInt(), 7591 eq(TEST_PACKAGE_NAME), anyInt()); 7592 } 7593 7594 @Test(expected = SecurityException.class) testRemoveNonCallerConfiguredNetworks_NormalAppCaller_ThrowsException()7595 public void testRemoveNonCallerConfiguredNetworks_NormalAppCaller_ThrowsException() { 7596 mWifiServiceImpl.removeNonCallerConfiguredNetworks(TEST_PACKAGE_NAME); 7597 } 7598 7599 @Test(expected = SecurityException.class) testRemoveNonCallerConfiguredNetworks_CallerIsProfileOwner_ThrowsException()7600 public void testRemoveNonCallerConfiguredNetworks_CallerIsProfileOwner_ThrowsException() { 7601 when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 7602 .thenReturn(true); 7603 mWifiServiceImpl.removeNonCallerConfiguredNetworks(TEST_PACKAGE_NAME); 7604 } 7605 7606 @Test testRemoveNonCallerConfiguredNetworks_NetworksRemoved()7607 public void testRemoveNonCallerConfiguredNetworks_NetworksRemoved() { 7608 final int callerUid = Binder.getCallingUid(); 7609 when(mWifiPermissionsUtil.isOrganizationOwnedDeviceAdmin( 7610 Binder.getCallingUid(), TEST_PACKAGE_NAME)).thenReturn(true); 7611 7612 mLooper.startAutoDispatch(); 7613 mWifiServiceImpl.removeNonCallerConfiguredNetworks(TEST_PACKAGE_NAME); 7614 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7615 7616 verify(mWifiConfigManager).removeNonCallerConfiguredNetwork(eq(callerUid)); 7617 } 7618 7619 /** 7620 * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to get network 7621 * suggestions. 7622 */ 7623 @Test testGetNetworkSuggestions()7624 public void testGetNetworkSuggestions() { 7625 List<WifiNetworkSuggestion> testList = new ArrayList<>(); 7626 when(mWifiNetworkSuggestionsManager.get(anyString(), anyInt())).thenReturn(testList); 7627 mLooper.startAutoDispatch(); 7628 assertEquals(testList, mWifiServiceImpl.getNetworkSuggestions(TEST_PACKAGE_NAME).getList()); 7629 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7630 7631 verify(mWifiNetworkSuggestionsManager).get(eq(TEST_PACKAGE_NAME), anyInt()); 7632 } 7633 7634 /** 7635 * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to get network 7636 * suggestions when the looper sync call times out. 7637 */ 7638 @Test testGetNetworkSuggestionsFailureInRunWithScissors()7639 public void testGetNetworkSuggestionsFailureInRunWithScissors() { 7640 mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut(); 7641 7642 mLooper.startAutoDispatch(); 7643 assertTrue(mWifiServiceImpl.getNetworkSuggestions(TEST_PACKAGE_NAME).getList().isEmpty()); 7644 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7645 7646 verify(mWifiNetworkSuggestionsManager, never()).get(eq(TEST_PACKAGE_NAME), anyInt()); 7647 } 7648 7649 /** 7650 * Verify that if the caller has NETWORK_SETTINGS permission, then it can invoke 7651 * {@link WifiManager#disableEphemeralNetwork(String)}. 7652 */ 7653 @Test testDisableEphemeralNetworkWithNetworkSettingsPerm()7654 public void testDisableEphemeralNetworkWithNetworkSettingsPerm() throws Exception { 7655 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 7656 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 7657 mWifiServiceImpl.disableEphemeralNetwork("", TEST_PACKAGE_NAME); 7658 mLooper.dispatchAll(); 7659 verify(mWifiConfigManager).userTemporarilyDisabledNetwork(anyString(), anyInt()); 7660 } 7661 7662 /** 7663 * Verify that if the caller does not have NETWORK_SETTINGS permission, then it cannot invoke 7664 * {@link WifiManager#disableEphemeralNetwork(String)}. 7665 */ 7666 @Test testDisableEphemeralNetworkWithoutNetworkSettingsPerm()7667 public void testDisableEphemeralNetworkWithoutNetworkSettingsPerm() throws Exception { 7668 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 7669 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 7670 mWifiServiceImpl.disableEphemeralNetwork("", TEST_PACKAGE_NAME); 7671 mLooper.dispatchAll(); 7672 verify(mWifiConfigManager, never()).userTemporarilyDisabledNetwork(anyString(), anyInt()); 7673 } 7674 7675 /** 7676 * Verify getting the factory MAC address. 7677 */ 7678 @Test testGetFactoryMacAddresses()7679 public void testGetFactoryMacAddresses() throws Exception { 7680 when(mWifiGlobals.isSaveFactoryMacToConfigStoreEnabled()).thenReturn(true); 7681 when(mWifiSettingsConfigStore.get(WIFI_STA_FACTORY_MAC_ADDRESS)).thenReturn(null); 7682 when(mClientModeManager.getFactoryMacAddress()).thenReturn(TEST_FACTORY_MAC); 7683 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 7684 mLooper.startAutoDispatch(); 7685 final String[] factoryMacs = mWifiServiceImpl.getFactoryMacAddresses(); 7686 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7687 assertEquals(1, factoryMacs.length); 7688 assertEquals(TEST_FACTORY_MAC, factoryMacs[0]); 7689 verify(mClientModeManager).getFactoryMacAddress(); 7690 verify(mWifiSettingsConfigStore).get(WIFI_STA_FACTORY_MAC_ADDRESS); 7691 } 7692 7693 /** 7694 * Verify getting the factory MAC address returns null when posting the runnable to handler 7695 * fails. 7696 */ 7697 @Test testGetFactoryMacAddressesPostFail()7698 public void testGetFactoryMacAddressesPostFail() throws Exception { 7699 mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut(); 7700 7701 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 7702 mLooper.startAutoDispatch(); 7703 assertArrayEquals(new String[0], mWifiServiceImpl.getFactoryMacAddresses()); 7704 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7705 verify(mClientModeManager, never()).getFactoryMacAddress(); 7706 } 7707 7708 /** 7709 * Verify getting the factory MAC address returns null when the lower layers fail. 7710 */ 7711 @Test testGetFactoryMacAddressesFail()7712 public void testGetFactoryMacAddressesFail() throws Exception { 7713 when(mClientModeManager.getFactoryMacAddress()).thenReturn(null); 7714 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 7715 mLooper.startAutoDispatch(); 7716 assertArrayEquals(new String[0], mWifiServiceImpl.getFactoryMacAddresses()); 7717 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7718 verify(mClientModeManager).getFactoryMacAddress(); 7719 } 7720 7721 /** 7722 * Verify getting the factory MAC address throws a SecurityException if the calling app 7723 * doesn't have NETWORK_SETTINGS permission. 7724 */ 7725 @Test testGetFactoryMacAddressesFailNoNetworkSettingsPermission()7726 public void testGetFactoryMacAddressesFailNoNetworkSettingsPermission() throws Exception { 7727 when(mClientModeManager.getFactoryMacAddress()).thenReturn(TEST_FACTORY_MAC); 7728 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 7729 try { 7730 mLooper.startAutoDispatch(); 7731 mWifiServiceImpl.getFactoryMacAddresses(); 7732 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7733 fail(); 7734 } catch (SecurityException e) { 7735 assertTrue("Exception message should contain 'factory MAC'", 7736 e.toString().contains("factory MAC")); 7737 } 7738 } 7739 7740 @Test testGetFactoryMacAddressesSuccessFromSettingStore()7741 public void testGetFactoryMacAddressesSuccessFromSettingStore() throws Exception { 7742 when(mWifiGlobals.isSaveFactoryMacToConfigStoreEnabled()).thenReturn(true); 7743 when(mWifiSettingsConfigStore.get(WIFI_STA_FACTORY_MAC_ADDRESS)) 7744 .thenReturn(TEST_FACTORY_MAC); 7745 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 7746 when(mClientModeManager.getFactoryMacAddress()).thenReturn(TEST_FACTORY_MAC); 7747 final String[] factoryMacs = mWifiServiceImpl.getFactoryMacAddresses(); 7748 assertEquals(1, factoryMacs.length); 7749 assertEquals(TEST_FACTORY_MAC, factoryMacs[0]); 7750 mLooper.dispatchAll(); 7751 verify(mClientModeManager, never()).getFactoryMacAddress(); 7752 } 7753 7754 /** 7755 * Verify that a call to setDeviceMobilityState throws a SecurityException if the 7756 * caller does not have WIFI_SET_DEVICE_MOBILITY_STATE permission. 7757 */ 7758 @Test(expected = SecurityException.class) setDeviceMobilityStateThrowsSecurityExceptionOnMissingPermissions()7759 public void setDeviceMobilityStateThrowsSecurityExceptionOnMissingPermissions() { 7760 doThrow(new SecurityException()).when(mContext) 7761 .enforceCallingOrSelfPermission( 7762 eq(android.Manifest.permission.WIFI_SET_DEVICE_MOBILITY_STATE), 7763 eq("WifiService")); 7764 mWifiServiceImpl.setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY); 7765 } 7766 7767 /** 7768 * Verifies that setDeviceMobilityState runs on a separate handler thread. 7769 */ 7770 @Test setDeviceMobilityStateRunsOnHandler()7771 public void setDeviceMobilityStateRunsOnHandler() { 7772 mWifiServiceImpl.setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY); 7773 verify(mWifiConnectivityManager, never()) 7774 .setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY); 7775 verify(mWifiHealthMonitor, never()) 7776 .setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY); 7777 verify(mWifiDataStall, never()) 7778 .setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY); 7779 mLooper.dispatchAll(); 7780 verify(mWifiConnectivityManager).setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY); 7781 verify(mWifiHealthMonitor).setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY); 7782 verify(mWifiDataStall).setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY); 7783 } 7784 7785 /** 7786 * Verify that a call to addOnWifiUsabilityStatsListener throws a SecurityException if 7787 * the caller does not have WIFI_UPDATE_USABILITY_STATS_SCORE permission. 7788 */ 7789 @Test testAddStatsListenerThrowsSecurityExceptionOnMissingPermissions()7790 public void testAddStatsListenerThrowsSecurityExceptionOnMissingPermissions() { 7791 doThrow(new SecurityException()).when(mContext) 7792 .enforceCallingOrSelfPermission( 7793 eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE), 7794 eq("WifiService")); 7795 try { 7796 mWifiServiceImpl.addOnWifiUsabilityStatsListener(mOnWifiUsabilityStatsListener); 7797 fail("expected SecurityException"); 7798 } catch (SecurityException expected) { 7799 } 7800 } 7801 7802 /** 7803 * Verify that a call to addOnWifiUsabilityStatsListener throws an IllegalArgumentException 7804 * if the parameters are not provided. 7805 */ 7806 @Test testAddStatsListenerThrowsIllegalArgumentExceptionOnInvalidArguments()7807 public void testAddStatsListenerThrowsIllegalArgumentExceptionOnInvalidArguments() { 7808 try { 7809 mWifiServiceImpl.addOnWifiUsabilityStatsListener(null); 7810 fail("expected IllegalArgumentException"); 7811 } catch (IllegalArgumentException expected) { 7812 } 7813 } 7814 7815 /** 7816 * Verify that a call to removeOnWifiUsabilityStatsListener throws a SecurityException if 7817 * the caller does not have WIFI_UPDATE_USABILITY_STATS_SCORE permission. 7818 */ 7819 @Test testRemoveStatsListenerThrowsSecurityExceptionOnMissingPermissions()7820 public void testRemoveStatsListenerThrowsSecurityExceptionOnMissingPermissions() { 7821 doThrow(new SecurityException()).when(mContext) 7822 .enforceCallingOrSelfPermission( 7823 eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE), 7824 eq("WifiService")); 7825 try { 7826 mWifiServiceImpl.removeOnWifiUsabilityStatsListener(mOnWifiUsabilityStatsListener); 7827 fail("expected SecurityException"); 7828 } catch (SecurityException expected) { 7829 } 7830 } 7831 7832 /** 7833 * Verify that addOnWifiUsabilityStatsListener adds listener to {@link WifiMetrics}. 7834 */ 7835 @Test testAddOnWifiUsabilityStatsListenerAndVerify()7836 public void testAddOnWifiUsabilityStatsListenerAndVerify() throws Exception { 7837 mWifiServiceImpl.addOnWifiUsabilityStatsListener(mOnWifiUsabilityStatsListener); 7838 mLooper.dispatchAll(); 7839 verify(mWifiMetrics).addOnWifiUsabilityListener(mOnWifiUsabilityStatsListener); 7840 } 7841 7842 /** 7843 * Verify that removeOnWifiUsabilityStatsListener removes listener from 7844 * {@link WifiMetrics}. 7845 */ 7846 @Test testRemoveOnWifiUsabilityStatsListenerAndVerify()7847 public void testRemoveOnWifiUsabilityStatsListenerAndVerify() throws Exception { 7848 mWifiServiceImpl.removeOnWifiUsabilityStatsListener(mOnWifiUsabilityStatsListener); 7849 mLooper.dispatchAll(); 7850 verify(mWifiMetrics).removeOnWifiUsabilityListener(mOnWifiUsabilityStatsListener); 7851 } 7852 7853 /** 7854 * Verify that a call to updateWifiUsabilityScore throws a SecurityException if the 7855 * caller does not have UPDATE_WIFI_USABILITY_SCORE permission. 7856 */ 7857 @Test testUpdateWifiUsabilityScoreThrowsSecurityExceptionOnMissingPermissions()7858 public void testUpdateWifiUsabilityScoreThrowsSecurityExceptionOnMissingPermissions() { 7859 doThrow(new SecurityException()).when(mContext) 7860 .enforceCallingOrSelfPermission( 7861 eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE), 7862 eq("WifiService")); 7863 try { 7864 mWifiServiceImpl.updateWifiUsabilityScore(anyInt(), anyInt(), 15); 7865 fail("expected SecurityException"); 7866 } catch (SecurityException expected) { 7867 } 7868 } 7869 7870 /** 7871 * Verify that mClientModeManager in WifiServiceImpl is being updated on Wifi usability score 7872 * update event. 7873 */ 7874 @Test testWifiUsabilityScoreUpdateAfterScoreEvent()7875 public void testWifiUsabilityScoreUpdateAfterScoreEvent() { 7876 mWifiServiceImpl.updateWifiUsabilityScore(5, 10, 15); 7877 mLooper.dispatchAll(); 7878 verify(mWifiMetrics).incrementWifiUsabilityScoreCount(WIFI_IFACE_NAME, 5, 10, 15); 7879 } 7880 startLohsAndTethering(boolean isApConcurrencySupported)7881 private void startLohsAndTethering(boolean isApConcurrencySupported) throws Exception { 7882 // initialization 7883 when(mActiveModeWarden.canRequestMoreSoftApManagers( 7884 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)))) 7885 .thenReturn(isApConcurrencySupported); 7886 // For these tests, always use distinct interface names for LOHS and tethered. 7887 mLohsInterfaceName = WIFI_IFACE_NAME2; 7888 7889 setupLocalOnlyHotspot(); 7890 reset(mActiveModeWarden); 7891 7892 when(mActiveModeWarden.canRequestMoreSoftApManagers( 7893 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)))) 7894 .thenReturn(isApConcurrencySupported); 7895 7896 // start tethering 7897 mLooper.startAutoDispatch(); 7898 boolean tetheringResult = mWifiServiceImpl.startSoftAp(null, TEST_PACKAGE_NAME); 7899 mLooper.stopAutoDispatchAndIgnoreExceptions(); 7900 assertTrue(tetheringResult); 7901 verify(mActiveModeWarden).startSoftAp(any(), 7902 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))); 7903 mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED); 7904 mLooper.dispatchAll(); 7905 } 7906 7907 /** 7908 * Verify LOHS gets stopped when trying to start tethering concurrently on devices that 7909 * doesn't support dual AP operation. 7910 */ 7911 @Test testStartLohsAndTethering1AP()7912 public void testStartLohsAndTethering1AP() throws Exception { 7913 startLohsAndTethering(false); 7914 7915 // verify LOHS got stopped 7916 verify(mLohsCallback).onHotspotFailed(anyInt()); 7917 verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY); 7918 } 7919 7920 /** 7921 * Verify LOHS doesn't get stopped when trying to start tethering concurrently on devices 7922 * that does support dual AP operation. 7923 */ 7924 @Test testStartLohsAndTethering2AP()7925 public void testStartLohsAndTethering2AP() throws Exception { 7926 startLohsAndTethering(true); 7927 7928 // verify LOHS didn't get stopped 7929 verifyNoMoreInteractions(ignoreStubs(mLohsCallback)); 7930 verify(mActiveModeWarden, never()).stopSoftAp(anyInt()); 7931 } 7932 7933 /** 7934 * Verify that the call to startDppAsConfiguratorInitiator throws a security exception when the 7935 * caller doesn't have NETWORK_SETTINGS permissions or NETWORK_SETUP_WIZARD. 7936 */ 7937 @Test(expected = SecurityException.class) testStartDppAsConfiguratorInitiatorWithoutPermissions()7938 public void testStartDppAsConfiguratorInitiatorWithoutPermissions() { 7939 mWifiServiceImpl.startDppAsConfiguratorInitiator(mAppBinder, TEST_PACKAGE_NAME, DPP_URI, 7940 1, 1, mDppCallback); 7941 } 7942 7943 /** 7944 * Verify that the call to startDppAsEnrolleeInitiator throws a security exception when the 7945 * caller doesn't have NETWORK_SETTINGS permissions or NETWORK_SETUP_WIZARD. 7946 */ 7947 @Test(expected = SecurityException.class) testStartDppAsEnrolleeInitiatorWithoutPermissions()7948 public void testStartDppAsEnrolleeInitiatorWithoutPermissions() { 7949 mWifiServiceImpl.startDppAsEnrolleeInitiator(mAppBinder, DPP_URI, mDppCallback); 7950 } 7951 7952 /** 7953 * Verify that the call to startDppAsEnrolleeResponder throws a security exception when the 7954 * caller doesn't have NETWORK_SETTINGS permissions or NETWORK_SETUP_WIZARD. 7955 */ 7956 @Test(expected = SecurityException.class) testStartDppAsEnrolleeResponderWithoutPermissions()7957 public void testStartDppAsEnrolleeResponderWithoutPermissions() { 7958 assumeTrue(SdkLevel.isAtLeastS()); 7959 mWifiServiceImpl.startDppAsEnrolleeResponder(mAppBinder, DPP_PRODUCT_INFO, 7960 EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1, mDppCallback); 7961 } 7962 7963 /** 7964 * Verify that a call to StartDppAsEnrolleeResponder throws an IllegalArgumentException 7965 * if the deviceInfo length exceeds the max allowed length. 7966 */ 7967 @Test(expected = SecurityException.class) testStartDppAsEnrolleeResponderThrowsIllegalArgumentExceptionOnDeviceInfoMaxLen()7968 public void testStartDppAsEnrolleeResponderThrowsIllegalArgumentExceptionOnDeviceInfoMaxLen() { 7969 assumeTrue(SdkLevel.isAtLeastS()); 7970 try { 7971 StringBuilder sb = new StringBuilder(); 7972 sb.append(Strings.repeat("a", 7973 WifiManager.getEasyConnectMaxAllowedResponderDeviceInfoLength() + 2)); 7974 String deviceInfo = sb.toString(); 7975 mWifiServiceImpl.startDppAsEnrolleeResponder(mAppBinder, deviceInfo, 7976 EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1, mDppCallback); 7977 fail("expected IllegalArgumentException"); 7978 } catch (IllegalArgumentException expected) { 7979 } 7980 } 7981 7982 /** 7983 * Verify that a call to StartDppAsEnrolleeResponder throws an IllegalArgumentException 7984 * if the deviceInfo contains characters which are not allowed as per spec (For example 7985 * semicolon) 7986 */ 7987 @Test(expected = SecurityException.class) testStartDppAsEnrolleeResponderThrowsIllegalArgumentExceptionOnWrongDeviceInfo()7988 public void testStartDppAsEnrolleeResponderThrowsIllegalArgumentExceptionOnWrongDeviceInfo() { 7989 assumeTrue(SdkLevel.isAtLeastS()); 7990 try { 7991 mWifiServiceImpl.startDppAsEnrolleeResponder(mAppBinder, "DPP;TESTER", 7992 EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1, mDppCallback); 7993 fail("expected IllegalArgumentException"); 7994 } catch (IllegalArgumentException expected) { 7995 } 7996 } 7997 7998 /** 7999 * Verify that the call to stopDppSession throws a security exception when the 8000 * caller doesn't have NETWORK_SETTINGS permissions or NETWORK_SETUP_WIZARD. 8001 */ 8002 @Test(expected = SecurityException.class) testStopDppSessionWithoutPermissions()8003 public void testStopDppSessionWithoutPermissions() { 8004 try { 8005 mWifiServiceImpl.stopDppSession(); 8006 } catch (RemoteException e) { 8007 } 8008 } 8009 8010 /** 8011 * Verifies that configs can be removed. 8012 */ 8013 @Test testRemoveNetworkIsAllowedForAppsTargetingBelowQSdk()8014 public void testRemoveNetworkIsAllowedForAppsTargetingBelowQSdk() { 8015 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8016 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8017 when(mWifiConfigManager.removeNetwork(eq(0), anyInt(), anyString())).thenReturn(true); 8018 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8019 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 8020 8021 mLooper.startAutoDispatch(); 8022 boolean result = mWifiServiceImpl.removeNetwork(0, TEST_PACKAGE_NAME); 8023 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8024 8025 assertTrue(result); 8026 verify(mWifiConfigManager).removeNetwork(anyInt(), anyInt(), anyString()); 8027 } 8028 8029 /** 8030 * Verify that addOrUpdatePasspointConfiguration is allowed for apps targeting below R SDK. 8031 */ 8032 @Test addOrUpdatePasspointConfigIsAllowedForAppsTargetingBelowRSdk()8033 public void addOrUpdatePasspointConfigIsAllowedForAppsTargetingBelowRSdk() throws Exception { 8034 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8035 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8036 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8037 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(true); 8038 PasspointConfiguration config = new PasspointConfiguration(); 8039 HomeSp homeSp = new HomeSp(); 8040 homeSp.setFqdn("test.com"); 8041 config.setHomeSp(homeSp); 8042 8043 when(mPasspointManager.addOrUpdateProvider( 8044 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8045 .thenReturn(true); 8046 mLooper.startAutoDispatch(); 8047 assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8048 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8049 reset(mPasspointManager); 8050 8051 when(mPasspointManager.addOrUpdateProvider( 8052 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8053 .thenReturn(false); 8054 mLooper.startAutoDispatch(); 8055 assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8056 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8057 } 8058 8059 /** 8060 * Verify that addOrUpdatePasspointConfiguration is not allowed for apps targeting R SDK. 8061 */ 8062 @Test addOrUpdatePasspointConfigIsNotAllowedForAppsTargetingRSdk()8063 public void addOrUpdatePasspointConfigIsNotAllowedForAppsTargetingRSdk() throws Exception { 8064 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8065 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8066 PasspointConfiguration config = new PasspointConfiguration(); 8067 HomeSp homeSp = new HomeSp(); 8068 homeSp.setFqdn("test.com"); 8069 config.setHomeSp(homeSp); 8070 8071 when(mPasspointManager.addOrUpdateProvider( 8072 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8073 .thenReturn(true); 8074 mLooper.startAutoDispatch(); 8075 assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8076 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8077 verify(mPasspointManager, never()) 8078 .addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), anyBoolean(), 8079 eq(false)); 8080 } 8081 8082 /** 8083 * Verify that addOrUpdatePasspointConfiguration is allowed for Settings apps. 8084 */ 8085 @Test addOrUpdatePasspointConfigIsAllowedSettingsApp()8086 public void addOrUpdatePasspointConfigIsAllowedSettingsApp() throws Exception { 8087 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 8088 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 8089 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8090 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false); 8091 PasspointConfiguration config = new PasspointConfiguration(); 8092 HomeSp homeSp = new HomeSp(); 8093 homeSp.setFqdn("test.com"); 8094 config.setHomeSp(homeSp); 8095 8096 when(mPasspointManager.addOrUpdateProvider( 8097 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8098 .thenReturn(true); 8099 mLooper.startAutoDispatch(); 8100 assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8101 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8102 verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), 8103 anyBoolean(), eq(false)); 8104 } 8105 8106 /** 8107 * Verify that addOrUpdatePasspointConfiguration is allowed for System apps. 8108 */ 8109 @Test addOrUpdatePasspointConfigIsAllowedSystemApp()8110 public void addOrUpdatePasspointConfigIsAllowedSystemApp() throws Exception { 8111 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8112 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8113 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8114 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false); 8115 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 8116 PasspointConfiguration config = new PasspointConfiguration(); 8117 HomeSp homeSp = new HomeSp(); 8118 homeSp.setFqdn("test.com"); 8119 config.setHomeSp(homeSp); 8120 8121 when(mPasspointManager.addOrUpdateProvider( 8122 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8123 .thenReturn(true); 8124 mLooper.startAutoDispatch(); 8125 assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8126 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8127 verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), 8128 anyBoolean(), eq(false)); 8129 } 8130 8131 /** 8132 * Verify that addOrUpdatePasspointConfiguration is allowed for DeviceOwner apps. 8133 */ 8134 @Test addOrUpdatePasspointConfigIsAllowedSystemAlertDOApp()8135 public void addOrUpdatePasspointConfigIsAllowedSystemAlertDOApp() throws Exception { 8136 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8137 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8138 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8139 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false); 8140 when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 8141 .thenReturn(true); 8142 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 8143 .thenReturn(true); 8144 PasspointConfiguration config = new PasspointConfiguration(); 8145 HomeSp homeSp = new HomeSp(); 8146 homeSp.setFqdn("test.com"); 8147 config.setHomeSp(homeSp); 8148 8149 when(mPasspointManager.addOrUpdateProvider( 8150 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8151 .thenReturn(true); 8152 mLooper.startAutoDispatch(); 8153 assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8154 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8155 verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), 8156 anyBoolean(), eq(false)); 8157 } 8158 8159 /** 8160 * Verify that addOrUpdatePasspointConfiguration is allowed for ProfileOwner apps. 8161 */ 8162 @Test addOrUpdatePasspointConfigIsAllowedSystemAlertPOApp()8163 public void addOrUpdatePasspointConfigIsAllowedSystemAlertPOApp() throws Exception { 8164 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8165 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8166 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8167 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false); 8168 when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 8169 .thenReturn(true); 8170 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 8171 .thenReturn(true); 8172 PasspointConfiguration config = new PasspointConfiguration(); 8173 HomeSp homeSp = new HomeSp(); 8174 homeSp.setFqdn("test.com"); 8175 config.setHomeSp(homeSp); 8176 8177 when(mPasspointManager.addOrUpdateProvider( 8178 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8179 .thenReturn(true); 8180 mLooper.startAutoDispatch(); 8181 assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8182 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8183 verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), 8184 anyBoolean(), eq(false)); 8185 } 8186 8187 /** 8188 * Verify that addOrUpdatePasspointConfiguration disconnects from current captive portal network 8189 * when provisioned via WifiInstaller. 8190 */ 8191 @Test addOrUpdatePasspointConfigDisconnectsCaptivePortal()8192 public void addOrUpdatePasspointConfigDisconnectsCaptivePortal() throws Exception { 8193 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8194 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, 8195 Process.myUid(), CERT_INSTALLER_PACKAGE_NAME); 8196 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8197 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false); 8198 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 8199 PasspointConfiguration config = new PasspointConfiguration(); 8200 HomeSp homeSp = new HomeSp(); 8201 homeSp.setFqdn("test.com"); 8202 config.setHomeSp(homeSp); 8203 WifiConfiguration captivePortalConfig = 8204 WifiConfigurationTestUtil.createCaptivePortalNetwork(); 8205 WifiInfo wifiInfo = new WifiInfo(); 8206 wifiInfo.setNetworkId(captivePortalConfig.networkId); 8207 when(mActiveModeWarden.getConnectionInfo()).thenReturn(wifiInfo); 8208 when(mWifiConfigManager.getConfiguredNetworkWithPassword(captivePortalConfig.networkId)) 8209 .thenReturn(captivePortalConfig); 8210 8211 when(mPasspointManager.addOrUpdateProvider( 8212 config, Binder.getCallingUid(), CERT_INSTALLER_PACKAGE_NAME, false, true, false)) 8213 .thenReturn(true); 8214 mLooper.startAutoDispatch(); 8215 assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, 8216 CERT_INSTALLER_PACKAGE_NAME)); 8217 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8218 verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), 8219 anyBoolean(), eq(false)); 8220 verify(mClientModeManager).disconnect(); 8221 } 8222 8223 /** 8224 * Verify that addOrUpdatePasspointConfiguration is not allowed for apps targeting below R SDK 8225 * when the DISALLOW_ADD_WIFI_CONFIG user restriction is set. 8226 */ 8227 @Test addOrUpdatePasspointConfigIsNotAllowedForAppsTargetingBelowRSdkWithUserRestriction()8228 public void addOrUpdatePasspointConfigIsNotAllowedForAppsTargetingBelowRSdkWithUserRestriction() 8229 throws Exception { 8230 assumeTrue(SdkLevel.isAtLeastT()); 8231 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8232 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8233 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8234 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(true); 8235 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 8236 any())).thenReturn(true); 8237 PasspointConfiguration config = new PasspointConfiguration(); 8238 HomeSp homeSp = new HomeSp(); 8239 homeSp.setFqdn("test.com"); 8240 config.setHomeSp(homeSp); 8241 8242 when(mPasspointManager.addOrUpdateProvider( 8243 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8244 .thenReturn(true); 8245 mLooper.startAutoDispatch(); 8246 assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8247 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8248 verify(mPasspointManager, never()) 8249 .addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), anyBoolean(), 8250 eq(false)); 8251 } 8252 8253 /** 8254 * Verify that addOrUpdatePasspointConfiguration is not allowed for system apps 8255 * when the DISALLOW_ADD_WIFI_CONFIG user restriction is set. 8256 */ 8257 @Test addOrUpdatePasspointConfigIsNotAllowedForSystemAppWithUserRestriction()8258 public void addOrUpdatePasspointConfigIsNotAllowedForSystemAppWithUserRestriction() 8259 throws Exception { 8260 assumeTrue(SdkLevel.isAtLeastT()); 8261 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8262 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8263 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8264 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false); 8265 when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true); 8266 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 8267 any())).thenReturn(true); 8268 PasspointConfiguration config = new PasspointConfiguration(); 8269 HomeSp homeSp = new HomeSp(); 8270 homeSp.setFqdn("test.com"); 8271 config.setHomeSp(homeSp); 8272 8273 when(mPasspointManager.addOrUpdateProvider( 8274 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8275 .thenReturn(true); 8276 mLooper.startAutoDispatch(); 8277 assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8278 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8279 verify(mPasspointManager, never()) 8280 .addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), anyBoolean(), 8281 eq(false)); 8282 } 8283 8284 /** 8285 * Verify that addOrUpdatePasspointConfiguration is allowed for admin apps 8286 * when the DISALLOW_ADD_WIFI_CONFIG user restriction is set. 8287 */ 8288 @Test addOrUpdatePasspointConfigIsAllowedSystemAlertAdminAppWithUserRestriction()8289 public void addOrUpdatePasspointConfigIsAllowedSystemAlertAdminAppWithUserRestriction() 8290 throws Exception { 8291 assumeTrue(SdkLevel.isAtLeastT()); 8292 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8293 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8294 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8295 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false); 8296 when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME)) 8297 .thenReturn(true); 8298 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG), 8299 any())).thenReturn(true); 8300 PasspointConfiguration config = new PasspointConfiguration(); 8301 HomeSp homeSp = new HomeSp(); 8302 homeSp.setFqdn("test.com"); 8303 config.setHomeSp(homeSp); 8304 8305 when(mPasspointManager.addOrUpdateProvider( 8306 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false)) 8307 .thenReturn(true); 8308 mLooper.startAutoDispatch(); 8309 assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME)); 8310 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8311 verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), 8312 anyBoolean(), eq(false)); 8313 } 8314 8315 /** 8316 * Verify that removePasspointConfiguration will redirect calls to {@link PasspointManager} 8317 * and returning the result that's returned from {@link PasspointManager}. 8318 */ 8319 @Test removePasspointConfig()8320 public void removePasspointConfig() throws Exception { 8321 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 8322 8323 String fqdn = "test.com"; 8324 when(mPasspointManager.removeProvider(anyInt(), anyBoolean(), isNull(), eq(fqdn))) 8325 .thenReturn(true); 8326 mLooper.startAutoDispatch(); 8327 assertTrue(mWifiServiceImpl.removePasspointConfiguration(fqdn, TEST_PACKAGE_NAME)); 8328 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8329 reset(mPasspointManager); 8330 8331 when(mPasspointManager.removeProvider(anyInt(), anyBoolean(), isNull(), eq(fqdn))) 8332 .thenReturn(false); 8333 mLooper.startAutoDispatch(); 8334 assertFalse(mWifiServiceImpl.removePasspointConfiguration(fqdn, TEST_PACKAGE_NAME)); 8335 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8336 } 8337 8338 /** 8339 * Test that DISABLE_NETWORK returns failure to public API when WifiConfigManager returns 8340 * failure. 8341 */ 8342 @Test testDisableNetworkFailureAppBelowQSdk()8343 public void testDisableNetworkFailureAppBelowQSdk() throws Exception { 8344 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 8345 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 8346 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 8347 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 8348 when(mWifiConfigManager.disableNetwork(anyInt(), anyInt(), anyString())).thenReturn(false); 8349 8350 mLooper.startAutoDispatch(); 8351 boolean succeeded = mWifiServiceImpl.disableNetwork(0, TEST_PACKAGE_NAME); 8352 mLooper.stopAutoDispatchAndIgnoreExceptions(); 8353 assertFalse(succeeded); 8354 } 8355 8356 @Test testSetNetworkSelectionConfig()8357 public void testSetNetworkSelectionConfig() throws Exception { 8358 assumeTrue(SdkLevel.isAtLeastT()); 8359 8360 WifiNetworkSelectionConfig nsConfig = new WifiNetworkSelectionConfig.Builder().build(); 8361 // no permission to call API 8362 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 8363 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 8364 .thenReturn(false); 8365 assertThrows(SecurityException.class, 8366 () -> mWifiServiceImpl.setNetworkSelectionConfig(nsConfig)); 8367 8368 // Null arguments 8369 assertThrows(IllegalArgumentException.class, 8370 () -> mWifiServiceImpl.setNetworkSelectionConfig(null)); 8371 8372 // has permission to call API 8373 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 8374 mWifiServiceImpl.setNetworkSelectionConfig(nsConfig); 8375 mLooper.dispatchAll(); 8376 verify(mWifiConnectivityManager).setNetworkSelectionConfig(nsConfig); 8377 verify(mLastCallerInfoManager).put( 8378 eq(WifiManager.API_SET_NETWORK_SELECTION_CONFIG), 8379 anyInt(), anyInt(), anyInt(), any(), eq(true)); 8380 } 8381 8382 @Test testGetNetworkSelectionConfig_Exceptions()8383 public void testGetNetworkSelectionConfig_Exceptions() { 8384 assumeTrue(SdkLevel.isAtLeastT()); 8385 IWifiNetworkSelectionConfigListener listener = 8386 mock(IWifiNetworkSelectionConfigListener.class); 8387 // null listener ==> IllegalArgumentException 8388 assertThrows(IllegalArgumentException.class, 8389 () -> mWifiServiceImpl.getNetworkSelectionConfig(null)); 8390 8391 // No permission ==> SecurityException 8392 assertThrows(SecurityException.class, 8393 () -> mWifiServiceImpl.getNetworkSelectionConfig(listener)); 8394 } 8395 8396 @Test testGetNetworkSelectionConfig_GoodCase()8397 public void testGetNetworkSelectionConfig_GoodCase() throws Exception { 8398 assumeTrue(SdkLevel.isAtLeastT()); 8399 IWifiNetworkSelectionConfigListener listener = 8400 mock(IWifiNetworkSelectionConfigListener.class); 8401 InOrder inOrder = inOrder(listener); 8402 8403 int [] defaultRssi2 = {-83, -80, -73, -60}; 8404 int [] defaultRssi5 = {-80, -77, -70, -57}; 8405 int [] defaultRssi6 = {-80, -77, -70, -57}; 8406 int [] customRssi2 = {-80, -70, -60, -50}; 8407 int [] customRssi5 = {-80, -75, -70, -65}; 8408 int [] customRssi6 = {-75, -70, -65, -60}; 8409 int [] resetArray = {0, 0, 0, 0}; 8410 8411 // has permission to call API 8412 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 8413 8414 // configure the default values for RSSI thresholds from ScoringParams 8415 when(mScoringParams.getRssiArray(ScanResult.BAND_24_GHZ_START_FREQ_MHZ)) 8416 .thenReturn(defaultRssi2); 8417 when(mScoringParams.getRssiArray(ScanResult.BAND_5_GHZ_START_FREQ_MHZ)) 8418 .thenReturn(defaultRssi5); 8419 when(mScoringParams.getRssiArray(ScanResult.BAND_6_GHZ_START_FREQ_MHZ)) 8420 .thenReturn(defaultRssi6); 8421 8422 // getting the WifiNetworkSelectionConfig when one hasn't been set returns the default one 8423 // built from the builder with RSSI thresholds from ScoringParams 8424 mWifiServiceImpl.getNetworkSelectionConfig(listener); 8425 mLooper.dispatchAll(); 8426 WifiNetworkSelectionConfig defaultConfig = new WifiNetworkSelectionConfig.Builder() 8427 .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, defaultRssi2) 8428 .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, defaultRssi5) 8429 .setRssiThresholds(WIFI_BAND_6_GHZ, defaultRssi6) 8430 .build(); 8431 inOrder.verify(listener).onResult(defaultConfig); 8432 8433 // set the WifiNetworkSelectionConfig and verify that same config is retrieved 8434 WifiNetworkSelectionConfig customConfig = new WifiNetworkSelectionConfig.Builder() 8435 .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, customRssi2) 8436 .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, customRssi5) 8437 .setRssiThresholds(WIFI_BAND_6_GHZ, customRssi6) 8438 .setUserConnectChoiceOverrideEnabled(false) 8439 .setLastSelectionWeightEnabled(false) 8440 .build(); 8441 8442 mWifiServiceImpl.setNetworkSelectionConfig(customConfig); 8443 mLooper.dispatchAll(); 8444 verify(mWifiConnectivityManager).setNetworkSelectionConfig(customConfig); 8445 8446 mWifiServiceImpl.getNetworkSelectionConfig(listener); 8447 mLooper.dispatchAll(); 8448 inOrder.verify(listener).onResult(customConfig); 8449 8450 // resetting the RSSI thresholds returns the config with RSSI from ScoringParams 8451 WifiNetworkSelectionConfig resetConfig = new WifiNetworkSelectionConfig.Builder() 8452 .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, resetArray) 8453 .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, resetArray) 8454 .setRssiThresholds(WIFI_BAND_6_GHZ, defaultRssi6) 8455 .build(); 8456 8457 WifiNetworkSelectionConfig resetExpectedConfig = new WifiNetworkSelectionConfig.Builder() 8458 .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, defaultRssi2) 8459 .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, defaultRssi5) 8460 .setRssiThresholds(WIFI_BAND_6_GHZ, defaultRssi6) 8461 .build(); 8462 8463 mWifiServiceImpl.setNetworkSelectionConfig(resetConfig); 8464 mLooper.dispatchAll(); 8465 verify(mWifiConnectivityManager).setNetworkSelectionConfig(resetConfig); 8466 8467 mWifiServiceImpl.getNetworkSelectionConfig(listener); 8468 mLooper.dispatchAll(); 8469 8470 inOrder.verify(listener).onResult(resetExpectedConfig); 8471 } 8472 8473 @Test testSetThirdPartyAppEnablingWifiConfirmationDialogEnabled()8474 public void testSetThirdPartyAppEnablingWifiConfirmationDialogEnabled() throws Exception { 8475 boolean enable = true; 8476 8477 // no permission to call APIs 8478 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 8479 when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())) 8480 .thenReturn(false); 8481 assertThrows(SecurityException.class, () -> 8482 mWifiServiceImpl.setThirdPartyAppEnablingWifiConfirmationDialogEnabled(enable)); 8483 assertThrows(SecurityException.class, 8484 () -> mWifiServiceImpl.isThirdPartyAppEnablingWifiConfirmationDialogEnabled()); 8485 8486 // has permission to call APIs 8487 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 8488 mWifiServiceImpl.setThirdPartyAppEnablingWifiConfirmationDialogEnabled(enable); 8489 verify(mWifiSettingsConfigStore).put( 8490 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI), eq(enable)); 8491 verify(mWifiSettingsConfigStore).put( 8492 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API), eq(true)); 8493 verify(mLastCallerInfoManager).put( 8494 eq(WifiManager.API_SET_THIRD_PARTY_APPS_ENABLING_WIFI_CONFIRMATION_DIALOG), 8495 anyInt(), anyInt(), anyInt(), any(), eq(enable)); 8496 8497 // get value before set by API 8498 when(mWifiSettingsConfigStore.get( 8499 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API))) 8500 .thenReturn(false); 8501 when(mResourceCache.getBoolean( 8502 R.bool.config_showConfirmationDialogForThirdPartyAppsEnablingWifi)) 8503 .thenReturn(false); 8504 assertFalse(mWifiServiceImpl.isThirdPartyAppEnablingWifiConfirmationDialogEnabled()); 8505 verify(mWifiSettingsConfigStore, never()) 8506 .get(eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI)); 8507 8508 // get value after set by API 8509 when(mWifiSettingsConfigStore.get( 8510 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API))) 8511 .thenReturn(true); 8512 when(mWifiSettingsConfigStore.get(eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI))) 8513 .thenReturn(true); 8514 assertTrue(mWifiServiceImpl.isThirdPartyAppEnablingWifiConfirmationDialogEnabled()); 8515 verify(mWifiSettingsConfigStore).get(eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI)); 8516 verify(mWifiSettingsConfigStore, times(2)).get( 8517 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API)); 8518 } 8519 8520 @Test(expected = SecurityException.class) testAllowAutojoinGlobalFailureNoPermission()8521 public void testAllowAutojoinGlobalFailureNoPermission() throws Exception { 8522 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 8523 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 8524 .thenReturn(false); 8525 when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), anyString())).thenReturn(false); 8526 when(mWifiPermissionsUtil.isProfileOwner(anyInt(), anyString())).thenReturn(false); 8527 mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mExtras); 8528 } 8529 8530 @Test testAllowAutojoinGlobalWithPermission()8531 public void testAllowAutojoinGlobalWithPermission() throws Exception { 8532 // verify allowAutojoinGlobal with MANAGE_WIFI_NETWORK_SELECTION 8533 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 8534 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 8535 .thenReturn(true); 8536 when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(false); 8537 mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mExtras); 8538 mLooper.dispatchAll(); 8539 verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(true, false); 8540 8541 // verify allowAutojoinGlobal with NETWORK_SETTINGS 8542 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 8543 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 8544 .thenReturn(false); 8545 when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(false); 8546 mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mExtras); 8547 mLooper.dispatchAll(); 8548 verify(mWifiConnectivityManager, times(2)).setAutoJoinEnabledExternal(true, false); 8549 8550 // verify allowAutojoinGlobal with device admin 8551 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 8552 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 8553 .thenReturn(false); 8554 when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(true); 8555 mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mExtras); 8556 mLooper.dispatchAll(); 8557 verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(true, true); 8558 } 8559 8560 @Test testAutoJoinGlobalWithAttributionSourceChain()8561 public void testAutoJoinGlobalWithAttributionSourceChain() { 8562 assumeTrue(SdkLevel.isAtLeastS()); 8563 8564 // verify allowAutojoinGlobal with device admin in attribution source chain 8565 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 8566 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 8567 .thenReturn(true); 8568 when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(false); 8569 // mock attribution chain 8570 AttributionSource attributionSource = mock(AttributionSource.class); 8571 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 8572 when(attributionSource.getUid()).thenReturn(TEST_UID); 8573 when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME); 8574 AttributionSource originalCaller = mock(AttributionSource.class); 8575 when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID); 8576 when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER); 8577 when(attributionSource.getNext()).thenReturn(originalCaller); 8578 // mock the original caller to be device admin via the isAdmin check 8579 when(mWifiPermissionsUtil.isAdmin(OTHER_TEST_UID, TEST_PACKAGE_NAME_OTHER)) 8580 .thenReturn(true); 8581 mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mAttribution); 8582 mLooper.dispatchAll(); 8583 verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(true, true); 8584 8585 // mock the original caller to be not a device admin and then verify again. 8586 when(mWifiPermissionsUtil.isAdmin(OTHER_TEST_UID, TEST_PACKAGE_NAME_OTHER)) 8587 .thenReturn(false); 8588 mWifiServiceImpl.allowAutojoinGlobal(false, TEST_PACKAGE_NAME, mAttribution); 8589 mLooper.dispatchAll(); 8590 verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(false, false); 8591 8592 // mock the original caller to be device admin via the isLegacyDeviceAdmin check 8593 when(mWifiPermissionsUtil.isLegacyDeviceAdmin(OTHER_TEST_UID, TEST_PACKAGE_NAME_OTHER)) 8594 .thenReturn(true); 8595 mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mAttribution); 8596 mLooper.dispatchAll(); 8597 verify(mWifiConnectivityManager, times(2)).setAutoJoinEnabledExternal(true, true); 8598 } 8599 8600 @Test testQueryAutojoinGlobal_Exceptions()8601 public void testQueryAutojoinGlobal_Exceptions() { 8602 // good inputs should result in no exceptions. 8603 IBooleanListener listener = mock(IBooleanListener.class); 8604 // null listener ==> IllegalArgumentException 8605 assertThrows(IllegalArgumentException.class, 8606 () -> mWifiServiceImpl.queryAutojoinGlobal(null)); 8607 8608 // No permission ==> SecurityException 8609 assertThrows(SecurityException.class, 8610 () -> mWifiServiceImpl.queryAutojoinGlobal(listener)); 8611 } 8612 8613 @Test testQueryAutojoinGlobal_GoodCase()8614 public void testQueryAutojoinGlobal_GoodCase() throws RemoteException { 8615 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 8616 IBooleanListener listener = mock(IBooleanListener.class); 8617 8618 InOrder inOrder = inOrder(listener); 8619 when(mWifiConnectivityManager.getAutoJoinEnabledExternal()).thenReturn(true); 8620 mWifiServiceImpl.queryAutojoinGlobal(listener); 8621 mLooper.dispatchAll(); 8622 inOrder.verify(listener).onResult(true); 8623 8624 when(mWifiConnectivityManager.getAutoJoinEnabledExternal()).thenReturn(false); 8625 mWifiServiceImpl.queryAutojoinGlobal(listener); 8626 mLooper.dispatchAll(); 8627 inOrder.verify(listener).onResult(false); 8628 } 8629 8630 @Test(expected = SecurityException.class) testSetSsidsDoNotBlocklist_NoPermission()8631 public void testSetSsidsDoNotBlocklist_NoPermission() throws Exception { 8632 // by default no permissions are given so the call should fail. 8633 mWifiServiceImpl.setSsidsAllowlist(TEST_PACKAGE_NAME, 8634 new ParceledListSlice<>(Collections.emptyList())); 8635 } 8636 8637 @Test testSetSsidsDoNotBlocklist_WithPermission()8638 public void testSetSsidsDoNotBlocklist_WithPermission() throws Exception { 8639 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 8640 8641 // verify setting an empty list 8642 mWifiServiceImpl.setSsidsAllowlist(TEST_PACKAGE_NAME, 8643 new ParceledListSlice<>(Collections.emptyList())); 8644 mLooper.dispatchAll(); 8645 verify(mWifiBlocklistMonitor).setSsidsAllowlist(Collections.emptyList()); 8646 8647 // verify setting a list of valid SSIDs 8648 List<WifiSsid> expectedSsids = new ArrayList<>(); 8649 expectedSsids.add(WifiSsid.fromString(TEST_SSID_WITH_QUOTES)); 8650 mWifiServiceImpl.setSsidsAllowlist(TEST_PACKAGE_NAME, 8651 new ParceledListSlice<>(expectedSsids)); 8652 mLooper.dispatchAll(); 8653 verify(mWifiBlocklistMonitor).setSsidsAllowlist(expectedSsids); 8654 } 8655 8656 @Test testSetSsidsDoNotBlocklist_WithPermissionAndroidT()8657 public void testSetSsidsDoNotBlocklist_WithPermissionAndroidT() 8658 throws Exception { 8659 assumeTrue(SdkLevel.isAtLeastT()); 8660 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 8661 .thenReturn(true); 8662 8663 List<WifiSsid> expectedSsids = new ArrayList<>(); 8664 expectedSsids.add(WifiSsid.fromString(TEST_SSID_WITH_QUOTES)); 8665 mWifiServiceImpl.setSsidsAllowlist(TEST_PACKAGE_NAME, 8666 new ParceledListSlice<>(expectedSsids)); 8667 mLooper.dispatchAll(); 8668 verify(mWifiBlocklistMonitor).setSsidsAllowlist(expectedSsids); 8669 } 8670 8671 @Test testAllowAutojoinFailureNoNetworkSettingsPermission()8672 public void testAllowAutojoinFailureNoNetworkSettingsPermission() throws Exception { 8673 doThrow(new SecurityException()).when(mContext) 8674 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 8675 eq("WifiService")); 8676 try { 8677 mWifiServiceImpl.allowAutojoin(0, true); 8678 fail("Expected SecurityException"); 8679 } catch (SecurityException e) { 8680 // Test succeeded 8681 } 8682 } 8683 8684 @Test testAllowAutojoinOnSuggestionNetwork()8685 public void testAllowAutojoinOnSuggestionNetwork() { 8686 WifiConfiguration config = new WifiConfiguration(); 8687 config.allowAutojoin = false; 8688 config.fromWifiNetworkSuggestion = true; 8689 when(mWifiConfigManager.getConfiguredNetwork(anyInt())).thenReturn(config); 8690 when(mWifiNetworkSuggestionsManager.allowNetworkSuggestionAutojoin(any(), anyBoolean())) 8691 .thenReturn(true); 8692 mWifiServiceImpl.allowAutojoin(0, true); 8693 mLooper.dispatchAll(); 8694 verify(mWifiConfigManager).getConfiguredNetwork(0); 8695 verify(mWifiNetworkSuggestionsManager).allowNetworkSuggestionAutojoin(any(), anyBoolean()); 8696 verify(mWifiConfigManager).allowAutojoin(anyInt(), anyBoolean()); 8697 verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_CONFIGURE_AUTO_CONNECT_ON), 8698 anyInt()); 8699 verify(mLastCallerInfoManager).put(eq(WifiManager.API_ALLOW_AUTOJOIN), anyInt(), 8700 anyInt(), anyInt(), anyString(), eq(true)); 8701 } 8702 8703 @Test testAllowAutojoinOnSavedNetwork()8704 public void testAllowAutojoinOnSavedNetwork() { 8705 WifiConfiguration config = new WifiConfiguration(); 8706 config.allowAutojoin = false; 8707 config.fromWifiNetworkSuggestion = false; 8708 config.fromWifiNetworkSpecifier = false; 8709 when(mWifiConfigManager.getConfiguredNetwork(0)).thenReturn(config); 8710 mWifiServiceImpl.allowAutojoin(0, true); 8711 mLooper.dispatchAll(); 8712 verify(mWifiConfigManager).getConfiguredNetwork(0); 8713 verify(mWifiNetworkSuggestionsManager, never()) 8714 .allowNetworkSuggestionAutojoin(any(), anyBoolean()); 8715 verify(mWifiConfigManager).allowAutojoin(anyInt(), anyBoolean()); 8716 } 8717 8718 @Test testAllowAutojoinOnWifiNetworkSpecifier()8719 public void testAllowAutojoinOnWifiNetworkSpecifier() { 8720 WifiConfiguration config = new WifiConfiguration(); 8721 config.fromWifiNetworkSpecifier = true; 8722 when(mWifiConfigManager.getConfiguredNetwork(0)).thenReturn(config); 8723 mWifiServiceImpl.allowAutojoin(0, true); 8724 mLooper.dispatchAll(); 8725 verify(mWifiConfigManager).getConfiguredNetwork(0); 8726 verify(mWifiNetworkSuggestionsManager, never()) 8727 .allowNetworkSuggestionAutojoin(config, true); 8728 verify(mWifiConfigManager, never()).allowAutojoin(0, true); 8729 } 8730 8731 @Test testAllowAutojoinOnSavedPasspointNetwork()8732 public void testAllowAutojoinOnSavedPasspointNetwork() { 8733 WifiConfiguration config = WifiConfigurationTestUtil.createPasspointNetwork(); 8734 when(mWifiConfigManager.getConfiguredNetwork(0)).thenReturn(config); 8735 when(mWifiNetworkSuggestionsManager.allowNetworkSuggestionAutojoin(any(), anyBoolean())) 8736 .thenReturn(true); 8737 mWifiServiceImpl.allowAutojoin(0, true); 8738 mLooper.dispatchAll(); 8739 verify(mWifiConfigManager).getConfiguredNetwork(0); 8740 verify(mWifiNetworkSuggestionsManager, never()) 8741 .allowNetworkSuggestionAutojoin(config, true); 8742 verify(mWifiConfigManager, never()).allowAutojoin(0, true); 8743 } 8744 8745 /** 8746 * Test that setMacRandomizationSettingPasspointEnabled is protected by NETWORK_SETTINGS 8747 * permission. 8748 */ 8749 @Test testSetMacRandomizationSettingPasspointEnabledFailureNoNetworkSettingsPermission()8750 public void testSetMacRandomizationSettingPasspointEnabledFailureNoNetworkSettingsPermission() 8751 throws Exception { 8752 doThrow(new SecurityException()).when(mContext) 8753 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 8754 eq("WifiService")); 8755 try { 8756 mWifiServiceImpl.setMacRandomizationSettingPasspointEnabled("TEST_FQDN", true); 8757 fail("Expected SecurityException"); 8758 } catch (SecurityException e) { 8759 // Test succeeded 8760 } 8761 } 8762 8763 /** 8764 * Test that setMacRandomizationSettingPasspointEnabled makes the appropriate calls. 8765 */ 8766 @Test testSetMacRandomizationSettingPasspointEnabled()8767 public void testSetMacRandomizationSettingPasspointEnabled() throws Exception { 8768 mWifiServiceImpl.setMacRandomizationSettingPasspointEnabled("TEST_FQDN", true); 8769 mLooper.dispatchAll(); 8770 verify(mPasspointManager).enableMacRandomization("TEST_FQDN", true); 8771 } 8772 8773 /** 8774 * Test that setPasspointMeteredOverride is protected by NETWORK_SETTINGS permission. 8775 */ 8776 @Test testSetPasspointMeteredOverrideFailureNoNetworkSettingsPermission()8777 public void testSetPasspointMeteredOverrideFailureNoNetworkSettingsPermission() 8778 throws Exception { 8779 doThrow(new SecurityException()).when(mContext) 8780 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 8781 eq("WifiService")); 8782 try { 8783 mWifiServiceImpl.setPasspointMeteredOverride("TEST_FQDN", METERED_OVERRIDE_METERED); 8784 fail("Expected SecurityException"); 8785 } catch (SecurityException e) { 8786 // Test succeeded 8787 } 8788 } 8789 8790 /** 8791 * Test that setPasspointMeteredOverride makes the appropriate calls. 8792 */ 8793 @Test testSetPasspointMeteredOverride()8794 public void testSetPasspointMeteredOverride() throws Exception { 8795 mWifiServiceImpl.setPasspointMeteredOverride("TEST_FQDN", METERED_OVERRIDE_METERED); 8796 mLooper.dispatchAll(); 8797 verify(mPasspointManager).setMeteredOverride("TEST_FQDN", METERED_OVERRIDE_METERED); 8798 } 8799 8800 /** 8801 * Test handle boot completed sequence. 8802 */ 8803 @Test testHandleBootCompleted()8804 public void testHandleBootCompleted() throws Exception { 8805 mWifiServiceImpl.handleBootCompleted(); 8806 mLooper.dispatchAll(); 8807 8808 verify(mWifiNetworkFactory).register(); 8809 verify(mUntrustedWifiNetworkFactory).register(); 8810 verify(mOemWifiNetworkFactory).register(); 8811 verify(mRestrictedWifiNetworkFactory).register(); 8812 verify(mMultiInternetWifiNetworkFactory).register(); 8813 verify(mPasspointManager).initializeProvisioner(any()); 8814 verify(mWifiP2pConnection).handleBootCompleted(); 8815 verify(mWifiCountryCode).registerListener(any(WifiCountryCode.ChangeListener.class)); 8816 verify(mWifiDeviceStateChangeManager).handleBootCompleted(); 8817 } 8818 8819 /** 8820 * Test handle user switch sequence. 8821 */ 8822 @Test testHandleUserSwitch()8823 public void testHandleUserSwitch() throws Exception { 8824 mWifiServiceImpl.handleUserSwitch(5); 8825 mLooper.dispatchAll(); 8826 verify(mWifiConfigManager).handleUserSwitch(5); 8827 verify(mWifiNotificationManager).createNotificationChannels(); 8828 verify(mWifiNetworkSuggestionsManager).resetNotification(); 8829 verify(mWifiCarrierInfoManager).resetNotification(); 8830 verify(mOpenNetworkNotifier).clearPendingNotification(false); 8831 verify(mWakeupController).resetNotification(); 8832 } 8833 8834 /** 8835 * Test handle user unlock sequence. 8836 */ 8837 @Test testHandleUserUnlock()8838 public void testHandleUserUnlock() throws Exception { 8839 mWifiServiceImpl.handleUserUnlock(5); 8840 mLooper.dispatchAll(); 8841 verify(mWifiConfigManager).handleUserUnlock(5); 8842 } 8843 8844 /** 8845 * Test handle user stop sequence. 8846 */ 8847 @Test testHandleUserStop()8848 public void testHandleUserStop() throws Exception { 8849 mWifiServiceImpl.handleUserStop(5); 8850 mLooper.dispatchAll(); 8851 verify(mWifiConfigManager).handleUserStop(5); 8852 } 8853 8854 /** 8855 * Test register scan result callback without permission. 8856 */ 8857 @Test(expected = SecurityException.class) testRegisterScanResultCallbackWithMissingPermission()8858 public void testRegisterScanResultCallbackWithMissingPermission() throws Exception { 8859 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 8860 eq(ACCESS_WIFI_STATE), eq("WifiService")); 8861 mWifiServiceImpl.registerScanResultsCallback(mScanResultsCallback); 8862 } 8863 8864 /** 8865 * Test unregister scan result callback without permission. 8866 */ 8867 @Test(expected = SecurityException.class) testUnregisterScanResultCallbackWithMissingPermission()8868 public void testUnregisterScanResultCallbackWithMissingPermission() throws Exception { 8869 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 8870 eq(ACCESS_WIFI_STATE), eq("WifiService")); 8871 mWifiServiceImpl.unregisterScanResultsCallback(mScanResultsCallback); 8872 } 8873 8874 /** 8875 * Test register scan result callback with illegal argument. 8876 */ 8877 @Test(expected = IllegalArgumentException.class) testRegisterScanResultCallbackWithIllegalArgument()8878 public void testRegisterScanResultCallbackWithIllegalArgument() throws Exception { 8879 mWifiServiceImpl.registerScanResultsCallback(null); 8880 } 8881 8882 /** 8883 * Test register and unregister callback will go to ScanRequestProxy; 8884 */ 8885 @Test testRegisterUnregisterScanResultCallback()8886 public void testRegisterUnregisterScanResultCallback() throws Exception { 8887 mWifiServiceImpl.registerScanResultsCallback(mScanResultsCallback); 8888 mLooper.dispatchAll(); 8889 verify(mScanRequestProxy).registerScanResultsCallback(mScanResultsCallback); 8890 mWifiServiceImpl.unregisterScanResultsCallback(mScanResultsCallback); 8891 mLooper.dispatchAll(); 8892 verify(mScanRequestProxy).unregisterScanResultsCallback(mScanResultsCallback); 8893 } 8894 8895 /** 8896 * Test register callback without ACCESS_WIFI_STATE permission. 8897 */ 8898 @Test(expected = SecurityException.class) testRegisterSuggestionNetworkCallbackWithMissingAccessWifiPermission()8899 public void testRegisterSuggestionNetworkCallbackWithMissingAccessWifiPermission() { 8900 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 8901 eq(ACCESS_WIFI_STATE), eq("WifiService")); 8902 mWifiServiceImpl.registerSuggestionConnectionStatusListener( 8903 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 8904 } 8905 8906 /** 8907 * Test register callback without ACCESS_FINE_LOCATION permission. 8908 */ 8909 @Test(expected = SecurityException.class) testRegisterSuggestionNetworkCallbackWithMissingFinePermission()8910 public void testRegisterSuggestionNetworkCallbackWithMissingFinePermission() { 8911 doNothing().when(mContext).enforceCallingOrSelfPermission( 8912 eq(ACCESS_WIFI_STATE), eq("WifiService")); 8913 if (SdkLevel.isAtLeastT()) { 8914 doThrow(new SecurityException()).when(mWifiPermissionsUtil) 8915 .enforceLocationPermissionInManifest(anyInt(), eq(false)); 8916 } else { 8917 doThrow(new SecurityException()).when(mWifiPermissionsUtil) 8918 .enforceLocationPermission(anyString(), anyString(), anyInt()); 8919 } 8920 mWifiServiceImpl.registerSuggestionConnectionStatusListener( 8921 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 8922 } 8923 8924 /** 8925 * Test register callback without callback 8926 */ 8927 @Test(expected = IllegalArgumentException.class) testRegisterSuggestionNetworkCallbackWithIllegalArgument()8928 public void testRegisterSuggestionNetworkCallbackWithIllegalArgument() { 8929 mWifiServiceImpl.registerSuggestionConnectionStatusListener(null, TEST_PACKAGE_NAME, 8930 TEST_FEATURE_ID); 8931 } 8932 8933 /** 8934 * Test unregister callback without permission. 8935 */ 8936 @Test(expected = SecurityException.class) testUnregisterSuggestionNetworkCallbackWithMissingPermission()8937 public void testUnregisterSuggestionNetworkCallbackWithMissingPermission() { 8938 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 8939 eq(ACCESS_WIFI_STATE), eq("WifiService")); 8940 mWifiServiceImpl.unregisterSuggestionConnectionStatusListener( 8941 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME); 8942 } 8943 8944 /** 8945 * Test register nad unregister callback will go to WifiNetworkSuggestionManager 8946 */ 8947 @Test testRegisterUnregisterSuggestionNetworkCallback()8948 public void testRegisterUnregisterSuggestionNetworkCallback() throws Exception { 8949 mWifiServiceImpl.registerSuggestionConnectionStatusListener( 8950 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 8951 mLooper.dispatchAll(); 8952 verify(mWifiNetworkSuggestionsManager).registerSuggestionConnectionStatusListener( 8953 eq(mSuggestionConnectionStatusListener), eq(TEST_PACKAGE_NAME), anyInt()); 8954 mWifiServiceImpl.unregisterSuggestionConnectionStatusListener( 8955 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME); 8956 mLooper.dispatchAll(); 8957 verify(mWifiNetworkSuggestionsManager).unregisterSuggestionConnectionStatusListener( 8958 eq(mSuggestionConnectionStatusListener), eq(TEST_PACKAGE_NAME), anyInt()); 8959 } 8960 8961 /** 8962 * Test to verify that the arguments are verified before dispatching the operation 8963 * 8964 * Steps: call acquireWifiLock with invalid arguments. 8965 * Expected: the call should throw proper Exception. 8966 */ 8967 @Test acquireWifiLockShouldThrowExceptionOnInvalidArgs()8968 public void acquireWifiLockShouldThrowExceptionOnInvalidArgs() { 8969 final int wifiLockModeInvalid = -1; 8970 8971 // Package name is null. 8972 assertThrows(NullPointerException.class, 8973 () -> mWifiServiceImpl.acquireWifiLock(mAppBinder, 8974 WifiManager.WIFI_MODE_FULL_LOW_LATENCY, "", null, null, null)); 8975 8976 // Invalid Lock mode. 8977 assertThrows(IllegalArgumentException.class, 8978 () -> mWifiServiceImpl.acquireWifiLock(mAppBinder, wifiLockModeInvalid, "", 8979 new WorkSource(TEST_UID, TEST_PACKAGE_NAME), TEST_PACKAGE_NAME, null)); 8980 } 8981 setupReportActivityInfo()8982 private void setupReportActivityInfo() { 8983 WifiLinkLayerStats stats = new WifiLinkLayerStats(); 8984 stats.on_time = 1000; 8985 stats.tx_time = 1; 8986 stats.rx_time = 2; 8987 stats.tx_time_per_level = new int[] {3, 4, 5}; 8988 stats.on_time_scan = 6; 8989 when(mClientModeManager.getWifiLinkLayerStats()).thenReturn(stats); 8990 when(mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_IDLE)) 8991 .thenReturn(7.0); 8992 when(mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_RX)) 8993 .thenReturn(8.0); 8994 when(mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_TX)) 8995 .thenReturn(9.0); 8996 when(mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE)) 8997 .thenReturn(10000.0); 8998 when(mClock.getElapsedSinceBootMillis()).thenReturn(9999L); 8999 } 9000 validateWifiActivityEnergyInfo(WifiActivityEnergyInfo info)9001 private void validateWifiActivityEnergyInfo(WifiActivityEnergyInfo info) { 9002 assertNotNull(info); 9003 assertEquals(9999L, info.getTimeSinceBootMillis()); 9004 assertEquals(WifiActivityEnergyInfo.STACK_STATE_STATE_IDLE, info.getStackState()); 9005 assertEquals(1, info.getControllerTxDurationMillis()); 9006 assertEquals(2, info.getControllerRxDurationMillis()); 9007 assertEquals(6, info.getControllerScanDurationMillis()); 9008 assertEquals(997, info.getControllerIdleDurationMillis()); 9009 } 9010 9011 /** 9012 * Tests that {@link WifiServiceImpl#getWifiActivityEnergyInfoAsync} throws 9013 * {@link SecurityException} if the caller doesn't have the necessary permissions. 9014 */ 9015 @Test(expected = SecurityException.class) getWifiActivityEnergyInfoAsyncNoPermission()9016 public void getWifiActivityEnergyInfoAsyncNoPermission() throws Exception { 9017 doThrow(SecurityException.class) 9018 .when(mContext).enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), any()); 9019 mWifiServiceImpl.getWifiActivityEnergyInfoAsync(mOnWifiActivityEnergyInfoListener); 9020 } 9021 9022 /** 9023 * Tests that {@link WifiServiceImpl#getWifiActivityEnergyInfoAsync} passes null to the listener 9024 * if link layer stats is unsupported. 9025 */ 9026 @Test getWifiActivityEnergyInfoAsyncFeatureUnsupported()9027 public void getWifiActivityEnergyInfoAsyncFeatureUnsupported() throws Exception { 9028 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(new BitSet()); 9029 9030 mWifiServiceImpl.getWifiActivityEnergyInfoAsync(mOnWifiActivityEnergyInfoListener); 9031 verify(mOnWifiActivityEnergyInfoListener).onWifiActivityEnergyInfo(null); 9032 } 9033 9034 /** 9035 * Tests that {@link WifiServiceImpl#getWifiActivityEnergyInfoAsync} passes the expected values 9036 * to the listener on success. 9037 */ 9038 @Test getWifiActivityEnergyInfoAsyncSuccess()9039 public void getWifiActivityEnergyInfoAsyncSuccess() throws Exception { 9040 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn( 9041 createCapabilityBitset(WifiManager.WIFI_FEATURE_LINK_LAYER_STATS)); 9042 setupReportActivityInfo(); 9043 mWifiServiceImpl.getWifiActivityEnergyInfoAsync(mOnWifiActivityEnergyInfoListener); 9044 mLooper.dispatchAll(); 9045 ArgumentCaptor<WifiActivityEnergyInfo> infoCaptor = 9046 ArgumentCaptor.forClass(WifiActivityEnergyInfo.class); 9047 verify(mOnWifiActivityEnergyInfoListener).onWifiActivityEnergyInfo(infoCaptor.capture()); 9048 validateWifiActivityEnergyInfo(infoCaptor.getValue()); 9049 } 9050 9051 /** 9052 * Tests that {@link WifiServiceImpl#getWifiActivityEnergyInfoAsync} throws exception when 9053 * listener is null 9054 */ 9055 @Test getWifiActivityEnergyInfoWithNullListener()9056 public void getWifiActivityEnergyInfoWithNullListener() throws Exception { 9057 assertThrows(IllegalArgumentException.class, 9058 () -> mWifiServiceImpl.getWifiActivityEnergyInfoAsync(null)); 9059 } 9060 9061 @Test testCarrierConfigChangeUpdateSoftApCapability()9062 public void testCarrierConfigChangeUpdateSoftApCapability() throws Exception { 9063 lenient().when(SubscriptionManager.getActiveDataSubscriptionId()) 9064 .thenReturn(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID); 9065 mWifiServiceImpl.checkAndStartWifi(); 9066 mLooper.dispatchAll(); 9067 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 9068 argThat((IntentFilter filter) -> 9069 filter.hasAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)), 9070 isNull(), 9071 any(Handler.class)); 9072 9073 // Send the broadcast 9074 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED); 9075 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 9076 mLooper.dispatchAll(); 9077 verify(mActiveModeWarden).updateSoftApCapability(any(), 9078 eq(WifiManager.IFACE_IP_MODE_TETHERED)); 9079 } 9080 9081 @Test testPhoneActiveDataSubscriptionIdChangedUpdateSoftApCapability()9082 public void testPhoneActiveDataSubscriptionIdChangedUpdateSoftApCapability() throws Exception { 9083 lenient().when(SubscriptionManager.getActiveDataSubscriptionId()) 9084 .thenReturn(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID); 9085 mWifiServiceImpl.checkAndStartWifi(); 9086 mLooper.dispatchAll(); 9087 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 9088 argThat((IntentFilter filter) -> 9089 filter.hasAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)), 9090 isNull(), 9091 any(Handler.class)); 9092 ArgumentCaptor<PhoneStateListener> phoneStateListenerCaptor = 9093 ArgumentCaptor.forClass(PhoneStateListener.class); 9094 verify(mTelephonyManager).listen(phoneStateListenerCaptor.capture(), 9095 eq(PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE)); 9096 mPhoneStateListener = phoneStateListenerCaptor.getValue(); 9097 assertNotNull(mPhoneStateListener); 9098 mPhoneStateListener.onActiveDataSubscriptionIdChanged(2); 9099 mLooper.dispatchAll(); 9100 verify(mActiveModeWarden).updateSoftApCapability(any(), 9101 eq(WifiManager.IFACE_IP_MODE_TETHERED)); 9102 } 9103 9104 /** 9105 * Verify that the call to getWifiConfigsForMatchedNetworkSuggestions is not redirected to 9106 * specific API getWifiConfigForMatchedNetworkSuggestionsSharedWithUser when the caller doesn't 9107 * have NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD. 9108 */ 9109 @Test(expected = SecurityException.class) testGetWifiConfigsForMatchedNetworkSuggestionsWithoutPermissions()9110 public void testGetWifiConfigsForMatchedNetworkSuggestionsWithoutPermissions() { 9111 mWifiServiceImpl.getWifiConfigForMatchedNetworkSuggestionsSharedWithUser( 9112 new ParceledListSlice<>(Collections.emptyList())); 9113 } 9114 9115 /** 9116 * Verify that the call to getWifiConfigsForMatchedNetworkSuggestions is redirected to 9117 * specific API getWifiConfigForMatchedNetworkSuggestionsSharedWithUser when the caller 9118 * have NETWORK_SETTINGS. 9119 */ 9120 @Test testGetWifiConfigsForMatchedNetworkSuggestionsWithSettingPermissions()9121 public void testGetWifiConfigsForMatchedNetworkSuggestionsWithSettingPermissions() { 9122 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9123 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 9124 mLooper.startAutoDispatch(); 9125 mWifiServiceImpl 9126 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser( 9127 new ParceledListSlice<>(createScanResultList())); 9128 mLooper.stopAutoDispatch(); 9129 verify(mWifiNetworkSuggestionsManager) 9130 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(any()); 9131 } 9132 9133 /** 9134 * Verify that the call to getWifiConfigsForMatchedNetworkSuggestions is redirected to 9135 * specific API getWifiConfigForMatchedNetworkSuggestionsSharedWithUser when the caller 9136 * have NETWORK_SETUP_WIZARD. 9137 */ 9138 @Test testGetWifiConfigsForMatchedNetworkSuggestionsWithSetupWizardPermissions()9139 public void testGetWifiConfigsForMatchedNetworkSuggestionsWithSetupWizardPermissions() { 9140 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD), 9141 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 9142 mLooper.startAutoDispatch(); 9143 mWifiServiceImpl 9144 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser( 9145 new ParceledListSlice<>(createScanResultList())); 9146 mLooper.stopAutoDispatch(); 9147 verify(mWifiNetworkSuggestionsManager) 9148 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(any()); 9149 } 9150 9151 @Test testGetWifiConfigsForMatchedNetworkSuggestionsWithInvalidScanResults()9152 public void testGetWifiConfigsForMatchedNetworkSuggestionsWithInvalidScanResults() { 9153 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9154 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 9155 mWifiServiceImpl 9156 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser( 9157 new ParceledListSlice<>(Collections.emptyList())); 9158 mLooper.dispatchAll(); 9159 verify(mWifiNetworkSuggestionsManager, never()) 9160 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(any()); 9161 } 9162 9163 /** 9164 * Verify that a call to setWifiConnectedNetworkScorer throws a SecurityException if 9165 * the caller does not have WIFI_UPDATE_USABILITY_STATS_SCORE permission. 9166 */ 9167 @Test testSetNetworkScorerThrowsSecurityExceptionOnMissingPermissions()9168 public void testSetNetworkScorerThrowsSecurityExceptionOnMissingPermissions() { 9169 doThrow(new SecurityException()).when(mContext) 9170 .enforceCallingOrSelfPermission( 9171 eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE), 9172 eq("WifiService")); 9173 try { 9174 mWifiServiceImpl.setWifiConnectedNetworkScorer(mAppBinder, mWifiConnectedNetworkScorer); 9175 fail("expected SecurityException"); 9176 } catch (SecurityException expected) { 9177 } 9178 } 9179 9180 /** 9181 * Verify that a call to setWifiConnectedNetworkScorer throws an IllegalArgumentException 9182 * if the parameters are not provided. 9183 */ 9184 @Test testSetScorerThrowsIllegalArgumentExceptionOnInvalidArguments()9185 public void testSetScorerThrowsIllegalArgumentExceptionOnInvalidArguments() { 9186 try { 9187 mWifiServiceImpl.setWifiConnectedNetworkScorer(mAppBinder, null); 9188 fail("expected IllegalArgumentException"); 9189 } catch (IllegalArgumentException expected) { 9190 } 9191 } 9192 9193 /** 9194 * Verify that a call to clearWifiConnectedNetworkScorer throws a SecurityException if 9195 * the caller does not have WIFI_UPDATE_USABILITY_STATS_SCORE permission. 9196 */ 9197 @Test testClearNetworkScorerThrowsSecurityExceptionOnMissingPermissions()9198 public void testClearNetworkScorerThrowsSecurityExceptionOnMissingPermissions() { 9199 doThrow(new SecurityException()).when(mContext) 9200 .enforceCallingOrSelfPermission( 9201 eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE), 9202 eq("WifiService")); 9203 try { 9204 mWifiServiceImpl.clearWifiConnectedNetworkScorer(); 9205 fail("expected SecurityException"); 9206 } catch (SecurityException expected) { 9207 } 9208 } 9209 9210 /** 9211 * Verify that setWifiConnectedNetworkScorer sets scorer to {@link WifiScoreReport}. 9212 */ 9213 @Test testSetWifiConnectedNetworkScorerAndVerify()9214 public void testSetWifiConnectedNetworkScorerAndVerify() throws Exception { 9215 when(mPackageManager.getPackagesForUid(anyInt())) 9216 .thenReturn(new String[]{EXTERNAL_SCORER_PKG_NAME}); 9217 when(mContext.bindServiceAsUser(any(), any(), anyInt(), any())).thenReturn(true); 9218 mLooper.startAutoDispatch(); 9219 9220 mWifiServiceImpl.setWifiConnectedNetworkScorer(mAppBinder, mWifiConnectedNetworkScorer); 9221 mLooper.stopAutoDispatch(); 9222 9223 assertNotNull(mWifiServiceImpl.mScorerServiceConnection); 9224 verify(mActiveModeWarden).setWifiConnectedNetworkScorer( 9225 mAppBinder, mWifiConnectedNetworkScorer, myUid()); 9226 } 9227 9228 /** 9229 * Verify that clearWifiConnectedNetworkScorer clears scorer from {@link WifiScoreReport}. 9230 */ 9231 @Test testClearWifiConnectedNetworkScorerUnbindService()9232 public void testClearWifiConnectedNetworkScorerUnbindService() throws Exception { 9233 when(mPackageManager.getPackagesForUid(anyInt())) 9234 .thenReturn(new String[]{EXTERNAL_SCORER_PKG_NAME}); 9235 when(mContext.bindServiceAsUser(any(), any(), anyInt(), any())).thenReturn(true); 9236 mLooper.startAutoDispatch(); 9237 mWifiServiceImpl.setWifiConnectedNetworkScorer(mAppBinder, mWifiConnectedNetworkScorer); 9238 mLooper.stopAutoDispatch(); 9239 assertNotNull(mWifiServiceImpl.mScorerServiceConnection); 9240 9241 mWifiServiceImpl.clearWifiConnectedNetworkScorer(); 9242 mLooper.dispatchAll(); 9243 9244 verify(mContext).unbindService(any()); 9245 verify(mActiveModeWarden).clearWifiConnectedNetworkScorer(); 9246 } 9247 9248 @Test testClearWifiConnectedNetworkScorerAndVerify()9249 public void testClearWifiConnectedNetworkScorerAndVerify() throws Exception { 9250 mWifiServiceImpl.mScorerServiceConnection = null; 9251 9252 mWifiServiceImpl.clearWifiConnectedNetworkScorer(); 9253 mLooper.dispatchAll(); 9254 9255 verify(mContext, never()).unbindService(any()); 9256 verify(mActiveModeWarden).clearWifiConnectedNetworkScorer(); 9257 } 9258 9259 /** 9260 * Verify that a call to addWifiCustomDhcpOptions throws a SecurityException if 9261 * the caller does not have NETWORK_SETTINGS or OVERRIDE_WIFI_CONFIG permission. 9262 */ 9263 @Test testAddCustomDhcpOptionsThrowsSecurityExceptionOnMissingPermissions()9264 public void testAddCustomDhcpOptionsThrowsSecurityExceptionOnMissingPermissions() { 9265 assumeTrue(SdkLevel.isAtLeastT()); 9266 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_SETTINGS)) 9267 .thenReturn(PackageManager.PERMISSION_DENIED); 9268 when(mContext.checkCallingOrSelfPermission( 9269 android.Manifest.permission.OVERRIDE_WIFI_CONFIG)) 9270 .thenReturn(PackageManager.PERMISSION_DENIED); 9271 try { 9272 mWifiServiceImpl.addCustomDhcpOptions(WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 9273 TEST_OUI, new ParceledListSlice<>(Collections.emptyList())); 9274 fail("expected SecurityException"); 9275 } catch (SecurityException expected) { 9276 } 9277 } 9278 9279 /** 9280 * Verify that a call to removeWifiCustomDhcpOptions throws a SecurityException if 9281 * the caller does not have NETWORK_SETTINGS or OVERRIDE_WIFI_CONFIG permission. 9282 */ 9283 @Test testRemoveCustomDhcpOptionsThrowsSecurityExceptionOnMissingPermissions()9284 public void testRemoveCustomDhcpOptionsThrowsSecurityExceptionOnMissingPermissions() { 9285 assumeTrue(SdkLevel.isAtLeastT()); 9286 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_SETTINGS)) 9287 .thenReturn(PackageManager.PERMISSION_DENIED); 9288 when(mContext.checkCallingOrSelfPermission( 9289 android.Manifest.permission.OVERRIDE_WIFI_CONFIG)) 9290 .thenReturn(PackageManager.PERMISSION_DENIED); 9291 try { 9292 mWifiServiceImpl.removeCustomDhcpOptions(WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 9293 TEST_OUI); 9294 fail("expected SecurityException"); 9295 } catch (SecurityException expected) { 9296 } 9297 } 9298 9299 /** 9300 * Verify that addWifiCustomDhcpOptions adds DHCP option. 9301 */ 9302 @Test testAddCustomDhcpOptionsAndVerify()9303 public void testAddCustomDhcpOptionsAndVerify() throws Exception { 9304 assumeTrue(SdkLevel.isAtLeastT()); 9305 mWifiServiceImpl.addCustomDhcpOptions(WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_OUI, 9306 new ParceledListSlice<>(Collections.emptyList())); 9307 mLooper.dispatchAll(); 9308 verify(mWifiConfigManager).addCustomDhcpOptions( 9309 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_OUI, new ArrayList<DhcpOption>()); 9310 } 9311 9312 /** 9313 * Verify that removeWifiCustomDhcpOptions removes DHCP option. 9314 */ 9315 @Test testRemoveCustomDhcpOptionsAndVerify()9316 public void testRemoveCustomDhcpOptionsAndVerify() throws Exception { 9317 assumeTrue(SdkLevel.isAtLeastT()); 9318 mWifiServiceImpl.removeCustomDhcpOptions(WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 9319 TEST_OUI); 9320 mLooper.dispatchAll(); 9321 verify(mWifiConfigManager).removeCustomDhcpOptions( 9322 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_OUI); 9323 } 9324 9325 @Test supportedFeaturesVerboseLoggingThrottled()9326 public void supportedFeaturesVerboseLoggingThrottled() { 9327 mWifiServiceImpl.enableVerboseLogging( 9328 WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED); // this logs 9329 when(mClock.getElapsedSinceBootMillis()).thenReturn(1000L); 9330 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn( 9331 createCapabilityBitset(WifiManager.WIFI_FEATURE_P2P)); 9332 mWifiServiceImpl.isFeatureSupported(WifiManager.WIFI_FEATURE_P2P); 9333 when(mClock.getElapsedSinceBootMillis()).thenReturn(1001L); 9334 mWifiServiceImpl.isFeatureSupported(WifiManager.WIFI_FEATURE_P2P); // should not log 9335 when(mClock.getElapsedSinceBootMillis()).thenReturn(5000L); 9336 mWifiServiceImpl.isFeatureSupported(WifiManager.WIFI_FEATURE_P2P); 9337 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(createCapabilityBitset( 9338 WifiManager.WIFI_FEATURE_P2P, WifiManager.WIFI_FEATURE_PASSPOINT)); 9339 mWifiServiceImpl.isFeatureSupported(WifiManager.WIFI_FEATURE_P2P); 9340 verify(mLog, times(4)).info(any()); 9341 } 9342 9343 /** 9344 * Verify startRestrictingAutoJoinToSubscriptionId is guarded by NETWORK_SETTINGS 9345 * permission. 9346 */ 9347 @Test testStartTemporarilyDisablingAllNonCarrierMergedWifiPermission()9348 public void testStartTemporarilyDisablingAllNonCarrierMergedWifiPermission() { 9349 assumeTrue(SdkLevel.isAtLeastS()); 9350 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9351 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 9352 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD), 9353 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 9354 try { 9355 mWifiServiceImpl.startRestrictingAutoJoinToSubscriptionId(1); 9356 fail(); 9357 } catch (SecurityException e) { 9358 // pass 9359 } 9360 } 9361 9362 /** 9363 * Verify startRestrictingAutoJoinToSubscriptionId works properly with permission. 9364 */ 9365 @Test testStartTemporarilyDisablingAllNonCarrierMergedWifi()9366 public void testStartTemporarilyDisablingAllNonCarrierMergedWifi() { 9367 assumeTrue(SdkLevel.isAtLeastS()); 9368 List<ClientModeManager> cmmList = new ArrayList<>(); 9369 ConcreteClientModeManager localOnlyCmm = mock(ConcreteClientModeManager.class); 9370 ConcreteClientModeManager secondaryTransientCmm = mock(ConcreteClientModeManager.class); 9371 when(localOnlyCmm.getRole()).thenReturn(ROLE_CLIENT_LOCAL_ONLY); 9372 when(secondaryTransientCmm.getRole()).thenReturn(ROLE_CLIENT_SECONDARY_TRANSIENT); 9373 cmmList.add(mClientModeManager); 9374 cmmList.add(localOnlyCmm); 9375 cmmList.add(secondaryTransientCmm); 9376 when(mActiveModeWarden.getClientModeManagers()).thenReturn(cmmList); 9377 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD), 9378 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 9379 9380 mWifiServiceImpl.startRestrictingAutoJoinToSubscriptionId(1); 9381 mLooper.dispatchAll(); 9382 verify(mWifiConfigManager).startRestrictingAutoJoinToSubscriptionId(1); 9383 verify(mWifiConnectivityManager).clearCachedCandidates(); 9384 verify(localOnlyCmm, never()).disconnect(); 9385 verify(secondaryTransientCmm).disconnect(); 9386 verify(mClientModeManager).disconnect(); 9387 } 9388 9389 /** 9390 * Verify stopRestrictingAutoJoinToSubscriptionId is guarded by NETWORK_SETTINGS 9391 * and NETWORK_SETUP_WIZARD permission. 9392 */ 9393 @Test testStopTemporarilyDisablingAllNonCarrierMergedWifiPermission()9394 public void testStopTemporarilyDisablingAllNonCarrierMergedWifiPermission() { 9395 assumeTrue(SdkLevel.isAtLeastS()); 9396 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9397 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 9398 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD), 9399 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED); 9400 try { 9401 mWifiServiceImpl.stopRestrictingAutoJoinToSubscriptionId(); 9402 fail(); 9403 } catch (SecurityException e) { 9404 // pass 9405 } 9406 } 9407 9408 /** 9409 * Verify stopRestrictingAutoJoinToSubscriptionId works properly with permission. 9410 */ 9411 @Test testStopTemporarilyDisablingAllNonCarrierMergedWifi()9412 public void testStopTemporarilyDisablingAllNonCarrierMergedWifi() { 9413 assumeTrue(SdkLevel.isAtLeastS()); 9414 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9415 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 9416 mWifiServiceImpl.stopRestrictingAutoJoinToSubscriptionId(); 9417 mLooper.dispatchAll(); 9418 verify(mWifiConfigManager).stopRestrictingAutoJoinToSubscriptionId(); 9419 } 9420 9421 @Test(expected = SecurityException.class) testGetCountryCodeThrowsException()9422 public void testGetCountryCodeThrowsException() { 9423 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 9424 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission( 9425 any(), any(), anyInt(), any())).thenReturn(false); 9426 mWifiServiceImpl.getCountryCode(TEST_PACKAGE_NAME, TEST_FEATURE_ID); 9427 } 9428 9429 @Test testGetCountryCode()9430 public void testGetCountryCode() { 9431 // verify get country code with network settings permission. 9432 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 9433 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission( 9434 any(), any(), anyInt(), any())).thenReturn(false); 9435 mWifiServiceImpl.getCountryCode(TEST_PACKAGE_NAME, TEST_FEATURE_ID); 9436 9437 // verify get country code with coarse location permission. 9438 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 9439 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission( 9440 any(), any(), anyInt(), any())).thenReturn(true); 9441 mWifiServiceImpl.getCountryCode(TEST_PACKAGE_NAME, TEST_FEATURE_ID); 9442 } 9443 9444 @Test testSetScanThrottleEnabledWithNetworkSettingsPermission()9445 public void testSetScanThrottleEnabledWithNetworkSettingsPermission() { 9446 doNothing().when(mContext) 9447 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9448 eq("WifiService")); 9449 mWifiServiceImpl.setScanThrottleEnabled(true); 9450 verify(mScanRequestProxy).setScanThrottleEnabled(true); 9451 9452 mWifiServiceImpl.setScanThrottleEnabled(false); 9453 verify(mScanRequestProxy).setScanThrottleEnabled(false); 9454 } 9455 9456 @Test(expected = SecurityException.class) testSetScanThrottleEnabledWithNoNetworkSettingsPermission()9457 public void testSetScanThrottleEnabledWithNoNetworkSettingsPermission() { 9458 doThrow(new SecurityException()).when(mContext) 9459 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9460 eq("WifiService")); 9461 9462 mWifiServiceImpl.setScanThrottleEnabled(true); 9463 verify(mScanRequestProxy, never()).setScanThrottleEnabled(true); 9464 } 9465 9466 @Test testIsScanThrottleEnabled()9467 public void testIsScanThrottleEnabled() { 9468 when(mScanRequestProxy.isScanThrottleEnabled()).thenReturn(true); 9469 assertTrue(mWifiServiceImpl.isScanThrottleEnabled()); 9470 verify(mScanRequestProxy).isScanThrottleEnabled(); 9471 } 9472 9473 @Test testSetAutoWakeupEnabledWithNetworkSettingsPermission()9474 public void testSetAutoWakeupEnabledWithNetworkSettingsPermission() { 9475 doNothing().when(mContext) 9476 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9477 eq("WifiService")); 9478 mWifiServiceImpl.setAutoWakeupEnabled(true); 9479 verify(mWakeupController).setEnabled(true); 9480 9481 mWifiServiceImpl.setAutoWakeupEnabled(false); 9482 verify(mWakeupController).setEnabled(false); 9483 } 9484 9485 @Test(expected = SecurityException.class) testSetAutoWakeupEnabledWithNoNetworkSettingsPermission()9486 public void testSetAutoWakeupEnabledWithNoNetworkSettingsPermission() { 9487 doThrow(new SecurityException()).when(mContext) 9488 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9489 eq("WifiService")); 9490 9491 mWifiServiceImpl.setAutoWakeupEnabled(true); 9492 mLooper.dispatchAll(); 9493 verify(mWakeupController, never()).setEnabled(true); 9494 } 9495 9496 @Test testIsAutoWakeupEnabled()9497 public void testIsAutoWakeupEnabled() { 9498 when(mWakeupController.isEnabled()).thenReturn(true); 9499 assertTrue(mWifiServiceImpl.isAutoWakeupEnabled()); 9500 verify(mWakeupController).isEnabled(); 9501 } 9502 9503 @Test testSetScanAlwaysAvailableWithNetworkSettingsPermission()9504 public void testSetScanAlwaysAvailableWithNetworkSettingsPermission() { 9505 doNothing().when(mContext) 9506 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9507 eq("WifiService")); 9508 mWifiServiceImpl.setScanAlwaysAvailable(true, TEST_PACKAGE_NAME); 9509 verify(mSettingsStore).handleWifiScanAlwaysAvailableToggled(true); 9510 verify(mActiveModeWarden).scanAlwaysModeChanged(); 9511 9512 mWifiServiceImpl.setScanAlwaysAvailable(false, TEST_PACKAGE_NAME); 9513 verify(mSettingsStore).handleWifiScanAlwaysAvailableToggled(false); 9514 verify(mActiveModeWarden, times(2)).scanAlwaysModeChanged(); 9515 } 9516 9517 @Test(expected = SecurityException.class) testSetScanAlwaysAvailableWithNoNetworkSettingsPermission()9518 public void testSetScanAlwaysAvailableWithNoNetworkSettingsPermission() { 9519 doThrow(new SecurityException()).when(mContext) 9520 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9521 eq("WifiService")); 9522 9523 mWifiServiceImpl.setScanAlwaysAvailable(true, TEST_PACKAGE_NAME); 9524 verify(mSettingsStore, never()).handleWifiScanAlwaysAvailableToggled(anyBoolean()); 9525 verify(mActiveModeWarden, never()).scanAlwaysModeChanged(); 9526 } 9527 9528 @Test testIsScanAlwaysAvailable()9529 public void testIsScanAlwaysAvailable() { 9530 when(mSettingsStore.isScanAlwaysAvailableToggleEnabled()).thenReturn(true); 9531 assertTrue(mWifiServiceImpl.isScanAlwaysAvailable()); 9532 verify(mSettingsStore).isScanAlwaysAvailableToggleEnabled(); 9533 } 9534 createScanResultList()9535 private List<ScanResult> createScanResultList() { 9536 return Collections.singletonList(new ScanResult.Builder(WifiSsid.fromUtf8Text(TEST_SSID), 9537 TEST_BSSID) 9538 .setHessid(1245) 9539 .setCaps(TEST_CAP) 9540 .setRssi(-78) 9541 .setFrequency(2450) 9542 .setTsf(1025) 9543 .setDistanceCm(22) 9544 .setDistanceSdCm(33) 9545 .setChannelWidth(20) 9546 .setIs80211McRTTResponder(true) 9547 .build()); 9548 } 9549 sendCountryCodeChangedBroadcast(String countryCode)9550 private void sendCountryCodeChangedBroadcast(String countryCode) { 9551 Intent intent = new Intent(TelephonyManager.ACTION_NETWORK_COUNTRY_CHANGED); 9552 intent.putExtra(TelephonyManager.EXTRA_NETWORK_COUNTRY, countryCode); 9553 assertNotNull(mBroadcastReceiverCaptor.getValue()); 9554 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 9555 } 9556 9557 @Test testCountryCodeBroadcastHanding()9558 public void testCountryCodeBroadcastHanding() { 9559 mWifiServiceImpl.checkAndStartWifi(); 9560 mLooper.dispatchAll(); 9561 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 9562 argThat((IntentFilter filter) -> 9563 filter.hasAction(TelephonyManager.ACTION_NETWORK_COUNTRY_CHANGED)), 9564 isNull(), 9565 any(Handler.class)); 9566 sendCountryCodeChangedBroadcast("US"); 9567 verify(mWifiCountryCode).setTelephonyCountryCodeAndUpdate(any()); 9568 } 9569 9570 @Test testDumpShouldDumpWakeupController()9571 public void testDumpShouldDumpWakeupController() { 9572 mWifiServiceImpl.checkAndStartWifi(); 9573 mLooper.dispatchAll(); 9574 mLooper.startAutoDispatch(); 9575 mWifiServiceImpl.dump(new FileDescriptor(), new PrintWriter(new StringWriter()), null); 9576 mLooper.stopAutoDispatchAndIgnoreExceptions(); 9577 verify(mWakeupController).dump(any(), any(), any()); 9578 verify(mPasspointNetworkNominateHelper).dump(any()); 9579 verify(mResourceCache).dump(any()); 9580 } 9581 9582 /** 9583 * Test register listener without permission. 9584 */ 9585 @Test(expected = SecurityException.class) testAddSuggestionUserApprovalStatusListenerWithMissingPermission()9586 public void testAddSuggestionUserApprovalStatusListenerWithMissingPermission() { 9587 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 9588 eq(ACCESS_WIFI_STATE), eq("WifiService")); 9589 mWifiServiceImpl.addSuggestionUserApprovalStatusListener( 9590 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME); 9591 } 9592 9593 /** 9594 * Test register listener from background user. 9595 */ 9596 @Test(expected = SecurityException.class) testAddSuggestionUserApprovalStatusListenerFromBackgroundUser()9597 public void testAddSuggestionUserApprovalStatusListenerFromBackgroundUser() { 9598 when(mWifiPermissionsUtil.doesUidBelongToCurrentUserOrDeviceOwner(anyInt())) 9599 .thenReturn(false); 9600 mWifiServiceImpl.addSuggestionUserApprovalStatusListener( 9601 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME); 9602 } 9603 9604 /** 9605 * Test unregister listener from background user. 9606 */ 9607 @Test(expected = SecurityException.class) testRemoveSuggestionUserApprovalStatusListenerFromBackgroundUser()9608 public void testRemoveSuggestionUserApprovalStatusListenerFromBackgroundUser() { 9609 when(mWifiPermissionsUtil.doesUidBelongToCurrentUserOrDeviceOwner(anyInt())) 9610 .thenReturn(false); 9611 mWifiServiceImpl.removeSuggestionUserApprovalStatusListener( 9612 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME); 9613 } 9614 9615 /** 9616 * Test register listener without listener 9617 */ 9618 @Test(expected = NullPointerException.class) testAddSuggestionUserApprovalStatusListenerWithIllegalArgument()9619 public void testAddSuggestionUserApprovalStatusListenerWithIllegalArgument() { 9620 mWifiServiceImpl.addSuggestionUserApprovalStatusListener(null, TEST_PACKAGE_NAME); 9621 } 9622 9623 /** 9624 * Test unregister callback without permission. 9625 */ 9626 @Test(expected = SecurityException.class) testUnregisterSuggestionUserApprovalStatusListenerWithMissingPermission()9627 public void testUnregisterSuggestionUserApprovalStatusListenerWithMissingPermission() { 9628 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 9629 eq(ACCESS_WIFI_STATE), eq("WifiService")); 9630 mWifiServiceImpl.removeSuggestionUserApprovalStatusListener( 9631 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME); 9632 } 9633 9634 /** 9635 * Test add and remove listener will go to WifiNetworkSuggestionManager 9636 */ 9637 @Test testAddRemoveSuggestionUserApprovalStatusListener()9638 public void testAddRemoveSuggestionUserApprovalStatusListener() { 9639 mWifiServiceImpl.addSuggestionUserApprovalStatusListener( 9640 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME); 9641 mLooper.dispatchAll(); 9642 verify(mWifiNetworkSuggestionsManager).addSuggestionUserApprovalStatusListener( 9643 eq(mSuggestionUserApprovalStatusListener), eq(TEST_PACKAGE_NAME), anyInt()); 9644 9645 mWifiServiceImpl.removeSuggestionUserApprovalStatusListener( 9646 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME); 9647 mLooper.dispatchAll(); 9648 verify(mWifiNetworkSuggestionsManager).removeSuggestionUserApprovalStatusListener( 9649 eq(mSuggestionUserApprovalStatusListener), eq(TEST_PACKAGE_NAME), anyInt()); 9650 } 9651 9652 @Test testGetDhcpInfo()9653 public void testGetDhcpInfo() throws Exception { 9654 DhcpResultsParcelable dhcpResultsParcelable = new DhcpResultsParcelable(); 9655 dhcpResultsParcelable.leaseDuration = 100; 9656 when(mClientModeManager.syncGetDhcpResultsParcelable()).thenReturn(dhcpResultsParcelable); 9657 9658 mLooper.startAutoDispatch(); 9659 DhcpInfo dhcpInfo = mWifiServiceImpl.getDhcpInfo(TEST_PACKAGE); 9660 mLooper.stopAutoDispatchAndIgnoreExceptions(); 9661 9662 assertEquals(dhcpResultsParcelable.leaseDuration, dhcpInfo.leaseDuration); 9663 } 9664 9665 @Test testGetDhcpInfoFromSecondaryCmmFromAppRequestingSecondaryCmm()9666 public void testGetDhcpInfoFromSecondaryCmmFromAppRequestingSecondaryCmm() throws Exception { 9667 DhcpResultsParcelable dhcpResultsParcelable = new DhcpResultsParcelable(); 9668 dhcpResultsParcelable.leaseDuration = 100; 9669 ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class); 9670 when(secondaryCmm.getRequestorWs()) 9671 .thenReturn(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE)); 9672 when(secondaryCmm.syncGetDhcpResultsParcelable()).thenReturn(dhcpResultsParcelable); 9673 when(mActiveModeWarden.getClientModeManagersInRoles( 9674 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED)) 9675 .thenReturn(Arrays.asList(secondaryCmm)); 9676 9677 mLooper.startAutoDispatch(); 9678 DhcpInfo dhcpInfo = mWifiServiceImpl.getDhcpInfo(TEST_PACKAGE); 9679 mLooper.stopAutoDispatchAndIgnoreExceptions(); 9680 9681 assertEquals(dhcpResultsParcelable.leaseDuration, dhcpInfo.leaseDuration); 9682 } 9683 9684 @Test testGetDhcpInfoFromPrimaryCmmFromAppNotRequestingSecondaryCmm()9685 public void testGetDhcpInfoFromPrimaryCmmFromAppNotRequestingSecondaryCmm() throws Exception { 9686 DhcpResultsParcelable dhcpResultsParcelable = new DhcpResultsParcelable(); 9687 dhcpResultsParcelable.leaseDuration = 100; 9688 when(mClientModeManager.syncGetDhcpResultsParcelable()).thenReturn(dhcpResultsParcelable); 9689 ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class); 9690 when(secondaryCmm.getRequestorWs()) 9691 .thenReturn(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME_OTHER)); 9692 when(mActiveModeWarden.getClientModeManagersInRoles( 9693 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED)) 9694 .thenReturn(Arrays.asList(secondaryCmm)); 9695 9696 mLooper.startAutoDispatch(); 9697 DhcpInfo dhcpInfo = mWifiServiceImpl.getDhcpInfo(TEST_PACKAGE); 9698 mLooper.stopAutoDispatchAndIgnoreExceptions(); 9699 9700 assertEquals(dhcpResultsParcelable.leaseDuration, dhcpInfo.leaseDuration); 9701 } 9702 9703 @Test testSetEmergencyScanRequestInProgress()9704 public void testSetEmergencyScanRequestInProgress() throws Exception { 9705 mWifiServiceImpl.setEmergencyScanRequestInProgress(true); 9706 verify(mActiveModeWarden).setEmergencyScanRequestInProgress(true); 9707 9708 mWifiServiceImpl.setEmergencyScanRequestInProgress(false); 9709 verify(mActiveModeWarden).setEmergencyScanRequestInProgress(false); 9710 } 9711 9712 @Test testSetCarrierNetworkOffloadEnabledWithoutPermissionThrowsException()9713 public void testSetCarrierNetworkOffloadEnabledWithoutPermissionThrowsException() 9714 throws Exception { 9715 try { 9716 mWifiServiceImpl.setCarrierNetworkOffloadEnabled(10, true, true); 9717 fail(); 9718 } catch (SecurityException e) { } 9719 } 9720 9721 @Test testSetCarrierNetworkOffloadEnabled()9722 public void testSetCarrierNetworkOffloadEnabled() throws Exception { 9723 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 9724 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 9725 mWifiServiceImpl.setCarrierNetworkOffloadEnabled(10, true, true); 9726 verify(mWifiCarrierInfoManager).setCarrierNetworkOffloadEnabled(10, true, true); 9727 9728 mWifiServiceImpl.setCarrierNetworkOffloadEnabled(5, false, false); 9729 verify(mWifiCarrierInfoManager).setCarrierNetworkOffloadEnabled(5, false, false); 9730 } 9731 9732 @Test testIsCarrierNetworkOffloadEnabled()9733 public void testIsCarrierNetworkOffloadEnabled() throws Exception { 9734 when(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(10, true)).thenReturn(true); 9735 assertTrue(mWifiServiceImpl.isCarrierNetworkOffloadEnabled(10, true)); 9736 verify(mWifiCarrierInfoManager).isCarrierNetworkOffloadEnabled(10, true); 9737 } 9738 9739 @Test testSetEmergencyScanRequestWithoutPermissionThrowsException()9740 public void testSetEmergencyScanRequestWithoutPermissionThrowsException() throws Exception { 9741 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK)) 9742 .thenReturn(PackageManager.PERMISSION_DENIED); 9743 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 9744 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any()); 9745 try { 9746 mWifiServiceImpl.setEmergencyScanRequestInProgress(true); 9747 fail(); 9748 } catch (SecurityException e) { } 9749 } 9750 9751 @Test testRemoveAppState()9752 public void testRemoveAppState() throws Exception { 9753 mWifiServiceImpl.removeAppState(TEST_UID, TEST_PACKAGE_NAME); 9754 mLooper.dispatchAll(); 9755 9756 verify(mScanRequestProxy).clearScanRequestTimestampsForApp(TEST_PACKAGE_NAME, TEST_UID); 9757 verify(mWifiNetworkSuggestionsManager).removeApp(TEST_PACKAGE_NAME); 9758 verify(mWifiNetworkFactory).removeApp(TEST_PACKAGE_NAME); 9759 verify(mPasspointManager).removePasspointProviderWithPackage(TEST_PACKAGE_NAME); 9760 } 9761 9762 @Test testRemoveAppStateWithoutPermissionThrowsException()9763 public void testRemoveAppStateWithoutPermissionThrowsException() throws Exception { 9764 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 9765 eq(Manifest.permission.NETWORK_SETTINGS), any()); 9766 try { 9767 mWifiServiceImpl.removeAppState(TEST_UID, TEST_PACKAGE_NAME); 9768 fail(); 9769 } catch (SecurityException e) { } 9770 } 9771 9772 @Test testNotificationResetWithLocaleChange()9773 public void testNotificationResetWithLocaleChange() { 9774 mWifiServiceImpl.checkAndStartWifi(); 9775 mLooper.dispatchAll(); 9776 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 9777 argThat((IntentFilter filter) -> 9778 filter.hasAction(Intent.ACTION_LOCALE_CHANGED)), 9779 isNull(), 9780 any(Handler.class)); 9781 verify(mWifiNotificationManager).createNotificationChannels(); 9782 clearInvocations(mWifiNotificationManager); 9783 9784 Intent intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 9785 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 9786 verify(mResourceCache).handleLocaleChange(); 9787 verify(mWifiNotificationManager).createNotificationChannels(); 9788 verify(mWifiNetworkSuggestionsManager).resetNotification(); 9789 verify(mWifiCarrierInfoManager).resetNotification(); 9790 verify(mOpenNetworkNotifier).clearPendingNotification(false); 9791 verify(mWakeupController).resetNotification(); 9792 } 9793 9794 /** 9795 * Verify that a call to setWifiScoringEnabled throws a SecurityException if the caller does 9796 * not have NETWORK_SETTINGS permission. 9797 */ 9798 @Test testSetWifiScoringEnabledThrowsSecurityExceptionOnMissingPermissions()9799 public void testSetWifiScoringEnabledThrowsSecurityExceptionOnMissingPermissions() { 9800 doThrow(new SecurityException()).when(mContext) 9801 .enforceCallingOrSelfPermission( 9802 eq(android.Manifest.permission.NETWORK_SETTINGS), 9803 eq("WifiService")); 9804 try { 9805 mWifiServiceImpl.setWifiScoringEnabled(true); 9806 fail("expected SecurityException"); 9807 } catch (SecurityException expected) { 9808 } 9809 } 9810 9811 /** 9812 * Verify that setWifiScoringEnabled sets the boolean to {@link WifiSettingsStore}. 9813 */ 9814 @Test testSetWifiScoringEnabledGoesToSettingsStore()9815 public void testSetWifiScoringEnabledGoesToSettingsStore() { 9816 when(mSettingsStore.handleWifiScoringEnabled(anyBoolean())).thenReturn(true); 9817 assertTrue(mWifiServiceImpl.setWifiScoringEnabled(true)); 9818 verify(mSettingsStore).handleWifiScoringEnabled(true); 9819 } 9820 9821 @Test testEnabledTdlsWithMacAddress()9822 public void testEnabledTdlsWithMacAddress() { 9823 mWifiServiceImpl.enableTdlsWithMacAddress(TEST_BSSID, true); 9824 mLooper.dispatchAll(); 9825 verify(mClientModeManager).enableTdls(TEST_BSSID, true); 9826 9827 mWifiServiceImpl.enableTdlsWithMacAddress(TEST_BSSID, false); 9828 mLooper.dispatchAll(); 9829 verify(mClientModeManager).enableTdls(TEST_BSSID, false); 9830 verify(mLastCallerInfoManager).put(eq(WifiManager.API_SET_TDLS_ENABLED_WITH_MAC_ADDRESS), 9831 anyInt(), anyInt(), anyInt(), anyString(), eq(false)); 9832 } 9833 9834 @Test testEnabledTdlsWithMacAddressCallback()9835 public void testEnabledTdlsWithMacAddressCallback() throws RemoteException { 9836 IBooleanListener listener = mock(IBooleanListener.class); 9837 InOrder inOrder = inOrder(listener); 9838 9839 when(mClientModeManager.enableTdls(TEST_BSSID, true)).thenReturn(true); 9840 mWifiServiceImpl.enableTdlsWithRemoteMacAddress(TEST_BSSID, true, listener); 9841 mLooper.dispatchAll(); 9842 inOrder.verify(listener).onResult(true); 9843 9844 when(mClientModeManager.enableTdls(TEST_BSSID, false)).thenReturn(false); 9845 mWifiServiceImpl.enableTdlsWithRemoteMacAddress(TEST_BSSID, false, listener); 9846 mLooper.dispatchAll(); 9847 inOrder.verify(listener).onResult(false); 9848 verify(mLastCallerInfoManager) 9849 .put(eq(WifiManager.API_SET_TDLS_ENABLED_WITH_MAC_ADDRESS), 9850 anyInt(), anyInt(), anyInt(), anyString(), eq(false)); 9851 } 9852 9853 @Test testEnabledTdlsWithIpAddressCallback()9854 public void testEnabledTdlsWithIpAddressCallback() throws RemoteException { 9855 IBooleanListener listener = mock(IBooleanListener.class); 9856 InOrder inOrder = inOrder(listener); 9857 9858 when(mClientModeManager.enableTdlsWithRemoteIpAddress(TEST_IP, true)) 9859 .thenReturn(true); 9860 mWifiServiceImpl.enableTdlsWithRemoteIpAddress(TEST_IP, true, listener); 9861 mLooper.dispatchAll(); 9862 inOrder.verify(listener).onResult(true); 9863 9864 when(mClientModeManager.enableTdlsWithRemoteIpAddress(TEST_IP, false)) 9865 .thenReturn(false); 9866 mWifiServiceImpl.enableTdlsWithRemoteIpAddress(TEST_IP, false, listener); 9867 mLooper.dispatchAll(); 9868 inOrder.verify(listener).onResult(false); 9869 verify(mLastCallerInfoManager) 9870 .put(eq(WifiManager.API_SET_TDLS_ENABLED), 9871 anyInt(), anyInt(), anyInt(), anyString(), eq(false)); 9872 } 9873 9874 @Test testIsTdlsOperationCurrentlyAvailable()9875 public void testIsTdlsOperationCurrentlyAvailable() throws RemoteException { 9876 IBooleanListener listener = mock(IBooleanListener.class); 9877 InOrder inOrder = inOrder(listener); 9878 9879 when(mClientModeManager.isTdlsOperationCurrentlyAvailable()).thenReturn(true); 9880 mWifiServiceImpl.isTdlsOperationCurrentlyAvailable(listener); 9881 mLooper.dispatchAll(); 9882 inOrder.verify(listener).onResult(true); 9883 9884 when(mClientModeManager.isTdlsOperationCurrentlyAvailable()).thenReturn(false); 9885 mWifiServiceImpl.isTdlsOperationCurrentlyAvailable(listener); 9886 mLooper.dispatchAll(); 9887 inOrder.verify(listener).onResult(false); 9888 } 9889 9890 @Test testGetMaxSupportedConcurrentTdlsSessions()9891 public void testGetMaxSupportedConcurrentTdlsSessions() throws RemoteException { 9892 assumeTrue(SdkLevel.isAtLeastU()); 9893 IIntegerListener listener = mock(IIntegerListener.class); 9894 9895 when(mClientModeManager.getMaxSupportedConcurrentTdlsSessions()).thenReturn(5); 9896 mWifiServiceImpl.getMaxSupportedConcurrentTdlsSessions(listener); 9897 mLooper.dispatchAll(); 9898 verify(listener).onResult(5); 9899 } 9900 9901 @Test testGetNumberOfEnabledTdlsSessions()9902 public void testGetNumberOfEnabledTdlsSessions() throws RemoteException { 9903 IIntegerListener listener = mock(IIntegerListener.class); 9904 9905 when(mClientModeManager.getNumberOfEnabledTdlsSessions()).thenReturn(3); 9906 mWifiServiceImpl.getNumberOfEnabledTdlsSessions(listener); 9907 mLooper.dispatchAll(); 9908 verify(listener).onResult(3); 9909 } 9910 9911 /** 9912 * Verify that a call to setOverrideCountryCode() throws a SecurityException if the caller does 9913 * not have the MANAGE_WIFI_COUNTRY_CODE permission. 9914 */ 9915 @Test testSetOverrideCountryCodeThrowsSecurityExceptionOnMissingPermissions()9916 public void testSetOverrideCountryCodeThrowsSecurityExceptionOnMissingPermissions() { 9917 assumeTrue(SdkLevel.isAtLeastS()); 9918 doThrow(new SecurityException()).when(mContext) 9919 .enforceCallingOrSelfPermission(eq(MANAGE_WIFI_COUNTRY_CODE), 9920 eq("WifiService")); 9921 try { 9922 mWifiServiceImpl.setOverrideCountryCode(TEST_COUNTRY_CODE); 9923 fail("expected SecurityException"); 9924 } catch (SecurityException expected) { } 9925 } 9926 9927 /** 9928 * Verify the call to setOverrideCountryCode() goes to WifiCountryCode 9929 */ 9930 @Test testSetOverrideCountryCode()9931 public void testSetOverrideCountryCode() throws Exception { 9932 assumeTrue(SdkLevel.isAtLeastS()); 9933 mWifiServiceImpl.setOverrideCountryCode(TEST_COUNTRY_CODE); 9934 mLooper.dispatchAll(); 9935 verify(mWifiCountryCode).setOverrideCountryCode(TEST_COUNTRY_CODE); 9936 } 9937 9938 /** 9939 * Verify that a call to clearOverrideCountryCode() throws a SecurityException if the caller 9940 * does not have the MANAGE_WIFI_COUNTRY_CODE permission. 9941 */ 9942 @Test testClearOverrideCountryCodeThrowsSecurityExceptionOnMissingPermissions()9943 public void testClearOverrideCountryCodeThrowsSecurityExceptionOnMissingPermissions() { 9944 assumeTrue(SdkLevel.isAtLeastS()); 9945 doThrow(new SecurityException()).when(mContext) 9946 .enforceCallingOrSelfPermission(eq(MANAGE_WIFI_COUNTRY_CODE), 9947 eq("WifiService")); 9948 try { 9949 mWifiServiceImpl.clearOverrideCountryCode(); 9950 fail("expected SecurityException"); 9951 } catch (SecurityException expected) { } 9952 } 9953 9954 /** 9955 * Verify the call to clearOverrideCountryCode() goes to WifiCountryCode 9956 */ 9957 @Test testClearOverrideCountryCode()9958 public void testClearOverrideCountryCode() throws Exception { 9959 assumeTrue(SdkLevel.isAtLeastS()); 9960 mWifiServiceImpl.clearOverrideCountryCode(); 9961 mLooper.dispatchAll(); 9962 verify(mWifiCountryCode).clearOverrideCountryCode(); 9963 } 9964 9965 /** 9966 * Verify that a call to setDefaultCountryCode() throws a SecurityException if the caller does 9967 * not have the MANAGE_WIFI_COUNTRY_CODE permission. 9968 */ 9969 @Test testSetDefaultCountryCodeThrowsSecurityExceptionOnMissingPermissions()9970 public void testSetDefaultCountryCodeThrowsSecurityExceptionOnMissingPermissions() { 9971 assumeTrue(SdkLevel.isAtLeastS()); 9972 doThrow(new SecurityException()).when(mContext) 9973 .enforceCallingOrSelfPermission(eq(MANAGE_WIFI_COUNTRY_CODE), 9974 eq("WifiService")); 9975 try { 9976 mWifiServiceImpl.setDefaultCountryCode(TEST_COUNTRY_CODE); 9977 fail("expected SecurityException"); 9978 } catch (SecurityException expected) { } 9979 } 9980 9981 /** 9982 * Verify the call to setDefaultCountryCode() goes to WifiCountryCode 9983 */ 9984 @Test testSetDefaultCountryCode()9985 public void testSetDefaultCountryCode() throws Exception { 9986 assumeTrue(SdkLevel.isAtLeastS()); 9987 mWifiServiceImpl.setDefaultCountryCode(TEST_COUNTRY_CODE); 9988 mLooper.dispatchAll(); 9989 verify(mWifiCountryCode).setDefaultCountryCode(TEST_COUNTRY_CODE); 9990 } 9991 9992 /** 9993 * Verify that a call to flushPasspointAnqpCache throws a SecurityException if the 9994 * caller does not have any permission. 9995 */ 9996 @Test (expected = SecurityException.class) testFlushPasspointAnqpCacheThrowsSecurityExceptionOnMissingPermissions()9997 public void testFlushPasspointAnqpCacheThrowsSecurityExceptionOnMissingPermissions() { 9998 when(mContext.checkCallingOrSelfPermission(anyString())) 9999 .thenReturn(PackageManager.PERMISSION_DENIED); 10000 when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), anyString())).thenReturn(false); 10001 when(mWifiPermissionsUtil.isProfileOwner(anyInt(), anyString())).thenReturn(false); 10002 10003 mWifiServiceImpl.flushPasspointAnqpCache(mContext.getPackageName()); 10004 } 10005 10006 /** 10007 * Verifies that the call to testFlushPasspointAnqpCache with DO permission calls Passpoint 10008 * manager to flush the ANQP cache and clear all pending requests. 10009 */ 10010 @Test testFlushPasspointAnqpCacheWithDoPermissions()10011 public void testFlushPasspointAnqpCacheWithDoPermissions() { 10012 when(mContext.checkCallingOrSelfPermission(anyString())) 10013 .thenReturn(PackageManager.PERMISSION_DENIED); 10014 10015 when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), eq(TEST_PACKAGE_NAME))).thenReturn(true); 10016 when(mWifiPermissionsUtil.isProfileOwner(anyInt(), 10017 eq(TEST_PACKAGE_NAME))).thenReturn(false); 10018 mWifiServiceImpl.flushPasspointAnqpCache(TEST_PACKAGE_NAME); 10019 mLooper.dispatchAll(); 10020 verify(mPasspointManager).clearAnqpRequestsAndFlushCache(); 10021 } 10022 10023 /** 10024 * Verifies that the call to testFlushPasspointAnqpCache with PO permission calls Passpoint 10025 * manager to flush the ANQP cache and clear all pending requests. 10026 */ 10027 @Test testFlushPasspointAnqpCacheWithPoPermissions()10028 public void testFlushPasspointAnqpCacheWithPoPermissions() { 10029 when(mContext.checkCallingOrSelfPermission(anyString())) 10030 .thenReturn(PackageManager.PERMISSION_DENIED); 10031 10032 when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), eq(TEST_PACKAGE_NAME))).thenReturn(false); 10033 when(mWifiPermissionsUtil.isProfileOwner(anyInt(), eq(TEST_PACKAGE_NAME))).thenReturn(true); 10034 mWifiServiceImpl.flushPasspointAnqpCache(TEST_PACKAGE_NAME); 10035 mLooper.dispatchAll(); 10036 verify(mPasspointManager).clearAnqpRequestsAndFlushCache(); 10037 } 10038 10039 /** 10040 * Verifies that the call to testFlushPasspointAnqpCache calls Passpoint manager to flush the 10041 * ANQP cache and clear all pending requests. 10042 */ 10043 @Test testFlushPasspointAnqpCache()10044 public void testFlushPasspointAnqpCache() { 10045 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_SETTINGS)) 10046 .thenReturn(PackageManager.PERMISSION_GRANTED); 10047 when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), eq(TEST_PACKAGE_NAME))).thenReturn(false); 10048 when(mWifiPermissionsUtil.isProfileOwner(anyInt(), 10049 eq(TEST_PACKAGE_NAME))).thenReturn(false); 10050 mWifiServiceImpl.flushPasspointAnqpCache(TEST_PACKAGE_NAME); 10051 mLooper.dispatchAll(); 10052 verify(mPasspointManager).clearAnqpRequestsAndFlushCache(); 10053 } 10054 10055 /** 10056 * Verify that a call to getUsableChannels() throws a SecurityException if the caller does 10057 * not have the LOCATION_HARDWARE permission. 10058 */ 10059 @Test testGetUsableChannelsThrowsSecurityExceptionOnMissingPermissions()10060 public void testGetUsableChannelsThrowsSecurityExceptionOnMissingPermissions() { 10061 assumeTrue(SdkLevel.isAtLeastS()); 10062 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 10063 doThrow(new SecurityException()).when(mWifiPermissionsUtil) 10064 .checkCallersHardwareLocationPermission(anyInt()); 10065 try { 10066 mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, FILTER_REGULATORY, 10067 TEST_PACKAGE_NAME, mExtras); 10068 fail("expected SecurityException"); 10069 } catch (SecurityException expected) { } 10070 } 10071 10072 @Test testGetUsableChannelsThrowsSecurityExceptionOnMissingPermissionsAfterU()10073 public void testGetUsableChannelsThrowsSecurityExceptionOnMissingPermissionsAfterU() { 10074 assumeTrue(SdkLevel.isAtLeastU()); 10075 10076 // verify app targeting prior to Android U can call API with location permission 10077 when(mWifiPermissionsUtil.isTargetSdkLessThan(any(), 10078 eq(Build.VERSION_CODES.UPSIDE_DOWN_CAKE), 10079 anyInt())).thenReturn(true); 10080 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 10081 when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt())) 10082 .thenReturn(true); 10083 10084 mLooper.startAutoDispatch(); 10085 mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, FILTER_REGULATORY, 10086 TEST_PACKAGE_NAME, mExtras); 10087 10088 // Verify app targeting prior to Android U fails to call API without location permission 10089 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(false); 10090 assertThrows(SecurityException.class, 10091 () -> mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, 10092 FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)); 10093 10094 // Verify app targeting Android U no longer need location. 10095 when(mWifiPermissionsUtil.isTargetSdkLessThan(any(), 10096 eq(Build.VERSION_CODES.UPSIDE_DOWN_CAKE), 10097 anyInt())).thenReturn(false); 10098 mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, FILTER_REGULATORY, 10099 TEST_PACKAGE_NAME, mExtras); 10100 10101 // Verify app targeting Android U will fail without nearby permission 10102 doThrow(new SecurityException()) 10103 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission( 10104 any(), anyBoolean(), any()); 10105 assertThrows(SecurityException.class, 10106 () -> mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, 10107 FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)); 10108 mLooper.stopAutoDispatch(); 10109 } 10110 10111 /** 10112 * Verify the call to isValidBandForGetUsableChannels() 10113 */ 10114 @Test testIsValidBandForGetUsableChannels()10115 public void testIsValidBandForGetUsableChannels() throws Exception { 10116 assumeTrue(SdkLevel.isAtLeastS()); 10117 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10118 WifiScanner.WIFI_BAND_UNSPECIFIED), true); 10119 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10120 WifiScanner.WIFI_BAND_24_GHZ), true); 10121 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10122 WifiScanner.WIFI_BAND_5_GHZ), false); 10123 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10124 WifiScanner.WIFI_BAND_BOTH), false); 10125 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10126 WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY), false); 10127 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10128 WifiScanner.WIFI_BAND_24_GHZ_WITH_5GHZ_DFS), false); 10129 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10130 WifiScanner.WIFI_BAND_5_GHZ_WITH_DFS), true); 10131 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10132 WifiScanner.WIFI_BAND_BOTH_WITH_DFS), true); 10133 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10134 WifiScanner.WIFI_BAND_6_GHZ), true); 10135 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10136 WifiScanner.WIFI_BAND_24_5_6_GHZ), false); 10137 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10138 WifiScanner.WIFI_BAND_24_5_WITH_DFS_6_GHZ), true); 10139 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10140 WifiScanner.WIFI_BAND_60_GHZ), true); 10141 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10142 WifiScanner.WIFI_BAND_24_5_6_60_GHZ), false); 10143 assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels( 10144 WifiScanner.WIFI_BAND_24_5_WITH_DFS_6_60_GHZ), true); 10145 } 10146 10147 /** 10148 * Verify that a call to getUsableChannels() throws an IllegalArgumentException 10149 * if the band specified is invalid for getAllowedChannels() method. 10150 */ 10151 @Test testGetUsableChannelsThrowsIllegalArgumentExceptionOnInValidBand()10152 public void testGetUsableChannelsThrowsIllegalArgumentExceptionOnInValidBand() { 10153 assumeTrue(SdkLevel.isAtLeastS()); 10154 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 10155 when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt())) 10156 .thenReturn(true); 10157 try { 10158 mWifiServiceImpl.getUsableChannels(WIFI_BAND_5_GHZ, OP_MODE_STA, FILTER_REGULATORY, 10159 TEST_PACKAGE_NAME, mExtras); 10160 fail("expected IllegalArgumentException"); 10161 } catch (IllegalArgumentException expected) { 10162 } 10163 } 10164 10165 /** 10166 * Verify the call to getUsableChannels() goes to WifiNative 10167 */ 10168 @Test testGetUsableChannels()10169 public void testGetUsableChannels() throws Exception { 10170 assumeTrue(SdkLevel.isAtLeastS()); 10171 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 10172 when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt())) 10173 .thenReturn(true); 10174 mLooper.startAutoDispatch(); 10175 mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, FILTER_REGULATORY, 10176 TEST_PACKAGE_NAME, mExtras); 10177 mLooper.stopAutoDispatch(); 10178 verify(mWifiNative).getUsableChannels(anyInt(), anyInt(), anyInt()); 10179 } 10180 10181 /** 10182 * Verify the call to getUsableChannels() goes to cached SoftAp capabilities 10183 */ 10184 @Test testGetUsableChannelsUsesStoredSoftApChannelsWhenDriverIsntUp()10185 public void testGetUsableChannelsUsesStoredSoftApChannelsWhenDriverIsntUp() throws Exception { 10186 mWifiServiceImpl.handleBootCompleted(); 10187 mLooper.dispatchAll(); 10188 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 10189 when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt())) 10190 .thenReturn(true); 10191 when(mWifiNative.isHalSupported()).thenReturn(true); 10192 when(mWifiNative.isHalStarted()).thenReturn(false); 10193 setup5GhzSupported(); 10194 setup6GhzSupported(); 10195 setup60GhzSupported(); 10196 when(mWifiCountryCode.getCountryCode()).thenReturn(TEST_COUNTRY_CODE); 10197 10198 // No values stored 10199 mLooper.startAutoDispatch(); 10200 assertThat(mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_SAP, 10201 FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)).isEmpty(); 10202 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10203 10204 // Country code doesn't match 10205 when(mWifiSettingsConfigStore.get(WifiSettingsConfigStore.WIFI_SOFT_AP_COUNTRY_CODE)) 10206 .thenReturn(TEST_COUNTRY_CODE); 10207 when(mWifiSettingsConfigStore.get(WifiSettingsConfigStore.WIFI_AVAILABLE_SOFT_AP_FREQS_MHZ)) 10208 .thenReturn("[2452,5180,5955,58320]"); 10209 when(mWifiCountryCode.getCountryCode()).thenReturn(TEST_NEW_COUNTRY_CODE); 10210 mLooper.startAutoDispatch(); 10211 assertThat(mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_SAP, 10212 FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)).isEmpty(); 10213 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10214 10215 // Matching country code 10216 when(mWifiCountryCode.getCountryCode()).thenReturn(TEST_COUNTRY_CODE); 10217 10218 mLooper.startAutoDispatch(); 10219 assertThat(mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_5_WITH_DFS_6_60_GHZ, OP_MODE_SAP, 10220 FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)).containsExactly( 10221 new WifiAvailableChannel(2452, WifiAvailableChannel.OP_MODE_SAP, 10222 ScanResult.CHANNEL_WIDTH_20MHZ), 10223 new WifiAvailableChannel(5180, WifiAvailableChannel.OP_MODE_SAP, 10224 ScanResult.CHANNEL_WIDTH_20MHZ), 10225 new WifiAvailableChannel(5955, WifiAvailableChannel.OP_MODE_SAP, 10226 ScanResult.CHANNEL_WIDTH_20MHZ), 10227 new WifiAvailableChannel(58320, WifiAvailableChannel.OP_MODE_SAP, 10228 ScanResult.CHANNEL_WIDTH_20MHZ)); 10229 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10230 } 10231 10232 /** 10233 * Verify that driver country code updates store the new available Soft AP channels. 10234 */ 10235 @Test testDriverCountryCodeChangedStoresAvailableSoftApChannels()10236 public void testDriverCountryCodeChangedStoresAvailableSoftApChannels() throws Exception { 10237 setup5GhzSupported(); 10238 setup24GhzSupported(); 10239 setup6GhzSupported(); 10240 setup60GhzSupported(); 10241 mWifiServiceImpl.handleBootCompleted(); 10242 mLooper.dispatchAll(); 10243 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true); 10244 when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt())) 10245 .thenReturn(true); 10246 when(mWifiNative.isHalSupported()).thenReturn(true); 10247 when(mWifiNative.isHalStarted()).thenReturn(true); 10248 when(mWifiNative.getUsableChannels(eq(WIFI_BAND_24_GHZ), anyInt(), anyInt())) 10249 .thenReturn(Arrays.asList( 10250 new WifiAvailableChannel(2452, WifiAvailableChannel.OP_MODE_SAP, 10251 ScanResult.CHANNEL_WIDTH_20MHZ))); 10252 when(mWifiNative.getUsableChannels(eq(WIFI_BAND_5_GHZ), anyInt(), anyInt())) 10253 .thenReturn(Arrays.asList( 10254 new WifiAvailableChannel(5180, WifiAvailableChannel.OP_MODE_SAP, 10255 ScanResult.CHANNEL_WIDTH_20MHZ))); 10256 when(mWifiNative.getUsableChannels(eq(WIFI_BAND_6_GHZ), anyInt(), anyInt())) 10257 .thenReturn(Arrays.asList( 10258 new WifiAvailableChannel(5955, WifiAvailableChannel.OP_MODE_SAP, 10259 ScanResult.CHANNEL_WIDTH_20MHZ))); 10260 when(mWifiNative.getUsableChannels(eq(WIFI_BAND_60_GHZ), anyInt(), anyInt())) 10261 .thenReturn(null); 10262 mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_COUNTRY_CODE); 10263 mLooper.dispatchAll(); 10264 verify(mWifiSettingsConfigStore).put( 10265 eq(WifiSettingsConfigStore.WIFI_SOFT_AP_COUNTRY_CODE), eq(TEST_COUNTRY_CODE)); 10266 verify(mWifiSettingsConfigStore).put( 10267 eq(WifiSettingsConfigStore.WIFI_AVAILABLE_SOFT_AP_FREQS_MHZ), 10268 eq("[2452,5180,5955]")); 10269 10270 // Make sure CC change to world mode won't update WIFI_SOFT_AP_COUNTRY_CODE 10271 when(mWifiSettingsConfigStore.get(WifiSettingsConfigStore.WIFI_SOFT_AP_COUNTRY_CODE)) 10272 .thenReturn(TEST_COUNTRY_CODE); 10273 when(mWifiCountryCode.isDriverCountryCodeWorldMode()).thenReturn(true); 10274 String testWorldModeCountryCode = "00"; 10275 mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(testWorldModeCountryCode); 10276 mLooper.dispatchAll(); 10277 verify(mWifiSettingsConfigStore, never()).put( 10278 eq(WifiSettingsConfigStore.WIFI_SOFT_AP_COUNTRY_CODE), 10279 eq(testWorldModeCountryCode)); 10280 } 10281 setupMultiTypeConfigs( BitSet featureFlags, boolean saeAutoUpgradeEnabled, boolean oweAutoUpgradeEnabled)10282 private List<WifiConfiguration> setupMultiTypeConfigs( 10283 BitSet featureFlags, boolean saeAutoUpgradeEnabled, boolean oweAutoUpgradeEnabled) { 10284 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(featureFlags); 10285 when(mWifiGlobals.isWpa3SaeUpgradeEnabled()).thenReturn(saeAutoUpgradeEnabled); 10286 when(mWifiGlobals.isOweUpgradeEnabled()).thenReturn(oweAutoUpgradeEnabled); 10287 10288 List<WifiConfiguration> multiTypeConfigs = new ArrayList<>(); 10289 multiTypeConfigs.add(WifiConfigurationTestUtil.createOpenOweNetwork()); 10290 multiTypeConfigs.add(WifiConfigurationTestUtil.createPskSaeNetwork()); 10291 multiTypeConfigs.add(WifiConfigurationTestUtil.createWpa2Wpa3EnterpriseNetwork()); 10292 return multiTypeConfigs; 10293 } 10294 isSecurityParamsSupported(SecurityParams params, long wifiFeatures)10295 private boolean isSecurityParamsSupported(SecurityParams params, long wifiFeatures) { 10296 switch (params.getSecurityType()) { 10297 case WifiConfiguration.SECURITY_TYPE_SAE: 10298 return 0 != (wifiFeatures & WifiManager.WIFI_FEATURE_WPA3_SAE); 10299 case WifiConfiguration.SECURITY_TYPE_OWE: 10300 return 0 != (wifiFeatures & WifiManager.WIFI_FEATURE_OWE); 10301 } 10302 return true; 10303 } 10304 generateExpectedConfigs( List<WifiConfiguration> testConfigs, boolean saeAutoUpgradeEnabled, boolean oweAutoUpgradeEnabled)10305 private List<WifiConfiguration> generateExpectedConfigs( 10306 List<WifiConfiguration> testConfigs, 10307 boolean saeAutoUpgradeEnabled, boolean oweAutoUpgradeEnabled) { 10308 if (!SdkLevel.isAtLeastS()) { 10309 return testConfigs; 10310 } 10311 WifiConfiguration tmpConfig; 10312 List<WifiConfiguration> expectedConfigs = new ArrayList<>(); 10313 tmpConfig = new WifiConfiguration(testConfigs.get(0)); 10314 tmpConfig.setSecurityParams( 10315 SecurityParams.createSecurityParamsBySecurityType( 10316 WifiConfiguration.SECURITY_TYPE_OPEN)); 10317 expectedConfigs.add(tmpConfig); 10318 if (oweAutoUpgradeEnabled) { 10319 tmpConfig = new WifiConfiguration(testConfigs.get(0)); 10320 tmpConfig.setSecurityParams( 10321 SecurityParams.createSecurityParamsBySecurityType( 10322 WifiConfiguration.SECURITY_TYPE_OWE)); 10323 expectedConfigs.add(tmpConfig); 10324 } 10325 tmpConfig = new WifiConfiguration(testConfigs.get(1)); 10326 tmpConfig.setSecurityParams( 10327 SecurityParams.createSecurityParamsBySecurityType( 10328 WifiConfiguration.SECURITY_TYPE_PSK)); 10329 expectedConfigs.add(tmpConfig); 10330 if (saeAutoUpgradeEnabled) { 10331 tmpConfig = new WifiConfiguration(testConfigs.get(1)); 10332 tmpConfig.setSecurityParams( 10333 SecurityParams.createSecurityParamsBySecurityType( 10334 WifiConfiguration.SECURITY_TYPE_SAE)); 10335 expectedConfigs.add(tmpConfig); 10336 } 10337 tmpConfig = new WifiConfiguration(testConfigs.get(2)); 10338 tmpConfig.setSecurityParams( 10339 SecurityParams.createSecurityParamsBySecurityType( 10340 WifiConfiguration.SECURITY_TYPE_EAP)); 10341 expectedConfigs.add(tmpConfig); 10342 tmpConfig = new WifiConfiguration(testConfigs.get(2)); 10343 tmpConfig.setSecurityParams( 10344 SecurityParams.createSecurityParamsBySecurityType( 10345 WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE)); 10346 expectedConfigs.add(tmpConfig); 10347 return expectedConfigs; 10348 } 10349 10350 /** 10351 * verify multi-type configs are converted to legacy configs in getConfiguredNetworks 10352 * and getPrivilegedConfiguredNetworks when auto-upgrade is enabled. 10353 */ 10354 @Test testGetConfiguredNetworksForMultiTypeConfigs()10355 public void testGetConfiguredNetworksForMultiTypeConfigs() { 10356 BitSet featureFlags = createCapabilityBitset( 10357 WifiManager.WIFI_FEATURE_WPA3_SAE, WifiManager.WIFI_FEATURE_OWE); 10358 List<WifiConfiguration> testConfigs = setupMultiTypeConfigs( 10359 featureFlags, true, true); 10360 when(mWifiConfigManager.getSavedNetworks(anyInt())) 10361 .thenReturn(testConfigs); 10362 when(mWifiConfigManager.getConfiguredNetworksWithPasswords()) 10363 .thenReturn(testConfigs); 10364 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 10365 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 10366 10367 mLooper.startAutoDispatch(); 10368 ParceledListSlice<WifiConfiguration> configs = 10369 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false); 10370 ParceledListSlice<WifiConfiguration> privilegedConfigs = 10371 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, 10372 mExtras); 10373 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10374 10375 List<WifiConfiguration> expectedConfigs = generateExpectedConfigs( 10376 testConfigs, true, true); 10377 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 10378 expectedConfigs, configs.getList()); 10379 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 10380 expectedConfigs, privilegedConfigs.getList()); 10381 } 10382 10383 /** 10384 * verify multi-type configs are converted to legacy configs in getConfiguredNetworks 10385 * and getPrivilegedConfiguredNetworks when auto-upgrade is not enabled. 10386 */ 10387 @Test testGetConfiguredNetworksForMultiTypeConfigsWithoutAutoUpgradeEnabled()10388 public void testGetConfiguredNetworksForMultiTypeConfigsWithoutAutoUpgradeEnabled() { 10389 BitSet featureFlags = createCapabilityBitset( 10390 WifiManager.WIFI_FEATURE_WPA3_SAE, WifiManager.WIFI_FEATURE_OWE); 10391 List<WifiConfiguration> testConfigs = setupMultiTypeConfigs( 10392 featureFlags, false, false); 10393 when(mWifiConfigManager.getSavedNetworks(anyInt())) 10394 .thenReturn(testConfigs); 10395 when(mWifiConfigManager.getConfiguredNetworksWithPasswords()) 10396 .thenReturn(testConfigs); 10397 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 10398 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 10399 10400 mLooper.startAutoDispatch(); 10401 ParceledListSlice<WifiConfiguration> configs = 10402 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false); 10403 ParceledListSlice<WifiConfiguration> privilegedConfigs = 10404 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, 10405 mExtras); 10406 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10407 10408 List<WifiConfiguration> expectedConfigs = generateExpectedConfigs( 10409 testConfigs, false, false); 10410 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 10411 expectedConfigs, configs.getList()); 10412 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 10413 expectedConfigs, privilegedConfigs.getList()); 10414 } 10415 10416 /** 10417 * verify multi-type configs are converted to legacy configs in getConfiguredNetworks 10418 * and getPrivilegedConfiguredNetworks when security types are not supported. 10419 */ 10420 @Test testGetConfiguredNetworksForMultiTypeConfigsWithoutHwSupport()10421 public void testGetConfiguredNetworksForMultiTypeConfigsWithoutHwSupport() { 10422 BitSet featureFlags = new BitSet(); 10423 List<WifiConfiguration> testConfigs = setupMultiTypeConfigs( 10424 featureFlags, true, true); 10425 when(mWifiConfigManager.getSavedNetworks(anyInt())) 10426 .thenReturn(testConfigs); 10427 when(mWifiConfigManager.getConfiguredNetworksWithPasswords()) 10428 .thenReturn(testConfigs); 10429 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 10430 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 10431 10432 mLooper.startAutoDispatch(); 10433 ParceledListSlice<WifiConfiguration> configs = 10434 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false); 10435 ParceledListSlice<WifiConfiguration> privilegedConfigs = 10436 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, 10437 mExtras); 10438 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10439 10440 List<WifiConfiguration> expectedConfigs = generateExpectedConfigs( 10441 testConfigs, true, true); 10442 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 10443 expectedConfigs, configs.getList()); 10444 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 10445 expectedConfigs, privilegedConfigs.getList()); 10446 } 10447 trySetTargetSdkToT()10448 private void trySetTargetSdkToT() { 10449 if (SdkLevel.isAtLeastT()) { 10450 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 10451 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false); 10452 } 10453 } 10454 10455 @Test (expected = SecurityException.class) testGetPrivilegedConnectedNetworkNoPermission()10456 public void testGetPrivilegedConnectedNetworkNoPermission() { 10457 trySetTargetSdkToT(); 10458 if (SdkLevel.isAtLeastT()) { 10459 doThrow(new SecurityException()) 10460 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission( 10461 any(), anyBoolean(), any()); 10462 } else { 10463 doThrow(new SecurityException()).when(mWifiPermissionsUtil) 10464 .enforceCanAccessScanResults(any(), any(), anyInt(), any()); 10465 } 10466 10467 mWifiServiceImpl.getPrivilegedConnectedNetwork(TEST_PACKAGE_NAME, TEST_FEATURE_ID, mExtras); 10468 mLooper.dispatchAll(); 10469 } 10470 10471 @Test testGetPrivilegedConnectedNetworkNotConnected()10472 public void testGetPrivilegedConnectedNetworkNotConnected() { 10473 trySetTargetSdkToT(); 10474 when(mActiveModeWarden.getConnectionInfo()).thenReturn(new WifiInfo()); 10475 10476 mLooper.startAutoDispatch(); 10477 assertNull(mWifiServiceImpl.getPrivilegedConnectedNetwork( 10478 TEST_PACKAGE_NAME, TEST_FEATURE_ID, mExtras)); 10479 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10480 10481 if (SdkLevel.isAtLeastT()) { 10482 verify(mWifiPermissionsUtil).enforceNearbyDevicesPermission(any(), eq(true), any()); 10483 } else { 10484 verify(mWifiPermissionsUtil).enforceCanAccessScanResults(any(), any(), anyInt(), any()); 10485 } 10486 } 10487 10488 @Test testGetPrivilegedConnectedNetworkSuccess()10489 public void testGetPrivilegedConnectedNetworkSuccess() { 10490 // mock testConfig as the currently connected network 10491 trySetTargetSdkToT(); 10492 WifiConfiguration testConfig = WifiConfigurationTestUtil.createPskSaeNetwork(); 10493 testConfig.networkId = TEST_NETWORK_ID; 10494 testConfig.setRandomizedMacAddress(TEST_FACTORY_MAC_ADDR); 10495 WifiInfo wifiInfo = new WifiInfo(); 10496 wifiInfo.setNetworkId(testConfig.networkId); 10497 when(mActiveModeWarden.getConnectionInfo()).thenReturn(wifiInfo); 10498 when(mWifiConfigManager.getConfiguredNetworkWithPassword(testConfig.networkId)).thenReturn( 10499 testConfig); 10500 10501 mLooper.startAutoDispatch(); 10502 WifiConfiguration result = mWifiServiceImpl.getPrivilegedConnectedNetwork( 10503 TEST_PACKAGE_NAME, TEST_FEATURE_ID, mExtras); 10504 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10505 10506 if (SdkLevel.isAtLeastT()) { 10507 verify(mWifiPermissionsUtil).enforceNearbyDevicesPermission(any(), eq(true), any()); 10508 } else { 10509 verify(mWifiPermissionsUtil).enforceCanAccessScanResults(any(), any(), anyInt(), any()); 10510 } 10511 verify(mWifiConfigManager).getConfiguredNetworkWithPassword(testConfig.networkId); 10512 // verify the credentials match 10513 assertEquals(testConfig.networkId, result.networkId); 10514 assertEquals(testConfig.SSID, result.SSID); 10515 assertEquals(testConfig.preSharedKey, result.preSharedKey); 10516 // verify the randomized MAC address is filtered out 10517 assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, result.getRandomizedMacAddress().toString()); 10518 } 10519 10520 /** 10521 * Verify that a call to isWifiPasspointEnabled throws a SecurityException if the 10522 * caller does not have the ACCESS_WIFI_STATE permission. 10523 */ 10524 @Test (expected = SecurityException.class) testIsWifiPasspointEnabledWithoutPermissions()10525 public void testIsWifiPasspointEnabledWithoutPermissions() { 10526 doThrow(new SecurityException()).when(mContext) 10527 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), 10528 eq("WifiService")); 10529 10530 mWifiServiceImpl.isWifiPasspointEnabled(); 10531 } 10532 10533 /** 10534 * Verify that the call to setWifiPasspointEnabled is not redirected to 10535 * specific API when the caller doesn't have 10536 * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD. 10537 */ 10538 @Test(expected = SecurityException.class) testSetWifiPasspointEnabledWithoutPermissions()10539 public void testSetWifiPasspointEnabledWithoutPermissions() { 10540 mLooper.startAutoDispatch(); 10541 mWifiServiceImpl.setWifiPasspointEnabled(false); 10542 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10543 } 10544 10545 /** 10546 * Verify that the call to setWifiPasspointEnabled is redirected to 10547 * specific API when the caller have 10548 * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD. 10549 */ 10550 @Test testSetWifiPasspointEnabledWithPermissions()10551 public void testSetWifiPasspointEnabledWithPermissions() { 10552 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 10553 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 10554 mLooper.startAutoDispatch(); 10555 mWifiServiceImpl.setWifiPasspointEnabled(false); 10556 mLooper.dispatchAll(); 10557 mLooper.stopAutoDispatchAndIgnoreExceptions(); 10558 verify(mPasspointManager).setWifiPasspointEnabled(false); 10559 } 10560 10561 @Test(expected = SecurityException.class) testSetScreenOnScanSchedule_NoPermission()10562 public void testSetScreenOnScanSchedule_NoPermission() { 10563 assumeTrue(SdkLevel.isAtLeastT()); 10564 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 10565 .thenReturn(false); 10566 mWifiServiceImpl.setScreenOnScanSchedule(null, null); 10567 } 10568 10569 @Test(expected = IllegalArgumentException.class) testSetScreenOnScanSchedule_BadInput1()10570 public void testSetScreenOnScanSchedule_BadInput1() { 10571 assumeTrue(SdkLevel.isAtLeastT()); 10572 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 10573 .thenReturn(true); 10574 // test that both arrays need to be null or non-null. Never one null one non-null. 10575 mWifiServiceImpl.setScreenOnScanSchedule(null, new int[] {1}); 10576 } 10577 10578 @Test(expected = IllegalArgumentException.class) testSetScreenOnScanSchedule_BadInput2()10579 public void testSetScreenOnScanSchedule_BadInput2() { 10580 assumeTrue(SdkLevel.isAtLeastT()); 10581 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 10582 .thenReturn(true); 10583 // test that the input should not be empty arrays. 10584 mWifiServiceImpl.setScreenOnScanSchedule(new int[0], new int[0]); 10585 } 10586 10587 @Test testSetScreenOnScanSchedule_Success()10588 public void testSetScreenOnScanSchedule_Success() { 10589 assumeTrue(SdkLevel.isAtLeastT()); 10590 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 10591 .thenReturn(true); 10592 int[] expectedSchedule = new int[] {20, 40, 80}; 10593 int[] expectedType = new int[] {2, 2, 1}; 10594 mWifiServiceImpl.setScreenOnScanSchedule(expectedSchedule, expectedType); 10595 mLooper.dispatchAll(); 10596 verify(mWifiConnectivityManager).setExternalScreenOnScanSchedule( 10597 expectedSchedule, expectedType); 10598 verify(mLastCallerInfoManager).put(eq(WifiManager.API_SET_SCAN_SCHEDULE), anyInt(), 10599 anyInt(), anyInt(), any(), eq(true)); 10600 10601 mWifiServiceImpl.setScreenOnScanSchedule(null, null); 10602 mLooper.dispatchAll(); 10603 verify(mWifiConnectivityManager).setExternalScreenOnScanSchedule(null, null); 10604 verify(mLastCallerInfoManager).put(eq(WifiManager.API_SET_SCAN_SCHEDULE), anyInt(), 10605 anyInt(), anyInt(), any(), eq(false)); 10606 } 10607 10608 @Test testSetOneShotScreenOnConnectivityScanDelayMillis()10609 public void testSetOneShotScreenOnConnectivityScanDelayMillis() { 10610 assumeTrue(SdkLevel.isAtLeastT()); 10611 int delayMs = 1234; 10612 10613 // verify permission checks 10614 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 10615 .thenReturn(false); 10616 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())) 10617 .thenReturn(false); 10618 assertThrows(SecurityException.class, 10619 () -> mWifiServiceImpl.setOneShotScreenOnConnectivityScanDelayMillis(delayMs)); 10620 10621 // verify correct input 10622 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 10623 .thenReturn(true); 10624 assertThrows(IllegalArgumentException.class, 10625 () -> mWifiServiceImpl.setOneShotScreenOnConnectivityScanDelayMillis(-1)); 10626 10627 // verify correct call 10628 mWifiServiceImpl.setOneShotScreenOnConnectivityScanDelayMillis(delayMs); 10629 mLooper.dispatchAll(); 10630 verify(mWifiConnectivityManager).setOneShotScreenOnConnectivityScanDelayMillis(delayMs); 10631 } 10632 10633 @Test(expected = SecurityException.class) testSetExternalPnoScanRequest_NoPermission()10634 public void testSetExternalPnoScanRequest_NoPermission() { 10635 assumeTrue(SdkLevel.isAtLeastT()); 10636 IPnoScanResultsCallback callback = mock(IPnoScanResultsCallback.class); 10637 List<WifiSsid> ssids = new ArrayList<>(); 10638 ssids.add(WifiSsid.fromString("\"TEST_SSID_1\"")); 10639 int[] frequencies = new int[] {TEST_AP_FREQUENCY}; 10640 10641 mWifiServiceImpl.setExternalPnoScanRequest(mAppBinder, callback, ssids, frequencies, 10642 TEST_PACKAGE_NAME, TEST_FEATURE_ID); 10643 } 10644 10645 @Test testSetExternalPnoScanRequest_Success()10646 public void testSetExternalPnoScanRequest_Success() throws Exception { 10647 assumeTrue(SdkLevel.isAtLeastT()); 10648 when(mWifiGlobals.isBackgroundScanSupported()).thenReturn(true); 10649 when(mActiveModeWarden.getSupportedFeatureSet()) 10650 .thenReturn(createCapabilityBitset(WifiManager.WIFI_FEATURE_PNO)); 10651 when(mWifiPermissionsUtil.checkRequestCompanionProfileAutomotiveProjectionPermission( 10652 anyInt())).thenReturn(true); 10653 when(mWifiPermissionsUtil.checkCallersLocationPermissionInManifest( 10654 anyInt(), anyBoolean())).thenReturn(true); 10655 IPnoScanResultsCallback callback = mock(IPnoScanResultsCallback.class); 10656 List<WifiSsid> ssids = new ArrayList<>(); 10657 ssids.add(WifiSsid.fromString("\"TEST_SSID_1\"")); 10658 int[] frequencies = new int[] {TEST_AP_FREQUENCY}; 10659 10660 mWifiServiceImpl.setExternalPnoScanRequest(mAppBinder, callback, ssids, frequencies, 10661 TEST_PACKAGE_NAME, TEST_FEATURE_ID); 10662 mLooper.dispatchAll(); 10663 verify(mWifiConnectivityManager).setExternalPnoScanRequest(anyInt(), any(), any(), 10664 eq(callback), eq(ssids), eq(frequencies)); 10665 } 10666 10667 @Test testSetExternalPnoScanRequest_PnoNotSupported()10668 public void testSetExternalPnoScanRequest_PnoNotSupported() throws Exception { 10669 assumeTrue(SdkLevel.isAtLeastT()); 10670 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(new BitSet()); 10671 when(mWifiPermissionsUtil.checkRequestCompanionProfileAutomotiveProjectionPermission( 10672 anyInt())).thenReturn(true); 10673 when(mWifiPermissionsUtil.checkCallersLocationPermissionInManifest( 10674 anyInt(), anyBoolean())).thenReturn(true); 10675 IPnoScanResultsCallback callback = mock(IPnoScanResultsCallback.class); 10676 List<WifiSsid> ssids = new ArrayList<>(); 10677 ssids.add(WifiSsid.fromString("\"TEST_SSID_1\"")); 10678 int[] frequencies = new int[] {TEST_AP_FREQUENCY}; 10679 10680 mWifiServiceImpl.setExternalPnoScanRequest(mAppBinder, callback, ssids, frequencies, 10681 TEST_PACKAGE_NAME, TEST_FEATURE_ID); 10682 mLooper.dispatchAll(); 10683 verify(callback).onRegisterFailed(WifiManager.PnoScanResultsCallback 10684 .REGISTER_PNO_CALLBACK_PNO_NOT_SUPPORTED); 10685 } 10686 10687 @Test testClearExternalPnoScanRequest()10688 public void testClearExternalPnoScanRequest() { 10689 assumeTrue(SdkLevel.isAtLeastT()); 10690 10691 mWifiServiceImpl.clearExternalPnoScanRequest(); 10692 mLooper.dispatchAll(); 10693 verify(mWifiConnectivityManager).clearExternalPnoScanRequest(anyInt()); 10694 } 10695 10696 @Test testGetLastCallerInfoForApi_Exceptions()10697 public void testGetLastCallerInfoForApi_Exceptions() { 10698 // good inputs should result in no exceptions. 10699 ILastCallerListener listener = mock(ILastCallerListener.class); 10700 // null listener ==> IllegalArgumentException 10701 assertThrows(IllegalArgumentException.class, 10702 () -> mWifiServiceImpl.getLastCallerInfoForApi( 10703 WifiManager.API_WIFI_ENABLED, null)); 10704 10705 // invalid ApiType ==> IllegalArgumentException 10706 assertThrows(IllegalArgumentException.class, 10707 () -> mWifiServiceImpl.getLastCallerInfoForApi(WifiManager.API_MAX + 1, listener)); 10708 10709 // No permission ==> SecurityException 10710 assertThrows(SecurityException.class, 10711 () -> mWifiServiceImpl.getLastCallerInfoForApi( 10712 WifiManager.API_WIFI_ENABLED, listener)); 10713 } 10714 10715 @Test testGetLastCallerInfoForApi_GoodCase()10716 public void testGetLastCallerInfoForApi_GoodCase() throws RemoteException { 10717 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 10718 ILastCallerListener listener = mock(ILastCallerListener.class); 10719 LastCallerInfoManager.LastCallerInfo expected = 10720 new LastCallerInfoManager.LastCallerInfo(0, 1, 2, TEST_PACKAGE_NAME, true); 10721 when(mLastCallerInfoManager.get(WifiManager.API_WIFI_ENABLED)).thenReturn(expected); 10722 10723 InOrder inOrder = inOrder(listener); 10724 mWifiServiceImpl.getLastCallerInfoForApi(WifiManager.API_WIFI_ENABLED, listener); 10725 mLooper.dispatchAll(); 10726 inOrder.verify(listener).onResult(TEST_PACKAGE_NAME, true); 10727 10728 // Verify null is returned as packageName if there's no information about this ApiType. 10729 mWifiServiceImpl.getLastCallerInfoForApi(WifiManager.API_SOFT_AP, listener); 10730 mLooper.dispatchAll(); 10731 inOrder.verify(listener).onResult(null, false); 10732 } 10733 10734 /** 10735 * Verify that a call to registerDriverCountryCodeChangedListener throws a SecurityException 10736 * if the caller doesnot have ACCESS_COARSE_LOCATION permission. 10737 */ 10738 @Test(expected = SecurityException.class) registerDriverCountryCodeChangedListenerThrowsSecurityExceptionWithoutPermission()10739 public void registerDriverCountryCodeChangedListenerThrowsSecurityExceptionWithoutPermission() { 10740 assumeTrue(SdkLevel.isAtLeastT()); 10741 doThrow(new SecurityException()) 10742 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(), eq(true)); 10743 mWifiServiceImpl.registerDriverCountryCodeChangedListener( 10744 mIOnWifiDriverCountryCodeChangedListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 10745 } 10746 10747 /** 10748 * Verify that a call registerDriverCountryCodeChangedListener throws an 10749 * IllegalArgumentException if the parameters are not provided. 10750 */ 10751 @Test registerDriverCountryCodeChangedListenerThrowsIllegalArgumentException()10752 public void registerDriverCountryCodeChangedListenerThrowsIllegalArgumentException() { 10753 assumeTrue(SdkLevel.isAtLeastT()); 10754 try { 10755 mWifiServiceImpl.registerDriverCountryCodeChangedListener( 10756 null, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 10757 fail("expected IllegalArgumentException"); 10758 } catch (IllegalArgumentException expected) { 10759 } 10760 } 10761 10762 /** 10763 * Verifies that we handle driver country code changed listener registration failure if we 10764 * encounter an exception while linking to death. 10765 */ 10766 @Test registerDriverCountryCodeChangedListenerFailureOnLinkToDeath()10767 public void registerDriverCountryCodeChangedListenerFailureOnLinkToDeath() throws Exception { 10768 assumeTrue(SdkLevel.isAtLeastT()); 10769 doThrow(new RemoteException()) 10770 .when(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt()); 10771 mWifiServiceImpl.registerDriverCountryCodeChangedListener( 10772 mIOnWifiDriverCountryCodeChangedListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 10773 mLooper.dispatchAll(); 10774 verify(mIOnWifiDriverCountryCodeChangedListener, never()) 10775 .onDriverCountryCodeChanged(anyString()); 10776 } 10777 10778 /** 10779 * Verify that a call to registerDriverCountryCodeChangedListener succeeded. 10780 */ verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener( IOnWifiDriverCountryCodeChangedListener listener)10781 private void verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener( 10782 IOnWifiDriverCountryCodeChangedListener listener) 10783 throws Exception { 10784 doNothing() 10785 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(), 10786 eq(true)); 10787 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(eq(TEST_PACKAGE_NAME), 10788 eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(true); 10789 when(mWifiCountryCode.getCurrentDriverCountryCode()).thenReturn(TEST_COUNTRY_CODE); 10790 mWifiServiceImpl.registerDriverCountryCodeChangedListener( 10791 listener, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 10792 mLooper.dispatchAll(); 10793 verify(listener) 10794 .onDriverCountryCodeChanged(TEST_COUNTRY_CODE); 10795 } 10796 10797 /** 10798 * Verify that a call to registerDriverCountryCodeChangedListener succeeded but we don't nofiy 10799 * listener because permission gets denied in OpNote. 10800 */ 10801 @Test verifyRegisterDriverCountryCodeChangedListenerSucceededButNoNotifyListener()10802 public void verifyRegisterDriverCountryCodeChangedListenerSucceededButNoNotifyListener() 10803 throws Exception { 10804 assumeTrue(SdkLevel.isAtLeastT()); 10805 doNothing() 10806 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(), 10807 eq(true)); 10808 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(eq(TEST_PACKAGE_NAME), 10809 eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(false); 10810 when(mWifiCountryCode.getCurrentDriverCountryCode()).thenReturn(TEST_COUNTRY_CODE); 10811 mWifiServiceImpl.registerDriverCountryCodeChangedListener( 10812 mIOnWifiDriverCountryCodeChangedListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 10813 mLooper.dispatchAll(); 10814 verify(mIOnWifiDriverCountryCodeChangedListener, never()) 10815 .onDriverCountryCodeChanged(TEST_COUNTRY_CODE); 10816 } 10817 10818 /** 10819 * Verify that DriverCountryCodeChanged will be dropped if register permission was removed. 10820 */ 10821 @Test testDriverCountryCodeChangedDropWhenRegisterPermissionRemoved()10822 public void testDriverCountryCodeChangedDropWhenRegisterPermissionRemoved() throws Exception { 10823 assumeTrue(SdkLevel.isAtLeastT()); 10824 doNothing() 10825 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(), 10826 eq(true)); 10827 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission( 10828 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(true); 10829 verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener( 10830 mIOnWifiDriverCountryCodeChangedListener); 10831 mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE); 10832 mLooper.dispatchAll(); 10833 verify(mIOnWifiDriverCountryCodeChangedListener) 10834 .onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE); 10835 // remove permission 10836 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission( 10837 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(false); 10838 reset(mIOnWifiDriverCountryCodeChangedListener); 10839 mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_COUNTRY_CODE); 10840 mLooper.dispatchAll(); 10841 verify(mIOnWifiDriverCountryCodeChangedListener, never()) 10842 .onDriverCountryCodeChanged(TEST_COUNTRY_CODE); 10843 } 10844 10845 /** 10846 * Verify that unregisterDriverCountryCodeChangedListener removes listener from registered 10847 * listener list 10848 */ 10849 @Test unregisterDriverCountryCodeChangedListenerRemovesListener()10850 public void unregisterDriverCountryCodeChangedListenerRemovesListener() throws Exception { 10851 assumeTrue(SdkLevel.isAtLeastT()); 10852 doNothing() 10853 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(), 10854 eq(true)); 10855 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission( 10856 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(true); 10857 verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener( 10858 mIOnWifiDriverCountryCodeChangedListener); 10859 mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE); 10860 mLooper.dispatchAll(); 10861 verify(mIOnWifiDriverCountryCodeChangedListener) 10862 .onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE); 10863 mWifiServiceImpl.unregisterDriverCountryCodeChangedListener( 10864 mIOnWifiDriverCountryCodeChangedListener); 10865 mLooper.dispatchAll(); 10866 reset(mIOnWifiDriverCountryCodeChangedListener); 10867 mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_COUNTRY_CODE); 10868 mLooper.dispatchAll(); 10869 verify(mIOnWifiDriverCountryCodeChangedListener, never()) 10870 .onDriverCountryCodeChanged(anyString()); 10871 } 10872 10873 10874 /** 10875 * Verify that onFailed is called when enabling Lohs with non-supported configuration. 10876 */ 10877 @Test testFailureCallbacksTriggeredWhenSoftApFailsBecauseNonSupportedConfiguration()10878 public void testFailureCallbacksTriggeredWhenSoftApFailsBecauseNonSupportedConfiguration() 10879 throws Exception { 10880 when(mResourceCache.getBoolean(R.bool.config_wifiSoftap6ghzSupported)).thenReturn(false); 10881 setupForCustomLohs(); 10882 SoftApConfiguration lohsConfig = createValidSoftApConfiguration(); 10883 SoftApConfiguration customizedConfig = new SoftApConfiguration.Builder(lohsConfig) 10884 .setBand(SoftApConfiguration.BAND_6GHZ) 10885 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE) 10886 .build(); 10887 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 10888 any(), any(), any(), eq(true))).thenReturn(customizedConfig); 10889 // Expect the result is registered but it should get failure because non-supported 10890 // configuration 10891 int result = mWifiServiceImpl.startLocalOnlyHotspot(mLohsCallback, TEST_PACKAGE_NAME, 10892 TEST_FEATURE_ID, customizedConfig, mExtras, true); 10893 assertEquals(LocalOnlyHotspotCallback.REQUEST_REGISTERED, result); 10894 mLooper.dispatchAll(); 10895 verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC); 10896 } 10897 /** 10898 * Registers a soft AP callback, then verifies that the current soft AP state and num clients 10899 * are sent to caller immediately after callback is registered. 10900 */ registerLohsSoftApCallbackAndVerify(ISoftApCallback callback, Bundle bundle)10901 private void registerLohsSoftApCallbackAndVerify(ISoftApCallback callback, Bundle bundle) 10902 throws Exception { 10903 mWifiServiceImpl.registerLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, bundle); 10904 mLooper.dispatchAll(); 10905 10906 ArgumentCaptor<SoftApState> softApStateCaptor = 10907 ArgumentCaptor.forClass(SoftApState.class); 10908 verify(mClientSoftApCallback).onStateChanged(softApStateCaptor.capture()); 10909 assertThat(softApStateCaptor.getValue().getState()).isEqualTo(WIFI_AP_STATE_DISABLED); 10910 try { 10911 softApStateCaptor.getValue().getFailureReason(); 10912 fail("getFailureReason should throw if not in failure state"); 10913 } catch (IllegalStateException e) { 10914 // Pass. 10915 } 10916 assertThat(softApStateCaptor.getValue().getFailureReasonInternal()).isEqualTo(0); 10917 verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged( 10918 new HashMap<String, SoftApInfo>(), 10919 new HashMap<String, List<WifiClient>>(), false, true); 10920 verify(mClientSoftApCallback).onCapabilityChanged( 10921 ApConfigUtil.updateCapabilityFromResource(mContext)); 10922 // Don't need to invoke callback when register. 10923 verify(mClientSoftApCallback, never()).onBlockedClientConnecting(any(), anyInt()); 10924 } 10925 10926 /** 10927 * Verify that unregisterLocalOnlyHotspotSoftApCallback removes callback from registered 10928 * callbacks list. 10929 */ 10930 @Test unregisterLohsSoftApCallbackRemovesCallback()10931 public void unregisterLohsSoftApCallbackRemovesCallback() throws Exception { 10932 assumeTrue(SdkLevel.isAtLeastT()); 10933 AttributionSource attributionSource = mock(AttributionSource.class); 10934 mExtras.putParcelable(WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 10935 registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras); 10936 10937 mWifiServiceImpl.unregisterLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, mExtras); 10938 mLooper.dispatchAll(); 10939 10940 reset(mClientSoftApCallback); 10941 mLohsApCallback.onConnectedClientsOrInfoChanged( 10942 mTestSoftApInfos, mTestSoftApClients, false); 10943 mLooper.dispatchAll(); 10944 verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged( 10945 any(), any(), anyBoolean(), anyBoolean()); 10946 } 10947 10948 /** 10949 * Verify that unregisterLocalOnlyHotspotSoftApCallback is no-op if callback not registered. 10950 */ 10951 @Test unregisterLohsSoftApCallbackDoesNotRemoveCallbackIfCallbackNotMatching()10952 public void unregisterLohsSoftApCallbackDoesNotRemoveCallbackIfCallbackNotMatching() 10953 throws Exception { 10954 assumeTrue(SdkLevel.isAtLeastT()); 10955 AttributionSource attributionSource = mock(AttributionSource.class); 10956 mExtras.putParcelable(WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 10957 registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras); 10958 10959 mWifiServiceImpl.unregisterLocalOnlyHotspotSoftApCallback(mAnotherSoftApCallback, mExtras); 10960 mLooper.dispatchAll(); 10961 mLohsApCallback.onConnectedClientsOrInfoChanged( 10962 mTestSoftApInfos, mTestSoftApClients, false); 10963 mLooper.dispatchAll(); 10964 verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged( 10965 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(false)); 10966 } 10967 10968 /** 10969 * Registers two lohs callbacks, remove one then verify the right callback is being called 10970 * on events. 10971 */ 10972 @Test correctLohsCallbackIsCalledAfterAddingTwoCallbacksAndRemovingOne()10973 public void correctLohsCallbackIsCalledAfterAddingTwoCallbacksAndRemovingOne() 10974 throws Exception { 10975 assumeTrue(SdkLevel.isAtLeastT()); 10976 WifiClient testWifiClient = new WifiClient(MacAddress.fromString("22:33:44:55:66:77"), 10977 WIFI_IFACE_NAME2); 10978 AttributionSource attributionSource = mock(AttributionSource.class); 10979 mExtras.putParcelable(WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 10980 registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras); 10981 mLooper.dispatchAll(); 10982 10983 reset(mClientSoftApCallback); 10984 when(mClientSoftApCallback.asBinder()).thenReturn(mAppBinder); 10985 // Change state from default before registering the second callback 10986 SoftApState state = new SoftApState(WIFI_AP_STATE_ENABLED, 0, 10987 TEST_TETHERING_REQUEST, TEST_IFACE_NAME); 10988 mLohsApCallback.onStateChanged(state); 10989 mLohsApCallback.onConnectedClientsOrInfoChanged( 10990 mTestSoftApInfos, mTestSoftApClients, false); 10991 mLohsApCallback.onBlockedClientConnecting(testWifiClient, 0); 10992 10993 10994 // Register another callback and verify the new state is returned in the immediate callback 10995 mWifiServiceImpl.registerLocalOnlyHotspotSoftApCallback(mAnotherSoftApCallback, mExtras); 10996 mLooper.dispatchAll(); 10997 verify(mAnotherSoftApCallback).onStateChanged(eq(state)); 10998 verify(mAnotherSoftApCallback).onConnectedClientsOrInfoChanged( 10999 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(true)); 11000 // Verify only first callback will receive onBlockedClientConnecting since it call after 11001 // first callback register but before another callback register. 11002 verify(mClientSoftApCallback).onBlockedClientConnecting(testWifiClient, 0); 11003 verify(mAnotherSoftApCallback, never()).onBlockedClientConnecting(testWifiClient, 0); 11004 11005 // unregister the fisrt callback 11006 mWifiServiceImpl.unregisterLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, mExtras); 11007 mLooper.dispatchAll(); 11008 11009 // Update soft AP state and verify the remaining callback receives the event 11010 state = new SoftApState( 11011 WIFI_AP_STATE_FAILED, SAP_START_FAILURE_NO_CHANNEL, 11012 TEST_TETHERING_REQUEST, TEST_IFACE_NAME); 11013 mLohsApCallback.onStateChanged(state); 11014 mLooper.dispatchAll(); 11015 verify(mClientSoftApCallback, never()).onStateChanged(eq(state)); 11016 verify(mAnotherSoftApCallback).onStateChanged(eq(state)); 11017 } 11018 11019 /** 11020 * Verify that wifi service registers for lohs callers BinderDeath event 11021 */ 11022 @Test registersForBinderDeathOnRegisterLohsSoftApCallback()11023 public void registersForBinderDeathOnRegisterLohsSoftApCallback() throws Exception { 11024 assumeTrue(SdkLevel.isAtLeastT()); 11025 AttributionSource attributionSource = mock(AttributionSource.class); 11026 mExtras.putParcelable(WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11027 registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras); 11028 verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt()); 11029 } 11030 11031 /** 11032 * Verify that we un-register the lohs soft AP callback on receiving BinderDied event. 11033 */ 11034 @Test unregistersLohsSoftApCallbackOnBinderDied()11035 public void unregistersLohsSoftApCallbackOnBinderDied() throws Exception { 11036 assumeTrue(SdkLevel.isAtLeastT()); 11037 ArgumentCaptor<IBinder.DeathRecipient> drCaptor = 11038 ArgumentCaptor.forClass(IBinder.DeathRecipient.class); 11039 AttributionSource attributionSource = mock(AttributionSource.class); 11040 mExtras.putParcelable(WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11041 registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras); 11042 verify(mAppBinder).linkToDeath(drCaptor.capture(), anyInt()); 11043 11044 drCaptor.getValue().binderDied(); 11045 mLooper.dispatchAll(); 11046 reset(mClientSoftApCallback); 11047 // Verify callback is removed from the list as well 11048 Map<String, List<WifiClient>> mTestSoftApClients = mock(Map.class); 11049 Map<String, SoftApInfo> mTestSoftApInfos = mock(Map.class); 11050 mLohsApCallback.onConnectedClientsOrInfoChanged( 11051 mTestSoftApInfos, mTestSoftApClients, false); 11052 mLooper.dispatchAll(); 11053 verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged( 11054 any(), any(), anyBoolean(), anyBoolean()); 11055 } 11056 11057 /** 11058 * Verify that a call to registerLocalOnlyHotspotSoftApCallback throws a SecurityException 11059 * if the caller target Android T or later and does not have nearby devices permission. 11060 */ 11061 @Test(expected = SecurityException.class) testRegisterLocalOnlyHotspotSoftApCallbackThrowsExceptionWithoutPermissionOnT()11062 public void testRegisterLocalOnlyHotspotSoftApCallbackThrowsExceptionWithoutPermissionOnT() { 11063 assumeTrue(SdkLevel.isAtLeastT()); 11064 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 11065 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false); 11066 doThrow(new SecurityException()) 11067 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission( 11068 any(), anyBoolean(), any()); 11069 mWifiServiceImpl.registerLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, mExtras); 11070 } 11071 11072 /** 11073 * Verify that a call to unregisterLocalOnlyHotspotSoftApCallback throws a SecurityException 11074 * if the caller targets Android T or later and does not have nearby devices permission. 11075 */ 11076 @Test(expected = SecurityException.class) testUnregisterLocalOnlyHotspotSoftApCallbackThrowsExceptionWithoutPermissionOnT()11077 public void testUnregisterLocalOnlyHotspotSoftApCallbackThrowsExceptionWithoutPermissionOnT() { 11078 assumeTrue(SdkLevel.isAtLeastT()); 11079 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 11080 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false); 11081 doThrow(new SecurityException()) 11082 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission( 11083 any(), anyBoolean(), any()); 11084 mWifiServiceImpl.unregisterLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, mExtras); 11085 } 11086 11087 /** 11088 * Verifies that a LOHS SoftApCallback is ignored if its AttributionSource no longer has the 11089 * NEARBY_WIFI_DEVICES permission 11090 */ 11091 @Test testRegisterLocalOnlyHotspotSoftApCallbackIgnoredWhenPermissionRevoked()11092 public void testRegisterLocalOnlyHotspotSoftApCallbackIgnoredWhenPermissionRevoked() 11093 throws Exception { 11094 assumeTrue(SdkLevel.isAtLeastT()); 11095 AttributionSource attributionSource = mock(AttributionSource.class); 11096 mExtras.putParcelable(WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11097 registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras); 11098 11099 // Revoke NEARBY_WIFI_DEVICES permission 11100 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 11101 .thenReturn(false); 11102 11103 // Callback should be ignored 11104 reset(mClientSoftApCallback); 11105 mLohsApCallback.onConnectedClientsOrInfoChanged( 11106 mTestSoftApInfos, mTestSoftApClients, false); 11107 mLooper.dispatchAll(); 11108 verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged( 11109 any(), any(), anyBoolean(), anyBoolean()); 11110 } 11111 11112 /** 11113 * Verify getStaConcurrencyForMultiInternetMode 11114 */ 11115 @Test testGetStaConcurrencyForMultiInternetMode()11116 public void testGetStaConcurrencyForMultiInternetMode() throws Exception { 11117 assumeTrue(SdkLevel.isAtLeastT()); 11118 when(mMultiInternetManager.getStaConcurrencyForMultiInternetMode()).thenReturn( 11119 WifiManager.WIFI_MULTI_INTERNET_MODE_DBS_AP); 11120 mLooper.startAutoDispatch(); 11121 final int mode = mWifiServiceImpl.getStaConcurrencyForMultiInternetMode(); 11122 verify(mMultiInternetManager).getStaConcurrencyForMultiInternetMode(); 11123 assertEquals(WifiManager.WIFI_MULTI_INTERNET_MODE_DBS_AP, mode); 11124 } 11125 11126 /** 11127 * Verify that a call to setStaConcurrencyForMultiInternetMode throws a SecurityException 11128 * if the caller target Android T or later and does not have network settings permission. 11129 */ 11130 @Test(expected = SecurityException.class) testSetStaConcurrencyForMultiInternetModeThrowsExceptionWithoutPermissionOnT()11131 public void testSetStaConcurrencyForMultiInternetModeThrowsExceptionWithoutPermissionOnT() { 11132 assumeTrue(SdkLevel.isAtLeastT()); 11133 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 11134 when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false); 11135 doThrow(new SecurityException()).when(mContext) 11136 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11137 eq("WifiService")); 11138 mLooper.startAutoDispatch(); 11139 mWifiServiceImpl.setStaConcurrencyForMultiInternetMode( 11140 WifiManager.WIFI_MULTI_INTERNET_MODE_DBS_AP); 11141 } 11142 11143 /** 11144 * Verify setStaConcurrencyForMultiInternetMode 11145 */ 11146 @Test testSetStaConcurrencyForMultiInternetMode()11147 public void testSetStaConcurrencyForMultiInternetMode() throws Exception { 11148 assumeTrue(SdkLevel.isAtLeastT()); 11149 when(mMultiInternetManager.setStaConcurrencyForMultiInternetMode(anyInt())) 11150 .thenReturn(true); 11151 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11152 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11153 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD), 11154 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11155 mLooper.startAutoDispatch(); 11156 assertTrue(mWifiServiceImpl.setStaConcurrencyForMultiInternetMode( 11157 WifiManager.WIFI_MULTI_INTERNET_MODE_MULTI_AP)); 11158 verify(mMultiInternetManager).setStaConcurrencyForMultiInternetMode( 11159 WifiManager.WIFI_MULTI_INTERNET_MODE_MULTI_AP); 11160 } 11161 11162 /** 11163 * Verify attribution is passed in correctly by WifiManager#addOrUpdateNetwork. 11164 */ 11165 @Test testAddOrUpdateNetworkAttribution_InvalidAttributions()11166 public void testAddOrUpdateNetworkAttribution_InvalidAttributions() { 11167 assumeTrue(SdkLevel.isAtLeastS()); 11168 AttributionSource attributionSource = mock(AttributionSource.class); 11169 when(attributionSource.checkCallingUid()).thenReturn(true); 11170 when(attributionSource.isTrusted(any(Context.class))).thenReturn(true); 11171 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11172 mWifiServiceImpl = spy(mWifiServiceImpl); 11173 lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID); 11174 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 11175 assertThrows(SecurityException.class, () -> { 11176 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, null); 11177 }); 11178 11179 assertThrows(SecurityException.class, () -> { 11180 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, new Bundle()); 11181 }); 11182 11183 assertThrows(SecurityException.class, () -> { 11184 Bundle nullEntry = new Bundle(); 11185 nullEntry.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, null); 11186 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, nullEntry); 11187 }); 11188 11189 assertThrows(SecurityException.class, () -> { 11190 Bundle incorrectEntry = new Bundle(); 11191 incorrectEntry.putInt(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, 10); 11192 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, incorrectEntry); 11193 }); 11194 11195 when(attributionSource.checkCallingUid()).thenReturn(false); 11196 assertThrows(SecurityException.class, () -> { 11197 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution); 11198 }); 11199 when(attributionSource.checkCallingUid()).thenReturn(true); // restore 11200 11201 // single first attributions should not fail - even if (theoretically, doesn't happen in 11202 // practice) are not trusted. I.e. this call checks that this method isn't called. 11203 AttributionSource freshAs = mock(AttributionSource.class); 11204 Bundle freshAttribution = new Bundle(); 11205 freshAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, freshAs); 11206 when(freshAs.checkCallingUid()).thenReturn(true); 11207 when(freshAs.isTrusted(any(Context.class))).thenReturn(false); 11208 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, freshAttribution); 11209 verify(freshAs, never()).isTrusted(any()); 11210 11211 AttributionSource originalCaller = mock(AttributionSource.class); 11212 when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID); 11213 when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER); 11214 when(originalCaller.isTrusted(any(Context.class))).thenReturn(false); 11215 when(attributionSource.getNext()).thenReturn(originalCaller); 11216 assertThrows(SecurityException.class, () -> { 11217 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution); 11218 }); 11219 } 11220 11221 /** 11222 * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's no chain. 11223 */ 11224 @Test testAddOrUpdateNetworkAttribution_CorrectParsingNoChainSystemServer()11225 public void testAddOrUpdateNetworkAttribution_CorrectParsingNoChainSystemServer() { 11226 assumeTrue(SdkLevel.isAtLeastS()); 11227 AttributionSource attributionSource = mock(AttributionSource.class); 11228 when(attributionSource.checkCallingUid()).thenReturn(true); 11229 when(attributionSource.isTrusted(any(Context.class))).thenReturn(true); 11230 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11231 mWifiServiceImpl = spy(mWifiServiceImpl); 11232 lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID); 11233 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11234 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11235 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false))) 11236 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 11237 when(attributionSource.getUid()).thenReturn(Process.SYSTEM_UID); 11238 when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME); 11239 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 11240 config.networkId = 1; 11241 11242 mLooper.startAutoDispatch(); 11243 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution); 11244 mLooper.stopAutoDispatch(); 11245 verify(mWifiConfigManager).addOrUpdateNetwork(config, Process.SYSTEM_UID, 11246 TEST_PACKAGE_NAME, false); 11247 verify(mLastCallerInfoManager).put(eq(WifiManager.API_UPDATE_NETWORK), anyInt(), 11248 anyInt(), anyInt(), anyString(), eq(true)); 11249 } 11250 11251 /** 11252 * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's no chain. 11253 */ 11254 @Test testAddOrUpdateNetworkAttribution_CorrectParsingNoChainNonSystemServer()11255 public void testAddOrUpdateNetworkAttribution_CorrectParsingNoChainNonSystemServer() { 11256 assumeTrue(SdkLevel.isAtLeastS()); 11257 mWifiServiceImpl = spy(mWifiServiceImpl); 11258 lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID); 11259 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11260 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11261 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false))) 11262 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 11263 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 11264 11265 mLooper.startAutoDispatch(); 11266 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, null); 11267 mLooper.stopAutoDispatch(); 11268 verify(mWifiConfigManager).addOrUpdateNetwork(config, TEST_UID, TEST_PACKAGE_NAME, false); 11269 } 11270 11271 /** 11272 * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's a chain. 11273 */ 11274 @Test testAddOrUpdateNetworkAttribution_CorrectParsingWithChain()11275 public void testAddOrUpdateNetworkAttribution_CorrectParsingWithChain() { 11276 assumeTrue(SdkLevel.isAtLeastS()); 11277 AttributionSource attributionSource = mock(AttributionSource.class); 11278 when(attributionSource.checkCallingUid()).thenReturn(true); 11279 when(attributionSource.isTrusted(any(Context.class))).thenReturn(true); 11280 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11281 mWifiServiceImpl = spy(mWifiServiceImpl); 11282 lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID); 11283 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11284 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11285 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false))) 11286 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 11287 11288 when(attributionSource.getUid()).thenReturn(TEST_UID); 11289 when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME); 11290 AttributionSource originalCaller = mock(AttributionSource.class); 11291 when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID); 11292 when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER); 11293 when(originalCaller.isTrusted(any(Context.class))).thenReturn(true); 11294 when(attributionSource.getNext()).thenReturn(originalCaller); 11295 11296 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 11297 11298 mLooper.startAutoDispatch(); 11299 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution); 11300 mLooper.stopAutoDispatch(); 11301 verify(mWifiConfigManager).addOrUpdateNetwork(config, OTHER_TEST_UID, 11302 TEST_PACKAGE_NAME_OTHER, false); 11303 } 11304 11305 /** 11306 * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's a chain, 11307 * When calling from {@link WifiManager#updateNetwork(WifiConfiguration)}, the creator will be 11308 * overridden by original caller. 11309 */ 11310 @Test testAddOrUpdateNetworkAttribution_CorrectParsingWithChain_WithUpdateNetwork()11311 public void testAddOrUpdateNetworkAttribution_CorrectParsingWithChain_WithUpdateNetwork() { 11312 assumeTrue(SdkLevel.isAtLeastS()); 11313 AttributionSource attributionSource = mock(AttributionSource.class); 11314 when(attributionSource.checkCallingUid()).thenReturn(true); 11315 when(attributionSource.isTrusted(any(Context.class))).thenReturn(true); 11316 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11317 mWifiServiceImpl = spy(mWifiServiceImpl); 11318 lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID); 11319 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11320 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11321 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(true))) 11322 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 11323 11324 when(attributionSource.getUid()).thenReturn(TEST_UID); 11325 when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME); 11326 AttributionSource originalCaller = mock(AttributionSource.class); 11327 when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID); 11328 when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER); 11329 when(originalCaller.isTrusted(any(Context.class))).thenReturn(true); 11330 when(attributionSource.getNext()).thenReturn(originalCaller); 11331 11332 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 11333 config.networkId = TEST_NETWORK_ID; 11334 11335 mLooper.startAutoDispatch(); 11336 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution); 11337 mLooper.stopAutoDispatch(); 11338 verify(mWifiConfigManager).addOrUpdateNetwork(config, OTHER_TEST_UID, 11339 TEST_PACKAGE_NAME_OTHER, true); 11340 } 11341 11342 /** 11343 * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's a chain. 11344 * However, if the call is not made from the system server then the attribution is ignored and 11345 * the attribution is simply to the calling app as before. 11346 */ 11347 @Test testAddOrUpdateNetworkAttribution_CorrectParsingWithChainButNotFromSystemServer()11348 public void testAddOrUpdateNetworkAttribution_CorrectParsingWithChainButNotFromSystemServer() { 11349 assumeTrue(SdkLevel.isAtLeastS()); 11350 AttributionSource attributionSource = mock(AttributionSource.class); 11351 when(attributionSource.checkCallingUid()).thenReturn(true); 11352 when(attributionSource.isTrusted(any(Context.class))).thenReturn(true); 11353 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11354 mWifiServiceImpl = spy(mWifiServiceImpl); 11355 lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID); 11356 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11357 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11358 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false))) 11359 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 11360 11361 when(attributionSource.getUid()).thenReturn(TEST_UID); 11362 when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME); 11363 AttributionSource originalCaller = mock(AttributionSource.class); 11364 when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID); 11365 when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER); 11366 when(originalCaller.isTrusted(any(Context.class))).thenReturn(true); 11367 when(attributionSource.getNext()).thenReturn(originalCaller); 11368 11369 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 11370 11371 mLooper.startAutoDispatch(); 11372 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution); 11373 mLooper.stopAutoDispatch(); 11374 verify(mWifiConfigManager).addOrUpdateNetwork(config, TEST_UID, 11375 TEST_PACKAGE_NAME, false); 11376 } 11377 11378 /** 11379 * Verify attribution passed to WifiManager#connect is parsed when there's a chain. 11380 */ 11381 @Test testConnectAttribution_CorrectParsingWithChain()11382 public void testConnectAttribution_CorrectParsingWithChain() { 11383 assumeTrue(SdkLevel.isAtLeastS()); 11384 AttributionSource attributionSource = mock(AttributionSource.class); 11385 when(attributionSource.checkCallingUid()).thenReturn(true); 11386 when(attributionSource.isTrusted(any(Context.class))).thenReturn(true); 11387 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11388 mWifiServiceImpl = spy(mWifiServiceImpl); 11389 lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID); 11390 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11391 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11392 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt())) 11393 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 11394 11395 when(attributionSource.getUid()).thenReturn(TEST_UID); 11396 when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME); 11397 when(attributionSource.getAttributionTag()).thenReturn(TEST_FEATURE_ID); 11398 AttributionSource originalCaller = mock(AttributionSource.class); 11399 when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID); 11400 when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER); 11401 when(originalCaller.getAttributionTag()).thenReturn(TEST_FEATURE_ID_OTHER); 11402 when(originalCaller.isTrusted(any(Context.class))).thenReturn(true); 11403 when(attributionSource.getNext()).thenReturn(originalCaller); 11404 11405 WifiConfiguration config = new WifiConfiguration(); 11406 config.SSID = TEST_SSID; 11407 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 11408 mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class), 11409 TEST_PACKAGE_NAME, mAttribution); 11410 mLooper.dispatchAll(); 11411 verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt()); 11412 verify(mConnectHelper).connectToNetwork(any(NetworkUpdateResult.class), 11413 any(ActionListenerWrapper.class), eq(OTHER_TEST_UID), eq(TEST_PACKAGE_NAME_OTHER), 11414 eq(TEST_FEATURE_ID_OTHER)); 11415 } 11416 11417 /** 11418 * Verify attribution passed to WifiManager#connect is parsed when there's a chain. 11419 * However, if the call is not made from the system server then the attribution is ignored and 11420 * the attribution is simply to the calling app as before. 11421 */ 11422 @Test testConnectAttribution_CorrectParsingWithChainButNotFromSystemServer()11423 public void testConnectAttribution_CorrectParsingWithChainButNotFromSystemServer() { 11424 assumeTrue(SdkLevel.isAtLeastS()); 11425 AttributionSource attributionSource = mock(AttributionSource.class); 11426 when(attributionSource.checkCallingUid()).thenReturn(true); 11427 when(attributionSource.isTrusted(any(Context.class))).thenReturn(true); 11428 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 11429 mWifiServiceImpl = spy(mWifiServiceImpl); 11430 lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID); 11431 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11432 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11433 when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt())) 11434 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID)); 11435 11436 when(attributionSource.getUid()).thenReturn(TEST_UID); 11437 when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME); 11438 when(attributionSource.getAttributionTag()).thenReturn(TEST_FEATURE_ID); 11439 AttributionSource originalCaller = mock(AttributionSource.class); 11440 when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID); 11441 when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER); 11442 when(originalCaller.getAttributionTag()).thenReturn(TEST_FEATURE_ID_OTHER); 11443 when(originalCaller.isTrusted(any(Context.class))).thenReturn(true); 11444 when(attributionSource.getNext()).thenReturn(originalCaller); 11445 11446 WifiConfiguration config = new WifiConfiguration(); 11447 config.SSID = TEST_SSID; 11448 when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config); 11449 mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class), 11450 TEST_PACKAGE_NAME, mAttribution); 11451 mLooper.dispatchAll(); 11452 verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt()); 11453 verify(mConnectHelper).connectToNetwork(any(NetworkUpdateResult.class), 11454 any(ActionListenerWrapper.class), eq(TEST_UID), eq(TEST_PACKAGE_NAME), 11455 eq(TEST_FEATURE_ID)); 11456 } 11457 11458 /** 11459 * Test that notifyWifiSsidPolicyChanged disconnects the current network 11460 * due to SSID allowlist restriction 11461 */ 11462 @Test testNotifyWifiSsidPolicyChangedWithAllowlistRestriction()11463 public void testNotifyWifiSsidPolicyChangedWithAllowlistRestriction() 11464 throws Exception { 11465 assumeTrue(SdkLevel.isAtLeastT()); 11466 11467 WifiInfo wifiInfo = new WifiInfo(); 11468 wifiInfo.setSSID(WifiSsid.fromUtf8Text(TEST_SSID)); 11469 wifiInfo.setBSSID(TEST_BSSID); 11470 wifiInfo.setNetworkId(TEST_NETWORK_ID); 11471 wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PSK); 11472 11473 when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS), 11474 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11475 when(mActiveModeWarden.getClientModeManagers()).thenReturn( 11476 Collections.singletonList(mClientModeManager)); 11477 when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo); 11478 11479 mWifiServiceImpl.notifyWifiSsidPolicyChanged(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST, 11480 new ParceledListSlice<>(List.of(WifiSsid.fromUtf8Text("SSID")))); 11481 mLooper.dispatchAll(); 11482 11483 verify(mClientModeManager).disconnect(); 11484 } 11485 11486 /** 11487 * Test that notifyWifiSsidPolicyChanged disconnects the current network 11488 * due to SSID denylist restriction 11489 */ 11490 @Test testNotifyWifiSsidPolicyChangedWithDenylistRestriction()11491 public void testNotifyWifiSsidPolicyChangedWithDenylistRestriction() 11492 throws Exception { 11493 assumeTrue(SdkLevel.isAtLeastT()); 11494 11495 WifiInfo wifiInfo = new WifiInfo(); 11496 wifiInfo.setSSID(WifiSsid.fromUtf8Text(TEST_SSID)); 11497 wifiInfo.setBSSID(TEST_BSSID); 11498 wifiInfo.setNetworkId(TEST_NETWORK_ID); 11499 wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PSK); 11500 11501 when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS), 11502 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11503 when(mActiveModeWarden.getClientModeManagers()).thenReturn( 11504 Collections.singletonList(mClientModeManager)); 11505 when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo); 11506 11507 mWifiServiceImpl.notifyWifiSsidPolicyChanged(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST, 11508 new ParceledListSlice<>(List.of(WifiSsid.fromUtf8Text(TEST_SSID)))); 11509 mLooper.dispatchAll(); 11510 11511 verify(mClientModeManager).disconnect(); 11512 } 11513 11514 /** 11515 * Test that notifyWifiSsidPolicyChanged does not disconnect the current network 11516 * due to SSID restriction for Passpoint networks 11517 */ 11518 @Test testNotifyWifiSsidPolicyChangedWithSsidRestrictionForPasspoint()11519 public void testNotifyWifiSsidPolicyChangedWithSsidRestrictionForPasspoint() 11520 throws Exception { 11521 assumeTrue(SdkLevel.isAtLeastT()); 11522 11523 WifiInfo wifiInfo = setupForGetConnectionInfo(); 11524 wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PASSPOINT_R1_R2); 11525 11526 when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS), 11527 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11528 when(mActiveModeWarden.getClientModeManagers()).thenReturn( 11529 Collections.singletonList(mClientModeManager)); 11530 when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo); 11531 11532 mWifiServiceImpl.notifyWifiSsidPolicyChanged(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST, 11533 new ParceledListSlice<>(List.of(WifiSsid.fromUtf8Text("SSID")))); 11534 mLooper.dispatchAll(); 11535 11536 verify(mClientModeManager, never()).disconnect(); 11537 } 11538 11539 /** 11540 * Test that notifyWifiSsidPolicyChanged does not disconnect the current network 11541 * due to SSID restriction for Osu networks 11542 */ 11543 @Test testNotifyWifiSsidPolicyChangedWithSsidRestrictionForOsu()11544 public void testNotifyWifiSsidPolicyChangedWithSsidRestrictionForOsu() 11545 throws Exception { 11546 assumeTrue(SdkLevel.isAtLeastT()); 11547 11548 WifiInfo wifiInfo = new WifiInfo(); 11549 wifiInfo.setSSID(WifiSsid.fromUtf8Text(TEST_SSID)); 11550 wifiInfo.setBSSID(TEST_BSSID); 11551 wifiInfo.setNetworkId(TEST_NETWORK_ID); 11552 wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PASSPOINT_R3); 11553 wifiInfo.setOsuAp(true); 11554 11555 when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS), 11556 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11557 when(mActiveModeWarden.getClientModeManagers()).thenReturn( 11558 Collections.singletonList(mClientModeManager)); 11559 when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo); 11560 11561 mWifiServiceImpl.notifyWifiSsidPolicyChanged(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST, 11562 new ParceledListSlice<>(List.of(WifiSsid.fromUtf8Text("SSID")))); 11563 mLooper.dispatchAll(); 11564 11565 verify(mClientModeManager, never()).disconnect(); 11566 } 11567 11568 /** 11569 * Test that notifyMinimumRequiredWifiSecurityLevelChanged disconnects the current network 11570 * due to minimum security level restriction 11571 */ 11572 @Test testNotifyMinimumRequiredWifiSecurityLevelChangedWithSecurityLevelRestriction()11573 public void testNotifyMinimumRequiredWifiSecurityLevelChangedWithSecurityLevelRestriction() 11574 throws Exception { 11575 assumeTrue(SdkLevel.isAtLeastT()); 11576 11577 WifiInfo wifiInfo = setupForGetConnectionInfo(); 11578 wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PSK); 11579 11580 when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS), 11581 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11582 when(mActiveModeWarden.getClientModeManagers()).thenReturn( 11583 Collections.singletonList(mClientModeManager)); 11584 when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo); 11585 11586 mWifiServiceImpl.notifyMinimumRequiredWifiSecurityLevelChanged( 11587 DevicePolicyManager.WIFI_SECURITY_ENTERPRISE_EAP); 11588 mLooper.dispatchAll(); 11589 11590 verify(mClientModeManager).disconnect(); 11591 } 11592 11593 @Test testIsItPossibleToCreateInterfaceInvalidConditions()11594 public void testIsItPossibleToCreateInterfaceInvalidConditions() { 11595 assumeTrue(SdkLevel.isAtLeastT()); 11596 11597 when(mWifiPermissionsUtil.checkManageWifiInterfacesPermission(anyInt())).thenReturn(true); 11598 IInterfaceCreationInfoCallback.Stub mockCallback = mock( 11599 IInterfaceCreationInfoCallback.Stub.class); 11600 11601 assertThrows(IllegalArgumentException.class, 11602 () -> mWifiServiceImpl.reportCreateInterfaceImpact(null, 11603 WifiManager.WIFI_INTERFACE_TYPE_AP, true, mockCallback)); 11604 assertThrows(IllegalArgumentException.class, 11605 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, 11606 WifiManager.WIFI_INTERFACE_TYPE_AP, true, null)); 11607 assertThrows(IllegalArgumentException.class, 11608 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, 11609 /* clearly invalid value */ 100, true, mockCallback)); 11610 11611 mWifiServiceImpl = spy(mWifiServiceImpl); 11612 when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID); 11613 doThrow(new SecurityException()).when(mWifiPermissionsUtil).checkPackage(TEST_UID, 11614 TEST_PACKAGE_NAME); 11615 assertThrows(SecurityException.class, 11616 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, 11617 WifiManager.WIFI_INTERFACE_TYPE_AP, false, mockCallback)); 11618 11619 when(mWifiPermissionsUtil.checkManageWifiInterfacesPermission(anyInt())).thenReturn(false); 11620 assertThrows(SecurityException.class, 11621 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, 11622 WifiManager.WIFI_INTERFACE_TYPE_AP, false, mockCallback)); 11623 11624 when(mWifiPermissionsUtil.checkManageWifiInterfacesPermission(anyInt())).thenReturn(true); 11625 doThrow(new SecurityException()).when(mContext) 11626 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), 11627 eq("WifiService")); 11628 assertThrows(SecurityException.class, 11629 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, 11630 WifiManager.WIFI_INTERFACE_TYPE_AP, false, mockCallback)); 11631 } 11632 11633 @Test testIsItPossibleToCreateInterface()11634 public void testIsItPossibleToCreateInterface() throws Exception { 11635 assumeTrue(SdkLevel.isAtLeastT()); 11636 11637 IInterfaceCreationInfoCallback.Stub mockCallback = mock( 11638 IInterfaceCreationInfoCallback.Stub.class); 11639 final int interfaceToCreate = WifiManager.WIFI_INTERFACE_TYPE_AWARE; 11640 final int interfaceToCreateInternal = HalDeviceManager.HDM_CREATE_IFACE_NAN; 11641 mWifiServiceImpl = spy(mWifiServiceImpl); 11642 when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID); 11643 when(mWifiPermissionsUtil.checkManageWifiInterfacesPermission(TEST_UID)).thenReturn(true); 11644 final WorkSource ws = new WorkSource(TEST_UID, TEST_PACKAGE_NAME); 11645 final WorkSource wsOther = new WorkSource(OTHER_TEST_UID, TEST_PACKAGE_NAME_OTHER); 11646 final String[] packagesOther = {TEST_PACKAGE_NAME_OTHER}; 11647 11648 ArgumentCaptor<Boolean> boolCaptor = ArgumentCaptor.forClass(Boolean.class); 11649 ArgumentCaptor<int[]> intArrayCaptor = ArgumentCaptor.forClass(int[].class); 11650 ArgumentCaptor<String[]> stringArrayCaptor = ArgumentCaptor.forClass(String[].class); 11651 11652 // 3 results: failure, success with no side effects, success with side effects 11653 when(mHalDeviceManager.reportImpactToCreateIface(interfaceToCreateInternal, true, ws)) 11654 .thenReturn(null) 11655 .thenReturn(Collections.emptyList()) 11656 .thenReturn(List.of(Pair.create(HalDeviceManager.HDM_CREATE_IFACE_P2P, wsOther))) 11657 .thenReturn(List.of(Pair.create(HalDeviceManager.HDM_CREATE_IFACE_NAN, 11658 new WorkSource(WIFI_UID)))); 11659 mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, interfaceToCreate, true, 11660 mockCallback); 11661 mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, interfaceToCreate, true, 11662 mockCallback); 11663 mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, interfaceToCreate, true, 11664 mockCallback); 11665 mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, interfaceToCreate, true, 11666 mockCallback); 11667 mLooper.dispatchAll(); 11668 verify(mHalDeviceManager, times(4)).reportImpactToCreateIface( 11669 interfaceToCreateInternal, true, ws); 11670 verify(mockCallback, times(4)).onResults(boolCaptor.capture(), intArrayCaptor.capture(), 11671 stringArrayCaptor.capture()); 11672 verify(mPackageManager).makeUidVisible(TEST_UID, OTHER_TEST_UID); 11673 11674 // result 0: failure 11675 assertFalse(boolCaptor.getAllValues().get(0)); 11676 assertNull(intArrayCaptor.getAllValues().get(0)); 11677 assertNull(stringArrayCaptor.getAllValues().get(0)); 11678 11679 // result 1: success with no side effects 11680 assertTrue(boolCaptor.getAllValues().get(1)); 11681 assertEquals(0, intArrayCaptor.getAllValues().get(1).length); 11682 assertEquals(0, stringArrayCaptor.getAllValues().get(1).length); 11683 11684 // result 2: success with side effects 11685 assertTrue(boolCaptor.getAllValues().get(2)); 11686 assertEquals(1, intArrayCaptor.getAllValues().get(2).length); 11687 assertEquals(WifiManager.WIFI_INTERFACE_TYPE_DIRECT, 11688 intArrayCaptor.getAllValues().get(2)[0]); 11689 assertArrayEquals(packagesOther, stringArrayCaptor.getAllValues().get(2)); 11690 11691 // result 2: success with side effects of empty packages 11692 assertTrue(boolCaptor.getAllValues().get(3)); 11693 assertEquals(1, intArrayCaptor.getAllValues().get(3).length); 11694 assertEquals(WifiManager.WIFI_INTERFACE_TYPE_AWARE, 11695 intArrayCaptor.getAllValues().get(3)[0]); 11696 assertEquals(1, stringArrayCaptor.getAllValues().get(3).length); 11697 assertNull(stringArrayCaptor.getAllValues().get(3)[0]); 11698 } 11699 11700 @Test testTetheredSoftApTrackerWhenCountryCodeChanged()11701 public void testTetheredSoftApTrackerWhenCountryCodeChanged() throws Exception { 11702 mWifiServiceImpl.handleBootCompleted(); 11703 mLooper.dispatchAll(); 11704 11705 registerSoftApCallbackAndVerify(mClientSoftApCallback); 11706 reset(mClientSoftApCallback); 11707 when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission( 11708 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(true); 11709 if (SdkLevel.isAtLeastT()) { 11710 verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener( 11711 mIOnWifiDriverCountryCodeChangedListener); 11712 reset(mIOnWifiDriverCountryCodeChangedListener); 11713 } 11714 ArgumentCaptor<SoftApCapability> capabilityArgumentCaptor = ArgumentCaptor.forClass( 11715 SoftApCapability.class); 11716 // Country code update with HAL started 11717 when(mWifiNative.isHalStarted()).thenReturn(true); 11718 // Channel 9 - 2452Mhz 11719 WifiAvailableChannel channels2g = new WifiAvailableChannel(2452, 11720 WifiAvailableChannel.OP_MODE_SAP, ScanResult.CHANNEL_WIDTH_20MHZ); 11721 when(mWifiNative.isHalSupported()).thenReturn(true); 11722 when(mWifiNative.isHalStarted()).thenReturn(true); 11723 when(mWifiNative.getUsableChannels(eq(WifiScanner.WIFI_BAND_24_GHZ), anyInt(), anyInt())) 11724 .thenReturn(new ArrayList<>(Arrays.asList(channels2g))); 11725 mWifiServiceImpl.mCountryCodeTracker.onCountryCodeChangePending(TEST_COUNTRY_CODE); 11726 mLooper.dispatchAll(); 11727 mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_COUNTRY_CODE); 11728 mLooper.dispatchAll(); 11729 if (SdkLevel.isAtLeastT()) { 11730 verify(mIOnWifiDriverCountryCodeChangedListener) 11731 .onDriverCountryCodeChanged(TEST_COUNTRY_CODE); 11732 } 11733 verify(mClientSoftApCallback).onCapabilityChanged(capabilityArgumentCaptor.capture()); 11734 assertEquals(1, capabilityArgumentCaptor.getValue() 11735 .getSupportedChannelList(SoftApConfiguration.BAND_2GHZ).length); 11736 assertEquals(9, capabilityArgumentCaptor.getValue() 11737 .getSupportedChannelList(SoftApConfiguration.BAND_2GHZ)[0]); 11738 reset(mClientSoftApCallback); 11739 // Country code update with HAL not started 11740 when(mWifiNative.isHalStarted()).thenReturn(false); 11741 mWifiServiceImpl.mCountryCodeTracker.onCountryCodeChangePending(TEST_NEW_COUNTRY_CODE); 11742 mLooper.dispatchAll(); 11743 if (SdkLevel.isAtLeastT()) { 11744 verify(mIOnWifiDriverCountryCodeChangedListener, never()) 11745 .onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE); 11746 } 11747 verify(mClientSoftApCallback) 11748 .onCapabilityChanged(capabilityArgumentCaptor.capture()); 11749 // The supported channels in soft AP capability got invalidated. 11750 assertEquals(0, capabilityArgumentCaptor.getValue() 11751 .getSupportedChannelList(SoftApConfiguration.BAND_2GHZ).length); 11752 verify(mWifiNative, times(2)).getUsableChannels(eq(WifiScanner.WIFI_BAND_24_GHZ), anyInt(), 11753 anyInt()); 11754 } 11755 11756 /** 11757 * Verify that change network connection state is not allowed for App target below Q SDK from 11758 * guest user 11759 */ 11760 @Test testNotAllowedToChangeWifiOpsTargetBelowQSdkFromGuestUser()11761 public void testNotAllowedToChangeWifiOpsTargetBelowQSdkFromGuestUser() throws Exception { 11762 doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager) 11763 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME); 11764 when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(), 11765 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true); 11766 when(mWifiPermissionsUtil.isGuestUser()).thenReturn(true); 11767 11768 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 11769 verify(mWifiMetrics, never()).incrementNumWifiToggles(anyBoolean(), anyBoolean()); 11770 verify(mWifiMetrics, never()).reportWifiStateChanged(anyBoolean(), anyBoolean(), 11771 anyBoolean()); 11772 11773 assertFalse(mWifiServiceImpl.disconnect(TEST_PACKAGE_NAME)); 11774 assertFalse(mWifiServiceImpl.reconnect(TEST_PACKAGE_NAME)); 11775 assertFalse(mWifiServiceImpl.reassociate(TEST_PACKAGE_NAME)); 11776 11777 assertTrue(mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE_NAME, TEST_FEATURE_ID, 11778 false).getList().isEmpty()); 11779 mLooper.dispatchAll(); 11780 verify(mWifiConfigManager, never()).getConfiguredNetworks(); 11781 11782 assertFalse(mWifiServiceImpl.removeNetwork(0, TEST_PACKAGE_NAME)); 11783 mLooper.dispatchAll(); 11784 verify(mWifiConfigManager, never()).removeNetwork(anyInt(), anyInt(), anyString()); 11785 11786 assertFalse(mWifiServiceImpl.enableNetwork(0, false, TEST_PACKAGE_NAME)); 11787 mLooper.dispatchAll(); 11788 verify(mWifiConfigManager, never()).enableNetwork(anyInt(), anyBoolean(), anyInt(), 11789 anyString()); 11790 verify(mWifiMetrics, never()).incrementNumEnableNetworkCalls(); 11791 11792 assertFalse(mWifiServiceImpl.disableNetwork(0, TEST_PACKAGE_NAME)); 11793 mLooper.dispatchAll(); 11794 verify(mWifiConfigManager, never()).disableNetwork(anyInt(), anyInt(), anyString()); 11795 11796 PasspointConfiguration passpointConfig = new PasspointConfiguration(); 11797 HomeSp homeSp = new HomeSp(); 11798 homeSp.setFqdn("test.com"); 11799 passpointConfig.setHomeSp(homeSp); 11800 assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(passpointConfig, 11801 TEST_PACKAGE_NAME)); 11802 mLooper.dispatchAll(); 11803 verify(mPasspointManager, never()).addOrUpdateProvider(any(), anyInt(), anyString(), 11804 anyBoolean(), anyBoolean(), eq(false)); 11805 11806 WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID); 11807 assertEquals(-1, mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, 11808 mAttribution)); 11809 } 11810 11811 /** 11812 * Tests that {@link WifiServiceImpl#getCurrentNetwork} throws 11813 * {@link SecurityException} if the caller doesn't have the necessary permissions. 11814 */ 11815 @Test(expected = SecurityException.class) testGetCurrentNetworkNoPermission()11816 public void testGetCurrentNetworkNoPermission() throws Exception { 11817 doThrow(SecurityException.class) 11818 .when(mContext).enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), any()); 11819 mWifiServiceImpl.getCurrentNetwork(); 11820 } 11821 11822 /** 11823 * Verifies that WifiServiceImpl#getCurrentNetwork() returns the current Wifi network. 11824 */ 11825 @Test testGetCurrentNetworkWithNetworkSettingsPermission()11826 public void testGetCurrentNetworkWithNetworkSettingsPermission() throws Exception { 11827 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 11828 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 11829 Network mockNetwork = mock(Network.class); 11830 when(mActiveModeWarden.getCurrentNetwork()).thenReturn(mockNetwork); 11831 assertEquals(mockNetwork, mWifiServiceImpl.getCurrentNetwork()); 11832 } 11833 11834 @Test testQueryLastConfiguredTetheredApPassphraseSinceBootExceptions()11835 public void testQueryLastConfiguredTetheredApPassphraseSinceBootExceptions() { 11836 // good inputs should result in no exceptions. 11837 IStringListener listener = mock(IStringListener.class); 11838 // null listener ==> IllegalArgumentException 11839 assertThrows(IllegalArgumentException.class, 11840 () -> mWifiServiceImpl.queryLastConfiguredTetheredApPassphraseSinceBoot(null)); 11841 11842 // No permission ==> SecurityException 11843 assertThrows(SecurityException.class, 11844 () -> mWifiServiceImpl.queryLastConfiguredTetheredApPassphraseSinceBoot(listener)); 11845 } 11846 11847 @Test testQueryLastConfiguredTetheredApPassphraseSinceBoot()11848 public void testQueryLastConfiguredTetheredApPassphraseSinceBoot() throws RemoteException { 11849 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 11850 IStringListener listener = mock(IStringListener.class); 11851 String lastPassphrase = "testLastPassphrase"; 11852 11853 InOrder inOrder = inOrder(listener); 11854 when(mWifiApConfigStore.getLastConfiguredTetheredApPassphraseSinceBoot()) 11855 .thenReturn(lastPassphrase); 11856 mWifiServiceImpl.queryLastConfiguredTetheredApPassphraseSinceBoot(listener); 11857 mLooper.dispatchAll(); 11858 inOrder.verify(listener).onResult(lastPassphrase); 11859 11860 // Test on null return. 11861 when(mWifiApConfigStore.getLastConfiguredTetheredApPassphraseSinceBoot()) 11862 .thenReturn(null); 11863 mWifiServiceImpl.queryLastConfiguredTetheredApPassphraseSinceBoot(listener); 11864 mLooper.dispatchAll(); 11865 inOrder.verify(listener).onResult(null); 11866 } 11867 11868 @Test testChannelDataThrowsExceptionsAndOnResult()11869 public void testChannelDataThrowsExceptionsAndOnResult() throws RemoteException { 11870 assumeTrue(SdkLevel.isAtLeastT()); 11871 List<Bundle> dataList = new ArrayList<>(); 11872 IListListener listener = new IListListener() { 11873 @Override 11874 public void onResult(List value) throws RemoteException { 11875 dataList.addAll(value); 11876 } 11877 @Override 11878 public IBinder asBinder() { 11879 return null; 11880 } 11881 }; 11882 11883 //verify listener null case 11884 assertThrows(IllegalArgumentException.class, 11885 () -> mWifiServiceImpl.getChannelData(null, TEST_PACKAGE_NAME, mExtras)); 11886 11887 when(mScanRequestProxy.getScanResults()).thenReturn(createChannelDataScanResults()); 11888 mWifiServiceImpl.getChannelData(listener, TEST_PACKAGE_NAME, mExtras); 11889 mLooper.dispatchAll(); 11890 11891 //verify the result 11892 assertEquals(2, dataList.size()); 11893 Bundle dataBundle1 = dataList.get(0); 11894 assertEquals(2412, dataBundle1.getInt(CHANNEL_DATA_KEY_FREQUENCY_MHZ)); 11895 assertEquals(1, dataBundle1.getInt(CHANNEL_DATA_KEY_NUM_AP)); 11896 Bundle dataBundle2 = dataList.get(1); 11897 assertEquals(5805, dataBundle2.getInt(CHANNEL_DATA_KEY_FREQUENCY_MHZ)); 11898 assertEquals(2, dataBundle2.getInt(CHANNEL_DATA_KEY_NUM_AP)); 11899 11900 //verify it will fail without nearby permission 11901 doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceNearbyDevicesPermission( 11902 any(), anyBoolean(), any()); 11903 assertThrows(SecurityException.class, 11904 () -> mWifiServiceImpl.getChannelData(listener, TEST_PACKAGE_NAME, mExtras)); 11905 } 11906 11907 /** 11908 * Test register callback without ACCESS_WIFI_STATE permission. 11909 */ 11910 @Test testRegisterLocalOnlyNetworkCallbackWithMissingAccessWifiPermission()11911 public void testRegisterLocalOnlyNetworkCallbackWithMissingAccessWifiPermission() { 11912 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 11913 eq(ACCESS_WIFI_STATE), eq("WifiService")); 11914 assertThrows(SecurityException.class, () -> mWifiServiceImpl 11915 .addLocalOnlyConnectionStatusListener( 11916 mLocalOnlyConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID)); 11917 } 11918 11919 /** 11920 * Test unregister callback without permission. 11921 */ 11922 @Test testUnregisterLocalOnlyNetworkCallbackWithMissingPermission()11923 public void testUnregisterLocalOnlyNetworkCallbackWithMissingPermission() { 11924 doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission( 11925 eq(ACCESS_WIFI_STATE), eq("WifiService")); 11926 assertThrows(SecurityException.class, () -> mWifiServiceImpl 11927 .removeLocalOnlyConnectionStatusListener( 11928 mLocalOnlyConnectionStatusListener, TEST_PACKAGE_NAME)); 11929 } 11930 11931 /** 11932 * Test register nad unregister callback will go to WifiNetworkSuggestionManager 11933 */ 11934 @Test testRegisterUnregisterLocalOnlyNetworkCallback()11935 public void testRegisterUnregisterLocalOnlyNetworkCallback() throws Exception { 11936 mWifiServiceImpl.addLocalOnlyConnectionStatusListener( 11937 mLocalOnlyConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID); 11938 mLooper.dispatchAll(); 11939 verify(mWifiNetworkFactory).addLocalOnlyConnectionStatusListener( 11940 eq(mLocalOnlyConnectionStatusListener), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID) 11941 ); 11942 mWifiServiceImpl.removeLocalOnlyConnectionStatusListener( 11943 mLocalOnlyConnectionStatusListener, TEST_PACKAGE_NAME); 11944 mLooper.dispatchAll(); 11945 verify(mWifiNetworkFactory).removeLocalOnlyConnectionStatusListener( 11946 eq(mLocalOnlyConnectionStatusListener), eq(TEST_PACKAGE_NAME)); 11947 } 11948 createChannelDataScanResults()11949 private List<ScanResult> createChannelDataScanResults() { 11950 List<ScanResult> scanResults = new ArrayList<>(); 11951 11952 scanResults.add(new ScanResult.Builder(WifiSsid.fromUtf8Text(TEST_SSID), TEST_BSSID) 11953 .setHessid(1245) 11954 .setCaps(TEST_CAP) 11955 .setRssi(-78) 11956 .setFrequency(2412) 11957 .setTsf(1025) 11958 .setDistanceCm(22) 11959 .setDistanceSdCm(33) 11960 .setChannelWidth(20) 11961 .setIs80211McRTTResponder(true) 11962 .build()); 11963 scanResults.add(new ScanResult.Builder(WifiSsid.fromUtf8Text(TEST_SSID), TEST_BSSID) 11964 .setHessid(1245) 11965 .setCaps(TEST_CAP) 11966 .setRssi(-85) 11967 .setFrequency(2417) 11968 .setTsf(1025) 11969 .setDistanceCm(22) 11970 .setDistanceSdCm(33) 11971 .setChannelWidth(20) 11972 .setIs80211McRTTResponder(true) 11973 .build()); 11974 scanResults.add(new ScanResult.Builder(WifiSsid.fromUtf8Text(TEST_SSID), TEST_BSSID) 11975 .setHessid(1245) 11976 .setCaps(TEST_CAP) 11977 .setRssi(-60) 11978 .setFrequency(5805) 11979 .setTsf(1025) 11980 .setDistanceCm(22) 11981 .setDistanceSdCm(33) 11982 .setChannelWidth(20) 11983 .setIs80211McRTTResponder(true) 11984 .build()); 11985 scanResults.add(new ScanResult.Builder(WifiSsid.fromUtf8Text(TEST_SSID), TEST_BSSID) 11986 .setHessid(1245) 11987 .setCaps(TEST_CAP) 11988 .setRssi(-70) 11989 .setFrequency(5805) 11990 .setTsf(1025) 11991 .setDistanceCm(22) 11992 .setDistanceSdCm(33) 11993 .setChannelWidth(20) 11994 .setIs80211McRTTResponder(true) 11995 .build()); 11996 return scanResults; 11997 } 11998 enableQosPolicyFeature()11999 private void enableQosPolicyFeature() { 12000 when(mApplicationQosPolicyRequestHandler.isFeatureEnabled()).thenReturn(true); 12001 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 12002 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 12003 .thenReturn(true); 12004 } 12005 createDownlinkQosPolicyParamsList(int size, boolean uniqueIds)12006 private List<QosPolicyParams> createDownlinkQosPolicyParamsList(int size, boolean uniqueIds) { 12007 List<QosPolicyParams> policyParamsList = new ArrayList<>(); 12008 for (int i = 0; i < size; i++) { 12009 int policyId = uniqueIds ? i + 2 : 5; 12010 policyParamsList.add(new QosPolicyParams.Builder( 12011 policyId, QosPolicyParams.DIRECTION_DOWNLINK) 12012 .setUserPriority(QosPolicyParams.USER_PRIORITY_VIDEO_LOW) 12013 .setIpVersion(QosPolicyParams.IP_VERSION_4) 12014 .build()); 12015 } 12016 return policyParamsList; 12017 } 12018 createUplinkQosPolicyParamsList(int size)12019 private static List<QosPolicyParams> createUplinkQosPolicyParamsList(int size) { 12020 List<QosPolicyParams> policyParamsList = new ArrayList<>(); 12021 QosCharacteristics mockQosCharacteristics = mock(QosCharacteristics.class); 12022 when(mockQosCharacteristics.validate()).thenReturn(true); 12023 12024 for (int i = 0; i < size; i++) { 12025 int policyId = i + 2; 12026 policyParamsList.add(new QosPolicyParams.Builder( 12027 policyId, QosPolicyParams.DIRECTION_UPLINK) 12028 .setQosCharacteristics(mockQosCharacteristics) 12029 .build()); 12030 } 12031 12032 return policyParamsList; 12033 } 12034 12035 /** 12036 * Verify that addQosPolicies works correctly. 12037 */ 12038 @Test testAddQosPoliciesSuccess()12039 public void testAddQosPoliciesSuccess() throws RemoteException { 12040 assumeTrue(SdkLevel.isAtLeastU()); 12041 enableQosPolicyFeature(); 12042 12043 ConcreteClientModeManager primaryCmm = mock(ConcreteClientModeManager.class); 12044 when(primaryCmm.isWifiStandardSupported(anyInt())).thenReturn(true); 12045 when(mActiveModeWarden.getPrimaryClientModeManager()).thenReturn(primaryCmm); 12046 mLooper.startAutoDispatch(); // handles call to isWifiStandardSupported 12047 12048 List<QosPolicyParams> paramsList = createDownlinkQosPolicyParamsList(5, true); 12049 IBinder binder = mock(IBinder.class); 12050 IListListener listener = mock(IListListener.class); 12051 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(paramsList), binder, 12052 TEST_PACKAGE_NAME, listener); 12053 int expectedNumCalls = 1; 12054 12055 if (SdkLevel.isAtLeastV()) { 12056 // Uplink policies are supported on SDK >= V 12057 paramsList = createUplinkQosPolicyParamsList(5); 12058 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(paramsList), binder, 12059 TEST_PACKAGE_NAME, listener); 12060 expectedNumCalls += 1; 12061 } 12062 12063 mLooper.dispatchAll(); 12064 verify(mApplicationQosPolicyRequestHandler, times(expectedNumCalls)).queueAddRequest( 12065 anyList(), any(), any(), anyInt()); 12066 mLooper.stopAutoDispatchAndIgnoreExceptions(); 12067 } 12068 12069 /** 12070 * Verify the expected error cases in addQosPolicies. 12071 */ 12072 @Test testAddQosPoliciesError()12073 public void testAddQosPoliciesError() throws RemoteException { 12074 assumeTrue(SdkLevel.isAtLeastU()); 12075 enableQosPolicyFeature(); 12076 List<QosPolicyParams> paramsList = createDownlinkQosPolicyParamsList(5, true); 12077 IBinder binder = mock(IBinder.class); 12078 IListListener listener = mock(IListListener.class); 12079 12080 // Feature disabled 12081 when(mApplicationQosPolicyRequestHandler.isFeatureEnabled()).thenReturn(false); 12082 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(paramsList), binder, 12083 TEST_PACKAGE_NAME, listener); 12084 enableQosPolicyFeature(); 12085 12086 verify(listener).onResult(mListCaptor.capture()); 12087 List<Integer> statusList = mListCaptor.getValue(); 12088 for (Integer status : statusList) { 12089 assertEquals(WifiManager.QOS_REQUEST_STATUS_FAILURE_UNKNOWN, (int) status); 12090 } 12091 12092 // Null argument 12093 assertThrows(NullPointerException.class, () -> 12094 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(null), binder, 12095 TEST_PACKAGE_NAME, listener)); 12096 assertThrows(NullPointerException.class, () -> 12097 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(paramsList), null, 12098 TEST_PACKAGE_NAME, listener)); 12099 assertThrows(NullPointerException.class, () -> 12100 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(paramsList), binder, 12101 TEST_PACKAGE_NAME, null)); 12102 12103 // Invalid QoS policy params list 12104 List<QosPolicyParams> emptyList = createDownlinkQosPolicyParamsList(0, true); 12105 List<QosPolicyParams> largeList = createDownlinkQosPolicyParamsList( 12106 WifiManager.getMaxNumberOfPoliciesPerQosRequest() + 1, true); 12107 List<QosPolicyParams> duplicatePolicyList = createDownlinkQosPolicyParamsList(5, false); 12108 assertThrows(IllegalArgumentException.class, () -> 12109 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(emptyList), binder, 12110 TEST_PACKAGE_NAME, listener)); 12111 assertThrows(IllegalArgumentException.class, () -> 12112 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(largeList), binder, 12113 TEST_PACKAGE_NAME, listener)); 12114 assertThrows(IllegalArgumentException.class, () -> 12115 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(duplicatePolicyList), 12116 binder, TEST_PACKAGE_NAME, listener)); 12117 12118 if (SdkLevel.isAtLeastV()) { 12119 List<QosPolicyParams> mixedDirectionList = createDownlinkQosPolicyParamsList(1, true); 12120 QosCharacteristics mockQosCharacteristics = mock(QosCharacteristics.class); 12121 when(mockQosCharacteristics.validate()).thenReturn(true); 12122 mixedDirectionList.add( 12123 new QosPolicyParams.Builder(101, QosPolicyParams.DIRECTION_UPLINK) 12124 .setQosCharacteristics(mockQosCharacteristics) 12125 .build()); 12126 assertThrows(IllegalArgumentException.class, () -> 12127 mWifiServiceImpl.addQosPolicies(new ParceledListSlice<>(mixedDirectionList), 12128 binder, TEST_PACKAGE_NAME, listener)); 12129 } 12130 } 12131 12132 /** 12133 * Verify that removeQosPolicies works correctly. 12134 */ 12135 @Test testRemoveQosPoliciesSuccess()12136 public void testRemoveQosPoliciesSuccess() throws RemoteException { 12137 assumeTrue(SdkLevel.isAtLeastU()); 12138 enableQosPolicyFeature(); 12139 12140 int[] policyIds = new int[]{1, 2, 3}; 12141 mWifiServiceImpl.removeQosPolicies(policyIds, TEST_PACKAGE_NAME); 12142 mLooper.dispatchAll(); 12143 verify(mApplicationQosPolicyRequestHandler).queueRemoveRequest(anyList(), anyInt()); 12144 } 12145 12146 /** 12147 * Verify the expected error cases in removeQosPolicies. 12148 */ 12149 @Test testRemoveQosPoliciesError()12150 public void testRemoveQosPoliciesError() { 12151 assumeTrue(SdkLevel.isAtLeastU()); 12152 enableQosPolicyFeature(); 12153 12154 // Invalid policy ID list 12155 int[] emptyPolicyIdList = new int[0]; 12156 int[] largePolicyIdList = new int[WifiManager.getMaxNumberOfPoliciesPerQosRequest() + 1]; 12157 int[] duplicatePolicyIdList = new int[] {1, 2, 2}; 12158 assertThrows(NullPointerException.class, () -> 12159 mWifiServiceImpl.removeQosPolicies(null, TEST_PACKAGE_NAME)); 12160 assertThrows(IllegalArgumentException.class, () -> 12161 mWifiServiceImpl.removeQosPolicies(emptyPolicyIdList, TEST_PACKAGE_NAME)); 12162 assertThrows(IllegalArgumentException.class, () -> 12163 mWifiServiceImpl.removeQosPolicies(largePolicyIdList, TEST_PACKAGE_NAME)); 12164 assertThrows(IllegalArgumentException.class, () -> 12165 mWifiServiceImpl.removeQosPolicies(duplicatePolicyIdList, TEST_PACKAGE_NAME)); 12166 } 12167 12168 /** 12169 * Verify that removeAllQosPolicies works correctly. 12170 */ 12171 @Test testRemoveAllQosPolicies()12172 public void testRemoveAllQosPolicies() { 12173 assumeTrue(SdkLevel.isAtLeastU()); 12174 enableQosPolicyFeature(); 12175 12176 mWifiServiceImpl.removeAllQosPolicies(TEST_PACKAGE_NAME); 12177 mLooper.dispatchAll(); 12178 verify(mApplicationQosPolicyRequestHandler).queueRemoveAllRequest(anyInt()); 12179 } 12180 12181 /** 12182 * Verify if set / get link layer stats polling interval works correctly 12183 */ 12184 @Test testSetAndGetLinkLayerStatsPollingInterval()12185 public void testSetAndGetLinkLayerStatsPollingInterval() throws Exception { 12186 assumeTrue(SdkLevel.isAtLeastT()); 12187 mWifiServiceImpl.setLinkLayerStatsPollingInterval( 12188 TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS); 12189 mLooper.dispatchAll(); 12190 verify(mClientModeManager).setLinkLayerStatsPollingInterval( 12191 eq(TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS)); 12192 12193 IIntegerListener listener = mock(IIntegerListener.class); 12194 when(mWifiGlobals.getPollRssiIntervalMillis()).thenReturn( 12195 TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS); 12196 mWifiServiceImpl.getLinkLayerStatsPollingInterval(listener); 12197 mLooper.dispatchAll(); 12198 verify(listener).onResult(TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS); 12199 } 12200 12201 /** 12202 * Test exceptions for set / get link layer stats polling interval 12203 */ 12204 @Test testSetAndGetLinkLayerStatsPollingIntervalThrowsExceptions()12205 public void testSetAndGetLinkLayerStatsPollingIntervalThrowsExceptions() throws Exception { 12206 assumeTrue(SdkLevel.isAtLeastT()); 12207 // Verify IllegalArgumentException for negative interval 12208 assertThrows(IllegalArgumentException.class, 12209 () -> mWifiServiceImpl.setLinkLayerStatsPollingInterval( 12210 -TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS)); 12211 // Verify NullPointerException for null listener 12212 assertThrows(NullPointerException.class, 12213 () -> mWifiServiceImpl.getLinkLayerStatsPollingInterval(null)); 12214 // Verify SecurityException when the caller does not have permission 12215 when(mContext.checkCallingOrSelfPermission(android.Manifest.permission 12216 .MANAGE_WIFI_NETWORK_SELECTION)).thenReturn(PackageManager.PERMISSION_DENIED); 12217 assertThrows(SecurityException.class, 12218 () -> mWifiServiceImpl.setLinkLayerStatsPollingInterval( 12219 TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS)); 12220 IIntegerListener listener = mock(IIntegerListener.class); 12221 assertThrows(SecurityException.class, 12222 () -> mWifiServiceImpl.getLinkLayerStatsPollingInterval(listener)); 12223 } 12224 12225 /** 12226 * Verify {@link WifiServiceImpl#setMloMode(int)}. 12227 */ 12228 @Test testSetMloMode()12229 public void testSetMloMode() throws RemoteException { 12230 // Android U+ only. 12231 assumeTrue(SdkLevel.isAtLeastU()); 12232 // Mock listener. 12233 IBooleanListener listener = mock(IBooleanListener.class); 12234 InOrder inOrder = inOrder(listener); 12235 12236 // Verify permission. 12237 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 12238 assertThrows(SecurityException.class, 12239 () -> mWifiServiceImpl.setMloMode(WifiManager.MLO_MODE_DEFAULT, listener)); 12240 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12241 true); 12242 12243 // Verify setMloMode() success. 12244 when(mWifiNative.setMloMode(eq(WifiManager.MLO_MODE_LOW_POWER))).thenReturn( 12245 WifiStatusCode.SUCCESS); 12246 mWifiServiceImpl.setMloMode(WifiManager.MLO_MODE_LOW_POWER, listener); 12247 mLooper.dispatchAll(); 12248 inOrder.verify(listener).onResult(true); 12249 12250 // Verify setMloMode() failure case. 12251 mLooper.startAutoDispatch(); 12252 when(mWifiNative.setMloMode(eq(WifiManager.MLO_MODE_HIGH_THROUGHPUT))).thenReturn( 12253 WifiStatusCode.ERROR_INVALID_ARGS); 12254 mWifiServiceImpl.setMloMode(WifiManager.MLO_MODE_HIGH_THROUGHPUT, listener); 12255 mLooper.dispatchAll(); 12256 inOrder.verify(listener).onResult(false); 12257 } 12258 12259 /** 12260 * Verify {@link WifiServiceImpl#getMloMode()}. 12261 */ 12262 @Test testGetMloMode()12263 public void testGetMloMode() throws RemoteException { 12264 // Android U+ only. 12265 assumeTrue(SdkLevel.isAtLeastU()); 12266 // Mock listener. 12267 IIntegerListener listener = mock(IIntegerListener.class); 12268 InOrder inOrder = inOrder(listener); 12269 12270 // Verify permission. 12271 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12272 false); 12273 assertThrows(SecurityException.class, 12274 () -> mWifiServiceImpl.getMloMode(listener)); 12275 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12276 true); 12277 12278 // Verify getMloMode() success. 12279 when(mWifiNative.getMloMode()).thenReturn(WifiManager.MLO_MODE_LOW_POWER); 12280 mWifiServiceImpl.getMloMode(listener); 12281 mLooper.dispatchAll(); 12282 inOrder.verify(listener).onResult(WifiManager.MLO_MODE_LOW_POWER); 12283 } 12284 12285 /** 12286 * Verify add and remove of Wi-Fi low latency listener. 12287 */ 12288 @Test testWifiDeviceLowLatencyModeListener()12289 public void testWifiDeviceLowLatencyModeListener() { 12290 // Setup listener. 12291 IWifiLowLatencyLockListener testListener = mock(IWifiLowLatencyLockListener.class); 12292 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 12293 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12294 true); 12295 12296 // Test success case. 12297 mWifiServiceImpl.addWifiLowLatencyLockListener(testListener); 12298 mLooper.dispatchAll(); 12299 verify(mLockManager).addWifiLowLatencyLockListener(testListener); 12300 mWifiServiceImpl.removeWifiLowLatencyLockListener(testListener); 12301 mLooper.dispatchAll(); 12302 verify(mLockManager).removeWifiLowLatencyLockListener(testListener); 12303 12304 // Test null listener. 12305 assertThrows(IllegalArgumentException.class, 12306 () -> mWifiServiceImpl.addWifiLowLatencyLockListener(null)); 12307 assertThrows(IllegalArgumentException.class, 12308 () -> mWifiServiceImpl.removeWifiLowLatencyLockListener(null)); 12309 12310 // Expect exception when caller has no permission. 12311 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 12312 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12313 false); 12314 assertThrows(SecurityException.class, 12315 () -> mWifiServiceImpl.addWifiLowLatencyLockListener(testListener)); 12316 12317 // No exception for remove. 12318 mWifiServiceImpl.removeWifiLowLatencyLockListener(testListener); 12319 } 12320 12321 /** 12322 * Verify that setWifiEnabled() returns false when satellite mode is on. 12323 */ 12324 @Test testSetWifiEnabledSatelliteModeOn()12325 public void testSetWifiEnabledSatelliteModeOn() { 12326 when(mSettingsStore.isSatelliteModeOn()).thenReturn(true); 12327 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 12328 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 12329 assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true)); 12330 } 12331 12332 /** 12333 * Verify {@link WifiServiceImpl#getMaxMloAssociationLinkCount(IIntegerListener)} and 12334 * {@link WifiServiceImpl#getMaxMloStrLinkCount(IIntegerListener)}. 12335 */ 12336 @Test testGetMloCapabilities()12337 public void testGetMloCapabilities() throws RemoteException { 12338 // Android U+ only. 12339 assumeTrue(SdkLevel.isAtLeastU()); 12340 // Mock listener. 12341 IIntegerListener listener = mock(IIntegerListener.class); 12342 InOrder inOrder = inOrder(listener); 12343 12344 // Verify permission. 12345 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12346 false); 12347 assertThrows(SecurityException.class, 12348 () -> mWifiServiceImpl.getMaxMloStrLinkCount(listener, mExtras)); 12349 assertThrows(SecurityException.class, 12350 () -> mWifiServiceImpl.getMaxMloAssociationLinkCount(listener, mExtras)); 12351 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12352 true); 12353 12354 // verify listener == null. 12355 assertThrows(NullPointerException.class, 12356 () -> mWifiServiceImpl.getMaxMloStrLinkCount(null, mExtras)); 12357 assertThrows(NullPointerException.class, 12358 () -> mWifiServiceImpl.getMaxMloAssociationLinkCount(null, mExtras)); 12359 12360 // Verify getMaxMloAssociationLinkCount(). 12361 when(mWifiNative.getMaxMloAssociationLinkCount(WIFI_IFACE_NAME)).thenReturn(3); 12362 mWifiServiceImpl.getMaxMloAssociationLinkCount(listener, mExtras); 12363 mLooper.dispatchAll(); 12364 inOrder.verify(listener).onResult(3); 12365 12366 // Verify getMaxMloStrLinkCount(). 12367 when(mWifiNative.getMaxMloStrLinkCount(WIFI_IFACE_NAME)).thenReturn(2); 12368 mWifiServiceImpl.getMaxMloStrLinkCount(listener, mExtras); 12369 mLooper.dispatchAll(); 12370 inOrder.verify(listener).onResult(2); 12371 } 12372 12373 @Test testSupportedBandCombinations()12374 public void testSupportedBandCombinations() throws RemoteException { 12375 // Android U+ only. 12376 assumeTrue(SdkLevel.isAtLeastU()); 12377 // Mock listener. 12378 IWifiBandsListener listener = mock(IWifiBandsListener.class); 12379 InOrder inOrder = inOrder(listener); 12380 12381 // Verify permission. 12382 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12383 false); 12384 assertThrows(SecurityException.class, 12385 () -> mWifiServiceImpl.getSupportedSimultaneousBandCombinations(listener, mExtras)); 12386 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn( 12387 true); 12388 12389 // verify listener == null. 12390 assertThrows(NullPointerException.class, 12391 () -> mWifiServiceImpl.getSupportedSimultaneousBandCombinations(null, mExtras)); 12392 12393 // verify the behaviour if the band information is not available. 12394 Set<List<Integer>> supportedBandsSet = null; 12395 when(mWifiNative.getSupportedBandCombinations(WIFI_IFACE_NAME)).thenReturn( 12396 supportedBandsSet); 12397 mWifiServiceImpl.getSupportedSimultaneousBandCombinations(listener, mExtras); 12398 mLooper.dispatchAll(); 12399 inOrder.verify(listener).onResult(eq(new WifiBands[0])); 12400 12401 // Verify positive case. 12402 supportedBandsSet = Set.of(new ArrayList(Arrays.asList(WifiScanner.WIFI_BAND_24_GHZ)), 12403 new ArrayList(Arrays.asList(WifiScanner.WIFI_BAND_5_GHZ)), 12404 new ArrayList(Arrays.asList(WifiScanner.WIFI_BAND_6_GHZ)), new ArrayList( 12405 Arrays.asList(WifiScanner.WIFI_BAND_24_GHZ, WifiScanner.WIFI_BAND_5_GHZ)), 12406 new ArrayList( 12407 Arrays.asList(WifiScanner.WIFI_BAND_24_GHZ, WifiScanner.WIFI_BAND_6_GHZ)), 12408 new ArrayList( 12409 Arrays.asList(WifiScanner.WIFI_BAND_5_GHZ, WifiScanner.WIFI_BAND_6_GHZ)), 12410 new ArrayList( 12411 Arrays.asList(WifiScanner.WIFI_BAND_24_GHZ, WifiScanner.WIFI_BAND_5_GHZ, 12412 WifiScanner.WIFI_BAND_6_GHZ))); 12413 when(mWifiNative.getSupportedBandCombinations(WIFI_IFACE_NAME)).thenReturn( 12414 supportedBandsSet); 12415 mWifiServiceImpl.getSupportedSimultaneousBandCombinations(listener, mExtras); 12416 mLooper.dispatchAll(); 12417 ArgumentCaptor<WifiBands[]> resultCaptor = ArgumentCaptor.forClass(WifiBands[].class); 12418 inOrder.verify(listener).onResult(resultCaptor.capture()); 12419 int entries = 0; 12420 for (WifiBands band : resultCaptor.getValue()) { 12421 ++entries; 12422 assertTrue(supportedBandsSet.stream().anyMatch(l -> { 12423 for (int i = 0; i < band.bands.length; ++i) { 12424 if (i >= l.size()) return false; 12425 if (band.bands[i] != l.get(i)) return false; 12426 } 12427 return true; 12428 })); 12429 } 12430 assertTrue(entries == supportedBandsSet.size()); 12431 } 12432 12433 /** 12434 * Verify that on a country code change, we inform the AFC Manager. 12435 */ 12436 @Test testInformAfcManagerOnCountryCodeChange()12437 public void testInformAfcManagerOnCountryCodeChange() { 12438 final String newCountryCode = "US"; 12439 mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(newCountryCode); 12440 mLooper.dispatchAll(); 12441 12442 // check that we let the AFC Manager know that the country code has changed 12443 verify(mAfcManager).onCountryCodeChange(newCountryCode); 12444 } 12445 12446 @Test testShutDownHandling()12447 public void testShutDownHandling() { 12448 mWifiServiceImpl.checkAndStartWifi(); 12449 mWifiServiceImpl.handleBootCompleted(); 12450 mLooper.dispatchAll(); 12451 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 12452 argThat((IntentFilter filter) -> 12453 filter.hasAction(ACTION_SHUTDOWN)), 12454 isNull(), 12455 any(Handler.class)); 12456 Intent intent = new Intent(ACTION_SHUTDOWN); 12457 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 12458 verify(mActiveModeWarden).notifyShuttingDown(); 12459 verify(mWifiScoreCard).resetAllConnectionStates(); 12460 verify(mWifiConfigManager).writeDataToStorage(); 12461 verify(mWifiNetworkSuggestionsManager).handleShutDown(); 12462 } 12463 12464 @Test(expected = SecurityException.class) testSetWepAllowedWithoutPermission()12465 public void testSetWepAllowedWithoutPermission() { 12466 // by default no permissions are given so the call should fail. 12467 mWifiServiceImpl.setWepAllowed(true); 12468 } 12469 12470 @Test testSetWepAllowedWithPermission()12471 public void testSetWepAllowedWithPermission() { 12472 // Test if WIFI_WEP_ALLOWED starts with false. 12473 when(mWifiSettingsConfigStore.get(eq(WIFI_WEP_ALLOWED))).thenReturn(false); 12474 mWifiServiceImpl.checkAndStartWifi(); 12475 mLooper.dispatchAll(); 12476 verify(mWifiSettingsConfigStore).get(eq(WIFI_WEP_ALLOWED)); 12477 verify(mWifiGlobals).setWepAllowed(eq(false)); 12478 verify(mWifiSettingsConfigStore).registerChangeListener( 12479 eq(WIFI_WEP_ALLOWED), 12480 mWepAllowedSettingChangedListenerCaptor.capture(), 12481 any(Handler.class)); 12482 // verify setWepAllowed with MANAGE_WIFI_NETWORK_SETTING 12483 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 12484 mWifiServiceImpl.setWepAllowed(true); 12485 verify(mWifiSettingsConfigStore).put(eq(WIFI_WEP_ALLOWED), eq(true)); 12486 mWepAllowedSettingChangedListenerCaptor.getValue() 12487 .onSettingsChanged(WIFI_WEP_ALLOWED, true); 12488 mLooper.dispatchAll(); 12489 verify(mWifiGlobals).setWepAllowed(true); 12490 } 12491 12492 @Test testSetWepDisAllowedWithPermission()12493 public void testSetWepDisAllowedWithPermission() { 12494 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 12495 ConcreteClientModeManager cmmWep = mock(ConcreteClientModeManager.class); 12496 ConcreteClientModeManager cmmWpa = mock(ConcreteClientModeManager.class); 12497 WifiInfo mockWifiInfoWep = mock(WifiInfo.class); 12498 WifiInfo mockWifiInfoWpa = mock(WifiInfo.class); 12499 List<ClientModeManager> cmms = Arrays.asList(cmmWep, cmmWpa); 12500 when(mActiveModeWarden.getClientModeManagers()).thenReturn(cmms); 12501 when(mockWifiInfoWep.getCurrentSecurityType()).thenReturn(WifiInfo.SECURITY_TYPE_WEP); 12502 when(mockWifiInfoWpa.getCurrentSecurityType()).thenReturn(WifiInfo.SECURITY_TYPE_PSK); 12503 when(cmmWep.getConnectionInfo()).thenReturn(mockWifiInfoWep); 12504 when(cmmWpa.getConnectionInfo()).thenReturn(mockWifiInfoWpa); 12505 mWifiServiceImpl.checkAndStartWifi(); 12506 mLooper.dispatchAll(); 12507 verify(mWifiSettingsConfigStore).get(eq(WIFI_WEP_ALLOWED)); 12508 verify(mWifiGlobals).setWepAllowed(eq(true)); 12509 verify(mWifiSettingsConfigStore).registerChangeListener( 12510 eq(WIFI_WEP_ALLOWED), 12511 mWepAllowedSettingChangedListenerCaptor.capture(), 12512 any(Handler.class)); 12513 12514 mWifiServiceImpl.setWepAllowed(false); 12515 verify(mWifiSettingsConfigStore).put(eq(WIFI_WEP_ALLOWED), eq(false)); 12516 mWepAllowedSettingChangedListenerCaptor.getValue() 12517 .onSettingsChanged(WIFI_WEP_ALLOWED, false); 12518 mLooper.dispatchAll(); 12519 verify(mWifiGlobals).setWepAllowed(false); 12520 // Only WEP disconnect 12521 verify(cmmWep).disconnect(); 12522 verify(cmmWpa, never()).disconnect(); 12523 } 12524 12525 @Test testQueryWepAllowedExceptionCases()12526 public void testQueryWepAllowedExceptionCases() { 12527 // null listener ==> IllegalArgumentException 12528 assertThrows(IllegalArgumentException.class, 12529 () -> mWifiServiceImpl.queryWepAllowed(null)); 12530 // by default no permissions are given so the call should fail. 12531 assertThrows(SecurityException.class, 12532 () -> mWifiServiceImpl.queryWepAllowed(mock(IBooleanListener.class))); 12533 } 12534 12535 @Test testQueryWepAllowedNormalCase()12536 public void testQueryWepAllowedNormalCase() throws Exception { 12537 when(mWifiSettingsConfigStore.get(eq(WIFI_WEP_ALLOWED))).thenReturn(false); 12538 mWifiServiceImpl.checkAndStartWifi(); 12539 mLooper.dispatchAll(); 12540 verify(mWifiSettingsConfigStore).get(eq(WIFI_WEP_ALLOWED)); 12541 verify(mWifiGlobals).setWepAllowed(eq(false)); 12542 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 12543 IBooleanListener listener = mock(IBooleanListener.class); 12544 12545 InOrder inOrder = inOrder(listener); 12546 when(mWifiSettingsConfigStore.get(eq(WIFI_WEP_ALLOWED))).thenReturn(true); 12547 mWifiServiceImpl.queryWepAllowed(listener); 12548 mLooper.dispatchAll(); 12549 verify(mWifiSettingsConfigStore, times(2)).get(eq(WIFI_WEP_ALLOWED)); 12550 inOrder.verify(listener).onResult(true); 12551 12552 when(mWifiSettingsConfigStore.get(eq(WIFI_WEP_ALLOWED))).thenReturn(false); 12553 mWifiServiceImpl.queryWepAllowed(listener); 12554 mLooper.dispatchAll(); 12555 verify(mWifiSettingsConfigStore, times(3)).get(eq(WIFI_WEP_ALLOWED)); 12556 inOrder.verify(listener).onResult(false); 12557 } 12558 12559 @Test testEnableAndDisableMscsSuccess()12560 public void testEnableAndDisableMscsSuccess() { 12561 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 12562 .thenReturn(true); 12563 when(mActiveModeWarden.getInternetConnectivityClientModeManagers()) 12564 .thenReturn(Arrays.asList(mClientModeManager)); 12565 when(mClientModeManager.getInterfaceName()).thenReturn(WIFI_IFACE_NAME); 12566 12567 // Test enableMscs 12568 MscsParams mscsParams = new MscsParams.Builder().build(); 12569 mWifiServiceImpl.enableMscs(mscsParams); 12570 mLooper.dispatchAll(); 12571 verify(mWifiNative).enableMscs(eq(mscsParams), eq(WIFI_IFACE_NAME)); 12572 12573 // Test disableMscs 12574 mWifiServiceImpl.disableMscs(); 12575 mLooper.dispatchAll(); 12576 verify(mWifiNative).disableMscs(eq(WIFI_IFACE_NAME)); 12577 } 12578 12579 @Test testEnableAndDisableMscsFailure()12580 public void testEnableAndDisableMscsFailure() { 12581 // Verify the permissions check on both methods 12582 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 12583 .thenReturn(false); 12584 assertThrows(SecurityException.class, 12585 () -> mWifiServiceImpl.enableMscs(mock(MscsParams.class))); 12586 assertThrows(SecurityException.class, () -> mWifiServiceImpl.disableMscs()); 12587 12588 // Verify the nullity check on enableMscs 12589 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 12590 .thenReturn(true); 12591 assertThrows(NullPointerException.class, () -> mWifiServiceImpl.enableMscs(null)); 12592 } 12593 12594 @Test(expected = SecurityException.class) testSetSendDhcpHostnameRestrictionWithoutPermission()12595 public void testSetSendDhcpHostnameRestrictionWithoutPermission() { 12596 // by default no permissions are given so the call should fail. 12597 mWifiServiceImpl.setSendDhcpHostnameRestriction( 12598 TEST_PACKAGE_NAME, WifiManager.FLAG_SEND_DHCP_HOSTNAME_RESTRICTION_OPEN); 12599 } 12600 12601 @Test(expected = IllegalArgumentException.class) testSetSendDhcpHostnameRestrictionInvalidFlags()12602 public void testSetSendDhcpHostnameRestrictionInvalidFlags() { 12603 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 12604 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 12605 mWifiServiceImpl.setSendDhcpHostnameRestriction( 12606 TEST_PACKAGE_NAME, -1); 12607 } 12608 12609 @Test testSetSendDhcpHostnameRestrictionWithPermission()12610 public void testSetSendDhcpHostnameRestrictionWithPermission() { 12611 // verify setSendDhcpHostnameRestriction with NETWORK_SETTINGS 12612 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 12613 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 12614 mWifiServiceImpl.setSendDhcpHostnameRestriction( 12615 TEST_PACKAGE_NAME, WifiManager.FLAG_SEND_DHCP_HOSTNAME_RESTRICTION_OPEN); 12616 mLooper.dispatchAll(); 12617 verify(mWifiGlobals).setSendDhcpHostnameRestriction( 12618 eq(WifiManager.FLAG_SEND_DHCP_HOSTNAME_RESTRICTION_OPEN)); 12619 } 12620 12621 @Test testQuerySendDhcpHostnameRestrictionExceptionCases()12622 public void testQuerySendDhcpHostnameRestrictionExceptionCases() { 12623 // null listener ==> IllegalArgumentException 12624 assertThrows(IllegalArgumentException.class, 12625 () -> mWifiServiceImpl.querySendDhcpHostnameRestriction(TEST_PACKAGE_NAME, null)); 12626 // by default no permissions are given so the call should fail. 12627 assertThrows(SecurityException.class, 12628 () -> mWifiServiceImpl.querySendDhcpHostnameRestriction( 12629 TEST_PACKAGE_NAME, mock(IIntegerListener.class))); 12630 } 12631 12632 @Test testQuerySendDhcpHostnameRestrictionNormalCase()12633 public void testQuerySendDhcpHostnameRestrictionNormalCase() throws Exception { 12634 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 12635 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 12636 IIntegerListener listener = mock(IIntegerListener.class); 12637 12638 InOrder inOrder = inOrder(listener); 12639 when(mWifiGlobals.getSendDhcpHostnameRestriction()) 12640 .thenReturn(0); 12641 mWifiServiceImpl.querySendDhcpHostnameRestriction(TEST_PACKAGE_NAME, listener); 12642 mLooper.dispatchAll(); 12643 verify(mWifiGlobals).getSendDhcpHostnameRestriction(); 12644 inOrder.verify(listener).onResult(0); 12645 12646 when(mWifiGlobals.getSendDhcpHostnameRestriction()) 12647 .thenReturn(WifiManager.FLAG_SEND_DHCP_HOSTNAME_RESTRICTION_OPEN); 12648 mWifiServiceImpl.querySendDhcpHostnameRestriction(TEST_PACKAGE_NAME, listener); 12649 mLooper.dispatchAll(); 12650 verify(mWifiGlobals, times(2)).getSendDhcpHostnameRestriction(); 12651 inOrder.verify(listener).onResult(WifiManager.FLAG_SEND_DHCP_HOSTNAME_RESTRICTION_OPEN); 12652 } 12653 12654 @Test testSetPerSsidRoamingModeByDeviceAdmin()12655 public void testSetPerSsidRoamingModeByDeviceAdmin() throws RemoteException { 12656 assumeTrue(SdkLevel.isAtLeastV()); 12657 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn( 12658 createCapabilityBitset(WifiManager.WIFI_FEATURE_AGGRESSIVE_ROAMING_MODE_SUPPORT)); 12659 assertThrows(SecurityException.class, 12660 () -> mWifiServiceImpl.setPerSsidRoamingMode( 12661 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 12662 WifiManager.ROAMING_MODE_NORMAL, TEST_PACKAGE_NAME)); 12663 when(mWifiPermissionsUtil.isOrganizationOwnedDeviceAdmin(anyInt(), 12664 eq(TEST_PACKAGE_NAME))).thenReturn(true); 12665 assertThrows(IllegalArgumentException.class, 12666 () -> mWifiServiceImpl.setPerSsidRoamingMode( 12667 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), -1, TEST_PACKAGE_NAME)); 12668 12669 mWifiServiceImpl.setPerSsidRoamingMode(WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 12670 WifiManager.ROAMING_MODE_NORMAL, TEST_PACKAGE_NAME); 12671 mLooper.dispatchAll(); 12672 verify(mWifiRoamingModeManager).setPerSsidRoamingMode( 12673 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 12674 WifiManager.ROAMING_MODE_NORMAL, true); 12675 } 12676 12677 @Test testSetPerSsidRoamingModeByNonAdmin()12678 public void testSetPerSsidRoamingModeByNonAdmin() throws RemoteException { 12679 assumeTrue(SdkLevel.isAtLeastV()); 12680 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn( 12681 createCapabilityBitset(WifiManager.WIFI_FEATURE_AGGRESSIVE_ROAMING_MODE_SUPPORT)); 12682 assertThrows(SecurityException.class, 12683 () -> mWifiServiceImpl.setPerSsidRoamingMode( 12684 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 12685 WifiManager.ROAMING_MODE_NORMAL, TEST_PACKAGE_NAME)); 12686 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission( 12687 anyInt())).thenReturn(true); 12688 assertThrows(IllegalArgumentException.class, 12689 () -> mWifiServiceImpl.setPerSsidRoamingMode( 12690 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), -1, TEST_PACKAGE_NAME)); 12691 12692 mWifiServiceImpl.setPerSsidRoamingMode(WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 12693 WifiManager.ROAMING_MODE_NORMAL, TEST_PACKAGE_NAME); 12694 mLooper.dispatchAll(); 12695 verify(mWifiRoamingModeManager).setPerSsidRoamingMode( 12696 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 12697 WifiManager.ROAMING_MODE_NORMAL, false); 12698 } 12699 12700 @Test testRemovePerSsidRoamingModeByDeviceAdmin()12701 public void testRemovePerSsidRoamingModeByDeviceAdmin() throws RemoteException { 12702 assumeTrue(SdkLevel.isAtLeastV()); 12703 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn( 12704 createCapabilityBitset(WifiManager.WIFI_FEATURE_AGGRESSIVE_ROAMING_MODE_SUPPORT)); 12705 assertThrows(SecurityException.class, 12706 () -> mWifiServiceImpl.removePerSsidRoamingMode( 12707 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_PACKAGE_NAME)); 12708 when(mWifiPermissionsUtil.isOrganizationOwnedDeviceAdmin(anyInt(), 12709 eq(TEST_PACKAGE_NAME))).thenReturn(true); 12710 12711 mWifiServiceImpl.removePerSsidRoamingMode(WifiSsid.fromString(TEST_SSID_WITH_QUOTES), 12712 TEST_PACKAGE_NAME); 12713 mLooper.dispatchAll(); 12714 verify(mWifiRoamingModeManager).removePerSsidRoamingMode( 12715 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), true); 12716 } 12717 12718 @Test testRemovePerSsidRoamingModeByNonAdmin()12719 public void testRemovePerSsidRoamingModeByNonAdmin() throws RemoteException { 12720 assumeTrue(SdkLevel.isAtLeastV()); 12721 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn( 12722 createCapabilityBitset(WifiManager.WIFI_FEATURE_AGGRESSIVE_ROAMING_MODE_SUPPORT)); 12723 assertThrows(SecurityException.class, 12724 () -> mWifiServiceImpl.removePerSsidRoamingMode( 12725 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_PACKAGE_NAME)); 12726 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 12727 12728 mWifiServiceImpl.removePerSsidRoamingMode( 12729 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_PACKAGE_NAME); 12730 mLooper.dispatchAll(); 12731 verify(mWifiRoamingModeManager).removePerSsidRoamingMode( 12732 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), false); 12733 } 12734 12735 @Test testGetPerSsidRoamingModesByDeviceAdmin()12736 public void testGetPerSsidRoamingModesByDeviceAdmin() throws RemoteException { 12737 assumeTrue(SdkLevel.isAtLeastV()); 12738 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn( 12739 createCapabilityBitset(WifiManager.WIFI_FEATURE_AGGRESSIVE_ROAMING_MODE_SUPPORT)); 12740 IMapListener listener = mock(IMapListener.class); 12741 InOrder inOrder = inOrder(listener); 12742 assertThrows(SecurityException.class, 12743 () -> mWifiServiceImpl.getPerSsidRoamingModes(TEST_PACKAGE_NAME, listener)); 12744 when(mWifiPermissionsUtil.isOrganizationOwnedDeviceAdmin(anyInt(), 12745 eq(TEST_PACKAGE_NAME))).thenReturn(true); 12746 12747 Map<String, Integer> deviceAdminRoamingPolicies = new ArrayMap<>(); 12748 deviceAdminRoamingPolicies.put(TEST_SSID_WITH_QUOTES, WifiManager.ROAMING_MODE_NORMAL); 12749 when(mWifiRoamingModeManager.getPerSsidRoamingModes(eq(true))).thenReturn( 12750 deviceAdminRoamingPolicies); 12751 12752 mWifiServiceImpl.getPerSsidRoamingModes(TEST_PACKAGE_NAME, listener); 12753 mLooper.dispatchAll(); 12754 ArgumentCaptor<Map<String, Integer>> resultCaptor = ArgumentCaptor.forClass(Map.class); 12755 inOrder.verify(listener).onResult(resultCaptor.capture()); 12756 12757 assertEquals(resultCaptor.getValue().get(TEST_SSID_WITH_QUOTES), 12758 deviceAdminRoamingPolicies.get(TEST_SSID_WITH_QUOTES)); 12759 assertEquals(resultCaptor.getValue().size(), 12760 deviceAdminRoamingPolicies.size()); 12761 } 12762 12763 @Test testGetPerSsidRoamingModesByNonAdmin()12764 public void testGetPerSsidRoamingModesByNonAdmin() throws RemoteException { 12765 assumeTrue(SdkLevel.isAtLeastV()); 12766 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn( 12767 createCapabilityBitset(WifiManager.WIFI_FEATURE_AGGRESSIVE_ROAMING_MODE_SUPPORT)); 12768 IMapListener listener = mock(IMapListener.class); 12769 InOrder inOrder = inOrder(listener); 12770 assertThrows(SecurityException.class, 12771 () -> mWifiServiceImpl.getPerSsidRoamingModes(TEST_PACKAGE_NAME, listener)); 12772 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission( 12773 anyInt())).thenReturn(true); 12774 12775 Map<String, Integer> nonAdminRoamingPolicies = new ArrayMap<>(); 12776 nonAdminRoamingPolicies.put(TEST_SSID_WITH_QUOTES, WifiManager.ROAMING_MODE_NONE); 12777 when(mWifiRoamingModeManager.getPerSsidRoamingModes(false)).thenReturn( 12778 nonAdminRoamingPolicies); 12779 12780 mWifiServiceImpl.getPerSsidRoamingModes(TEST_PACKAGE_NAME, listener); 12781 mLooper.dispatchAll(); 12782 ArgumentCaptor<Map<String, Integer>> resultCaptor = ArgumentCaptor.forClass(Map.class); 12783 inOrder.verify(listener).onResult(resultCaptor.capture()); 12784 12785 assertEquals(resultCaptor.getValue().get(TEST_SSID_WITH_QUOTES), 12786 nonAdminRoamingPolicies.get(TEST_SSID_WITH_QUOTES)); 12787 assertEquals(resultCaptor.getValue().size(), 12788 nonAdminRoamingPolicies.size()); 12789 } 12790 verifyIsPnoSupported(boolean isBackgroundScanSupported, boolean isSwPnoEnabled, boolean isPnoFeatureSet)12791 private void verifyIsPnoSupported(boolean isBackgroundScanSupported, boolean isSwPnoEnabled, 12792 boolean isPnoFeatureSet) { 12793 when(mWifiGlobals.isBackgroundScanSupported()).thenReturn(isBackgroundScanSupported); 12794 when(mWifiGlobals.isSwPnoEnabled()).thenReturn(isSwPnoEnabled); 12795 if (isPnoFeatureSet) { 12796 when(mActiveModeWarden.getSupportedFeatureSet()) 12797 .thenReturn(createCapabilityBitset(WifiManager.WIFI_FEATURE_PNO)); 12798 } else { 12799 when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(new BitSet()); 12800 } 12801 assertEquals(mWifiServiceImpl.isPnoSupported(), 12802 (isBackgroundScanSupported && isPnoFeatureSet) || isSwPnoEnabled); 12803 } 12804 12805 /* 12806 * Verify that Pno is supported. 12807 */ 12808 @Test testIsPnoSupported()12809 public void testIsPnoSupported() throws Exception { 12810 verifyIsPnoSupported(false, false, false); 12811 verifyIsPnoSupported(true, false, false); 12812 verifyIsPnoSupported(false, true, false); 12813 verifyIsPnoSupported(false, false, true); 12814 verifyIsPnoSupported(true, true, false); 12815 verifyIsPnoSupported(false, true, true); 12816 verifyIsPnoSupported(true, false, true); 12817 verifyIsPnoSupported(true, true, true); 12818 } 12819 12820 @Test testSetD2dAllowedWhenInfraStaDisabled()12821 public void testSetD2dAllowedWhenInfraStaDisabled() throws Exception { 12822 // by default no permissions are given so the call should fail. 12823 assertThrows(SecurityException.class, 12824 () -> mWifiServiceImpl.setD2dAllowedWhenInfraStaDisabled(true)); 12825 mWifiServiceImpl.checkAndStartWifi(); 12826 mLooper.dispatchAll(); 12827 // verify setD2DAllowedWhenInfraStaDisabled with MANAGE_WIFI_NETWORK_SETTING 12828 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 12829 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 12830 mWifiServiceImpl.setD2dAllowedWhenInfraStaDisabled(true); 12831 mLooper.dispatchAll(); 12832 verify(mWifiSettingsConfigStore).put(eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED), eq(true)); 12833 12834 mWifiServiceImpl.setD2dAllowedWhenInfraStaDisabled(false); 12835 mLooper.dispatchAll(); 12836 verify(mWifiSettingsConfigStore).put(eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED), eq(false)); 12837 } 12838 12839 @Test testQueryD2dAllowedWhenInfraStaDisabled()12840 public void testQueryD2dAllowedWhenInfraStaDisabled() throws Exception { 12841 // null listener ==> IllegalArgumentException 12842 assertThrows(IllegalArgumentException.class, 12843 () -> mWifiServiceImpl.queryD2dAllowedWhenInfraStaDisabled(null)); 12844 12845 mWifiServiceImpl.checkAndStartWifi(); 12846 mLooper.dispatchAll(); 12847 IBooleanListener listener = mock(IBooleanListener.class); 12848 12849 InOrder inOrder = inOrder(listener); 12850 when(mWifiSettingsConfigStore.get(eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED))) 12851 .thenReturn(true); 12852 mWifiServiceImpl.queryD2dAllowedWhenInfraStaDisabled(listener); 12853 mLooper.dispatchAll(); 12854 verify(mWifiSettingsConfigStore).get(eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED)); 12855 inOrder.verify(listener).onResult(true); 12856 12857 when(mWifiSettingsConfigStore.get(eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED))) 12858 .thenReturn(false); 12859 mWifiServiceImpl.queryD2dAllowedWhenInfraStaDisabled(listener); 12860 mLooper.dispatchAll(); 12861 verify(mWifiSettingsConfigStore, times(2)).get(eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED)); 12862 inOrder.verify(listener).onResult(false); 12863 } 12864 12865 @Test testGetTwtCapabilities()12866 public void testGetTwtCapabilities() { 12867 assumeTrue(SdkLevel.isAtLeastV()); 12868 ITwtCapabilitiesListener iTwtCapabilitiesListener = mock(ITwtCapabilitiesListener.class); 12869 // Test permission check 12870 when(mContext.checkCallingOrSelfPermission( 12871 android.Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION)).thenReturn( 12872 PackageManager.PERMISSION_DENIED); 12873 assertThrows(SecurityException.class, 12874 () -> mWifiServiceImpl.getTwtCapabilities(iTwtCapabilitiesListener, mExtras)); 12875 mWifiServiceImpl.checkAndStartWifi(); 12876 mLooper.dispatchAll(); 12877 when(mContext.checkCallingOrSelfPermission( 12878 android.Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION)).thenReturn( 12879 PackageManager.PERMISSION_GRANTED); 12880 // Test with null parameters 12881 assertThrows(IllegalArgumentException.class, 12882 () -> mWifiServiceImpl.getTwtCapabilities(null, mExtras)); 12883 // Test getTwtCapabilities call 12884 mWifiServiceImpl.getTwtCapabilities(iTwtCapabilitiesListener, mExtras); 12885 mLooper.dispatchAll(); 12886 verify(mTwtManager).getTwtCapabilities(eq(WIFI_IFACE_NAME), eq(iTwtCapabilitiesListener)); 12887 } 12888 12889 @Test testSetupTwtSession()12890 public void testSetupTwtSession() throws RemoteException { 12891 assumeTrue(SdkLevel.isAtLeastV()); 12892 ITwtCallback iTwtCallback = mock(ITwtCallback.class); 12893 TwtRequest twtRequest = mock(TwtRequest.class); 12894 // Test permission check 12895 when(mContext.checkCallingOrSelfPermission( 12896 android.Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION)).thenReturn( 12897 PackageManager.PERMISSION_DENIED); 12898 assertThrows(SecurityException.class, 12899 () -> mWifiServiceImpl.setupTwtSession(twtRequest, iTwtCallback, mExtras)); 12900 mWifiServiceImpl.checkAndStartWifi(); 12901 mLooper.dispatchAll(); 12902 when(mContext.checkCallingOrSelfPermission( 12903 android.Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION)).thenReturn( 12904 PackageManager.PERMISSION_GRANTED); 12905 // Test with null parameters 12906 assertThrows(IllegalArgumentException.class, 12907 () -> mWifiServiceImpl.setupTwtSession(null, iTwtCallback, mExtras)); 12908 assertThrows(IllegalArgumentException.class, 12909 () -> mWifiServiceImpl.setupTwtSession(twtRequest, null, mExtras)); 12910 // Test with station not connected 12911 when(mClientModeManager.isConnected()).thenReturn(false); 12912 mWifiServiceImpl.setupTwtSession(twtRequest, iTwtCallback, mExtras); 12913 mLooper.dispatchAll(); 12914 verify(iTwtCallback).onFailure(eq(TwtSessionCallback.TWT_ERROR_CODE_NOT_AVAILABLE)); 12915 // Test setupTwtSession with station connected 12916 when(mClientModeManager.isConnected()).thenReturn(true); 12917 when(mClientModeManager.getConnectedBssid()).thenReturn(TEST_BSSID); 12918 mWifiServiceImpl.setupTwtSession(twtRequest, iTwtCallback, mExtras); 12919 mLooper.dispatchAll(); 12920 verify(mTwtManager).setupTwtSession(eq(WIFI_IFACE_NAME), eq(twtRequest), eq(iTwtCallback), 12921 eq(Binder.getCallingUid()), eq(TEST_BSSID)); 12922 } 12923 12924 @Test testGetStatsTwtSession()12925 public void testGetStatsTwtSession() { 12926 assumeTrue(SdkLevel.isAtLeastV()); 12927 int sessionId = 10; 12928 ITwtStatsListener iTwtStatsListener = mock(ITwtStatsListener.class); 12929 // Test permission check 12930 when(mContext.checkCallingOrSelfPermission( 12931 android.Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION)).thenReturn( 12932 PackageManager.PERMISSION_DENIED); 12933 assertThrows(SecurityException.class, 12934 () -> mWifiServiceImpl.getStatsTwtSession(sessionId, iTwtStatsListener, mExtras)); 12935 mWifiServiceImpl.checkAndStartWifi(); 12936 mLooper.dispatchAll(); 12937 when(mContext.checkCallingOrSelfPermission( 12938 android.Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION)).thenReturn( 12939 PackageManager.PERMISSION_GRANTED); 12940 // Test with null parameters 12941 assertThrows(IllegalArgumentException.class, 12942 () -> mWifiServiceImpl.getStatsTwtSession(sessionId, null, mExtras)); 12943 // Test getStatsTwtSession call 12944 mWifiServiceImpl.getStatsTwtSession(sessionId, iTwtStatsListener, mExtras); 12945 mLooper.dispatchAll(); 12946 verify(mTwtManager).getStatsTwtSession(eq(WIFI_IFACE_NAME), eq(iTwtStatsListener), 12947 eq(sessionId)); 12948 } 12949 12950 @Test testTeardownTwtSession()12951 public void testTeardownTwtSession() { 12952 assumeTrue(SdkLevel.isAtLeastV()); 12953 int sessionId = 10; 12954 // Test permission check 12955 when(mContext.checkCallingOrSelfPermission( 12956 android.Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION)).thenReturn( 12957 PackageManager.PERMISSION_DENIED); 12958 assertThrows(SecurityException.class, 12959 () -> mWifiServiceImpl.teardownTwtSession(sessionId, mExtras)); 12960 mWifiServiceImpl.checkAndStartWifi(); 12961 mLooper.dispatchAll(); 12962 when(mContext.checkCallingOrSelfPermission( 12963 android.Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION)).thenReturn( 12964 PackageManager.PERMISSION_GRANTED); 12965 // Test teardownTwtSession call 12966 mWifiServiceImpl.teardownTwtSession(sessionId, mExtras); 12967 mLooper.dispatchAll(); 12968 verify(mTwtManager).tearDownTwtSession(eq(WIFI_IFACE_NAME), eq(sessionId)); 12969 } 12970 12971 @SuppressWarnings("BoxedPrimitiveEquality") 12972 @Test testRetrieveWifiBackupData()12973 public void testRetrieveWifiBackupData() throws Exception { 12974 assumeTrue(SdkLevel.isAtLeastV()); 12975 // Expect exception when caller has no permission 12976 doThrow(new SecurityException()).when(mContext) 12977 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 12978 eq("WifiService")); 12979 IByteArrayListener mockTestListener = mock(IByteArrayListener.class); 12980 // by default no permissions are given so the call should fail. 12981 assertThrows(SecurityException.class, 12982 () -> mWifiServiceImpl.retrieveWifiBackupData(mockTestListener)); 12983 doNothing().when(mContext) 12984 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 12985 eq("WifiService")); 12986 // null listener ==> IllegalArgumentException 12987 assertThrows(IllegalArgumentException.class, 12988 () -> mWifiServiceImpl.retrieveWifiBackupData(null)); 12989 mWifiServiceImpl.retrieveWifiBackupData(mockTestListener); 12990 mLooper.dispatchAll(); 12991 verify(mBackupRestoreController).retrieveBackupData(); 12992 verify(mockTestListener).onResult(any()); 12993 } 12994 12995 @SuppressWarnings("BoxedPrimitiveEquality") 12996 @Test testRestoreWifiBackupData()12997 public void testRestoreWifiBackupData() throws Exception { 12998 assumeTrue(SdkLevel.isAtLeastV()); 12999 byte[] mockTestRestoredData = new byte[0]; 13000 // Expect exception when caller has no permission 13001 doThrow(new SecurityException()).when(mContext) 13002 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 13003 eq("WifiService")); 13004 // by default no permissions are given so the call should fail. 13005 assertThrows(SecurityException.class, 13006 () -> mWifiServiceImpl.restoreWifiBackupData(mockTestRestoredData)); 13007 doNothing().when(mContext) 13008 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 13009 eq("WifiService")); 13010 mWifiServiceImpl.restoreWifiBackupData(mockTestRestoredData); 13011 mLooper.dispatchAll(); 13012 verify(mBackupRestoreController).parserBackupDataAndDispatch(mockTestRestoredData); 13013 } 13014 13015 @Test testWepAllowedChangedFromCloudRestoration()13016 public void testWepAllowedChangedFromCloudRestoration() { 13017 when(mWifiSettingsConfigStore.get(eq(WIFI_WEP_ALLOWED))).thenReturn(true); 13018 when(mWifiGlobals.isWepAllowed()).thenReturn(true); 13019 mWifiServiceImpl.checkAndStartWifi(); 13020 mLooper.dispatchAll(); 13021 verify(mWifiSettingsConfigStore).registerChangeListener( 13022 eq(WIFI_WEP_ALLOWED), 13023 mWepAllowedSettingChangedListenerCaptor.capture(), 13024 any(Handler.class)); 13025 verify(mWifiGlobals).setWepAllowed(true); 13026 // Mock wep connection to make sure it will disconnect 13027 ConcreteClientModeManager cmmWep = mock(ConcreteClientModeManager.class); 13028 WifiInfo mockWifiInfoWep = mock(WifiInfo.class); 13029 List<ClientModeManager> cmms = Arrays.asList(cmmWep); 13030 when(mActiveModeWarden.getClientModeManagers()).thenReturn(cmms); 13031 when(mockWifiInfoWep.getCurrentSecurityType()).thenReturn(WifiInfo.SECURITY_TYPE_WEP); 13032 when(cmmWep.getConnectionInfo()).thenReturn(mockWifiInfoWep); 13033 13034 // Test wep is changed from cloud restoration. 13035 mWepAllowedSettingChangedListenerCaptor.getValue() 13036 .onSettingsChanged(WIFI_WEP_ALLOWED, false); 13037 mLooper.dispatchAll(); 13038 verify(mWifiGlobals).setWepAllowed(false); 13039 // Only WEP disconnect 13040 verify(cmmWep).disconnect(); 13041 } 13042 13043 @Test testGetWifiConfigForMatchedNetworkSuggestionsSharedWithUserForMultiTypeConfigs()13044 public void testGetWifiConfigForMatchedNetworkSuggestionsSharedWithUserForMultiTypeConfigs() { 13045 BitSet featureFlags = createCapabilityBitset( 13046 WifiManager.WIFI_FEATURE_WPA3_SAE, WifiManager.WIFI_FEATURE_OWE); 13047 List<WifiConfiguration> testConfigs = setupMultiTypeConfigs(featureFlags, true, true); 13048 when(mWifiNetworkSuggestionsManager 13049 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(anyList())) 13050 .thenReturn(testConfigs); 13051 when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS), 13052 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 13053 ScanResult[] scanResults = 13054 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0] 13055 .getResults(); 13056 List<ScanResult> scanResultList = 13057 new ArrayList<>(Arrays.asList(scanResults)); 13058 13059 mLooper.startAutoDispatch(); 13060 ParceledListSlice<WifiConfiguration> configs = 13061 mWifiServiceImpl.getWifiConfigForMatchedNetworkSuggestionsSharedWithUser( 13062 new ParceledListSlice<>(scanResultList)); 13063 mLooper.stopAutoDispatchAndIgnoreExceptions(); 13064 13065 List<WifiConfiguration> expectedConfigs = generateExpectedConfigs( 13066 testConfigs, true, true); 13067 WifiConfigurationTestUtil.assertConfigurationsEqualForBackup( 13068 expectedConfigs, configs.getList()); 13069 } 13070 13071 @Test testSetAutojoinDisallowedSecurityTypesWithPermission()13072 public void testSetAutojoinDisallowedSecurityTypesWithPermission() throws RemoteException { 13073 assumeTrue(SdkLevel.isAtLeastT()); 13074 // No permission to call API 13075 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 13076 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 13077 .thenReturn(false); 13078 assertThrows(SecurityException.class, 13079 () -> mWifiServiceImpl.setAutojoinDisallowedSecurityTypes(0/*restrict none*/, 13080 mExtras)); 13081 // Has permission to call API 13082 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 13083 // Null argument 13084 assertThrows(IllegalArgumentException.class, 13085 () -> mWifiServiceImpl.setAutojoinDisallowedSecurityTypes(0/*restrict none*/, 13086 null)); 13087 // Invalid argument 13088 assertThrows(IllegalArgumentException.class, 13089 () -> mWifiServiceImpl.setAutojoinDisallowedSecurityTypes( 13090 0x1 << WifiInfo.SECURITY_TYPE_OWE, mExtras)); 13091 assertThrows(IllegalArgumentException.class, 13092 () -> mWifiServiceImpl.setAutojoinDisallowedSecurityTypes( 13093 0x1 << WifiInfo.SECURITY_TYPE_SAE, mExtras)); 13094 assertThrows(IllegalArgumentException.class, 13095 () -> mWifiServiceImpl.setAutojoinDisallowedSecurityTypes( 13096 0x1 << WifiInfo.SECURITY_TYPE_EAP_WPA3_ENTERPRISE, mExtras)); 13097 // Valid argument 13098 int restrictions = (0x1 << WifiInfo.SECURITY_TYPE_OPEN) 13099 | (0x1 << WifiInfo.SECURITY_TYPE_OWE) | (0x1 << WifiInfo.SECURITY_TYPE_WEP); 13100 mWifiServiceImpl.setAutojoinDisallowedSecurityTypes(restrictions, mExtras); 13101 mLooper.dispatchAll(); 13102 verify(mWifiConnectivityManager).setAutojoinDisallowedSecurityTypes(eq(restrictions)); 13103 } 13104 13105 @Test testGetAutojoinDisallowedSecurityTypesWithPermission()13106 public void testGetAutojoinDisallowedSecurityTypesWithPermission() throws RemoteException { 13107 assumeTrue(SdkLevel.isAtLeastT()); 13108 // Mock listener. 13109 IIntegerListener listener = mock(IIntegerListener.class); 13110 InOrder inOrder = inOrder(listener); 13111 // No permission to call API 13112 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 13113 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 13114 .thenReturn(false); 13115 assertThrows(SecurityException.class, 13116 () -> mWifiServiceImpl.getAutojoinDisallowedSecurityTypes(listener, mExtras)); 13117 // Null arguments 13118 assertThrows(IllegalArgumentException.class, 13119 () -> mWifiServiceImpl.getAutojoinDisallowedSecurityTypes(null, mExtras)); 13120 assertThrows(IllegalArgumentException.class, 13121 () -> mWifiServiceImpl.getAutojoinDisallowedSecurityTypes(listener, null)); 13122 // has permission to call API 13123 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 13124 when(mWifiConnectivityManager.getAutojoinDisallowedSecurityTypes()).thenReturn(7); 13125 mWifiServiceImpl.getAutojoinDisallowedSecurityTypes(listener, mExtras); 13126 mLooper.dispatchAll(); 13127 inOrder.verify(listener).onResult(7); 13128 } 13129 /** 13130 * Verify UwbManager.AdapterStateCallback onStateChanged could update mLastUwbState in 13131 * WifiMetrics properly 13132 */ 13133 @Test testServiceImplAdapterStateCallback()13134 public void testServiceImplAdapterStateCallback() { 13135 assumeTrue(SdkLevel.isAtLeastT()); 13136 UwbAdapterStateListener uwbAdapterStateListener = 13137 mWifiServiceImpl.new UwbAdapterStateListener(); 13138 13139 uwbAdapterStateListener.onStateChanged(2, 1); 13140 verify(mWifiMetrics).setLastUwbState(2); 13141 } 13142 13143 /** 13144 * Verify ThreadNetworkController.StateCallback onDeviceRoleChanged could update 13145 * mLastThreadDeviceRole in WifiMetrics properly 13146 */ 13147 @Test testServiceImplThreadStateCallback()13148 public void testServiceImplThreadStateCallback() { 13149 assumeTrue(SdkLevel.isAtLeastV()); 13150 ThreadStateListener threadStateListener = 13151 mWifiServiceImpl.new ThreadStateListener(); 13152 13153 threadStateListener.onDeviceRoleChanged(3); 13154 verify(mWifiMetrics).setLastThreadDeviceRole(3); 13155 } 13156 13157 @Test testSetQueryAllowedWhenWepUsageControllerSupported()13158 public void testSetQueryAllowedWhenWepUsageControllerSupported() { 13159 when(mFeatureFlags.wepDisabledInApm()).thenReturn(true); 13160 WepNetworkUsageController testWepNetworkUsageController = 13161 mock(WepNetworkUsageController.class); 13162 when(mWifiInjector.getWepNetworkUsageController()) 13163 .thenReturn(testWepNetworkUsageController); 13164 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 13165 ConcreteClientModeManager cmmWep = mock(ConcreteClientModeManager.class); 13166 WifiInfo mockWifiInfoWep = mock(WifiInfo.class); 13167 List<ClientModeManager> cmms = Arrays.asList(cmmWep); 13168 when(mActiveModeWarden.getClientModeManagers()).thenReturn(cmms); 13169 when(mockWifiInfoWep.getCurrentSecurityType()).thenReturn(WifiInfo.SECURITY_TYPE_WEP); 13170 when(cmmWep.getConnectionInfo()).thenReturn(mockWifiInfoWep); 13171 mWifiServiceImpl = makeWifiServiceImpl(); 13172 mWifiServiceImpl.checkAndStartWifi(); 13173 mWifiServiceImpl.handleBootCompleted(); 13174 mLooper.dispatchAll(); 13175 // Verify boot complete go through the new design. 13176 verify(mWifiSettingsConfigStore, never()).registerChangeListener( 13177 eq(WIFI_WEP_ALLOWED), 13178 mWepAllowedSettingChangedListenerCaptor.capture(), 13179 any(Handler.class)); 13180 verify(mWifiGlobals, never()).setWepAllowed(anyBoolean()); 13181 verify(testWepNetworkUsageController).handleBootCompleted(); 13182 13183 mWifiServiceImpl.setWepAllowed(false); 13184 mLooper.dispatchAll(); 13185 verify(mWifiGlobals, never()).setWepAllowed(anyBoolean()); 13186 verify(mWifiSettingsConfigStore).put(eq(WIFI_WEP_ALLOWED), eq(false)); 13187 // WEP disconnect logic moved to WepNetworkUsageController. 13188 verify(cmmWep, never()).disconnect(); 13189 verify(mWifiGlobals, never()).setWepAllowed(anyBoolean()); 13190 } 13191 13192 @Test testUpdateSoftApCapabilityCheckMLOSupport()13193 public void testUpdateSoftApCapabilityCheckMLOSupport() throws Exception { 13194 lenient().when(SubscriptionManager.getActiveDataSubscriptionId()) 13195 .thenReturn(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID); 13196 ArgumentCaptor<SoftApCapability> capabilityArgumentCaptor = ArgumentCaptor.forClass( 13197 SoftApCapability.class); 13198 when(mWifiNative.isMLDApSupportMLO()).thenReturn(true); 13199 mWifiServiceImpl.checkAndStartWifi(); 13200 mLooper.dispatchAll(); 13201 verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(), 13202 argThat((IntentFilter filter) -> 13203 filter.hasAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)), 13204 isNull(), 13205 any(Handler.class)); 13206 13207 // Send the broadcast 13208 Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED); 13209 mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent); 13210 mLooper.dispatchAll(); 13211 verify(mActiveModeWarden).updateSoftApCapability(capabilityArgumentCaptor.capture(), 13212 eq(WifiManager.IFACE_IP_MODE_TETHERED)); 13213 assertTrue(capabilityArgumentCaptor.getValue() 13214 .areFeaturesSupported(SoftApCapability.SOFTAP_FEATURE_MLO)); 13215 } 13216 13217 @Test testCustomUserLohs()13218 public void testCustomUserLohs() { 13219 assumeTrue(Environment.isSdkAtLeastB()); 13220 SoftApConfiguration customConfig = new SoftApConfiguration.Builder() 13221 .setSsid("customConfig") 13222 .build(); 13223 assertThrows(SecurityException.class, 13224 () -> mWifiServiceImpl.startLocalOnlyHotspot( 13225 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, 13226 customConfig, mExtras, false)); 13227 setupLohsPermissions(); 13228 mWifiServiceImpl.startLocalOnlyHotspot(mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, 13229 customConfig, mExtras, false); 13230 } 13231 13232 @Test testDisallowCurrentSuggestedNetwork()13233 public void testDisallowCurrentSuggestedNetwork() { 13234 BlockingOption blockingOption = new BlockingOption.Builder(100).build(); 13235 WifiInfo info = new WifiInfo(); 13236 info.setRequestingPackageName(TEST_PACKAGE_NAME); 13237 when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_ENABLED); 13238 when(mActiveModeWarden.getConnectionInfo()).thenReturn(info); 13239 mWifiServiceImpl.disallowCurrentSuggestedNetwork(blockingOption, TEST_PACKAGE_NAME); 13240 mLooper.dispatchAll(); 13241 verify(mClientModeManager).blockNetwork(eq(blockingOption)); 13242 } 13243 13244 /** 13245 * Test add and remove listener will go to ActiveModeWarden. 13246 */ 13247 @Test testAddRemoveWifiStateChangedListener()13248 public void testAddRemoveWifiStateChangedListener() throws Exception { 13249 assumeTrue(SdkLevel.isAtLeastS()); 13250 when(mWifiStateChangedListener.asBinder()).thenReturn(mAppBinder); 13251 mWifiServiceImpl.addWifiStateChangedListener(mWifiStateChangedListener); 13252 mLooper.dispatchAll(); 13253 verify(mActiveModeWarden).addWifiStateChangedListener(mWifiStateChangedListener); 13254 mWifiServiceImpl.removeWifiStateChangedListener(mWifiStateChangedListener); 13255 mLooper.dispatchAll(); 13256 verify(mActiveModeWarden).removeWifiStateChangedListener(mWifiStateChangedListener); 13257 } 13258 13259 /** 13260 * Verify that a call to addWifiStateChangedListener throws a SecurityException if the 13261 * caller does not have the ACCESS_WIFI_STATE permission. 13262 */ 13263 @Test testAddWifiStateChangedListenerThrowsSecurityExceptionOnMissingPermissions()13264 public void testAddWifiStateChangedListenerThrowsSecurityExceptionOnMissingPermissions() { 13265 doThrow(new SecurityException()).when(mContext) 13266 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), 13267 eq("WifiService")); 13268 try { 13269 mWifiServiceImpl.addWifiStateChangedListener(mWifiStateChangedListener); 13270 fail("expected SecurityException"); 13271 } catch (SecurityException expected) { } 13272 } 13273 13274 /** 13275 * Verify that a call to removeWifiStateChangedListener throws a SecurityException if the caller 13276 * does not have the ACCESS_WIFI_STATE permission. 13277 */ 13278 @Test testRemoveWifiStateChangedListenerThrowsSecurityExceptionOnMissingPermissions()13279 public void testRemoveWifiStateChangedListenerThrowsSecurityExceptionOnMissingPermissions() { 13280 doThrow(new SecurityException()).when(mContext) 13281 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), 13282 eq("WifiService")); 13283 try { 13284 mWifiServiceImpl.addWifiStateChangedListener(mWifiStateChangedListener); 13285 fail("expected SecurityException"); 13286 } catch (SecurityException expected) { } 13287 } 13288 13289 @Test testCustomLohs_NotExclusive5GConfigButNewRequestorLowerPriority()13290 public void testCustomLohs_NotExclusive5GConfigButNewRequestorLowerPriority() { 13291 assumeTrue(Environment.isSdkAtLeastB()); 13292 when(mFeatureFlags.publicBandsForLohs()).thenReturn(true); 13293 when(mWorkSourceHelper.getRequestorWsPriority()) 13294 .thenReturn(WorkSourceHelper.PRIORITY_FG_APP) 13295 .thenReturn(WorkSourceHelper.PRIORITY_BG); 13296 setupForCustomLohs(); 13297 setup5GhzSupported(); 13298 SoftApConfiguration custom5GBandConfig = new SoftApConfiguration.Builder() 13299 .setSsid("TestAp") 13300 .setBand(SoftApConfiguration.BAND_5GHZ) 13301 .build(); 13302 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 13303 any(), any(), any(), eq(false))).thenReturn(custom5GBandConfig); 13304 when(mRequestInfo.getCustomConfig()).thenReturn(custom5GBandConfig); 13305 when(mRequestInfo2.getCustomConfig()).thenReturn(null); 13306 mLooper.startAutoDispatch(); 13307 assertThat(mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo)) 13308 .isEqualTo(REQUEST_REGISTERED); 13309 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 13310 // Test second requestor gets fail since it has lower priority 13311 assertThat(mWifiServiceImpl.registerLOHSForTest(TEST_PID2, mRequestInfo2)) 13312 .isEqualTo(ERROR_GENERIC); 13313 } 13314 13315 @Test testCustomLohs_NotExclusive2GConfigSharedEvenIfNewRequestorLowerPriority()13316 public void testCustomLohs_NotExclusive2GConfigSharedEvenIfNewRequestorLowerPriority() 13317 throws Exception { 13318 assumeTrue(Environment.isSdkAtLeastB()); 13319 when(mFeatureFlags.publicBandsForLohs()).thenReturn(true); 13320 when(mWorkSourceHelper.getRequestorWsPriority()) 13321 .thenReturn(WorkSourceHelper.PRIORITY_FG_APP) 13322 .thenReturn(WorkSourceHelper.PRIORITY_BG); 13323 setupForCustomLohs(); 13324 SoftApConfiguration custom2GBandConfig = new SoftApConfiguration.Builder() 13325 .setSsid("TestAp") 13326 .setBand(SoftApConfiguration.BAND_2GHZ) 13327 .build(); 13328 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 13329 any(), any(), any(), eq(false))).thenReturn(custom2GBandConfig); 13330 when(mRequestInfo.getCustomConfig()).thenReturn(custom2GBandConfig); 13331 when(mRequestInfo2.getCustomConfig()).thenReturn(null); 13332 mLooper.startAutoDispatch(); 13333 assertThat(mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo)) 13334 .isEqualTo(REQUEST_REGISTERED); 13335 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 13336 mLooper.startAutoDispatch(); 13337 // Test second requestor gets registered even if it has lower priority 13338 assertThat(mWifiServiceImpl.registerLOHSForTest(TEST_PID2, mRequestInfo2)) 13339 .isEqualTo(REQUEST_REGISTERED); 13340 verify(mRequestInfo, never()).unlinkDeathRecipient(); 13341 verify(mRequestInfo2).sendHotspotStartedMessage(eq(custom2GBandConfig)); 13342 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 13343 } 13344 13345 @Test testCustomLohs_NotExclusive5GConfigButNewRequestorHigherPriority()13346 public void testCustomLohs_NotExclusive5GConfigButNewRequestorHigherPriority() 13347 throws Exception { 13348 assumeTrue(Environment.isSdkAtLeastB()); 13349 when(mFeatureFlags.publicBandsForLohs()).thenReturn(true); 13350 when(mWorkSourceHelper.getRequestorWsPriority()) 13351 .thenReturn(WorkSourceHelper.PRIORITY_FG_APP) // first requestor 13352 .thenReturn(WorkSourceHelper.PRIORITY_FG_APP) // new requestor 13353 .thenReturn(WorkSourceHelper.PRIORITY_BG); // first requestor to BG 13354 setupForCustomLohs(); 13355 setup5GhzSupported(); 13356 SoftApConfiguration custom5GBandConfig = new SoftApConfiguration.Builder() 13357 .setSsid("TestAp") 13358 .setBand(SoftApConfiguration.BAND_5GHZ) 13359 .build(); 13360 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 13361 any(), any(), any(), eq(false))).thenReturn(custom5GBandConfig); 13362 when(mRequestInfo.getCustomConfig()).thenReturn(custom5GBandConfig); 13363 when(mRequestInfo2.getCustomConfig()).thenReturn(null); 13364 mLooper.startAutoDispatch(); 13365 assertThat(mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo)) 13366 .isEqualTo(REQUEST_REGISTERED); 13367 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 13368 mLooper.startAutoDispatch(); 13369 // Test second requestor gets succeeded since it has higher priority 13370 assertThat(mWifiServiceImpl.registerLOHSForTest(TEST_PID2, mRequestInfo2)) 13371 .isEqualTo(REQUEST_REGISTERED); 13372 // Make sure first requestor dead since it was replaced by second requestor. 13373 verify(mRequestInfo).sendHotspotFailedMessage(eq(ERROR_INCOMPATIBLE_MODE)); 13374 verify(mRequestInfo).unlinkDeathRecipient(); 13375 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 13376 } 13377 13378 @Test testCustomLohs_NotExclusive2GConfigSharedWhenNewRequestorHihgerPriority()13379 public void testCustomLohs_NotExclusive2GConfigSharedWhenNewRequestorHihgerPriority() 13380 throws Exception { 13381 assumeTrue(Environment.isSdkAtLeastB()); 13382 when(mFeatureFlags.publicBandsForLohs()).thenReturn(true); 13383 when(mWorkSourceHelper.getRequestorWsPriority()) 13384 .thenReturn(WorkSourceHelper.PRIORITY_BG) 13385 .thenReturn(WorkSourceHelper.PRIORITY_FG_APP); 13386 setupForCustomLohs(); 13387 SoftApConfiguration custom2GBandConfig = new SoftApConfiguration.Builder() 13388 .setSsid("TestAp") 13389 .setBand(SoftApConfiguration.BAND_2GHZ) 13390 .build(); 13391 when(mWifiApConfigStore.generateLocalOnlyHotspotConfig( 13392 any(), any(), any(), eq(false))).thenReturn(custom2GBandConfig); 13393 when(mRequestInfo.getCustomConfig()).thenReturn(custom2GBandConfig); 13394 when(mRequestInfo2.getCustomConfig()).thenReturn(null); 13395 mLooper.startAutoDispatch(); 13396 assertThat(mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo)) 13397 .isEqualTo(REQUEST_REGISTERED); 13398 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 13399 mLooper.startAutoDispatch(); 13400 // Test second requestor gets succeeded since it has higher priority 13401 assertThat(mWifiServiceImpl.registerLOHSForTest(TEST_PID2, mRequestInfo2)) 13402 .isEqualTo(REQUEST_REGISTERED); 13403 // Make sure first requestor still alive since 2.4G can be shared. 13404 verify(mRequestInfo2).sendHotspotStartedMessage(eq(custom2GBandConfig)); 13405 verify(mRequestInfo, never()).unlinkDeathRecipient(); 13406 stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper); 13407 } 13408 } 13409